0

我必须用 JavaScript 为两个玩家做一个琐事游戏。根据掷骰子后落入哪个“盒子”,规则如下:

  1. 他们必须回答一个问题;如果他们回答正确,他们会留在那个地方;否则他们必须回到两个地方。
  2. 他们失去了一个回合。
  3. 正确回答五个问题中的三个:如果回答正确,掷骰子并推进给定的数字,如果回答错误,则返回那个数字。
  4. 正确回答一个问题并推进两个方框,否则留在原地。
  5. 自动前进两个位置。

你认为哪个是轮到谁存储的最佳方式?我正在考虑使用类似“继承和原型链”的东西,但我不太确定如何使用它,因为我还没有学会它。有任何想法吗?谢谢!:D

4

1 回答 1

1

如果你真的想用原型做到这一点,你可以像这样创建一个播放器对象:

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!");}

我不知道你希望游戏什么时候结束,所以在这个例子中,是谁先走到棋盘的尽头。你问了一个非常广泛的问题,所以我试图包括很多细节。如果您需要澄清,请发表评论。

于 2013-06-15T23:27:10.270 回答