2015-11-21 57 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>

相关问题