7
\$\begingroup\$

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?

\$\endgroup\$
1
  • \$\begingroup\$ Loop only when it is needed. You do not need to redraw the screen when nothing changes in the game world. When it updates, then it is time to redraw it. \$\endgroup\$
    – GSquadron
    Oct 13 '15 at 23:14
3
\$\begingroup\$

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
}
\$\endgroup\$
2
  • \$\begingroup\$ that's exactly what I think I should do, but I do have doubts so I asked here first. Will try :) \$\endgroup\$
    – userx01
    Oct 7 '15 at 16:56
  • 1
    \$\begingroup\$ It's good to note that although there is no explicit loop structure (while/for) in this code, the JavaScript event loop in the background is what causes setInterval and requestAnimationFrame to fire. \$\endgroup\$
    – Anko
    Oct 7 '15 at 17:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.