簡體   English   中英

在JavaScript中的岩石,紙,剪刀

[英]Rock, Paper, Scissors in JavaScript

我正在制作我的第一個游戲(Rock Paper Sissors),我遇到了一個問題,當userChoice剪刀而且computerChoice搖滾時 ,程序無法將獲勝者視為搖滾。 我可以讓程序給我任何其他組合的贏家。

我的代碼在這里:

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

要研究的東西:

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

由於代碼縮進不當,您無法看到問題。 正確縮進問題很清楚:

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") { 永遠不會達到內部代碼。

如此多的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));

我提出了一個替代方案,您應該很容易理解並避免代碼中的某些問題,例如過多的重復和固定的選擇。 因此,它更靈活,更易於維護。

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

你有一個不匹配的支具:

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

我作為一個新手來到的解決方案似乎相對簡單..

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

我得到了這個工作:

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按鈕點擊上調用的函數中。

沒有所有{}的示例,否則if

如果可以的話,總是使用else ..因為你的if語句是不同的情況,只有一個適用你應該使用else if ..

if if語句如果你在條件之后只有1個語句你不需要{}(下面的條件1)..即使你有一個if .. else if ... block語句它被認為是一個語句..(條件2下面)..但如果它有幫助你可以使用它們圍繞if .. else if ...塊語句來幫助你更好地理解它...(條件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";
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);
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;}
}
}

這個將創造一個完美的,自我重復的游戲,直到有人贏了。 它還會顯示您玩了多少游戲。 所有沒有使用循環!

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

這是我在本練習中所做的代碼,它就像一個魅力...我在我的“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); 

嘗試這個 :

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM