JavaScript 中的石头、纸、剪刀

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17976883/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 10:18:37  来源:igfitidea点击:

Rock, Paper, Scissors in JavaScript

javascript

提问by Godzdude

I'm working on making my first game (Rock Paper Sissors) and I ran into an issue where when the userChoiceis scissorsand the computerChoiceis rock, the program cannot return the winner as rock. I can get the program to give me the winner for any other combination.

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

I have my code here:

我的代码在这里:

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);

回答by

Something to study:

学习的东西:

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


Here's an alternate that will work for expanded sets. The assumption is that there's an odd number of possibilities, and from any given point, of the total number of opposition, reading forward from our given point (and wrapping around when we reach the end)the first half will win over the given point, and the second half will lose.

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

Or another way to describe it would be that the half of the remaining opponents that precede our given point will lose, and the half that follow will win.

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

Therefore the proper order in the choicesArray is crucial.

因此,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";
}

回答by James Montagne

You were unable to see the issue most likely due to poor indentation of your code. Properly indented the issue is clear:

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

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

Your if (choice1 === "scissors") {is within if (choice1 === "paper") {. The code within will never be reached.

if (choice1 === "scissors") {if (choice1 === "paper") {. 永远不会到达其中的代码。

回答by Paul

So many if statements. They are confusing.

这么多if语句。他们很困惑。

Also, all those if statements lock in the game and make it hard to reuse the logic for another game.

此外,所有这些 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));

回答by Paulo Almeida

I came up with an alternative that should be easy for you to understand and avoids some issues in your code, like excessive repetition and fixed choices. It is thus much more flexible and easier to maintain.

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

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

choices is var choices = ["rock", "paper", "scissors"];. You can see a demonstration.

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



To generalize the solution to larger lists, this modulo techniquecan be helpful:

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

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

Then it's much easier to write the comparison code:

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

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

The corresponding jsFiddle.

相应的jsfiddle

回答by Dan

You have a mismatched brace:

你有一个不匹配的括号:

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

I'd actually remove the last ifin that block, you don't need it. The last block (choice1 === "scissors") is correct, but again the last if is not required.

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

To show you whyit's failing in that particular way, I have re-indented the relevant part of your code to illustrate how it is being interpreted:

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

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

回答by ashley brandon

The solution I came to as a fellow novice seems relatively simple..

我作为新手的解决方案似乎比较简单..

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

回答by Ehsan

Try This :

试试这个 :

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 + ' ) ') ;

回答by Time

I got this to work:

我让这个工作:

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)
} 

All I changed was instead of returning a message, it pops up an alert with the answer. I also put it into one function that could be called on an HTML button click.

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

回答by gezzuzz

Example without all the {} and else if

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

always use else if when you can.. since your if statements are different cases and only one applies you should use else if..

如果可以的话,总是使用 else if.. 因为你的 if 语句是不同的情况,只有一种适用,你应该使用 else if..

with if statements if you only have 1 statement after the condition you don't need {} (condition 1 below).. even if you have a if.. else if...block statement its considered one statement..(condition 2 below).. but if it helps you can use them around the if.. else if...block statement to help your understand it better ..(condition 3 below).. ..

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

also don't use === unless you really know what it does.. it can cause you trouble being a rookie.. use == by default..

也不要使用 === 除非你真的知道它是做什么的..它会导致你成为菜鸟的麻烦..默认使用 == ..

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";

回答by rahuljaincse

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);