2015-11-21 6 views
0

У меня есть игровой цикл, который повторно рисует игровое поле после того, как каждый игрок совершит движение. Я хотел бы приостановить основной цикл и подождать, пока игрок разместит кусок на доске, т. Е. Запускает событие мыши вниз на холсте. Прямо сейчас игровой цикл продолжает перерисовывать доску. Есть ли способ дождаться, когда игрок переместится, прежде чем продолжить цикл?Подождите, пока пользователь не выйдет из игры, прежде чем продолжить цикл игры

var initGameLoop = function() { 
 
    player1 = new humanPlayer(); 
 
    player2 = new computerPlayer(); 
 
    while (gameState) { 
 
    redraw(); 
 
    player1.acceptMove(); 
 
    redraw(); 
 
    player2.acceptMove(); 
 
    } 
 
}; 
 

 
var humanPlayer = function() { 
 
    this.acceptMove = function() { 
 
    canvas.addEventListener("mousedown", addPieceWithMouse); 
 
    }; 
 
}; 
 

 
var computerPlayer = function() { 
 
    this.acceptMove = function() { 
 
    computerMove(); 
 
    }; 
 
};

+1

Это 'while' петля подозрительна, и, вероятно, что нужно изменить. Узнайте о асинхронном программировании в JavaScript (обратные вызовы, события, обещания ...). Это слишком широкая тема для ответа StackOverflow. – Touffy

ответ

0

Это показывает желаемый эффект, используя непрерывный цикл игры. Он не запускает перерисовку, а gameState - playerMove.

var canvas = document.getElementById("can"); 
 
var ctx = canvas.getContext('2d'); 
 
var gameState = "normal"; 
 

 
var initGameLoop = function() { 
 
    player1 = new humanPlayer(); 
 
    player2 = new computerPlayer(); 
 
    function animate() { 
 
    if(gameState === "playerMove") { 
 
     
 
    } else { 
 
     player1.acceptMove(); 
 
     player2.acceptMove(); 
 
     redraw(); 
 
    } 
 
    requestAnimationFrame(animate) 
 
    } 
 
    animate() 
 
}; 
 

 
function redraw() { 
 
    ctx.font="10px Sans-serif"; 
 
    ctx.fillStyle="#333333"; 
 
    ctx.fillRect(0,0,canvas.width,canvas.height); 
 
    ctx.fillStyle="#00FFFF"; 
 
    ctx.fillText(player1.count,100,50); 
 
    ctx.fillStyle="#FFFF00"; 
 
    ctx.fillText(player2.count,100,70); 
 
    ctx.fillStyle="#EEEEEE"; 
 
    ctx.fillText("PLAYER 1:", 40,50); 
 
    ctx.fillText("PLAYER 2:", 40,70); 
 
} 
 

 
function addPieceWithMouse() { 
 
    gameState = "playerMove"; 
 
} 
 

 
function finishMove() { 
 
    gameState = "normal"; 
 
} 
 

 
canvas.addEventListener("mousedown", addPieceWithMouse); 
 
canvas.addEventListener("mouseup", finishMove); 
 

 
var humanPlayer = function() { 
 
    this.count = 0; 
 
    this.acceptMove = function() { 
 
    this.count += Math.floor(Math.random()*2) 
 
    }; 
 
}; 
 

 
var computerPlayer = function() { 
 
    this.count = 0; 
 
    this.acceptMove = function() { 
 
    this.computerMove(); 
 
    }; 
 
    this.computerMove = function() { 
 
    this.count += Math.floor(Math.random()*2); 
 
    }; 
 
}; 
 

 

 
    
 
    initGameLoop();
<canvas id="can"></canvas>

Смежные вопросы