FuturLiberta
FuturLiberta

Reputation: 21

Handle a clock in multiplayer game

I'm working on a quick game where players have a block (a clock like).

So I store in a database when the game starts and when every move is made so I can easily compute the time it took for each player to make moves.

I know I can't trust client to say when the opponent timer is over so, currently, I check every second the time remaining for each ongoing game.

I know it's not sustainable and I want to know how I can check server-side that ongoing games are not over because one player no longer have time.

So, this is how I do currently :

  1. I store in database when the game start (server time)
  2. I store each move in database and when it was make (server time)
  3. Clients are updated via sockets after a move with the time remaining
  4. Clients update the clock (only for display).

  5. Every second, I calculate server-side :

    • The time between the first move and the start of the game, the time between the 2nd move and the 3rd move, etc. to know how many times it took for the first player to play every moves
    • I do the same for the 2nd player with the time between 1st move and 2nd move, 3rd and 4th, etc...
  6. When the time elapsed for one player is more than the time allowed, the server send (via sockets) the end of the game.

I want to know how I can do not compute every second because I want the server to update the result when no one is connected to the game.

Thank you.

Upvotes: 1

Views: 962

Answers (1)

Max13
Max13

Reputation: 921

Not only you must not trust client-side clock, but you also don't need to.

As said by @Roko-c-buljan, build your timer/clock logic server side. On every move, both players are "synced" and will locally start their timer. If you have a streamed connection to the server, then the server can notify both clients that the timer is over and give the other player its move.

This way, if there is a cracked client, the server will simply ignore the move while it's already the other client's turn.

Upvotes: 1

Related Questions