text:
Tetris Movement - Implementation
I'm developing a Tetris clone and working on the input at the moment.
When I was prototyping, movement was triggered by releasing a directional key. However, in most Tetris games I've played the movement is a bit more complex.

When a directional key is pressed, the shape moves one space in that direction. After a short interval, if the key is still held down, the shape starts moving in the direction continuously until the key is released.
In the case of the down key being pressed, there is no pause between the initial movement and the subsequent continuous movement.

I've come up with a solution, and it works well, but it's totally over-engineered. Hey, at least I can recognize when things are getting silly, right? :)

    public class TetrisMover
    {
        List registeredKeys;
        Dictionary continuousPressedTime;
        Dictionary totalPressedTime;
        Dictionary initialIntervals;
        Dictionary continousIntervals;
        Dictionary keyActions;
        Dictionary initialActionDone;
        KeyboardState currentKeyboardState;

        public TetrisMover()
        {
            *snip*
        }

        public void Update(GameTime gameTime)
        {
            currentKeyboardState = Keyboard.GetState();

            foreach (Keys currentKey in registeredKeys)
            {
                if (currentKeyboardState.IsKeyUp(currentKey))
                {
                    continuousPressedTime[currentKey] = TimeSpan.Zero;
                    totalPressedTime[currentKey] = TimeSpan.Zero;
                    initialActionDone[currentKey] = false;
                }
                else
                {
                    if (initialActionDone[currentKey] == false)
                    {
                        keyActions[currentKey]();
                        initialActionDone[currentKey] = true;
                    }

                    totalPressedTime[currentKey] += gameTime.ElapsedGameTime;

                    if (totalPressedTime[currentKey] >= initialIntervals[currentKey])
                    {
                        continuousPressedTime[currentKey] += gameTime.ElapsedGameTime;
                        if (continuousPressedTime[currentKey] >= continousIntervals[currentKey])
                        {
                            keyActions[currentKey]();
                            continuousPressedTime[currentKey] = TimeSpan.Zero;
                        }
                    }
                }
            }
        }

        public void RegisterKey(Keys key, TimeSpan initialInterval, TimeSpan continuousInterval, Action keyAction)
        {
            if (registeredKeys.Contains(key))
                throw new InvalidOperationException(
                    string.Format("The key %s is already registered.", key));

            registeredKeys.Add(key);
            continuousPressedTime.Add(key, TimeSpan.Zero);
            totalPressedTime.Add(key, TimeSpan.Zero);
            initialIntervals.Add(key, initialInterval);
            continousIntervals.Add(key, continuousInterval);
            keyActions.Add(key, keyAction);
            initialActionDone.Add(key, false);
        }

        public void UnregisterKey(Keys key)
        {
            *snip*
        }
    }

I'm updating it every frame, and this is how I'm registering keys for movement:

            tetrisMover.RegisterKey(
                Keys.Left, keyHoldStartSpecialInterval, keyHoldMovementInterval,
                () => { Move(Direction.Left); });

            tetrisMover.RegisterKey(
                Keys.Right, keyHoldStartSpecialInterval, keyHoldMovementInterval,
                () => { Move(Direction.Right); });

            tetrisMover.RegisterKey(
                Keys.Down, TimeSpan.Zero, keyHoldMovementInterval,
                () => { PerformGravity(); });

Issues that this doesn't address:

If both left and right are held down,
the shape moves back and forth really
quick.
If a directional key is held down and
the turn finishes and the shape is
replaced by a new one, the new one
will move quickly in that direction
instead of the little pause it is
supposed to have.

I could fix the issues, but I think it will make the solution even worse. How would you implement this?

What you need is a simple key repeating algorithm. This is how I usually do it.
FRAMES_FOR_FIRST_PRESS = 4;
FRAMES_FOR_OTHER_PRESS = 1;

key_pending_frames = -1;

now, for every frame:
function OnFrame()
{
    if (IsKeyPressed())
    {
        if (key_pending_frames < 0) // not pressed
        {
            key_pending_frames = FRAMES_FOR_FIRST_PRESS;
        }
        key_pending_frames--;
        if (key_pending_frames == 0)
        {
            DoYourAction();
            key_pending_frames = FRAMES_FOR_OTHER_PRESS;
        }
    }
    else
    {
        key_pending_frames = -1;
    }
}

You'd need a key_pending_frames for each key you want, and you can reset any key's counter just by setting its variable to -1.
Note that for non-fixed frame lengths, you can use clock ticks, or another time interval structure you have. You just have to make sure your non-pressed value is unreachable by simply decrementing the counter. To be on the safe side, you can simply add a bool key_pressed for each key.


text:
Android: Layouts and views or a single full screen custom view?
I'm developing an Android game, and I'm making it so that it can run on low end devices without GPU, so I'm using the 2D API. I have so far tried to use Android's mechanisms such as layouts and activities where possible, but I'm beginning to wonder if it's not easier to just create a single custom view (or one per activity) and do all the work there.
Here's an example of how I currently do things: I'm using a layout to display the game's background as an image view and the square game area, which is a custom view, centered in the middle.
What would you say? Should I continue to use layouts where possible or is it more common/reasonable to just use a large custom view? I'm thinking that this would probably also make it easier to port my code to other platforms.

It depends on your game. It's probably okay to use several views for more passive games like minesweeper or sudoku, but not for a shoot 'em up or a platformer. If your current setup is working fine and you find it easier to code using views then you might as well continue doing things that way. It doesn't really matters as long as you're satisfied with the result.
If porting is an issue then you want to use abstractions for the platform-specific stuff regardless of your implementation. But I think that you're right about it being easier with using a custom view, mainly because you wouldn't worry about parsing the layout XML files on the new platform (unless you define the layout in code).

I  have also developed a casual game for Android version 1.6. As you have done, i have also used a imageview as the background, added custom views to accomodate my gameplay area.
This is working very fine for my game. Because, first thing, the views are not complex, second thing, the responsiveness is good, and third, the game flow is also maintained efficiently.
But this is okay for a casual games like board games, games where only 2/3 activities are used (my game uses only 2 activities, with complete game life cycle) or simple puzzle games.
So depending on the complexity of the project the views must be defined. It is better to keep the flow simple and responsive.

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/2.5/

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

sort: votes


text:
My first animation - Using SDL.NET C#
I'm trying to animate a player object in my 2D grid when the user clicks somewhere in the screen.
I got the following 4 variables:

oX (Current player position X)
oY (Current player position Y)
dX (Destination X)
dY (Destination Y)

How can I make sure the player moves in a straight line to the new XY coordinates. The way I'm doing it now is really awfull and causes the player to first move along x axis, and finally in y axis.
Can someone give me some guidance with the involved math cause I'm really not sure on how to accomplish this.
Thank you for your time.
Kind regards,
Mark
Update: It's working now but whats the right way to check if the current positions are equal to the target position?
    private static void MovePlayer(double x2, double y2, int duration)
{
    double hX = x2 - m_PlayerPosition.X;
    double hY = y2 - m_PlayerPosition.Y;

    double Length = Math.Sqrt(Math.Pow(hX, 2) + Math.Pow(hY, 2));
    hX = hX / Length;
    hY = hY / Length;

    while (m_PlayerPosition.X != Convert.ToInt32(x2) || m_PlayerPosition.Y != Convert.ToInt32(y2))
    {
        m_PlayerPosition.X += Convert.ToInt32(hX * 1);
        m_PlayerPosition.Y += Convert.ToInt32(hY * 1);

        UpdatePlayerLocation();
    }
}

Hello Mark, welcome to gamedev. You will find your answer here: http://gamedev.stackexchange.com/questions/7540/enemy-movement-in-straight-line-to-player-in-chase-game/ .

You will want to look into vector maths for this. The basic way you would handle this is as follows:
You'd want two variables as your "heading", this will tell you the direction you want to be heading in.
Let's call them hX and hY.
hX = dX - oX
hY = dY - oY
You should probably normalize these values (meaning, the length of the vector is equal to 1). You do that by performing the following:
Length = sqrt( hX^2 + hY^2 )
hX = hX / Length
hY = hY / Length
Now you can use a speed multiplier to determine how quickly you want your agent to move to the destination position.
currentX += hX * SPEED
currentY += hY * SPEED
That should be everything really. To make this a LOT easier, it might be worth looking into incorporating a maths library with SDL so that you can use vectors and vector operations.
EDIT FOR UPDATED QUESTION:
The way you have your while loop at the moment will lock up your entire game until the player has arrived at the position.
A better way is to have a standard game loop with an Update() function like so:
public class Game
{
    // Other implementations left out
    public void Update()
    {
        UpdatePlayer()
    }
};

In your UpdatePlayer() function you can call MovePlayer() and within MovePlayer() since the Length variable is always updated every time you call the function, all you have to do is update MovePlayer() to do something like this:
private static void MovePlayer(double x2, double y2, int duration)
{
    double hX = x2 - m_PlayerPosition.X;
    double hY = y2 - m_PlayerPosition.Y;

    double Length = Math.Sqrt(Math.Pow(hX, 2) + Math.Pow(hY, 2));

    if( Length < 0.1f )    // Less-than rather than Length == 0.0 to handle floating point errors
        return;

    hX = hX / Length;
    hY = hY / Length;

    m_PlayerPosition.X += Convert.ToInt32(hX * 1);
    m_PlayerPosition.Y += Convert.ToInt32(hY * 1);

    UpdatePlayerLocation();
}

Thank you Ray for your explanation, i've tried to make a method with your input and it works but I'm not sure on how to do the loop. Please see my edited function in my question. Thanks!!

@Mark edited for your updated question :)

Thank you so much Ray this is what I was looking for! I will probably have to buy a gamedesign math book to fully understand everything and come up with own implementations. The player moves to the excact location now but it still doesn't travel in a straight line to the target. Let's say the player is in bottom-left corner and target is top right, then it will travel from left to right first and just before the target x it will travel a diagonal line to the top screen. But maybe its good for me to figure something out myself too instead of spoonfeeding me haha, sometimes it DOES travel straig

