【问题标题】:Rock, Paper, Scissors, Lizard, Spock in JavaScriptJavaScript 中的石头、纸、剪刀、蜥蜴、Spock
【发布时间】:2014-03-25 00:35:43
【问题描述】:

我对 JavaScript 有点陌生。我刚开始学习它,我决定制作一个“石头、纸、剪刀、蜥蜴、史波克”的游戏。这是代码:

var userChoice = prompt("Do you choose rock, paper, scissors, lizard, or spock?")
var computerChoice = Math.random();
if (computerChoice < 0.2) {
    computerChoice = "rock";
} else if (computerChoice <= 0.4) {
    computerChoice = "paper";
} else if (computerChoice <= 0.6) {
    computerChoice = "scissors";
} else if (computerChoice <= 0.8) {
    computerChoice = "lizard";
} else {
    computerChoice = "spock";
}

alert("The computer chose " + computerChoice);

var compare = function(choice1, choice2){
    if (choice1 === choice2) {
        alert("And... It's a tie!");
    }

//If the user chose rock...
else if (choice1 === "rock") {
    if (choice2 === "scissors") {
        alert("Rock wins!");
    } else if (choice2 === "paper") {
        alert("Paper wins!");
    } else if (choice2 === "lizard") {
        alert("Rock wins!");
    } else {
        alert("Spock wins!");
    }
}

//If the user chose paper...
else if (choice1 === "paper") {
    if (choice2 === "scissors") {
        alert("Scissors wins!");
    } else if (choice2 === "rock") {
        alert("Paper wins!");
    } else if (choice2 === "lizard") {
        alert("Lizard wins!");
    } else {
        alert("Paper wins!");
    }
}

//If the user chose scissors...
else if (choice1 === "scissors") {
    if (choice2 === "paper") {
        alert("Scissors wins!");
    } else if (choice2 === "rock") {
        alert("Rock wins!");
    } else if (choice2 === "lizard") {
        alert("Scissors wins!");
    } else {
        alert("Spock wins!");
    }
}

//If the user chose lizard...
else if (choice1 === "lizard") {
    if (choice2 === "scissors") {
        alert("Scissors wins!");
    } else if (choice2 === "rock") {
        alert("Rock wins!");
    } else if (choice2 === "paper") {
        alert("Lizard wins!");
    } else {
        alert("Lizard wins!");
    }
}

//If the user chose spock...
else if (choice1 === "spock") {
    if (choice2 === "scissors") {
        alert("Spock wins!");
    } else if (choice2 === "rock") {
        alert("Spock wins!");
    } else if (choice2 === "lizard") {
        alert("Lizard wins!");
    } else {
        alert("Paper wins!");
    }
}
};
compare(userChoice, computerChoice);

我想在我的代码中添加两个主要内容,但我不知道如何:

  1. 现在,如果用户输入,例如,带有大写“R”的“Rock”,它不会被识别为五个有效输入之一(石头、纸、剪刀、蜥蜴和斯波克)。有没有办法让它在用户输入有效的大写字母(或多个字母)时仍然有效?

  2. 我想添加一些内容,以便每当有人输入无效的内容(例如“树懒”)时,它会提醒他们输入无效,并再次要求他们输入石头、纸、剪刀、蜥蜴,或spock。

【问题讨论】:

  • choice1.toLowerCase()
  • 考虑使用switch 语句,让事情变得更加清晰,您可以指定一个“默认”,只要其他选择都不为真,该默认值就会运行,因此您可以在default: alert("sorry your selection was invalid") break; 下设置
  • 这个问题真的是关于石头剪刀布的问题,还是关于如何让 JavaScript 将大写输入识别为小写输入?
  • 最近Too many 'if' statements? 关于简化 swith 语句,当两名玩家每人使用 4 个选项进行战斗时。它真的很相似,并且有很多很好的答案。我推荐使用矩阵方法来表示您的数据。另外,它是 PHP,但是对于这个 case 来说几乎是一样的。

标签: javascript


【解决方案1】:

用数学简化结果函数。 http://jsfiddle.net/afrievalt/qBbJn/

var options = ["paper", "rock", "lizard", "spock", "scissors"],
  result = [" ties ", " beats ", " loses to "],
  bigBang = function(choice1, choice2) {
      var index1 = options.indexOf(choice1), //spock => 3
          index2 = options.indexOf(choice2), //rock=> 1
          dif = index2 - index1; // 1 - 3 => -2
      if(dif < 0) { // -2 < 0 => truthy
          dif += options.length; // -2 + 5 => 3
      }
      while(dif > 2) { //3 > 2 => truthy
          dif -= 2; // 3 - 2 => 1
      }
      return choice1 + result[dif] + choice2; //spock beats rock
  };

.

  bigBang("spock", "paper");  // spock losses to paper 

  var i = Math.floor(Math.random() * 5),
      randomChoice = options[i];
  bigBang(randomChoice, userChoice);

