我正在 Node 和套接字中创建一个绘图/猜测游戏。 简单地说: 我有一个Room类、Game(扩展了Room)和一个Round类(每场游戏10个)。 每轮都会分配一个用户作为抽屉,猜测者有 45 秒的时间来猜测单词。
第一次猜测计时器是否高于 20 秒时,计时器将减少至 20 秒。
我不确定,但这就是我开始的方式:
类(class)回合:
function Round(id, game){
var ROUNDTIME = 45,
timer = new Date();
this.id = id;
this.game = game;
this.endTime = timer.setSeconds(timer.getSeconds() + ROUNDTIME);
...
}
类游戏:
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(){
...
}
之后,我有一个 Round 函数,每次提交答案/消息时都会检查答案。第一次回答后,我将 endTime 减少到还剩 20 秒。
有两个问题:
- 这是正确/良好的实践方法吗?
- 我应该如何进一步将其实现到应用程序本身中? (setInterval 为 1 秒并发出?或者只是在到达 endDate 时发出?或者其他方式?)
最佳答案
你可以做类似的事情
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();
}
}
...
关于javascript - Node 套接字io定时器实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26375884/