Reputation: 6117
I'm coding some kind of video game where players take turns of N seconds, where in those N seconds they are able to enter keyboard inputs. Once the N seconds passed, the entered input would be returned (e.g. in an Array), processed and some actions will be performed.
The execution flow would be something similar to the following:
while (!gameOver) {
// do some stuff like knowing who's player turn is it
var enteredInput = captureKeyboardInputsFor(seconds);
// process input & do actions
}
I do have the game logic well defined in mind, but I'm trying to figure out how can I do this with TypeScript, keeping my loop game synchronous (as the players play in turns), having the
var enteredInput = captureKeyboardInputsFor(seconds);
line waiting until the N seconds passed.
Also, I was thinking about the possibility of having CPU Players. In that case there would be no need to wait or capture inputs:
while (!gameOver) {
// do some stuff like knowing who's player turn is it
var enteredInput;
if (player.isHuman()) {
enteredInput = captureKeyboardInputsFor(seconds);
} else {
enteredInput = calculateRandomCPUPlayerInput();
}
// process input & do actions
}
Upvotes: 2
Views: 398
Reputation: 3106
You can unbind the captureKeyboardInputs listener after N seconds have passed with the setTimeout function like shown below. Is this what you are looking for:
let fn = () => {
// unbind capture keys event
// process input & do actions
};
let a = setTimeout(this.fn, seconds * 1000);
if you need to modify this then you can do:
clearTimeout(a);
if (isProcessNow) {
this.fn();
} else {
a = setTimeout(this.fn, newSeconds * 1000);
}
Upvotes: 2