Fix election timeout bug and tidy up fixes #34

This commit is contained in:
Chris Blanchard 2015-09-20 00:48:07 +01:00
parent c0f6f80423
commit 5337789772

View file

@ -25,9 +25,12 @@ function Gather (options) {
options.onEvent : noop;
this.TEAM_SIZE = 6;
this.gatherers = [];
this.ELECTION_INTERVAL = 120000; // 2 mins
this.REGATHER_THRESHOLD = 6;
this.electionStartTime = null;
this.election = {
INTERVAL: 120000, // 2 mins
startTime: null,
timer: null
};
this.initState();
}
@ -70,17 +73,11 @@ StateMachine.create({
onenterelection: () => {
// Setup timer for elections
let self = this;
self.electionStartTime = new Date();
setTimeout(() => {
if (self.can("electionTimeout")) {
self.electionTimeout();
}
}, self.ELECTION_INTERVAL);
this.startElectionCountdown();
},
onleaveelection: () => {
this.electionStartTime = null;
this.cancelElectionCountdown();
},
// Selection State
@ -282,9 +279,9 @@ Gather.prototype.marines = () => {
return this.retrieveGroup("marine");
};
Gather.prototype.electionTimer = () => {
return (this.electionStartTime === null) ?
null : this.electionStartTime.toISOString();
Gather.prototype.electionStartTime = () => {
return (this.election.startTime === null) ?
null : this.election.startTime.toISOString();
};
Gather.prototype.toJson = () => {
@ -293,8 +290,8 @@ Gather.prototype.toJson = () => {
state: this.current,
pickingTurn: this.pickingTurn(),
election: {
startTime: this.electionTimer(),
interval: this.ELECTION_INTERVAL
startTime: this.electionStartTime(),
interval: this.election.INTERVAL
}
}
};
@ -332,6 +329,21 @@ Gather.prototype.regatherVotes = () => {
if (gatherer.regatherVote) acc++;
return acc;
}, 0);
}
};
// Initiates a timer which will push gather into next state
Gather.prototype.startElectionCountdown = () => {
let self = this;
self.election.startTime = new Date();
this.election.timer = setTimeout(() => {
if (self.can("electionTimeout")) self.electionTimeout();
}, self.election.INTERVAL);
};
Gather.prototype.cancelElectionCountdown = () => {
clearInterval(this.election.timer);
this.election.timer = null;
this.election.startTime = null;
};
module.exports = Gather;