Implementing a game turn-timeout on the server side - c++

At the moment I am writing a turn based game for the iOS platform. The client is written in Objective-C with CocoaTouch, and the server is written in C++ for the Ubuntu Server OS. The server is connected to a MySQL database, in which it stores user & game data.
Right now I wish to implement a time-per-turn restriction, and this has to be done on the server side. When a user takes a turn, the next user will have a maximum of 24 hours to answer, otherwise I want the game to skip this user's turn and move on to the next player. I have some ideas about how to do this, but I am not sure if they are any good. What I've been thinking of is storing the date&time of the last turn taken as an entity related to the Game table on my SQL database. Then I'm thinking of launching a thread on the server which runs until termination, and looks up current time minus every game's last turn, say every minute or so. If it's been more than 24hrs since the last turn was taken, this thread allows the next player in the queue to take their turn, and skips the lazy player.
Does it sound over-complicated? Is there another, more simple way to do this? I know it's been done in many games before, I just don't know how. Thanks in advance!

I don't think you need any threads or background processes at all in this case.
What I see here is a simple algorithm:
When a user logs in to the game/match - check up the last turn ending time in the database,
If the elapsed time from the last turn ending time is greater than 24h, get the current time, substract the time from the database (obviously you need to convert both times into hours) and divide it by 24,
If the division yelds an odd number, it's the turn of the other player (player A)
If the division yelds an even number, it's the turn of the player B.
Set the database time to databaseTime+division*24
This algorithm can skip multiple turns. When player A finishes his move, and 48h passed, it's players B turn.

You probably just want a background process that has a schedule of "next actions" to take, a sort of priority queue you can work through as the events should be triggered.
A single process can handle a lot of independent games if you design the server properly. The architecture would pick up an event, load any associated data, dispatch accordingly, and then go back to waiting for new events.
C++ does have frameworks for this, but you could prototype it in NodeJS or Python's Twisted really quickly.

Please look at the reactor pattern (boost.asio, ACE). These frameworks are asynchronous, use an event-driven model and require no threads. Below is pseudo code on how you can solve it:
reactor.addTCPListener(acceptSock(), Handler::AcceptSock) // calls AcceptSock when accepting a new TCP connection
rector.addTCPListener(clientSock, Handler::ClientData) // calls ClientData when user is sending the server game stats (its move, status etc)
.
.
.
later on somewhere
.
.
.
for(set<Game>::Iterator it = games.begin(); it != games.end(); ++it) {
(it*)->checkTurn() // this call can be responsible for checking the timestamps from the ClientData function
}
Summary:
With the reactor pattern you will be able to have a non-blocking server that can do cleanup tasks when it is not handling IO. That cleanup can be comparing timestamps to switch/pass turns.

Related

Limit a Game Server Thread loop to 30FPS without a game engine/rendering window

