8

我正在制作我的第一个游戏(Rock Paper Sissors),我遇到了一个问题,当userChoicescissors并且computerChoicerock时,程序无法将获胜者返回为摇滚。我可以让程序给我任何其他组合的赢家。

我在这里有我的代码:

var userChoice = prompt("Do you choose rock, paper or scissors?");
var computerChoice = Math.random();
if (computerChoice < 0.34) {
    computerChoice = "rock";
} else if(computerChoice <= 0.67) {
    computerChoice = "paper";
} else {
    computerChoice = "scissors";
}

var compare = function(choice1, choice2) {
    if(choice1 === choice2) {
    return "The result is a tie!";
}
if(choice1 === "rock") {
    if(choice2 === "scissors") {
        return "rock wins";
    } else {
        return "paper wins";
    }
}
if(choice1 === "paper") {
    if(choice2 === "rock") {
        return "paper wins";
    } else {
        if(choice2 === "scissors") {
            return "scissors wins";
    }
}
if(choice1 === "scissors") {
    if(choice2 === "rock") {
        return "rock wins";
    } else {
        if(choice2 === "paper") {
            return "scissors wins";
        }
    }
}
}
};
console.log("User Choice: " + userChoice);
console.log("Computer Choice: " + computerChoice);
compare(userChoice, computerChoice);
4

14 回答 14

18

学习的东西:

var choices = ["rock", "paper", "scissors"];
var map = {};

choices.forEach(function(choice, i) {
    map[choice] = {};
    map[choice][choice] = "Was a tie"
    map[choice][choices[(i+1)%3]] = choices[(i+1)%3] + " wins"
    map[choice][choices[(i+2)%3]] = choice + " wins"
})

function compare(choice1, choice2) {
    return (map[choice1] || {})[choice2] || "Invalid choice";
}

这是适用于扩展集的替代方法。假设有奇数个可能性,并且从任何给定点来看,反对的总数,从我们给定的点向前阅读(并在我们到达终点时环绕)上半场将赢得给定的点,下半场会输。

或者另一种描述它的方式是,在我们给定点之前的剩余对手中的一半将输,而在我们给定点之后的一半将获胜。

因此,数组中的正确顺序choices至关重要。

var choices = ["rock", "spock", "paper", "lizard", "scissors"];
var map = {};

choices.forEach(function(choice, i) {
    map[choice] = {};
    for (var j = 0, half = (choices.length-1)/2; j < choices.length; j++) {
        var opposition = (i+j)%choices.length
        if (!j)
            map[choice][choice] = "Was a tie"
        else if (j <= half)
            map[choice][choices[opposition]] = choices[opposition] + " wins"
        else
            map[choice][choices[opposition]] = choice + " wins"
    }
})

function compare(choice1, choice2) {
    return (map[choice1] || {})[choice2] || "Invalid choice";
}
于 2013-07-31T17:58:15.707 回答
10

由于代码缩进不佳,您很可能无法看到问题。正确缩进问题很清楚:

if (choice1 === "paper") {
    if (choice2 === "rock") {
        return "paper wins";
    } else {
        if (choice2 === "scissors") {
            return "scissors wins";
        }
    }
    if (choice1 === "scissors") {
        if (choice2 === "rock") {
            return "rock wins";
        } else {
            if (choice2 === "paper") {
                return "scissors wins";
            }
        }
    }
}

