如果你真的想用原型做到这一点,你可以像这样创建一个播放器对象:
function Player() {
this.position = 0; //the player's current position starts at zero
this.questionsCorrect = 0; //number of questions this player has answered
}
Player.prototype.move = function(spaces) { //use prototype to give ALL player objects a "move" function
this.position += spaces; //increment the player's position
}
老实说,你不应该为这么简单的游戏需要对象,但这应该留有足够的扩展空间。现在,您需要一些代码来管理游戏。
//make two new players
var player1 = new Player();
var player2 = new Player();
var currentPlayer = player1; //it starts as player 1's turn
现在,您需要一个游戏循环。
function gameStep() {
for (var i=0; i<5; i++) { //your outline doesn't really make sense, but I assume you want each player to be asked 5 questions at a time
var result = askQuestionTo(currentPlayer); //ask a question to whomever's turn it is
if (result==answer) {
currentPlayer.questionsCorrect += 1; //increment correct counter for this player
}
else {
currentPlayer.move(-2); //move two backwards if incorrect
//you talk about "losing a turn", but that doesn't really make sense here.
//please clarify.
}
}
var diceRoll = 1+Math.floor(Math.random()*12); //calculate a random dice number
if (currentPlayer.questionsCorrect>=3) {
currentPlayer.move(diceRoll); //if at least three correct, move forward
}
else {
currentPlayer.move(-diceRoll); //otherwise, move backward
}
currentPlayer.move(2); //you said that the player moves forward two regardless
currentPlayer.questionsCorrect = 0;
currentPlayer = currentPlayer==player1?player2:player1; //it's the other player's turn
}
你必须实现 askQuestion 来询问玩家一些问题,并且你必须以某种方式将 answer 替换为正确的答案(可能来自一个数组)。现在,你必须重复调用 gameStep() 来让游戏运行。
var boardLength = 50;
while (player1.position<boardLength && player2.position<boardLength) {
gameStep(); //keep doing turns until someone wins;
}
if (player1.position>player2.position) {alert("Player1 wins!");}
else {alert("Player2 wins!");}
我不知道你希望游戏什么时候结束,所以在这个例子中,是谁先走到棋盘的尽头。你问了一个非常广泛的问题,所以我试图包括很多细节。如果您需要澄清,请发表评论。