存储球员转身

时间:2013-06-15 22:48:36

标签: javascript

我必须在JavaScript中只为两名玩家做一个琐事游戏。 根据投掷骰子后落下的“盒子”,规则是:

  1. 他们必须回答一个问题;如果他们回答正确,他们会留下来 在那个地方;否则他们必须回到两个地方。
  2. 他们失去了一个回合。
  3. 正确回答五个问题中的三个:如果回答正确,掷骰子并推进给定的数字,如果回答错误,请返回该号码。
  4. 正确回答一个问题并提前两个方框,否则留下来 到位。
  5. 自动前进两个位置。
  6. 您认为哪种方式最佳存储方式? 我正在考虑使用像"Inheritance and the prototype chain"这样的东西,但我不太清楚如何使用它,因为我还没有学到它。 有任何想法吗?谢谢! :d

1 个答案:

答案 0 :(得分: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来向玩家询问一些问题,并且你必须以某种方式用正确的答案替换答案(可能来自数组。)现在,你必须反复调用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!");}

我不知道你什么时候想要游戏结束,所以在这个例子中,无论谁先到达董事会的最后。你提出了一个非常广泛的问题,所以我试图包含很多细节。如果您需要澄清,请发表评论。