if (choice1 === "scissors") {if (choice1 === "paper") {. 永远无法访问其中的代码。

于 2013-07-31T17:25:36.360 回答
3

我想出了一个让你容易理解的替代方案,并避免了代码中的一些问题,比如过度重复和固定选择。因此,它更加灵活且易于维护。

function compare(choice1, choice2) {
    choice1 = choices.indexOf(choice1);
    choice2 = choices.indexOf(choice2);
    if (choice1 == choice2) {
        return "Tie";
    }
    if (choice1 == choices.length - 1 && choice2 == 0) {
        return "Right wins";
    }
    if (choice2 == choices.length - 1 && choice1 == 0) {
        return "Left wins";
    }
    if (choice1 > choice2) {
        return "Left wins";
    } else {
        return "Right wins";
    }
}

选择是var choices = ["rock", "paper", "scissors"];。你可以看一个演示


要将解决方案推广到更大的列表,这种模技术可能会有所帮助:

function mod(a, b) {
    c = a % b
    return (c < 0) ? c + b : c
}

那么写比较代码就容易多了:

function compare(choice1, choice2) {
    x = choices.indexOf(choice1);
    y = choices.indexOf(choice2);
    if (x == y) {
        return "Tie";
    }
    if (mod((x - y), choices.length) < choices.length / 2) {
        return choice1 + " wins";
    } else {
        return choice2 + " wins";
    }
}

对应的jsFiddle

于 2013-07-31T20:46:52.200 回答
2

这么多 if 语句。他们令人困惑。

此外,所有这些 if 语句都会锁定游戏,并且很难将逻辑重用于另一个游戏。

function referee(){
    var training = {};
    function learn(winner,loser){
        if (!training[winner]) training[winner] = {};
        training[winner][loser]=1;
    }
    function judge(play1,play2){
        if (play1 === play2){ return 'tie'; }
        return ( (training[play1][play2] === 1)? play1: play2 )+' wins!';
    }
    function validate(choice) {
        return choice in training;
    }
    function choices() {
        return Object.keys(training);
    }
    return {
        'learn': learn,
        'judge': judge,
        'validAction': validate,
        'getChoices': choices
    };
}

var ref = referee();
ref.learn('rock','scissors');
ref.learn('paper','rock');
ref.learn('scissors','paper');

do {
    var userChoice = prompt("Do you choose rock, paper or scissors?");
} while(!ref.validAction(userChoice))
var choices = ref.getChoices(),
    computerChoice = choices[Math.floor(Math.random()*choices.length)];

console.log("User Choice: " + userChoice);
console.log("Computer Choice: " + computerChoice);
console.log(ref.judge(userChoice, computerChoice));
于 2013-07-31T17:48:20.473 回答
1

你有一个不匹配的括号:

if(choice1 === "paper") {
    if(choice2 === "rock") {
        return "paper wins";
    } else {
        if(choice2 === "scissors") {
            return "scissors wins";
    }
}

我实际上会删除该if块中的最后一个,您不需要它。最后一个块 ( choice1 === "scissors") 是正确的,但最后一个 if 不是必需的。

为了向您展示为什么它以这种特定方式失败,我重新缩进了代码的相关部分以说明它是如何被解释的:

if(choice1 === "paper") {
    if(choice2 === "rock") {
        return "paper wins";
    } else {
        if(choice2 === "scissors") {
            return "scissors wins";
        }
    }
    if(choice1 === "scissors") {
        if(choice2 === "rock") {
            return "rock wins";
        } else {
            if(choice2 === "paper") {
                return "scissors wins";
            }
        }
    }
}
于 2013-07-31T17:24:07.110 回答
1

这就是我的做法:


    //player choice
    var playerChoice = prompt("What is your choice of weapon: rock, paper, or scissors?");
    
    //Computer Choice
    var computerChoice = Math.ceil(Math.random() *3);
    
    //variables as numbers
    if (computerChoice < 1) {
        computerChoice = "rock";
    } else if(1 <= computerChoice <= 2) {
        computerChoice = "paper";
    } else {
        computerChoice = "scissors";
    }
    
    
    //defining function
    function game(playerChoice, computerChoice){
    
    //Checking for a tie
    if (playerChoice === computerChoice) {
          return "It is a tie";
        }
    
        //Check for Rock
        if (playerChoice === "rock") {
          if (computerChoice === "scissors") {
            return "Player Wins";
          } else {
            return "Computer Wins";
          }
        }
        //Check for Paper
        if (playerChoice === "paper") {
          if (computerChoice === "scissors") {
            return "Computer Wins";
          } else {
            return "Player Wins";
          }
        }
        //Check for Scissors
        if (playerChoice === "scissors") {
          if (computerChoice === "rock") {
            return "Computer Wins";
          } else {
                    return "Player Wins";
          }
        }
    }
    
    //start the game function
    game();
    //print winner
    console.log(game(playerChoice, computerChoice))

我选择让我的计算机选择是随机的,整数,0-3,但你可以把那部分去掉。

于 2021-05-07T03:02:05.953 回答
0

我得到了这个工作:

function playFunction() {
var userChoice = prompt("Do you choose rock, paper or scissors?");
var computerChoice = Math.random();
if (computerChoice < 0.34) {
    computerChoice = "rock";
} else if(computerChoice <= 0.67) {
    computerChoice = "paper";
} else {
    computerChoice = "scissors";
}

var compare = function(choice1, choice2) {
    if(choice1 === choice2) {
      alert("The result is a tie!");
}
if(choice1 === "rock") {
    if(choice2 === "scissors") {
        alert("rock wins");
    } else {
        alert("paper wins");
    }
}
if(choice1 === "paper") {
    if(choice2 === "rock") {
        alert("paper wins");
    } else {
        if(choice2 === "scissors") {
            alert("scissors wins");
    }
}
if(choice1 === "scissors") {
    if(choice2 === "rock") {
        alert("rock wins");
    } else {
        if(choice2 === "paper") {
           alert("scissors wins");
        }
    }
}
}
};
console.log("User Choice: " + userChoice);
console.log("Computer Choice: " + computerChoice);
compare(userChoice, computerChoice)
} 

我所做的只是没有返回一条消息,而是弹出一个带有答案的警报。我还将它放入一个可以在单击 HTML 按钮时调用的函数中。

于 2013-07-31T17:58:33.740 回答
0

没有所有 {} 和 else if 的示例

如果可以,请始终使用 else if.. 因为您的 if 语句是不同的情况,并且只有一个适用,所以您应该使用 else if..

使用 if 语句,如果您在不需要 {} 的条件之后只有 1 个语句(下面的条件 1).. 即使您有 if.. else if...block 语句,它也被视为一个语句..(条件 2下面).. 但如果它有帮助,您可以在 if.. else if...block 语句周围使用它们来帮助您更好地理解它..(下面的条件 3).. ..

也不要使用 === 除非你真的知道它的作用.. 它可能会给你作为菜鸟带来麻烦.. 默认使用 ==..

if(choice1 == choice2)  //condition 1
    return "The result is a tie!";
else if(choice1 == "rock") //condition 2
    if(choice2 == "scissors") 
        return "rock wins";
     else 
        return "paper wins";
else if(choice1 == "paper"){ //condition 3
    if(choice2 == "rock") 
        return "paper wins";
     else 
        return "scissors wins";
}
else if(choice1 == "scissors")
    if(choice2 == "rock")
       return "rock wins";
    else 
       return "scissors wins";
于 2013-07-31T19:39:16.873 回答
0
var userChoice = prompt("Do you choose rock, paper or scissors? ");


var computerChoice=Math.random();

{


if(computerChoice <= ".33") 

{
    computerChoice === 'rock';


    }


    else if(computerChoice<='.66' & '>=.34')


    {

computerChoice === 'paper';


        }

        else

{

            computerChoice ===' scissors';


            }


            }


console.log( computerChoice);
于 2014-05-20T05:57:33.547 回答
0
var compare = function (choice1, choice2)
{
    if (choice1 === choice2)
    {
        return "The result is a tie!";
    }
    else
    {
        if(choice1 === "rock")
        {
            if(choice2 === "paper")
            {
               return "Paper beats rock. Computer Wins.";
            }
            else
            {
                return "Rock beats scissors. You win.";

            }
        }
        else
        {
            if(choice1 === "paper")
                {
                     if(choice2 === "rock")
                        {
                             return "Paper beats rock. You Win.";
                        }
            else
                {
                return "Scissors beat paper. Computer Wins.";               }

                }
    if(choice1 === "scissors")
                {
                     if(choice2 === "rock")
                        {
                             return "Rock beats scissors. Computer Wins.";
                        }
            else
                {
                return "Scissors beat paper. You Win.";               }

                }
        }
    }



};
var r = function(user)
{
    while(user < 0 | user >3)
    {user = prompt("Please don't act oversmart. Press '1' for rock, '2' for paper, and '3' for scissors.");
    }

    if(user === "1")
    user = "rock";

    else
    {
        if(user === "2")
        {user = "paper";}
        else
        {user = "scissors";}
    };
    console.log("You chose: " + user);

    computerChoice = Math.random()
    if(computerChoice <= 0.33)
    {
        computerChoice = "rock";
    }
    else
    {
        if(computerChoice > 0.33 && computerChoice <=0.66)
        {computerChoice = "paper";}
        else
        {computerChoice = "scissors";}
    }

    console.log("The computer chose: "+computerChoice)
    console.log(compare(user, computerChoice));
    if(user===computerChoice)
    {
        userChoice = user;
        return "1";}

};


var userChoice = prompt("Press '1' for rock, '2' for paper, and '3' for scissors")
var computerChoice;

var a = r(userChoice);
if(a === "1")
{//console.log("1");
while(userChoice === computerChoice)
{
    var a = prompt("Since there was a tie, please choose again. Press 1 for rock, 2 for paper and 3 for scissors.")
    var b = r(a);
    if(b !== "1")
    {break;}
}
}
于 2014-08-16T13:55:18.330 回答
0

这将创造完美的、自我重复的游戏,直到有人获胜。它还显示您玩了多少游戏。全部不使用循环!

count = 1;

var Decisions = function() {
    if (count === 1) {
        userChoice = prompt("Do you choose rock, paper or scissors?");
    } else {
        userChoice = prompt("It's a tie. Please make your choice again!");
    }
    computerChoice = Math.random();

    if (computerChoice < 0.4) {
        computerChoice = "rock";
    } else if(computerChoice <= 0.8) {
        computerChoice = "paper";
    } else {
        computerChoice = "scissors";
    }
    console.log("User: " + userChoice);
    console.log("Computer: " + computerChoice);
}

Decisions();

var compare = function(choice1, choice2) {
    if (choice1 === choice2) {

        count = count + 1
        console.log("The result is a tie!");
        Decisions();
        return compare(userChoice, computerChoice);

    } else if (choice1 === "rock") {
        if (choice2 === "scissors") {
            return "rock wins";
        } else {
            return "paper wins";
        }
    } else if (choice1 === "paper") {
        if (choice2 === "rock") {
            return "paper wins";
        } else {
            return "scissors wins";
        }
    } else if (choice1 === "scissors") {
        if (choice2 === "paper") {
            return "scissors win";
        } else {
            return "rock wins";
        }
    }
}

console.log(compare(userChoice,computerChoice));
console.log("Wow, you played " + count + " times!");
于 2016-03-11T07:32:49.830 回答
0

这是我在这个练习中编写的代码,它就像一个魅力......我在我的“if”语句中使用了逻辑运算符,它被接受了(显然)。

试试看 :D

var userChoice = prompt("Do you choose rock, paper or scissor?");
var computerChoice = Math.random();
if (computerChoice > 0 && computerChoice < 0.33) {
  computerChoice = "Rock";
} else if (computerChoice > 0.34 && computerChoice < 0.67) {
  computerChoice = "Paper";
} else {
  computerChoice = "Scissor";
}
console.log(computerChoice);

于 2016-04-14T02:06:16.720 回答
0

我作为新手的解决方案似乎相对简单..

var userChoice = prompt ("Do you choose rock, paper or scissors?");

var computerChoice = Math.random();
console.log(computerChoice);

if (computerChoice <=0.33) {
    "rock";
} else if (computerChoice <=0.66) {
    "paper";
} else {
    "scissors";
}
于 2016-08-09T19:38:37.190 回答
0

试试这个 :

var UserChoice = window.prompt("Do you choose rock, paper or scissors ?");

var computChoice = Math.random();

var computChoice = computChoice < 0.34 ? "rock" : ( computChoice > 0.67 ? "scissors" : "paper" ) ;

var mess = { 
  rock : { scissors : 'You Win!, Rock smashes scissors!', paper : 'You lose!, Paper covers rock!'} ,
  paper : { rock : 'You Win!, Paper covers rock!', scissors : 'You lose!, Scissors cut paper!' },
  scissors : { paper : 'You Win!, Scissors cut paper!', rock : 'You lose!, Rock smashes scissors!' }
}

if ( computChoice === UserChoice)
  result = "It's a tie!" ; 
	 
else if ( UserChoice !== "rock" && UserChoice !== "paper" && UserChoice !== "scissors" )
  result = "Invalid choice! Choose from rock, paper, or scissors" ;

else
  result = mess[UserChoice][computChoice] ;

console.log( 'you chose ' + UserChoice + ' and computer chose ' + computChoice + ' ( ' + result + ' ) ') ;

于 2019-02-25T10:15:39.883 回答