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\$ Commented Oct 13, 2015 at 23:14

1 Answer 1

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\$ Commented Oct 7, 2015 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\$ Commented Oct 7, 2015 at 17:55

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.