I'll try to explain this as easily as I can.
I basically have a game that hosts multiple matches.
All the matches on the server are all processed by the server, no players host a match on their computers via port forwarding, it's all done by the server so they don't have to.
When a player requests to make a match, a match object with a thread is made on the server. This works fine. Each match object has it's own list of players. However, the game client runs at 30FPS and it needs to be in sync with the server, so just updating all the players in the thread loop will not do since it's not run at 30FPS.
What I'm doing right now is I use a game engine: SFML, which in its window loop, goes through all the players in the server and runs their update code at 30FPS.
This is fine however, when there comes a time where they may be a huge chunk of people, it will be better that the players are updated via the match threads so as not to slow down the processing speed by having it all done in one render loop.
What I want to know is, how would I simulate 30FPS in a match's thread loop? Basically have it so each player's update() function is called in the timeframe of 30FPS, without having to use a rendering engine such as SFML to limit how fast the code is to be run? The code is run in the background and output is shown on a console, no rendering is needed on the server.
Or put simply, how do I limit a while loop code to run in 30FPS without a game engine?
This seems a bit like a X Y problem : You try to sync players via server "FPS" limit. Server side doesn't really work like that.
Servers sync with clients in terms of time by passing to the client the server's time on each package or via a specific package (in other words, all clients have only the server's time).
But regarding server side implementations for gaming :
The problem is a bit more broad than what you mentioned. I'll post some guidelines which hopefully will help your research.
First of all, on server you don't require rendering, so FPS is not relevant (30 fps is required in order to give our eyes the sensation of fluidity). Server usually handles logic, like for example various events (for example someone fires a rocket, or a new enemy has spawned). As you can see events don't require FPS, and they are randomly triggered.
Something else that is done on the server is the Physics (or other player-player or player-environment interactions ). Collisions are done using a fixed update step. Physics are usually calculated at 20 FPS for example. Moving objects get capsule colliders in order to properly simulate interaction. In other words, severs ,while not rendering anything, are responsible for movement/collisions (meaning that if you don't have a connection to the server you won't move / go through walls , etc - implementation dependent).
Modern games also have prediction in order to reduce lagging (after all, after you give any input to your character, that input needs to get to the server first, get processed and be received back in order to have any effect on the client). This means that when you have an input on a client (let's take moving for example) , the client starts making the action in anticipation , and when the server response comes (for our example the new position) it will be considered as a correction. That's why sometimes in a game when you have lag you perceive that you are moving in a certain direction then all of a sudden you are somewhere completely different.
Regarding your question :
Inside your while loop, make a deltaT , and if that deltaT is lesser than 33 miliseconds use sleep(33-deltaT) .
As you requested, I'm posting a sample of deltaT Code :
while (gameIsRunning)
{
double time = GetTickCount();
UpdateGame();
double deltaT = GetTickCount()-time;
if (deltaT < 33 )
{
sleep(33- deltaT);
}
}
Where gameIsRunning is a global boolean, and UpdateGame is your game update function.
Please note that the code above works on Windows. For linux, you will require other functions instead of GetTicksCount and sleep.

Is it possible to avoid threads in multiplayer Hangman game?

I wish to implement a simple multiplayer Hangman game with the rule slightly bended.
Rule:
All the players have to guess the alphabets in the word at the same time. Whoever player guesses a correct alphabet gets a point, and the player who puts the ending alphabet gets bonus points.
This will be about speed. The faster correct guess gets you ahead of others.
I intend to have a Qt/QML based GUI and the programming language will be C++. Platform will be Linux.
I am thinking I'll need:
- One thread for handling user typing.
- Second thread for parallel display of what other players are typing.
- Third thread for parallel display of scores of every player on every player's screen.
Do I need these 3 threads or I am barking the wrong tree?
It sounds like you're planning to have this game communicating over the network, where each player is using their own computers and running a copy of the program.
You should only need one thread for the application, but you might decided that more threads will make it easier on you.
You can easily connect signals from player's typing (either use an event handler, or connect your widget's "editingDone" signal.) to the appropriate logic for updating the scores and showing the other player's answers.
I think you'll run into the most problems with deciding on how to properly network the application to all instances, assuming that that's what you're trying to do. But the Qt network stack can allow you to do asynchronous network communication without having to manually create new threads.

How to stop or pause glutTimerFunc in GLUT?

In my project i'm running a train which stops moving when it reaches a particular point this moving is carried out by glutTimerFunc .I once again want the train to start from the location where i click my mouse to a particular location
BUT THE PROBLEM HERE IS,
My timer still running even after reaching that location,so even when i initialise the starting point its not working(it continues from the left location).
Now i need to stop the timer and start the train timer for the new location.
The API documentation has the following to say:
There is no support for canceling a registered callback. Instead, ignore a callback based on its value parameter when it is triggered.
So, add a boolean to your software and ignore the event whenever it is triggered. It would be better to use a clock-based timer rather than an event-driven timer and do your timed updates manually everytime the main loop runs (you detect the amount of time since the last update, and you determine whether to perform an update tick(s)), in the long run however. This is how physics and various other time-based simulations are handled in most professional software, using the event-driven model sets you up to miss or frequently wind up handling a timed event excessively late.
Welcome to the world of game engines and actors.
My recommendation is that you don't try to do this by turning glutTimerFunc on or off directly. The timer function should be the top level "heartbeat" for the entire program, and it's job is just to tell every object that has behaviour - an "actor" - that it should update itself. The train should have its own internal state that knows where it is and whether it should be moving or not.

Is it possible to do real time network games in Actionscript 3.0

