我有一个游戏循环,在每个玩家移动后重新绘制游戏板。我想暂停主循环并等待玩家在棋盘上放置一块,即在画布上触发鼠标按下事件。现在游戏循环继续重绘棋盘。有没有办法在继续循环之前等待玩家移动?
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();
};
};
答案 0 :(得分: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>
&#13;