此函数也适用于 options = ["cockroach", "nuke", "shoe"],(来自 70 年代的节目)或任何奇数长度数组,例如 options = ["water", "fire", "paper ”、“岩石”、“树”、“金属”、“泥”] //todo: 如果任何 index = -1 则抛出错误

【讨论】:

  • +1 indexOf .... 现在我为什么没想到!我必须借用来改进我的答案!
【解决方案2】:

让我们在这方面进行面向对象。它将减少逻辑中的重复:

//Set up the choices with what they can beat
//This is a hash table of objects you can referecne by name
var choices  =  {rock : {name: "Rock", defeats: ["scissors","lizard"]},
                 paper: {name: "Paper", defeats: ["rock", "spock"]},
                 scissors: {name: "Scissors", defeats: ["paper", "lizard"]},
                 lizard: {name: "Lizard", defeats:["paper","spock"]},
                 spock: {name: "Spock", defeats:["scissors","rock"]}
                };


//Get the computers choice
var computerChoice = Math.random();
if (computerChoice < 0.2) {
    computerChoice = "rock";
} else if (computerChoice <= 0.4) {
    computerChoice = "paper";
} else if (computerChoice <= 0.6) {
    computerChoice = "scissors";
} else if (computerChoice <= 0.8) {
    computerChoice = "lizard";
} else {
    computerChoice = "spock";
}


//Get the users choice, normalising to lower case    
var userChoice = prompt("Do you choose rock, paper, scissors, lizard, or spock?").toLowerCase();

alert("The computer chose " + computerChoice);    

//Check for a tie
if(computerChoice == userChoice){
    alert("It's a tie");
//Check for a valid choice
}else if(choices[userChoice] === undefined){
    alert("Invalid Choice");
}else{
    //Get the chosen one as an object
    userChoice = choices[userChoice];



    //Check For a win
    /*var victory = false;
    for(var i = 0; i < userChoice.defeats.length; i++){
        if(computerChoice == userChoice.defeats[i])
        {
            victory = true;
            break;
        }
    }*/

    //Improved check, inspired by Mke Spa Guy
    var victory = userChoice.defeats.indexOf(computerChoice) > -1;

    //Display result
    if(victory) {
        alert("Vitory! " + userChoice.name + " wins!")
    }else{
        alert("Defeat, " + computerChoice + " wins!");
    }   
}

就是这样,Spocks 是你的叔叔。

Demo

Demo with full action : 例如:Paper Covers Rock;

更多阅读:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Introduction_to_Object-Oriented_JavaScript

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects

http://www.mojavelinux.com/articles/javascript_hashes.html

【讨论】:

    【解决方案3】:

    我会编写一个函数来获得正确的响应,而不是全部内联......这就是我......

    function getUserChoice(){
        var invalidPin = true;
        var response;
        while(invalidPin){
            response = prompt("choose your thing..");
                if(response == "rock" || response == "paper" || response == "scizerz"){
                    invalidPin = false;
                }
            }
        }
        return response;
    }
    

    那么你只需调用函数就可以得到用户的选择

    var userChoice = getUserChoice();
    

    【讨论】:

      【解决方案4】:

      正如一些用户所提到的,最好的比较方法是将输入转换为小写。

      对于您的第二点,我会将输入解析包装在一个循环中,如下所示:

      while(true){
          var input = getInput();
      
          if(isValid(input)){
              // check for the winner
              break;
          }else{
              // tell the user that their input is invalid
          }
      }
      

      【讨论】:

        【解决方案5】:

        我会做如下的事情(请注意语法可能略有偏差):

        var compare = function (choice1, choice2)
        {
            switch (choice1.tolower())
            {
                case "rock"
                    RockPicked(choice2);
                    break;
                case "scissors"
                    ScissorsPicked(choice2);
                    break;
                ....
                ....
                case default
                    alert ("Selection was invalid")
                    break;
            }
        
        }
        
        // if the user picked rock then we compare the computers choice and decide winner
        var RockPicked = function(choice2)
        {
            if (choice2 === "scissors") 
            {
                alert("Rock wins!");
            } 
            else if (choice2 === "paper") 
            {
                alert("Paper wins!");
            } 
            else if (choice2 === "lizard") 
            {
                alert("Rock wins!");
            } 
            else 
            {
                alert("Spock wins!");
            }
        }
        

        【讨论】:

          【解决方案6】:

          如果您帮助自己制作一张像这样的组合表 -
          https://commons.wikimedia.org/wiki/File:Normal_form_matrix_of_Rock-paper-scissors-lizard-Spock.jpg

          我使用 2 而不是 -1(0 - 平局;1 - 排赢;2 - 排输)

          那么你的代码就变成了:

              var options=["Rock","Paper","Scissors","Lizard","Spock"]
              var outcomes=[[0,2,1,1,2],[1,0,2,2,1],[2,1,0,1,2],[2,1,2,0,1],[1,2,1,2,0]]
          
              function RPSLS(user){
          
              var computer=Math.floor(Math.random()*5);
          
              if (outcomes[user][computer]==0){alert("Tie");}
              if (outcomes[user][computer]==1){alert("User Wins");}
              if (outcomes[user][computer]==2){alert("Computer Wins");}
              txt1.value=options[user];
              txt2.value=options[computer];}
          

          然后是输出的HMTL部分:

              Please choose:<br>
              <button onclick="RPSLS(0)">Rock</button>
              <button onclick="RPSLS(1)">Paper</button>
              <button onclick="RPSLS(2)">Scissors</button>
              <button onclick="RPSLS(3)">Lizard</button>
              <button onclick="RPSLS(4)">Spock</button>
              <button onclick="RPSLS(Math.floor(Math.random()*4))">Random    Game</button><P>
              <textarea id="txt1"></textarea><textarea id="txt1"></textarea>
          

          【讨论】:

            猜你喜欢
            • 2015-01-25
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2014-11-21
            相关资源
            最近更新 更多