Good idea of the game update method method cause I saw my FPS dropped to 20 with the way I did it before. So much to learn for me but I really like it!!

No problem :) it might be because you have a grid based world, but I'll leave that to you. I would recommend getting Game Coding Complete by Mike McShaffry, it contains a lot of help regarding the game loop and even basic vector maths operations :)

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/2.5/


text:
Tips for building an AI for a 2D racing game
I have a school project to build an AI for a 2D racing game in which it will compete with several other AIs (no collision).
We are given a black and white bitmap image of the racing track, we are allowed to choose basic stats for our car (handling, acceleration, max speed and brakes) after we receive the map. The AI connects to the game's server and gives to it several times a second numbers for the current acceleration and steering. The language I chose is C++, by the way. The questions are:
What is the best strategy or algorithm (since I want to try and
win)? I currently have in mind some ideas found on the net and one or
two of my own, but I would like before I start to code that my
perspective is one of the best.
What good books are there on that matter?
What sites should I refer to?

It would depend on the accuracy of the physics simulation. If there is no physics, I'd go full speed all the time... otherwise, I'd start slowing down before each turn and speed up 2/3rd through the turn.

Set up a basic AI, then set up an API to handle your own car.
If you can beat it, you should set up a recording algorithm that can then positively reinforce your AI. This could be a neural network to tweak your AI's actions. Such as gradual braking into a corner etc.
Are you allowed to use external libraries in your project? If so, I suggest you look at FANN. It is a fast neural network library; to save you writing your own. If you need the source code, you could always write it yourself, it can take some time however.

Seems overkill to me.

@Lo'oris Definitely, especially since this is probably a fairly simple school project with a limited amount of time to create a solution for, I don't think supervised learning is the way to go with this, just for practicality's sake.

Its not that hard to set up, and depending on the level of the subject the OP is doing, this approach may not necessarily be overkill. It is what I would (and have done), its fun, and can be quite simple to achieve effective results. The hardest part is determining what should be done in the pre-processing...

If you can preprocess the map before running the AI, then just calculate the best racing lines through segments of the map.
This post on GameDev.net has a number of suggestions.
The AI Wisdom books have A LOT of articles about racing AI. I'd definitely recommend them, especially the first one which has articles describing how you can represent the map as a data structure within your AI.
Another method I've seen is simple reinforcement learning (Q-learning), which will probably take a good few thousand iterations to get the optimal path. It's described in this paper: http://www.cs.ubc.ca/~zhijin/540report.pdf

Here is an excellent reference for driving AI: Steering Behaviours for Autonomous Characters. Posted here for everyone's reference. There is plenty of information to get you started, but also a lot of information, so don't get too bogged down in the details.


text:
What is an active Indie iOS development community?
I've just gotten into iOS development, and would love to develop some games, but need inspiration/support, all that stuff a great community gives you.
Does anyone know of a community to get involved with?

I'd say check out the cocos2d forums. They are really active and supportive. There is also iDevGames.

If you ask the right questions, this place and StackOverflow can be pretty useful. I find most of my coding questions aren't iOS specific.

It is not a specifically iOS forum, but try Gamedev.net. They are friendly and [very] active. (Unless you act like a moron)


text:
Marketing games for the android - what are the best sites to contact for reviews/advertising?
WE are in final dev stages of our latest game and want to release it for the android market.
What are the best sites to contact for reviews/advertising that specifically target the android users???

Triplepoint PR helped Dave Whatley sell a few hundred thousand iOS copies of geoDefense. Chris Pruett, creator of Replica Island and Google employee talked about the importance of PR somewhere on his blog and also in this video. He has all kinds of great graphs and stuff too.
Also, TalkAndroid and AndroidCentral seem to always be happy to do reviews of apps. I personally follow them both on Twitter.

Thanks very much for this info! I"m a Producer at Blowfish Studios in Sydney Australia. "Qbism HD" was our first game release and we are now working on our next title which will be released for Android and iOs! Thanks again for your help!


text:
Is it possible to have vehicles with physics like GTA in an MMO game?
I haven't seen any MMO games with vehicles with realistic physics and that could achieve high speed, why? Is it because of network bandwidth limitations?
Second Life has vehicles, but physics are poor and max speed is pathetic.

Didn't APB do all that kind of stuff?

I covered some details on this kind of thing at http://gamedev.stackexchange.com/questions/6645/lag-compensation-with-networked-2d-games/6653#6653 that should explain a lot of why it can or can't work.

I know this is an old question, but I would like to mention Auto Assault. It was an MMO with vehicle physics.

