I am using javascript and HTML5 canvas for turn-based games (e.g., checkers, mastermind, minesweeper).
Should I write a fixed-timestep game loop? What are the alternatives?
I am using javascript and HTML5 canvas for turn-based games (e.g., checkers, mastermind, minesweeper).
Should I write a fixed-timestep game loop? What are the alternatives?
Constantly looping is probably unnecessary for a turn-based game.
If the only time something is going to change is when a player moves, consider using setTimeout()
or requestAnimationFrame()
.
Here's an approximate setup:
var player = {x: 0, y: 0};
//to be executed whenever the player moves
function animate(xDifference, yDifference){
var pixelsLeftX = xDifference,
pixelsLeftY = yDifference,
finishedMoving = false;
var xInterval = setInterval(function(){
pixelsLeftX = xDifference > 0 ? pixelsLeftX - 1 : pixelsLeftX + 1;
if(pixelsLeftX === 0){
clearInterval(xInterval);
if(finishedMoving){
continue()
}else{
finishedMoving = true;
}
}
}, 10),
yInterval = setInterval(function(){
pixelsLeftY = yDifference > 0 ? pixelsLeftY - 1 : pixelsLeftY + 1;
if(pixelsLeftX === 0){
clearInterval(xInterval);
if(finishedMoving){
continue()
}else{
finishedMoving = true;
}
}
});
}
function continue(){
//etc
}
while
/for
) in this code, the JavaScript event loop in the background is what causes setInterval
and requestAnimationFrame
to fire.
\$\endgroup\$