Sign up ×
Game Development Stack Exchange is a question and answer site for professional and independent game developers. It's 100% free, no registration required.

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?

share|improve this question
    
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. – GSquadron 2 days ago

1 Answer 1

up vote 3 down vote accepted

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
}
share|improve this answer
    
that's exactly what I think I should do, but I do have doubts so I asked here first. Will try :) – userx01 Oct 7 at 16:56
1  
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. – Anko Oct 7 at 17:55

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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