Yes and no (but mostly, no).
Any MMO game has several limitations that affect its physics. The most important of these is latency. Latency is time it takes a client to send a request to server and receive an answer back. Even in very best circumstances, this time is around 50-100 milliseconds. In real world, it can be as high as 500 ms. This means, that whenever a players does something - like, say, turns his car's wheel - he can see the game react to it only 100-500 ms later.
100 ms is actually quite a lot. Any game that has as much latency will feel unresponsive, and 500 ms feels downright unplayable. That's why game clients employ a lot of tricks to mask this latency. For example, the player's car can begin turning the moment he turns the wheel, without waiting for the server. However, these tricks only mask latency, and can never actually reduce it.
Suppose, for example, that we have two players in cars steering simultaneously towards one another. Each client will start turning its own car immediately; but the other player's car will not turn - because the information of it changing course has not yet reached the client, because of latency. Both players happily steer theirs cars, and then bam! - the server notices that they actually crashed into each other.
Situations like this cannot be prevented. No matter what clever prediction schemes we use, where there are other players, there's always a chance for things to go wrong. In any MMO game, about half a second that you just saw hasn't really happened yet, and can change in any moment. Now, in slower-paced games like traditional MMORPG's, half a second is not really that long. Characters only move maybe a meter or two during this time. However, if we're talking about fast-paced car race, half a second is a really long time! You could crash, like, three times in half a second (-8
Actually, a fast-paced game can work even with these limitations. It would have some unpleasant moments, but as long as all players have good connections, it would be playable. That's how multiplayer racing games work. However, there's another MMO limitation: the N-squared update count.
Imagine 10 players playing simultaneously. For them to see each other, the server has to send every player information about every other player. This means, in our example, 10x10 = 100 pieces of information to prepare and send. That's the number of players squared, hence "N-squared". This number grows quite fast, and even traditional MMORPG's begin to struggle when there are lots of players in the same area. For our imaginary fast-paced game with cars, these pieces of information have to be sent much faster than in a slower game. AND they probably are bigger themselves - you have se send not only positions, but velocities, acceleration, angular velocities etc. This means that any fast multi-player game can only have a limited number of players.
Both above problems cannot in principle be solved by software, only masked to some extent. They can be reduced a bit by limiting number of players - so, for example, a game where fast cars are only used in instances with limited number of players is probably doable. I believe that's what APB did. But a full open-world MMO game with fast cars is just not gonna happen. Not until we have quantum-entaglement network interfaces or something.

Have you seen DCUO, full physics world, high speed travel, throwing buses and cars around, all that good stuff.  The masking is quite effective.  Considering that all physics simulations are, in fact, just simulations what players need is not reality but a simulation that feels fair and unbiased.  And you definitely don't need star trek plot physics like entanglement to get that =)

@Patrick Hughes I haven't played DCUO, but judging by the videos it's nowhere near "GTA-like" physics. It does not seem to have vehicles - and this is an important part, because you can get away with "fake" physics for superheroes much easier that for real-world cars. A lot of people have pretty high expectations about "realistic" car physics.

While this is true it is also not entirely correct. It is possible to play large scale vehicular combat games with cars, tanks and planes, battlefield 3 is quite a big game, even without being an MMO the makers were able ton run with over 100 players simultaneously. Check http://www.battlegroundeurope.com for an MMOFPS where physics plays a major role.

If you have deterministic physics engine, latency is not a problem, as you may simulate physics on both server and client. The problem is mostly processing power needed, or it's profitability.

@Markus von Broady Yeah, as long as your players' input doesn't affect physics in any way - you're golden.

@Nevermind player's input doesn't affect physics - well, it could change gravity for some reason, but that's not the point. Player's input is as much problematic in real-time game with physics as without physics - same synchronization rules apply.

Yes.
You have to deal with network latency and syncing the game state across the network. The faster the cars move the more notable the network latency becomes. Players might crash into a wall, because their game client fails to update the game state on the server due to network issues. Which isn't an issue when players move at walk speed ;-)
An MMO server has more load. A multiplayer racing game might run fine with 10 people connected, but will crash and burn if the server gets unresponsive under heavy load from hundreds of users.
Second Life's vehicle physics are just badly implemented. (Is this still alive?)

Garry's Mod is pretty much all physics. I don't think it counts as an MMO as such - though it will support 32 players per server - and that has the most realistic physics I've seen (not just vehicles).
I guess that there hasn't been an MMO designed with physics in mind.

They tried to accomplish this in a major fail of a game called all points bulletin. Well the concept was great the execution not so much.  Random cars would appear out of nowhere.  You would be driving and just hit a wall which would then turn into a car.  I can see it being done somehow in the next five years though more cpu less gpu.

Let's look at your reference first.
GTA itself has a few problems with multiplayer, but this is to be expected. An example is when latency turns your car chase into a nightmare. Sometimes players kill each other because of the latency.
But latency is not the only problem, you can not run an MMO only with clients, you need servers and these servers have to manage most if not all of the physics to avoid cheaters.
So imagine having to run with thousands of players. Imagine also the stress on the CPUs during physics intensive activities. You can offset a chunk of the stress to dedicated GPUs. Bullet Physics has an implementation that runs on CPU.
But to avoid overload in a server you will need to implement a mechanism to handle dynamic zones redefinitions depending on players density. It is much more important in that case than in other MMOs.
It is doable. The issue here is the need to scale the game to handle more players and to run the main instance of the game distributed across servers.
If you manage to optimize your physics, transfer objects quickly and efficiently across servers and find a way to avoid mega crowds (instances for example), then you can do it with similar limitations as your reference and a few other ones due to the MMO nature of the game.
Remember that you don't have to send all game state updates to all players all the time, just the changes that are immediately relevant to the player should be sent constantly, the rest can be sent at a lower rate.

check gta 5 rage mp mode, russian red age or FiveStar roleplay have about at maximum 1200 up to 1600 players at single server, pretty impressive, yet they are trying ot add back AI traffic with version 0.4

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
Game engine design: Multiplayer and listen servers
My game engine right now consists of a working singleplayer part. I'm now starting to think about how to do the multiplayer part.
I have found out that many games actually don't have a real singleplayer mode, but when playing alone you are actually hosting a local server as well, and almost everything runs as if you were in multiplayer (except that the data packets can be passed over an alternate route for better performance)
My engine would need major refactoring to adapt to this model. There would be three possible modes: Dedicated client, Dedicated server and Client-Server (listen mode)

How often is the listen-server model used in the gaming industry?
What are the (dis)advantages of it?
What other options do I have?

The first question is pretty irrelevant. Why should it matter how the industry does it? They don't do everything the best way.

I'll see if I can answer this the best I can:

How often is the listen-server model used in the gaming industry?

When it comes to most online games, you'll find that a large majority of games use a client-server architecture, though not always in the way you think. Take any Source game, for instance. Most will use a standard client-server with a master server architecture (to list games available), in that one person will host a dedicated server and anyone with a client can join it.
However, you have some games and services, take for instance Left 4 Dead, League of Legends, and some XBox Live games, that take a slightly different approach. These all use a client-server architecture with a controlling server. The main idea here is that someone creates a dedicated server that isn't "running" any game. The controlling server will create a "lobby" of sorts, and when the game is started, the controlling server will add them to a queue, and when it is that lobby's turn, it will select a matching dedicated server (in terms of location/speed, availability, numerous factors), and assign the players to that server. Only then will the server actually "run" the game. It's the same idea, but a little simplified, as the client doesn't need to "pick" a server, only join a game and let the controlling server do the work.
Of course, the biggest client-server model is the MMO model, where one or many servers runs a persistent world that handles almost all data and logic. Some of the more famous games using this model are World of Warcraft, Everquest, anything like that.
So where does a listen server fit in here? To be honest, not really that well, however, you will still find many games using it. For instance, most Source games allow listen servers to be created, and many XBox Live games do (it's been a while, but I believe Counter Strike did, as well as Quake 4, and many others). In general though, they seem to be frowned upon due to the advantages of the client-server model, which brings us to our next point.

What are the (dis)advantages of it?

First and foremost: performance. In a client-server model, the client will handle local changes (such as input, graphics, sounds, etc) on each cycle of the game. At the end of the cycle, it will package up relevant data (such as, did the player move? If so, where to? Where is s/he looking now? Velocity? Did they shoot? If so, information on the bullet. Etc) and send that to the server for processing. The server will take this data and determine if every thing is valid such as, is the user moving in a way that indicates hacking (more on that later), is the move valid (anything in the way?), did the bullet from player 1 hit player 2?, and more. Then the server packages this up, and sends it to the clients, which then update whatever necessary, such as adjusting health if the player was shot, kicking the player if it is determined that they are hacking, etc.
A listen server, however, must deal with all of this at the same time. Since I assume you are familiar with programming, you probably realize how much power a game can rob from a computer, especially a poorly designed one. Adding on network processing, security processing, and more as well as the client's game, you can see where performance would take a serious hit, at least as far as just standard processing goes. Furthermore, most servers run on fast networks, and are servers designed to withstand network traffic. If a listen server's network is slow, the entire game will suffer.
Second security, as stated earlier, one of the main things a server will do is determine if a player is exploiting the game. You may have seen these as Punkbuster, VAC, etc. There are a very complicated set of rules that run these programs, for instance, determining the difference between a hacker, and just a very good player. It would be very bad for your game if you weren't able to catch hackers, but even worse if you executed action against a falsely accused one.
A listen server will generally not be able to handle the client's game, the server processing, and the hack detection, and in most cases, detectors like Punkbuster are very hard to, if not impossible to get to run on a listen server, because it's hard for it to function correctly without the necessary processing power, as generally the game logic is prioritized over security, and if the detector is not allowed to process for one frame it may lose the data it needed to convict someone.
Lastly, gameplay. The biggest thing about servers is that they are persistent, meaning that even if everyone leaves, the server will continue to run. This is useful if you have a popular server that doesn't have much activity in the night time, people can still join when they are ready to play and not have to wait for it to be brought back online.
In a listen server, the main disadvantage is that as soon as the client hosting the listen server leaves, the game must either be transferred to another player (creating a lul in the game that can last minutes in some cases), or must end completely. This is not preferable on a big server, as the host must either stay online (wasting a slot in the server, and his/her computer power, which could also slow the game), or end the game for everyone.
However, despite these problems, listen servers do have a few advantages.
Easy to set up: Most listen servers are nothing more than hitting "New game" and letting people join. This is easy for people who just want to play with their friends, and don't wish to have to try to find an empty dedicated server, or play with other people.
Good for testing: If one owns a dedicated server and wishes to change it's configuration, it is generally a better idea to test the configuration first. The user would either have to create a backup of the dedicated server and go blindly into the changes, with the only option being to roll back if something goes wrong, create a new dedicated server to test them, of just create a simple listen server to test them. And in with point 1, these are generally easier to start up and configure. This is especially true, as most dedicated servers are not within the administrators immediate access (most dedicated servers are rented from a remote location). It takes much longer to push configuration changes, as well as commands for restarting, etc, to a remote location than a machine that the administrator is currently on.
Less resources: In most dedicated servers, a user with the same IP cannot connect to the dedicated server (meaning, the client must either host the server, or play, they cannot do both). If the client wishes to play on his/her own server, they will usually need a second machine to host the server, or buy or rent a dedicated server so that they can actually play on it. A listen server requires only one machine, which may be the only thing the client can use.
In either case, both have advantages and disadvantages, and you need to weigh them with what you're willing to design and implement. From my experience, I believe that if you were to implement a listen server it would get used, if for nothing else than for a few users wishing to play around with friends, or test settings.
Lastly:

What other options do I have?

This is an industrial can of worms. In reality, any type of network architecture can be applied to video games. However, from what I've seen, like most internet communication, most boil down to some form of client-server model.
Please let me know if I didn't answer your question, or if you need something expanded, and I'll see what I can do.

"In most dedicated servers, a user with the same IP cannot connect to the dedicated server (meaning, the client must either host the server, or play, they cannot do both)." WAT? Where? Why? If some servers have this apparently senseless arbitrary limitation, it doesn't mean he would be forced to do the same when he writes one...

It's an artifact from older games, from when computers couldn't handle server algorithms, graphics calculations and game logic all at once. Many dedicated server models would prevent a client that attempted to connect from the same machine from successfully connecting, and this practice is still enforced in some games today. I never said this applies to all models, nor did I say he had to model his to this particular paradigm. However, technically, allowing same-host connections defeats the purpose of the dedicated server, and the only benefit is leaving the server active upon disconnect.


text:
Multiplayer / Networking options for a 2D game with physics
Summary:
My 50% finished 2D sidescroller with Box2D as physics engine should have multiplayer support in the final version. However, the current code is just a singleplayer game.

What should I do now?
And more important, how should I implement multiplayer and combine it with singleplayer?
Is it a bad idea to code the singleplayer mode separated from multiplayer mode (like Notch did it with Minecraft)?

The performance in singleplayer should be as good as possible (Simulating physics with using a loopback server to implement singleplayer mode would be a problem there)
Full background / questions:
I'm working on a relatively large 2D game project in C++, with physics as a core element of it. (I use Box2D for that)
The finished game should have full multiplayer support, however I made the mistake that I didn't plan the networking part properly and basically worked on a singleplayer game until now.
I thought that multiplayer support could be added to the almost finished singleplayer game in a relatively easy and clear way, but apparently, from what I have read this is wrong.
I even read that a multiplayer game should be programmed as one from the beginning, with the singleplayer mode actually just consisting of hosting an invisible local server and connecting to it via loopback. (I found out that most FPS game engines do it that way, an example would be Source)
So here I am, with my half finished 2D sidescroller game, and I don't really know how to go on.
Simply continueing to work on the singleplayer / client seems useless to me now, as I'd have to recode and refactor even more later.
First, a general question to anybody who possibly found himself in a situation like this:

How should I proceed?

Then, the more specific one - I have been trying to find out how I can approach the networking part for my game:
(Possible solutions:)

Invisible / loopback server for singleplayer

This would have the advantage that there basically is no difference between singleplayer and multiplayer mode. Not much additional code would be needed.
A big disadvantage: Performance and other limitations in singleplayer. There would be two physics simulations running. One for the client and one for the loopback server.
Even if you work around by providing a direct path for the data from the loopback server, through direct communcation by the threads for example, the singleplayer would be limited.
This is a problem because people should be allowed to play around with masses of objects at once.

Separated singleplayer / Multiplayer mode

There would be no server involved in singleplayer mode.
I'm not really sure how this would work. But at least I think that there would be a lot of additional work, because all of the singleplayer features would have to be re-implemented or glued to multiplayer mode.

Multiplayer mode as a module for singleplayer

This is merely a quick thought I had. Multiplayer could consist of a singleplayer game, with an additional networking module loaded and connected to a server, which sends and receives data and updates the singleplayer world.
In the retrospective, I regret not having planned the multiplayer mode earlier. I'm really stuck at this point and I hope that somebody here is able to help me!

Maybe slightly off topic, an I guess you already know it by now, but there is a chance that your game wasn't 50% finished.

You will find an example (with source) of latency-proof networked physics here: http://gafferongames.com/2010/03/11/gdc-2010-networked-physics-slides-demo/
But first, focus on the gameplay of your multiplayer mode.
If it is competitive and cheating (through reverse-engineering or packet tampering) is an issue, the proposed solution might not fit your needs.
Let's say your multiplayer mode is cooperative. For your singleplayer mode. I would just run the same game engine, but with the network features disabled, so that the world would not be populated with any other player characters. You would also probably want to load specific data for the multiplayer mode, to adjust the content to the number of players.

This book might be of some help to you. I believe that the company that I work for used the examples in this book even though we're not a game shop.
http://www.amazon.com/Multiplayer-Programming-Prima-Techs-Development/dp/0761532986/ref=pd_sim_b_7

I think that the positives of a local loop back server, far out weigh the negatives. The amount of code reduction is extremely valuable, in my opinion.
With regard to running redundant physics simulations, you should look into server ticks, Valve has a great writeup on it here. In a local server environment, you maybe able to remove the "client simulation" and simply send full-world updates, in a local-only situation to avoid the redundant physics simulations since you'll have plenty of bandwidth.


text:
Converting 2D coordinates from multiple viewpoints into 3D coordinates
Here's the situation.  I've got a set of 2D coordinates that specify a point on an image.  These 2D coordinates relate to an event that happened in a 3D space (video game).
I have 5 images with the same event point on it, so I have 5 sets of 2D coordinates for a single 3D coordinate.  I've tried everything I can think to translate these 2D coordinates into 3D coordinates, but the math just escapes me.  I have a good estimate of the coordinates from which each image was taken, they're not perfect but they're close.
I tried simplifying this and opening up Cinema 4D, a 3D modeling application.  I placed 5 cameras at the coordinates where the pictures were taken and lined up the pictures with the event points for each one and tried to find a link, but nothing was forthcoming.  I know it's a math question, but like I said, I just can't get it.  I took physics in high school 6 years ago, but we didn't deal with a whole lot of this sort of thing.
Any help will be very much appreciated, I've been thinking on it for quite a while and I just can't come up with anything.

It's just a set of equations for several unknowns, isn't it? Why don't you write them down and solve them? The solution is not trivial at the verbal level so that it would require no maths. Obviously, your information is overdetermined, so you will have to choose the optimum way to find the 3D coordinates.

There is no physics in this, it's just geometry. Try math.SE or SO (things like these are often done in computer graphics) instead.

You really only need two viewpoints to locate the point.  From each viewpoint, you have a camera location and a direction; that is, you have everything you need to uniquely define a line in 3d Cartesian space.  All this amounts to is finding the intersection of two lines.

You only need two viewpoints under certain constraints.

The only constraint is that the two viewpoints are not collinear with the object.

It depends just how much freedom you have with this scenario. In the worst case you will need to set up some 3x3 matrices and do some coordinate transformations between different coordinate systems.
However if you have control over the layout, then the simplest situation would arise if three of those five projection angles happen to be mutually perpendicular. Then each just corresponds to different planes: x-y, y-z, x-z. So if the coordinates in the x-y plane are (a,b) and in the y-z plane are (b,c) then the coordinates should be (a,b,c). Of course this means that the coordinates in the x-z plane are (a,c), as we are assuming that they are perpendicular and there is no scale change between planes. You will also be choosing origins appropriately etc.
However if you have an independent coordinate system for the 3D space (X,Y,Z) then you will need to find the transformation matrix between the various coordinate systems: M(a,b,c) = (X,Y,Z).
In the general case you are looking for 3 (or 5) projection 3x3 matrices $P_1$, $P_2$, $P_3$ which will have the property that $P_{i}^2 = P_i$ and they are of rank two. The 2 eigenvectors of P will correspond to the two axes of the projection plane. If you need to know more about this then a book on 3D geometry for computer modelling will be required. Some of the maths can be quite sophisticated - a subject called "Geometric Algebra" has recently become quite popular in this area, to assist with visualising and efficiently calculating the various formulae involved.

just looking at   vision.middlebury.edu    has a bunch of stuff.
I used to have an old text with the stereo to 3d algorithm in BASIC !
long gone.  There is quite a bit on the web.

If you have projection matrices of each image, you can use triangulation (for example here). It works for two cameras and generates one 3D point.

Hey thanks for all the answers.  Unfortunately, I have no control over the scene.  The images have been taken from fixed points and I had to do a lot of visual comparisons to get a decent approximation of where they were taken from.
Basically what happens is an event happens within the game (a kill or a death) and the event is sent to the server when the game ends.  The software behind the server takes the 3D coordinates from that event and maps it to a 2D image that you can look at and see where that kill or death happened.  Those coordinates are relative to the image, though, not the actual game space.  All I know about the images is an estimate of the coordinates where it was taken at (in game space) and the field of view (78°).  Here are the position and rotation coordinates for 3 of the images in (X, Z, Y) / (yaw, pitch):
1: (15.894, 152.263, 43.839) / (53.34, -14.61)
2: (27.205, 170.375, 72.500) / (0.00, -85.50)
3: (51.987, 184.236, 41.290) / (206.38, -14.07)

And here are the coordinates that the server is calculating for those 3 points of view, remember they're relative to the image, (X, Y):
1: (322, 205)
2: (389, 232)
3: (240, 109)

And finally, the actual in-game cordinates where this event happened, (X, Z, Y):
(25, 164, 039)

Hopefully someone here can lend me their brain for a bit, I'm completely at a loss.
Edit: Perhaps I should have used the same name I posted the original question with.  My mistake, I am the original poster.

I'm assuming the second set of coordinates is a set of screen coordinates.  It would be helpful to know the resolution of the images.  But here's what you do: calculate the direction of the vector between each viewpoint and the event point.  You can get cartesian coordinates by just subtracting, and you can compare these direction vectors to the rotation vectors of your viewpoints.  That should give you a start at the very least.

As long as you have used the same OpenID to sign up for both Physics and Game Dev and you associate your accounts you will regain ownership of the question. You can still associate accounts even if you have used different OpenID's - I'm just not sure of the exact process.

@Tristan: Sorry about that, the images are 640x360.  And I'll look into that Chris, thanks.

Sorry for the double comment, it won't let me edit.  I didn't sign up at Physics, I posted as an unregistered user with my real name.  I just used my OpenID to sign up there but it didn't associate the accounts, the question stil shows as being asked by the unregistered account (my real name).  Oh well, not a big deal.


text:
Blending animations for more character movements
I am making a hack n slash 3rd person game, and I want the character movements to be more dynamic not like fighting games where you have a moves list.
I want to animate tons of different animations and have them "Tween" between each other.
I do not want the to use the mouse for controls, I want it to be all keyboard, that way you have up to 10 inputs (All your fingers) to blend and morph animations to create more fluid movements. In the end this will almost be similar to characters typing a phrase or string of keys rather than move forward mouse look click to melee.
My questions are:

Has anyone done this before?
How would someone go about trying to tween?

lets say one for key on the keyboard excluding Tab, Caps, R+Shift, L+Shift, Enter, R+Ctrl, L+Ctrl, L+Alt, R+Alt, Windows Key, and Menu.
So thats all the numbers, letters and punctuation keys. Thats 46 keys gives me a combination of 46P1 = 5502622159812088949850305428800254892961651752960000000000L (used Python), and with a minimum entry value of 2 keypresses shortening to half. This is not humanly possible to create so many inique animations in one lifetime. But I'm guessing there is a reason this hasn't been done already.
Or if I just used 10 basic keys. Maybe ASDF SPACE (RIGHT HAND) 456+0 (LEFT HAND KEYPAD)
it would give me 3,628,800 posible unique animations.

Something you'd need to worry about is keyboard ghosting. The vast majority of keyboards have a limit on the number of simultaneous keypresses they support, and have problems with multiple nearby keys being pressed at once.

I have no idea what are you expecting to achive by this blending. Could you show an example, of how the effect would look like, on a manualy 'blended' animation? It could be just stick figures or something, just to show your idea.

I will as soon as I get some. I'm still painting and texturing. I'm not a great artist but can manage I'm a lot better at programming.

That type of control scheme is totally useless as you will overload the players with information and at least the reaction time will suffer considerably,that is why mouse is preferable since a lot of variation can be made
If you want variety in animation you don't need convoluted controls schemes, you can use either procedural animations and/or blend multiple animations togheter

Well... the reason there's a moves list is because each "attack" has to do SOMETHING. Limiting the options does limit the gameplay but it also limits players from being overwhelmed and it limits the chances of something obscenely overpowered sneaking in.
If the "something" for the attack is, for example, a slash attack but one varies one degree from another then you're likely better off with a different interface, maybe like an aiming icon that's mouse based but changes the angle of attack and one or two buttons for the slash. That gives you simplicity but also variety.
Anywho, as far as the animations go then I would suggest having a discreet set of starting points or stances for the animations. Each animation that you want to form for the attack would then only have to start from those discreet start points, and to tween between animations then you would just, at worst, have to tween between the start points. It's not quite the same pie-in-the-sky type of animation that you sound like you're describing, but it's vastly more feasible to do.

The closest thing I can think of to what you are talking about is Die by the Sword. It was a hack'n'slash that didn't have any fixed moves. Instead you used either the numberpad or the mouse to directly control the weapon arm. The end result was frankly a bit difficult to control, but did have the occasional moments of brilliance particularly in multiplayer.
The biggest problem here is in getting players to make the mental translation between input and what's occurring on screen. Things like the WiiMote, Move, and Kinect can shorten that mental gap between what the player and avatar are doing. Although any block attacks will continue to create a disconnect.
In the more experimental spaces, other games that play with direct control of limbs as opposed to pre-recorded movements include QWOP and Toribash


text:
What would be the level of effort required to implement a screencapture command on a PS3 game?
Looking to see what the level of effort is for implementing a screen capture command into PS3 game by a mid-level PS3 game developer.
Bonus for a description of what is involved in the process...
EDIT
Not sure how to get back my question since it was the first but let me clarify some things. @Nate Bross, nope I am not the actor although i've fielded calls for him on occasion
@coderanger my intent was to try and speak to other PS3 developers, however coming from a web development no one in my social circle close or extended develops on the PS3. Additionally i'm interested in hearing the effort required in terms of hours so that this information can be passed on to a client. A client who has a game on the PS3 using the unreal engine. Convo with devs sometimes go something like "can you implement feature a" which gets a response "this will take us 8 weeks and an army". Trying to be educated before the ask. I hope that helps
If anyone here is a PS3 game dev and would like to respond off site so as not to break NDA that would be awesome.
@Roger it would be from within the game, something that users can use. Something akin to the iphone screencap utility. No need to get fancier than that.

Your middle name isn't William is it?

If you're a licensed developer, the tools allow you to take a screen capture. If you want a command line alternative, raise a support issue and someone from SN will be glad to help.

Sean, please clarify exactly what you are looking for here. I believe any discussion of Sony Playstation 3 development would be under NDA, so we don't want to encourage anyone to break any such NDAs. If you are asking about homebrew development please be explicit about that and I suppose it would be okay here (I'm not familiar with the PS3 platform). But if you are indeed asking about NDA-covered development, I don't think you will get any answers and I would encourage you to close your question and speak with Sony or other fellow PS3 developers.

@Ricket: If the information is obtained through reverse engineering, it can be published, and then it can be used by non-homebrew developers unless Sony somehow managed to forbid it in their developer contract. Reverse engineering for interoperability is usually legal (for example, it has been recognized as legal in the US for the iPhone).

@Giles I don't think that is a legal battle this site wants to become involved in. The SDK is the legal property of Sony and anything inside it is covered by an NDA, making an argument that this would be covered under fair use I leave to people with lawyers and money.

If you are using the Unreal engine there is a way to answer this without breaking the Sony NDA. Although, now we are talking about potentially breaking the Unreal NDA....

Do you want to capture the screenshot from within the game for some purpose, or from a development PC?
From the development PC there are simple facilities provided, you easily use the Target Manager SDK to achieve this (you'll need to read the full description to see what else you need to set up as specifics are NDA'd).
From within the game, the simplest way is to insert something after the frame has been rendered to first flush the GPU (to ensure that everything has finished being rendered before you continue). The game should have a pointer to the current frame buffer somewhere, you'll know the format of that buffer (the stride, etc), you can then do what you want, including writing it out in a format of your own choice with a little work.

As your client is using the Unreal Engine, I recommend looking at the UDN. Here you will find all the information you need relating to implementing features within the Unreal Engine itself. I couldn't tell you exactly what you would need to call though as a good portion of it (any link that is red) is blocked off only to licensed developers.
You will need to make some sort of arrangement with your client for them to let you access their development materials.

The PS3 runs a variant of OpenGL ES (which is the same thing most mobile devices are using), though I don't know of anyone that actually uses OpenGL directly. http://www.bit-101.com/blog/?p=1861 shows how to create a screenshot an an iPhone, I wouldn't expect it to be very different.


text:
Java graphic objects as in flashgames
How is it possible (with the standard Java2D engine) to use small sprites like graphic objects?
For those who don't know what I mean, in all those Flash-games like on Facebook they put small sprites on the screen which react to mouse-over and clicks. I tried to do the same in Java but can't find a good method. Swing components always spread over the whole bitmap, but I only want to get a reaction from the object when the mouse is over a pixel that's not transparent.
So basically checking every time if the object below the mouse contains a non-transparent pixel (which i believe could be pretty intense in a gameloop or repaint loop). I have no idea how to implement such a thing efficiently.

Is it really that expensive to check one pixel for transparency every frame?
Of course, you only check if the cursor is within the sprites bounding box.
Assuming you use BufferedImage to hold your image data, you can dom something along this (sorry, code is really not exact, look up how BufferedImage work):
image.getRaster().getPixel(x, y, array);
alpha = array[4]
if (alpha > 0.5f) { ...

Area can be used for operations between shapes (such as add and subtract). It's fairly easy to make a algorithm that cover an area with as few rectangles as possible (if you don't want it to have the guaranteed best solution). Cover all opaque pixels with rects and leave out the transparent ones. Use the Area class for unifying them into a single path. BUT, I think that checking the sprite for transparency is more efficient.

+1, though you might find "if ((image.getRGB()>>>24)>128) ..." works a bit faster

You could try a reduced bounding box.
Let's say you have a 20x20 px sprite, with 2 px of transparency around the borders.
Set up a 18x18 px bounding box, and check at the end of every buffer update if the mouse pointer coordinates are included in the bounding box coordinates.

I thought about generating a shape, maybe with some bezier cuves or something like that, but failed to find a proper way to implement such a shape. Shape would give the neccesary methods tho.

You could use PulpCore, a lightwight 2D framework, which will let you use sprites really easily:
http://www.interactivepulp.com/pulpcore/


text:
Sprites are sometimes blurry in Flash
I am playing around with drawing an SVG sprite (imported in through [Embed]). Depending on the coordinates of the image, sometimes it appears more crisp than others.
The following image shows how at different locations is it rendered differently:

(Image link - You may have to download and zoom in with an image editor to see it)
You'll notice that the middle sprite is more blurry than the ones on the sides. Does anyone know why this is? Any help would be appreciated.

That's your sub pixel accuracy. It's a feature, rather than a bug but it's annoying in the wrong context.  What's happening is that somewhere in the pipeline the x coordinates of your sprite are being rasterized to the screen a little off the pixel boundaries. This causes the flash renderer to interpolate between one pixel and the next, resulting in the blur you see. This actually aids animation as objects can smoothly transition from one pixel to the next but you don't want it here.
You can try two things - either look at the source svg and ensure that every coordinate is integer (i.e. no fractional part) or if that doesn't work, try offsetting everything by half a texel - that'll be 0.5 * the_width_of_your_drawing_surface.

I have already ensured that my SVG is only using whole numbers. I will look into the offsetting right now.

As Luther already wrote, it's how the flash renderer works. One thing that will guarantee pixel-accuracy is to turn your sprites into bitmaps and then set the pixelSnapping property to PixelSnapping.ALWAYS.
Or try cacheAsBitmap = true on your vector sprites (see here).


text:
How do I place a progress bar in AndEngine?
I am developing game using AndEngine. I need to place a progress bar in my game to denote time remaining in the game. Is there a built-in method for doing this in AndEngine? My searches only turned up results for Android, not for AndEngine.

If you simply need to have a progress bar alongside your game you can use the LayoutGameActivity which was added for that purpose. LayoutGameActivity allows you to place the andEngine View into a standard Android layout which is loaded from XML, rather than using its default layout. As mentioned in the article, this is accomplished by overriding getLayoutID() and getRenderSurfaceViewID() in your game LayoutGameActivity class.
For example:
@Override
protected int getLayoutID() {
        return R.layout.xmllayoutexample;
}

@Override
protected int getRenderSurfaceViewID() {
        return R.id.xmllayoutexample_rendersurfaceview;
}

Code fragment from the linked forum post.

You could also just vary the width of a simple rectangle over time, or if you want to have it nicer, stitch together a couple of sprites.


text:
Flash framerate reliability
I am working in Flash and a few things have been brought to my attention. Below is some code I have some questions on:
addEventListener(Event.ENTER_FRAME, function(e:Event):void
{
    if (KEY_RIGHT)
    {
        // Move character right
    }
    // Etc.
});

stage.addEventListener(KeyboardEvent.KEY_DOWN, function(e:KeyboardEvent):void
{
    // Report key which is down
});

stage.addEventListener(KeyboardEvent.KEY_UP, function(e:KeyboardEvent):void
{
    // Report key which is up
});

I have the project configured so that it has a framerate of 60 FPS. The two questions I have on this are:

What happens when it is unable to call that function every 1/60 of a second?
Is this a way of processing events that need to be limited by time (ex: a ball which needs to travel to the right of the screen from the left in X seconds)? Or should it be done a different way?

About your code:
I think it's funny that you use anonymous functions for event listeners, it's something I don't see that often in ActionScript (it is more common with JavaScript).
You should be aware that you can run into some garbage-collection issues if you add event listeners like that (because you're no longer able to remove them later on). As long as your event listeners stay up during the whole execution time of your app, it isn't an issue though.
Regarding your questions:

An update step can take longer to execute than 1/60 of a second, even if you specified the FPS to be 60. It just means it won't go above 60, but can easily drop below 60 FPS. You can test this yourself by adding some dummy loop in your event listener, something like: for(var i:int = 0; i < 1000000; i++){ var tmp:Number = 1000.0/20.0; }. The Flash runtime will use as much time as required for a frame. That means it will try to run at the specified framerate, but it won't enforce it in any way (eg. stopping execution of code). An endless loop (while(true){}) will freeze your game on the first frame...
I don't understand what you mean by "limited by time"? Are you asking whether or not to use/assume a fixed or variable timestep?

Update (regarding 2.): To make an object travel some distance in a given time, you could either use a tweening-library like tweenlite or implement it yourself like this:
// initalize this with getTimer() in your constructor or init method
private var _time:Number;

// how long the sprite should be animated.. here 3.5 seconds
private var _duration:Number = 3.5;

// event listener. needs to be bound to Event.ENTER_FRAME using addEventListener
private function handleEnterFrame(evt:Event):void {
    var t:Number = getTimer();
    var elapsed:Number = (t - _time) * 0.001;
    _time = t;

    _duration -= elapsed;
    if(_duration <= 0){
         // ensure that elapsed doesn't overshoot the duration
         elapsed += _duration;

         // remove the event listener.. this will stop executing further updates
         removeEventListener(evt.type, handleEnterFrame);
    }

    // the sprite will travel 200 pixels per second (in the x-axis)
    // so 700 pixels in total (200 * 3.5)
    _sprite.x += 200 * elapsed;
}

The question you need to ask yourself is: Is the duration of this motion related to the frame rate of the final swf?
In the past the only to create motion was through the timeline or enterFrame making the framerate extremely crucial. Today you can create motion independent of the framerate. You will be surprised that most swfs today are set to a standard rate that works for video or audio imports on the timeline (30 fps).
I would recommend you explore: fl.transitions.Tween.

This is all known as the Elastic Racetrack.

This tutorial at 8bitrocket offers a good method of maintaining smooth movement and a fairly constant framerate, for many applications this is more than necessary, but built into it is a method of changing the framerate on the fly with a great deal of precision.


text:
Help me choose an engine
So far i've been trying to make a RTS in pygame but, i feel like 2d is not enough and pygame has me do a lot of stuff that i would not like doing. What i would like doing is working on the AI gameplay and such and not worying too much about how to display stuff,physics and the like too much.
So far Unity has boo which is supposed to be similar to python i wonder if that could work. How similar is it to python should i use this?
Other options as far as i can see are ogre3d python bindings and UDK.
Which would best suit my needs?

For any information about: Boo (for usage with Unity):
http://boo.codehaus.org/Gotchas+for+Python+Users
Boo != Python, rather Boo > Python.

Boo is a great language, however it is almost undocumented. I tried more than once to use it with Unity3D, but C# always turned out much easier and almost as powerful.

First of all, if you don't want to worry about other aspects EXCEPT graphics (physics, etc), forget about using Ogre. It's a graphics engine, not a game engine.
Unity has all of the aspects that you want already in there and can offer you a quick turnaround time.
The UDK is a good one, but it does involve a bit more work to get up and running before you can focus on the AI and gameplay aspects.
If your aim is to get something up and running in a very short amount of time, go for Unity. If you don't like Boo (which personally I have no experience in whatsoever), you can always use the C# and/or Javascript alternatives.

It sounds like what you want is to just do the actual meat of your game. To use the smallest amount of boilerplate, I would use Unity.
Boo seems a mixture of C# and Python, to me. It shouldn't be difficult to pick up (and there's always Javascript too).
If you don't want to go to Unity or UDK or another editor-type program, there is this question about RTS engines (though this is C++)

see Spring RTS, it is a good engine with a lot of games runing over it (that means a lot of examples), it is open source and written in C/C++ with LUA over it.


text:
What's a good way to check that a player has clicked on an object in a 3D game?
I'm programming a 3D game (using C++ and OpenGL), and I have a few 3D objects in the scene, we can say they are boxes for this example. I want to let the player click on those boxes to select them (ie. they might change color) with the typical restriction like if more than one box is located where the user clicked, only the one closest to the camera would get selected.
What would be the best way to do this? The fact that these objects go through several transforms before getting to window coordinates is what makes this a bit tricky.
One approach I thought about was that if the player clicks on the screen, I could normalize the x,y coordinates of mouse click and then transform the bounding box coordinates of the objects into clip-space so that I could compare then to the normalized mouse coordinates. I guess I could then do some sort of ray-box collision test to see if any objects lie as the path of the mouse click. I'm afraid I might be over complicating it. Any better methods out there?

First off you need to convert your mouse coordinate to a ray (a position and direction vector combo).  This process is called 'un-projection' and the way I do it is to take the mouse x/y coordinate, convert it into screen space (-1 to +1 in both axes) by adding half the dimensions of the screen and then dividing by the screen dimensions and then construct two points (x, y, z, w):
  p(xi, yi, 0, 1)
  p1(xi, yi, 1, 1)
where xi and yi are screen space coordinate points (-1 to +1 rather than 0 to 'pixel_size_of_display')
now multiply these by the inverse of the projection matrix and then divide the x,y,z components by the final 'w' component that you get after the matrix multiplication, i.e:
p.x = p.x / p.w;
p.y = p.y / p.w;
p.z = p.z / p.w;
You should now have two points: p and p1. Your ray will be formed from the point 'p' and the normalized vector between 'p' and 'p1'.
Finally, rotate the whole ray by the inverse of the view matrix and you have a ray that you can use to intersect with any primitive in the scene.
Test that it works by drawing the ray and constructing a new view of the scene from a different angle - this is pretty essential if you're testing visibility or intersection code anyway.
Next, Look up ray/sphere and ray/aabb intersection algorithms. I'd list ray/sphere here but this post is getting a bit long! Ray/Sphere intersections are quicker than ray/box intersections and generally I do a ray/sphere before final checking of a ray/box or ray/polygon mesh.

Usually, the mouse click co-ordinates are unprojected into world space, and then a ray intersection is performed. There are samples in the DirectX SDK but I wouldn't know where to find one for OGL.

Depends if you need this to be 100% accurate or not. If you want perfect accuracy then you have two answers already. However, if you want it fast and simple but less accurate you can project each object's bounding box on the screen and check if the mouse click is within it. Object's distance from the camera will be the third component of a projected vertex. You can perform the usual optimisations and this method is essentially free if you're already drawing some sort of selection box around objects your camera points at.


text:
Does one need normals for a strictly 2d Game?
I'm starting to learn OpenGL by creating a pure 2D game.
I have to decide on the format of the Vertices. Do I need a normal component? Or is this for a 2d component not needed?
My gut feeling says I won't need it since everything is flat. But perhaps I need it for some shader or other thing I don't see yet.

Does one need normals for a 2D game? No. You don't even need normals for a 3D game if you're not going to bother with lighting. However, normals and lighting very much can apply to 2D games. You just go about it in a different way. Rather than explicitly defining a 3D normal vector that aligns with your vertex, you can define a normal map that lines up with your 2D graphics. This lets you have incredibly epic lighting even in a 2D game.

Strictly speaking, the normal component will be ignored if you've turned off lighting. If you're able to write your own shaders in whatever language/toolkit you're using then you can make absolutely sure they're not used.

If I turn off lighting, I still can use colors on my vertices right?

You should be able to do that yes, as long as you've enabled glEnableClientState(GL_COLOR_ARRAY) (remember to disable GL_NORMAL_ARRAY)

You don't need normals unless you're doing lighting simulations. They're fairly trivial to add in once you need them, compared to the actual difficulty of writing lighting shaders.

If you are drawing your triangles in a 3D space, and then viewing everything from the side to make it look 2D (which is what you should be doing), then you'll need normals in order to be able to draw lights over top of your quads.
If you don't light anything, then you won't need normals.
My recommendation since you're asking this question, is to omit normals for now, regardless of what your plans are later. It won't be hard to add them later if you need them.

Only you know whether you'll need normals in a 2d game. They may make sense - DOOM, for instance, had normals even though it was a 2d game (yes yes, it looked pretty 3d, but technically it was still a 2d game).
One good reason for having normals in a 2d game would be to be able to check whether you're inside or outside some shape. It may also accelerate wall collision response (knowing the direction to push objects out of the wall).
There's no reason to give the normals to OpenGL or whatever rendering package you use if it doesn't need it for anything (like the lighting pretty much everyone else has pointed out).

What sort of game is it? If you have a top-down perspective, normals might come in handy for strafing movement of your characters (you know, shifting position along the normal of the direction the character is facing)
Normals are also useful for quite a range of steering behaviours. But a link says more than thousand words: http://www.red3d.com/cwr/steer

Pretty sure the OP is specifically asking about normals for the verts.  Not talking about velocity vectors and that kind of thing.

Pretty sure the OP is specifically asking about normals for the verts or (quote start) other thing I don't see yet (quote end) ...


text:
zoom to cursor calculation
I want to be able to zoom in and out of the map using the scroll wheel. I want to zoom towards the cursor like Google Maps does, but I'm completely lost on how to calculate the movements.
So far, all I have is the resizing, but I now need to change the map position.
What I have: map x and y; map width and height; cursor x and y.
Any help would be most welcome.

Assuming that your map_x and map_y mean the top left corner of the screen area over your map in map coordinates and map width and map height are the dimensions of your map at the actual zoom level again in map coordinates (not screen coordinates), first, calculate your zoom ratio:
zoom_x = screen_width / map_width;

Let's assume the aspect ratio does not change: zoom_x = zoom_y = zoom;
If you want to change the zoom to next_zoom, first find the coords of the new screen over your map:
new_map_width = screen_width / next_zoom

new_map_height = screen_height / next_zoom

We need to find the change in both values and distribute these depending on the mouse position on the screen. If the mouse position would be in the exact center screen position, then this change would be evenly divided between the top-bottom and left-right sides. Since the mouse is at an arbitrary position, we need to find the ratios for the height and width changes for the sides.
Let's assume that the screen dimensions are screen_max_width and screen_max_height;
The new coordinates of your screen (dimensions new_map_width, new_map_height) over your map are:
new_map_x = map_x - (cursor_x / screen_max_width * (new_map_width - map_width))
new_map_y = map_y - (cursor_y / screen_max_height * (new_map_height - map_height))

To convert any map coordinate to a screen coordinate:
screen_x = map_x * zoom

and to convert back:
map_x = screen_x / zoom

I couldn't figure out what Konrad's variables were supposed to mean in my game (map width? My map is infinite, so... that's the same as the screen width then maybe? It didn't work out), so I figured it out from scratch. The way I figured:
(TL;DR: read only the bold parts.)

When zooming, some pixels drop off the screen (zooming in) or newly become visible on the screen (zooming out). This number of pixels determines the maximum amount by which you want to shift your view. For example, if you have a view of 800px wide and you have your cursor at 200px, then you want 25% of the new pixels to appear left of the cursor and 75% to the right.
To calculate the ratio of pixels that should drop off on the left vs. the right, one has to look from the center and see how far off to the side it is. In the example, the middle is at 400px, so the cursor being at 200px means you're at -25% (-0.25). On the far right (cursor at 800px), you would be at +50% (0.5).
view_width / 2 gives us the center and mouse_x - (view_width / 2) gives us the difference, in pixels. To get the (float) ratio, you need to divide that difference by the total again, i.e.
side_ratio = (mouse_x - (view_width / 2)) / view_width
To find the number of pixels that will drop off the side, you want to find the difference between the two zoom levels.
The part of the view visible on the current zoom level is view_width * zoom where zoom is 1.0 for no zoom or 0.5 for having everything at half size (zoomed out).
The number of pixels newly visible is therefore:
pixels_difference = (view_width / old_zoom) - (view_width / new_zoom)
Finally, multiply the two together:
view_x_offset += pixels_difference * side_ratio
Apply the same to your Y axis, using view_height and mouse_y instead.

Full code to scroll upon mouse wheel for Phaser 3:
function create() { // called upon scene creation
    document.addEventListener('wheel', function(scroll_event) {
        handle_scroll(scroll_event);
        scroll_event.preventDefault();
        return false;
    }, false);
}

function handle_scroll(scroll_event) {
    var cam = sceneMain.cameras.cameras[0];

    var oldzoom = cam.zoom;
    var newzoom = oldzoom * (scroll_event.deltaY > 0 ? 1.1 : 0.9); // deltaY>0 means we scrolled down

    var mouse_x = scroll_event.clientX;
    var mouse_y = scroll_event.clientY;

    var pixels_difference_w = (view_width / oldzoom) - (view_width / newzoom);
    var side_ratio_x = (mouse_x - (view_width / 2)) / view_width;
    cam.scrollX += pixels_difference_w * side_ratio_x;

    var pixels_difference_h = (view_height / oldzoom) - (view_height / newzoom);
    var side_ratio_h = (mouse_y - (view_height / 2)) / view_height;
    cam.scrollY += pixels_difference_h * side_ratio_h;

    cam.setZoom(newzoom);
}

(The code is copied from my game, but I changed some of the structure and edited most variable names to match the explanation, so while I tested my code, please let me know if I introduced any mistakes in this example.)

Or for people using XNA when the system is flipped.
First calculate the mouse cursor in the world. Since the mouse position system in XNA is flipped subtract the mouse Y from the height of the screen.
var mouseinWorld = new Vector2(
    (cursor.X * oldZoomLevel) - world.X,
    ((cursor.Y - screen.Height) * oldZoomLevel) + world.Y));

Now change your zoomlevel.
Next is to calculate the new world location.
var newX = (cursor.X * newZoomLevel) - mouseinWorld.X;
var newY = mouseinWorld.Y - ((cursor.Y - screen.Height) * newZoomLevel)

Now update the world location with the newly calculated coordinates.
world = new Vector2(newX, newY)

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
How do I allow a player to manager several games at once with different players using game center?
I wish to do a turn based multiplayer game like Words with friends on the iphone. I would like to know the approach for the implementation to allow the user to continue games that are currently still active even after a couple of days. Is this even possible using Game Center?

All that you need to do is store the game state somewhere persistent where all the players can get at it. For example in a database accessed via a web server. That server could also process each players turns on the game if you want it to (this helps prevent cheating). You can then easily control how long it stores the game state for. For example it would appear words with friends simply allows a maximum of 20 in progress games per player, and the game state is probably no more than a few hundred bytes per game so the storage requirements on the server would be quite small.
I'm not certain about Game Center, but a quick look suggests that as long as your game can get at the User ID of the player that's all you'd need to track the game in your database.

I would implement that functionality on your server, and have your data stored temporarily (the stuff that you know won't change) on the iPhone itself.
(edit) whoah, do you even have a server when you use game center?

the idea of using game center is such that I don't have to build a server because I have no knowledge of building a server.

Ohhhh gotchya =), good to know!


text:
Am I allowed to sell a XNA game by myself?
I've just started the development of an XNA game, and I'm asking myself if it wouldn't be better to use an open-source alternative since I absolutely want to keep the complete control over my game. I need to be able to sell it to whoever I want, using the media I want.
Based on the XNA license and all that sort of legal stuff, am I allowed to sell an XNA game on my own, or am I forced to sell it through the Xbox Live Marketplace?
I'd like to see some reliable reference with your answer.

Which platform(s) are you making the game for?

PC (Windows) only.

Check out this answer here. The simple answer is: Yes.
The networking stuff that uses "Games for Windows Live" does not work on Windows without Microsoft's blessing. But you can always just use the plain ol' networking stuff in the .NET Framework.
You cannot distribute XNA Game Studio (the Visual Studio bit) - this affects the Content Pipeline APIs for building content. This means, if you have a level editor for example, your users will have to manually install XNA GS.
The XNA Framework runtime, on the other hand, is redistributable.

Yes you can sell it by yourself, XNA inhibits no restrictions like that whatsoever. However you can't package the XNA framework installer into your installer, you will have to ask people to download it separately.
Edit: on the PC that is, there is no way to bypass the Xbox and WP7 stores.

I think you mean the XNA Game Studio installer, which is required to use the Content Pipeline APIs. The XNA Framework Redistributable is, in fact, redistributable.

Ah yes, you're right.

I couldn't find easy 'official' reference on the subject, but I can provide indirect evidence.
There are currently several XNA games on sale on Steam, which is not related to Microsoft in any way, see for instance Beat Hazard: on Steam store and on XBox Live Indy Games.
There are parts of XNA that are off-limits though. You can't use most of the online functionality on the PC, as it is related to XBox Live and using MS's dedicated servers.

And Magicka as well

Yup, Magicka as well. There are several examples available.


text:
C# Pathing algorithm for moving a object from point(X, Y) to point(X, Y)
Given a object which may move forward, backward, left and right at a given X,Y point. How to efficiently direct the object to a X,Y point using the given movement mechanics in the most efficient and human natural way.
The object is available for movement in real time, you may tell them to "startMoving|Direction|()" and "stopMoving|Direction|()" to any heading of 360 degrees. Though as a additional twist and the part I am having trouble with, is the facing of the object is never known, only its current location is known, so the algorithm must "detect" direction. The location of the object is updated in a separate thread in 500-1second intervals. A "Request" to update the location within the algorithm made be made at any point, but it is not immediately available and the algorithm must keep that in consideration. Doing something like requestAndWaitForCoordUpdate() is perfectly acceptable, however likely not needed.
In addition, no obstacles appear, it can be assumed you are on a MOSTLY open plane, stray to far from the direct straight line between the paths and you may run into obstacles. It is safe to assume that 1/4th the distance between a target and source, should be available in width on a given direct path.
I would also mention I am not sure A* applys in this scenario, if it does I am unsure how to implement it given the constraints. The only real variable here is the facing of the object.
Here is some example code:
public int[] currentCoords;
public void movement() {
  currentCoords[0] = 1005; // starting y coord
  currentCoords[1] = 1007; // starting x coord
  moveTo(1050, 1025);
}

public void moveTo(int x, int y) {
  ... how?
}

public void threadUpdatingCoords() {
   ... periodically check for source coord updates
   ... between 200ms and 1000ms apart.
}

What means of rotating does the object has available?

Not sure if I understand the question. The object may only move horizontally and vertically and cannot rotate? Is that right?

I suggest the first thing you do is move the object straight ahead for a short duration. Now you will know the original position as well as it's new position. From the knowledge of these you will be able to calculate the rotation of the object.
originalPosition = (3 ; 2)
newPosition = (3.5 ; 1.7)
offset = (newPosition - originalPosition) = (0.5 ; -0.3)
offsetLength = sqrt(0.5^2-0.3^2) = 0.583
currentDirection = Normalize(offset) = (0.5 / 0.583 ; -0.3 / 0.583) =(0.857 ; -0.515)

Once the current direction is known, all you have to do is to offset the direction so it points towards the goal location and start moving until you reach it.
For additional information such as ETA you could compute the speed of object while it's moving.


text:
Are there any issues with not drawing to all render targets when using MRT?
Lets say I set 2 render targets:
device.SetRenderTargets(color, depth);
And then half my draw code only outputs color and not depth. This works fine on the PC and produces the expected results however I feel like this might be an issue on the Xbox.
Are there any issues I should be aware of when using MRT while only outputing to one render target?

First of all, using a color buffer and a depth buffer isn't really MRT.  That term is used when you have multiple color buffers and are sending different outputs to each.
But to answer your question, no, there should be no issue.  Any render targets that are disabled by the current states will not be written to.  You can turn color writes or depth writes on and off whenever you like.
The X360 GPU is really just a slightly-modified version of a certain PC GPU chipset.  It's not like it's different in a fundamental enough way that enabling/disabling depth writes behaves differently.

Color and depth are used as MRT when the depth buffer really is a separate render target used to encode depth in a color buffer (although most of the time typically written as a single vector or red-green encoding).

I don't think it'll be an issue on the Xbox as long as you don't accidentally clear the rendertarget before you are done with it. To be on the sure side when only writing to your color rendertarget, make sure to choose a BlendState which disables color writes to your depth rendertarget. You'll even save some bandwith/performance this way.
E.g. create a new BlendState disabling color writes to second rendertarget:
protected override void LoadContent()
{
    this._blendState = new Blendstate()
    {
        ColorWriteChannels1 = ColorWriteChannels.None,
    }
}

Then set this state before you do your draw calls only outputting to the color rendertarget (and reset afterwards):
protected override void Draw(GameTime gameTime)
{
    GraphicsDevice.SetRendertargets(color, depth);
    GraphicsDevice.BlendState = BlendState.Opaque; // .. or any other BlendState

    {.. draws to both rendertargets ..}

    GraphicsDevice.BlendState = this._blendState;

    {.. draws only to color rendertarget ..}
}


text:
Is it possible to program the entire logic and flow of a game without ever touching a graphic's engine?
I'm not interested in rendering engines or level design, but I'm very interested in programming the AI that drives all of the characteristics of game play. I'm thinking of how the d20 system drives the rules behind D&D games. Is there a person that programs that logic, and is it possible to program almost all of an API without ever touching a graphic's engine? I'm a software engineer by trade (Java with some C# experience), so I'm looking to use those programming skills.

See my post on Open Source Bot API's.  Programming the AI not the engine. http://gamedev.stackexchange.com/questions/8920/open-source-ai-bot-interfaces

Yes
It is possible to program games without touching a graphics or rendering engine. But it will limit you to text based games. Some good examples of these games would be nethack, dwarf fortress, and online MUDS(multi-user-dungeons).
If you want to make a game with graphics, I suggest you join a team where you can program logic and AI without having to know to much about graphics.

Also think of simple dynamic websites, where you generate every result into HTML and keep the values on the server in some sort of local storage (SQL, ascii, xml or whatever)

Yes,
a game engine is made of lots subsystems. Graphics Engine, AI Engine, the input system, the sound system, a game editor and many more.
A game is composed by a game engine ( and for small games it's not a need ) and much content: textures, levels, 3d models, sounds, and GAME LOGIC, yes, the game logic is a content.
You can made a game without a engine, or with a engine with only two or three subsystems. A game without graphics, only on text mode. On a great company, small groups are dedicated only a part of the game. ( AI scripting, lighting, network, etc..)

Are you interested in creating a new game, or just trying to implement various AI techniques? In the second case, there are many video games that offer APIs to interact with the game. For example, you could create a bot for StarCraft using BWAPI.

Is there a person that programs that
  logic, and is it possible to program
  almost all of an API without ever
  touching a graphic's engine? I'm a
  software engineer by trade (Java with
  some C# experience), so I'm looking to
  use those programming skills.

Definitely. Gameplay programmers often never touch actual rendering code. We're a few layers separated (dealing with actors and controllers and such). That being said, as a gameplay programmer on triple-A FPS's, I found myself frequently working with animation code.
And, you still have to know your math and, depending on the platform, understand what's happening under the covers with the decisions you make.
Your mileage will vary depending on the technology and company; but, generally, you're talking about gameplay or AI programming.

Yes, I think you can. Although you should know that usually the AI system communicates with the animation system to manage character movement and actions.
It really depends on the game you're going to implement.

IF you have a good game engine available you don't have to focus on the graphics part and let the engine handle it.

I think the great thing about this approach, which I have done myself, is that you are free to reuse your "rules engine" after you complete it.
This gave me a chance to apply it to many different engines/renderers. I just layer the UI on top and can easily create (almost) completely different games.  I could make one a 2d sidescroller using sprites, another a 3d dungeon, another a isometric rotating map.

It is possible.
Microsoft recently released Kodu.
You should watch the series of videos made on Kodu.


text:
How do I store and handle time in social game?
I intend to develop a social game on flash like farmville. I have got a problem in event time handling though.
For Example, if I breed a horse in game and I don't feed it every hour then its health points will decrease. If I log out of the game for 3 days, when I log in again the horse will be dead. I was thinking I would save the last time the user fed the horse in a database, then when the user logs in again I will compare the current time with the time stored in the database.
The problem is, I think this is not an efficient way of doing it. Can anyone show me a more efficient way of doing that?
I'd appreciate anyone who could show me a way.

I think this belongs on GameDev

Why isn't it efficient? You don't use any resources when the user is offline, and calculate everything as soon as it's needed.. Sounds very efficient to me.

I think It's not efficient because I must save time in database any action of user. For example, time when user feed horse, time when user wash horse, time when user plant a plant,...Many queries will be excuted in database at the same time. What if we have 5000 users then that's really a mess!

If you need this data you'll have to store it. That's the easy part. If this becomes a mess depends only on your database design. You'll have a record for the plant anyway and it won't give problems to have a few additional fields like time_planted, last_watered and so on. In business applications this kind and amount of data is quite common. Having fields like created_at, last_edit, booked_at is quite common for much more than 5000 users and millions of records with bookings or similar actions.

I don't see why this is inefficient either. If you're already storing user actions in the database then adding a Timestamp field is trivial. (If you're not storing user actions, you might consider doing that for logging and metrics purposes anyway.)

Thinking about the bigger picture may be helpful.
First where do you store the current state of their entire "farm". It's obviously not on the user side. It must be on the server side. If you are storing the entire state of the farm which would include each horse and the amount of energy they have then you are correct.
This is how I would handle it.
You store the farms current status which is made up of everything and their current decaying energy value. The rate of decay is where time comes in. It is a function based on how much they were fed and how fast the energy from said food decays. You don't store their feed times, you store their current state and the last time of update for the entire farm.
When they send a request for an update then you look at their last overall update time and then send back the new state of the farm and all of the decayed energies.
The update request is going to be the same whether it be right when they log in, or in a polling situation every 10 seconds. Client side if you want a finer time window than 10 seconds you can have their client update the decayed values, but always verify when the new server update comes in 10 seconds. (Or whatever time frame you choose)
So Old Solution:

New Solution:

EDIT: Just to clarify to anyone that didn't get his concern, he probably didn't like storing a last update time for each and every object in the farm. My optimization is to store a global one and instead store energies and user their respective decay functions on global updates

If I am understanding your question right, while the user is logged in and playing, time moves in normal, real-time fashion.  If that is the case, you could rely on a wrapped time source where you can manipulate the current reference point in time.
I know your question specifically mentions Flash and my code example here is in Java, but I believe it should be easily adaptable for your needs:
  public class TimeSource {
    private static Long staticStart = System.currentTimeMillis();
    private static Long fixPoint = System.currentTimeMillis();

    public static void setCurrentTimeMillis(Long currentTimeMillis) {
        staticStart = System.currentTimeMillis();
        fixPoint = currentTimeMillis;
    }

    public static Long getCurrentTimeMillis() {
        Long offset = System.currentTimeMillis() - staticStart;
        return fixPoint + offset;
    }
  }

Basically when the application starts up, we initialize to the current time in millis.  However, if we set an alternate time as our "current" then the offset is calculated and used to generate the time whenever it is requested.
In the case of your game, you can set the current time to 0 when the game is very first initialized for a new user.  Then, time will proceed as normal during play.  When the user ends their session, you can store the current game time and restore that when the user logs in again.
Now all of your elapsed time logic can be based just on in-game time.

Thanks for your replies. I have an idea that I will store info of time in files. Everyboy have a separate file store their "last-times". How do you think about that? would reading and writing file speed is faster than call in database?

You shouldn't answer your own question with another one.

Use the DB, for the same reason you use a DB. Speed of the DB can be "configured" if ever necessary.

Files will perform much worse if you have to query stuff (eg. get me the last time user X fed the horse).

Having such restrictions on your players would get extremely annoying for them very quickly.
You're effectively forcing them to be online and playing your game nearly 24/7.
What will happen when a user can't log on for a few days because they're on a vacation? All their animals and plants would die, there might be other disasters.
Not very userfriendly.
Better to stop the timer when the user logs off, and start it again when he next logs on. Effectively their farm only exists when they're on the server (except of course that noone can buy land on its area, if you're working with such a system).

I disagree. It's a question of what game he wants to design. Some are more involving, some are less. Not every game that doesn't appeal to the casual players who only have 1 hour a day is non-user-friendly, it's just less casual-user-friendly, which is completely fine if that's what the game designer wants. If you have to log in every day to "survive" in the game it's fine if that's what the game designer wants. About the vacation thing some games have special systems for exactly that purpose, like when a friend takes over your account for a while with limited privilages :)

If you are concerned with the volume of operations in the database, you should have a look at a databse that supports sharding well. As your query path is essentially a key lookup you are free to choose from a number of databases. I would recomend MongoDB as it has native drivers for many languages, and is extremely easy to manage.
I would not recommend you store this in files, as a database system can better optimize performance by keeping part of the data in ram and apply indexing on keys (depending on file system file access performance can degrade quite dramatically as the number of files in a folder increases).
Also, when you need to distribute load to more servers it is much easier when you have a database that can do sharding and balancing for you.


text:
Theoretic question about rendering in sfml and in general
I have read whole tutorial section on sfml-dev.org and have some question.
What are exactly views and how to use them ?
Should I render things in views or in renderwindow ?

Views in SFML, like it says in the docs, are like 2D cameras. Essentially it represents what you would see through a camera and allows you to zoom in or out and to scroll in any direction easily. Doing this with a RenderWindow would mean that in order to zoom in, you would need move/scale every sprite. Same thing for scrolling, you would need to move every sprite on screen depending on the scroll direction.
On the other hand I have used sfml once, to make a multiplayer 2D shooter. I didn't use views at all when doing all the rendering. Everything was drawn directly to the RenderWindow and I had no performance problems or anything else.

Why is this answer CW?

Good question! must have clicked that by mistake. My bad.


text:
Is there a simple C++/.NET game with scripting?
I would like to play around with games that use scripting to see how much easier it makes development. What --simple-- C++ or .NET game may i download and play with using a scripting language. I dont really care which scripting language it is.

Lots of games use scripting which allows for not only modding but the creation of completely different games.
Your welcome to purchase Puzzle Quest 2 (or any Infinite Interactive game) and see just how easy it is to script with Lua. Pretty much everything you can do is already in there in the existing scripts.

Even though it's not directly what you were asking for, there already is a question regarding games that utilize scripting. Some of them might be options for you as well, notably LÖVE (Engine)
Game engine with good Lua entity creation/management