Goowik
Goowik

Reputation: 803

node socket io timer implementation

I'm creating a drawing/guess game in node & socket. Simply said: I have a class Room, Game (which extends Room) and a class Round (10 per game). Each round a user is assigned as the drawer, the guessers have 45 seconds to guess the word.

Upon the first guess if the timer is higher than 20 seconds, the timer is reduced to 20 seconds.

I'm not certainly sure but this is how I started:

class Round:

function Round(id, game){
  var ROUNDTIME = 45,
      timer = new Date();
  this.id = id;
  this.game = game;
  this.endTime = timer.setSeconds(timer.getSeconds() + ROUNDTIME);
  ...
}

class Game:

function Game(){
  this.MAX_ROUNDS = 10;
  this.rounds = [];
  this.currentRound = null;
  ...
}

Game.prototype.start = function(){
  this.nextRound;
}

Game.prototype.nextRound = function(){
  if(this.rounds.length <= this.MAX_ROUNDS){
    this.currentRound = new Round(this.rounds.length + 1, this);
    ...
  } else {
    this.endGame();
  }
}

Game.prototype.endGame = function(){
  ...
}

Afterwards I have a Round function which checks for the answer each time an answer/message is submitted. Upon first answer I reduce the endTime till 20 seconds left.

So have 2 questions:

  1. Is this a correct/good practive approach?
  2. How should I implement it further into the application itself? (setInterval of 1 second with emit? or Simply emit when the endDate is reached? or another way?)

Upvotes: 1

Views: 786

Answers (1)

mido
mido

Reputation: 25034

you can do something like

function Round(id, game,loseCallbackFn){
var ROUNDTIME = 45, startTime = new Date();
this.id = id;
this.game = game;
this.endTime = startTime.getTime()+45*1000;
this.timerId = setTimeout(loseCallbackFn,45*1000);
...
}
...
Round.onWrongGuess(){
    if((this.endTime-(new Date()).getTime())>20*1000) {// he has more than 20s left
        clearTimeout(this.timerId);
        this.timerId = setTimeout(loseCallbackFn,20*1000);
        ...
    }else{
        loseCallbackFn();
    }
}
...

Upvotes: 1

Related Questions