Webster Webster - 18 days ago 5
Node.js Question

Timeout-per-turn logic for a game

I'm creating a game in telegram bot and now i already reached the "PLAYING" state. The most difficult part is the timeout-per-turn algorithm (for me).

Here's the breakdown:


Game starting.. Got 4 players

The game objective is to answer the question. The question is :
Mention the names of animal.

The order to answer is : Player C --> Player B --> Player D --> Player
A.

Each player has the maximum 5 seconds to answer (can be less).

Okay now, the game will begin in 3.. 2.. 1.. GO!!

Player C answer: dog (1 sec)

Player B answer : cat (1 sec)

Player D answer : deer (1 sec)

Player A answer : bird (2 sec)

And when it goes back to Player C, it will be 5 secs, and my logic is
to check whether the oldTurnId (Player C) === currentTurnId (Player
C). In this case, player C will get notified that the time is out, and he will be sent off, but
player C is about to answer for the 2nd time.


I have this columns on my table : previousTurnId, currentTurnId, nextTurnId
.

But i can't find any direction to tackle this problem.

FYI, I'm using node.js to create this game and the main part is I'm using setTimeOut a lot for this timeout-per-turn logic.

Anyone has better idea for tackling this problem?

Thanks a lot guys,
All help will be appreciated.

Thanks

Answer

Sounds like what you want is a clearTimeout. Basically, you would clear the timeout if the player answers within the next five seconds, otherwise, you carry on with kicking the player out of the game as normal. You can get the timeout ID as a return value from setTimeout.

I'm making an assumption on your code, but this would basically be how it would go:

var playerTimeout = setTimeout(function () {
  removePlayer(player);
  startNextPlayersTurn();
}, 5000);

player.on('answer', function() {
  clearTimeout(playerTimeout);
  startNextPlayersTurn();
});