Question: Is it possible to update 100+ objects in the Flash Player over Socket Connections? More details and my own try's below!
Details
For my internship I got the time to create a multiplayer physics game. I worked for a steady three months on it. My internship is coming to an end and I couldn't finish my game.
My problem is that its hard to send multiple packets each time-step to the server and back. The packets I send are position updates of the objects and mouse of other clients.
I will try to explain the network/game flow.
Client connects to the server using the binary Socket class in AS3
Server ask for verification and client sends name and thumbnail.
Server waits until 4 clients are connected (Some matchmaking etc)
Server picks 4 clients and makes them run on a separate Thread(Combined as a Team)
Client sends his performance score to the server range 1-100.
Server makes the best client the host machine for the physics and the other 3 slaves
Host game sets up the level and makes around 1-100 shapes in the level(primary shapes and complex shapes like bridges, motors, springs)
Every time-step the host gets all updated property's of the shapes and sends them to the clients (x, y, rotation, sleep)
The client applys all the shape property's to the correct shapes
I tried different time-steps and noticed that until a time-step of 1/15 second the client(slave) won't notice any lagging in the game. I also tried to pick a lower time-step and tween the movement of the shapes but that did give some strange movement on the client(slave) side.
I will give an example of a single object update packet.
<O|t=s:u|x=201|y=202|f=automaticoo</O
<O|t=m:p|x=100|y=345|f=automaticoo</O
I noticed that the Flash Player can stack a lot of packets in the buffer before sending. For example if I send a lot of packets at once it stacks them up and send them together to the server. With faster time-steps you don't get more updates on the client(slave) side but more updates in the same packet row.
Tries
Use the new RTMFP(udp & p2p) protocol for updates. (little bit better in performance but less in reliability)
Code my entire socket server in c++ instead of Air(with the ServerSocket) (better in performance but noticed the lagging part is not the server but the Flash Player)
Use the ByteArray compress method and the AMF serialized format (performance about the same except the c++ server can't unserialize the messages)
Do you guys think it is possible in the Flash Player too handle so many update request each time-step.
Discoveries
There is a stick arena game that is multiplayer in ActionScript 3.0. They used a lot of tricking and even then I get a ping of about 300ms and it only updates the players constantly (4 players in a lobby).
Sorry for the long post.
I believe your problem comes down to type of game and data.
This again is broken up into:
server speed (calculations need in CPU + RAM requirements for world/player data)
connection speed (bandwidth on server)
data size (how much info is needed and how often)
player interaction form (event or FPS)
distance from client to server (ping)
MMORG
Eg. World Of Warcraft, is to my knowledge on the none-PVP worlds using a "client is a viewport" and "client sends keystrokes", "server validates and performs, and tells client what happens" on a CLIENT-SERVER base.
This gives the game a lot of acceptable latency as you only need to transfer commands from client and then results to the client. The rest is drawn on the client.
Its very event driven and from you click an icon or press a key, its okay that your "spell" needs some time to fire on the server. Secondly there is no player collision needed. This lets the server process less data too and keeps the requirements to the server CPU smaller.
Counter-Strike / Battlefield etc.
FPS, fast paced action, with quick response needs to get information about every detail all the time. This makes a higher demand on precision. Collision is a must for both player and weapons.
This sort of game usually doesnt handle more than 32 players on a single map, as they all need to be able to share their positions, bullets, explosions etc. very fast and all this data has to go through the server-validation which again is a bottleneck for any type of online game.
Network latency
In a perfect world this would be 0 ms, but as we all know. All the hardware from client to the server and back takes time. Both going through the network stacks and through the internet connection (switch, router, modem, fiber centrals etc) so the way many modern real time games fixes this is by "prediction". The let the server look at your direction and speed. Then they try to predict (much like the GPS do in a tunnel too) that you were last seen moving forward with a speed of +4 so given timeframe you have moved (timeframes x 4) - but what if you had slowed down or speeded up? then they either instantly "hyperjump" you from A to B in a split second and this you feel like a lagging game or they easy up to the real position so your "hero" slides a little faster or slower into the right possition.
This technique is explained many places on the net, so no need for details in here, but it takes time and tweaks to get a good performance from this - but it works and saves a lot of headaches for the programmers.
What network data is needed?
I read your question and thought: that could be compressed quite a lot. Secondly, I have made a Flash socket chat with pure ByteStream and that worked awesome. It was hard to get running for a start, but once I got it up and running it was fast.
The flash client/player itself isnt the biggest networking client, so expect a lot of lost speed there too. I would go for 10-15 fps for the networking part and then use a more RAW approach for the data sent back and forth.
Lastly, try to keep the data as simple as possible.
Eg. use COMMANDS/SHORTCUTS for certain data/events.
Like a server data bytestring could be: 0x99, 0x45,0x75,0x14,0x04,0x06
Where 0x99 means : BIG EXPLOSION at the following COORDS: (0x45,0x75)
Then 0x14 means: PLAYER 0x14 (player 20 in decimal) has moved to (0x04, 0x06)
So the staring opcode tells the networking protocol handler in your client and server what to expect next. (Its how a CPU knows how to read memory btw.)
For my chat I had commands for each type of data parsed. One for login, one for broadcasting, for for telling the name of a user etc. So once the client made a login, the client received a command + a packed of online users. This was only transfed once to the client. After that each attached client received a "new user online" command too with the name of the new user. Each client maintained its own list with current users and ID's so that I only needed to tell which client number say the text. This kept the traffic at a minimum. Same would go for coordinates or commands of what to do. "Player #20 goes north" etc. could be be 0x14, 0x41, 0xf0 (0x41 could be MOVE, 0xf0 could be NORTH, 0xf1 EAST etc.)
This physical distance to the game
This one you cant change, but you can put in some restrictions or make the servers run in multiple locations worldwide, depending on what type of game you wanna make. Amazon EC2 is a great platform for such projects as they have data-centers all over the world and then you can benchmark the users network against these and then redirect the users to the nearest datacenter where you are running a server.
Hacking/cheating
Also remember, if something gets popular and you start earning money on it, sooner or later SOMEONE will try to break the protocols or break down the accounts to gain access to servers, informations or cheat to get further items/points in the games. You could also be attacked by DDOS where they bomb your network with wrong data just to crash everything and render the game unusable.
Dont mind it so much for a start, just remember that once you go online, you NEVER know who in the world or where in the world they are. I'm not trying to make you paranoid, but there are sick people who will try to earn money by cheating others.
So think this into your structures, dont show data in network packages that isnt needed. Dont believe data from client always is correct. Validate data on server-side.
This also takes time if you have 100 active players at the same time.
But once you do it, you can sleep much better if it gets to be a big success for you, which I really hope.
That was my thoughts from experience. Hope some of it might be usefull eventhough I didnt quite answer if 100 players are possible.
Infact I would say: YES 100 players is possible, but it depends if they all move at the same time and there is collission testing involved and if you will accept lag or not.
Question: Is it possible to update 100+ objects in the Flash Player over Socket Connections?
Phosphor 2 seems to pull it off.
Maybe the best option was do the physics on server AND on each client, with synchronization (server object positions are overwriting client's). This way all clients get equal lags. Until discrepancy is low (as it should be) corrections will not be noticeable. If you use Box2D, you have both AS3 and C++ version ready. But this is totally different architecture, worth 3 month to implement by itself. What lag do you get on empty/simple arena? In limited time, simplification may be your only option.

Optimum Update frequency for a client server based multiplayer game

I am making a multiplayer game in c++ :
The clients simply take commands from the users, calculate their player's new position and communicate it to the server. The server accepts such position updates from all clients and broadcasts the same about each to every. In such a scenario, what parameters should determine the time gap between consecutive updates ( i dont want too many updates, hence choking the n/w). I was thinking, the max ping among the clients should be one of the contributing parameters.
Secondly, how do i determine this ping/latency of the clients ? Other threads on this forum suggest using "raw sockets" or using the system's ping command and collecting the output from a file .. do they mean using something like system('ping "client ip add" > file') or forking and exec'ing a ping command..
This answer is going to depend on what kind of a multiplayer game you are talking about. It sounds like you are talking about an mmo-type game.
If this is the case then it will make sense to use an 'ephemeral channel', which basically means the client can generate multiple movement packets per second, but only the most recent movement packets are sent to the server. If you use a technique like this then you should base your update rate on the rate in which players move in the game. By doing this you can ensure that players don't slip through walls or run past a trigger too quickly.
Your second question I would use boost::asio to set up a service that your clients can 'ping' by sending a simple packet, then the service would send a message back to the client and you could determine the time it took to get the packet returned.
If you're going to end up doing raw-packet stuff, you might as well roll your own ICMP packet; the structure is trivial (http://en.wikipedia.org/wiki/Ping).
The enet library does a lot of the networking for you. It calculates latency as well.