如何在不打字完整比较的情况下添加无限变化的石头剪刀布

我想在玩石头剪刀布游戏(steen, papier, schaar === rock, paper, scissor)时添加无数可供选择的选项。我查看了 Stackoverflow 并找到了一些解决方案,但我不知道如何在我自己的代码中实现它。

这是解决方案的链接,没有在我自己的代码中实现它:


let userScore = 0;

let computerScore = 0;

let userScore_span = document.getElementById("user-score");

let computerScore_span = document.getElementById("computer-score");

let scoreMessage = document.getElementById("score-message");

const schaar_div = document.getElementById("schaar");

const steen_div = document.getElementById("steen");

const papier_div = document.getElementById("papier");


// Computer choice

function getRandomChoise() {

const choises = ["schaar", "steen", "papier"];

const randomNumber = Math.floor(Math.random() * choises.length);

return choises[randomNumber];

}


function win() {

userScore++;

userScore_span.innerHTML = userScore;

scoreMessage.innerHTML = "<span style='color: green;'>You Won!</span>";

}


function lose() {

computerScore++;

computerScore_span.innerHTML = computerScore;

scoreMessage.innerHTML = "<span style='color: red;'>You Lost!</span>"

}


function draw() {

scoreMessage.innerHTML = "It's a Draw!"


}



function Game(userChoise) {

const computerChoise = getRandomChoise();

if (userChoise + computerChoise === "steenschaar") {

    win();

} else if (userChoise + computerChoise === "papiersteen") {

    win();

} else if (userChoise + computerChoise === "schaarpapier") {

    win();

} else if (userChoise + computerChoise === "steenpapier") {

    lose();

} else if (userChoise + computerChoise === "papierschaar") {

    lose();

} else if (userChoise + computerChoise === "schaarsteen") {

    lose();

} else if (userChoise + computerChoise === "schaarschaar") {

    draw();

} else if (userChoise + computerChoise === "steensteen") {

    draw();

} else if (userChoise + computerChoise === "papierpapier") {

    draw();

}



}


function main() {

schaar_div.addEventListener("click", function () {

    Game("schaar");

})


我希望能够为游戏添加无限数量的选项(lizzard、spock 等),而无需一遍又一遍地编写 else if 声明。


素胚勾勒不出你
浏览 178回答 3
3回答

函数式编程

您链接的文章为您提供了这种剪刀石头布的逻辑方法:泛化 对于 n >= 3 和 n 奇数:令 d = (n + a - b) % n。然后:如果 d = 0 => 平局如果 d % 2 = 1 => a 获胜如果 d % 2 = 0 => b 获胜你可以这样实现:// convert names to numbersconst options = {&nbsp; rock: 0,&nbsp; paper: 1,&nbsp; scissors: 2}// length of objectconst length = Object.keys(options).length// user inputconst user = options[prompt().toLowerCase()]// randomly generate input for opponentconst comp = Math.floor(Math.random() * Math.floor(length));// debugconsole.log(user, comp)// conditionsconst win = () => console.log('win')const lose = () => console.log('lose')const tie = () => console.log('tie')// calculate outputconst d = (length + user - comp) % length// d = 0 -> tie// d % 2 = 1 -> win// d % 2 = 0 -> losed ? d % 2 ? win() : lose() : tie()这种方法是自动扩展的;您可以在对象中再添加两个条目,代码将自动适应它。我将代码提取到一个函数中,让它更像一个游戏:// convert names to numbersconst options = {&nbsp; rock: 0,&nbsp; paper: 1,&nbsp; scissors: 2,&nbsp; spock: 3,&nbsp; lizard: 4}const condition = (input, comp, condition) => {&nbsp; switch (condition) {&nbsp; &nbsp; case 'win':&nbsp; &nbsp; &nbsp; order = [input, comp]&nbsp; &nbsp; &nbsp; break&nbsp; &nbsp; case 'lose':&nbsp; &nbsp; &nbsp; order = [comp, input]&nbsp; &nbsp; &nbsp; break&nbsp; &nbsp; case 'tie':&nbsp; &nbsp; &nbsp; order = [input]&nbsp; &nbsp; &nbsp; break&nbsp; }&nbsp;&nbsp;&nbsp; console.log(`You chose ${input}, and the opponent chose ${comp},`)&nbsp; order.length > 1&nbsp; &nbsp; ? console.log(`${order[0]} beats ${order[1]}.`)&nbsp; &nbsp; : console.log(`${order[0]} cannot beat iself.`)&nbsp; &nbsp;&nbsp;&nbsp; console.log(`You ${condition}.`)&nbsp;&nbsp;}const play = (input, options) => {&nbsp; input = options[input.toLowerCase()]&nbsp; var length = Object.keys(options).length&nbsp; var comp = Math.floor(Math.random() * Math.floor(length))&nbsp; var d = (length + input - comp) % length&nbsp;&nbsp;&nbsp; input = Object.keys(options)[input]&nbsp; comp = Object.keys(options)[comp]&nbsp;&nbsp;&nbsp; condition(input, comp, d ? d % 2 ? 'win' : 'lose' : 'tie')}const input = prompt()play(input, options)

肥皂起泡泡

我和乔纳斯威尔姆斯有同样的想法,但它让我有更多时间详细说明const win3 = { Rock:&nbsp; &nbsp; &nbsp;{ e: [ 'Scissors' ], m: [ 'Rock crushes Scissors'] },&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Paper:&nbsp; &nbsp; { e: [ 'Rock' ],&nbsp; &nbsp; &nbsp;m: ['Paper cover Rock']&nbsp; &nbsp; &nbsp; &nbsp;},&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Scissors: { e: [ 'Paper'],&nbsp; &nbsp; &nbsp;m: ['Scissors cuts Paper']&nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }const win5 = { Rock:&nbsp; &nbsp; &nbsp;{ e: [ 'Scissors', 'Lizard'&nbsp; &nbsp;], m: [ 'Rock crushes Scissors', 'Rock crushes Lizard'&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;] },&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Paper:&nbsp; &nbsp; { e: [ 'Rock'&nbsp; &nbsp; , 'Spock'&nbsp; &nbsp; ], m: [ 'Paper cover Rock',&nbsp; &nbsp; &nbsp; 'Paper disproves Spock'&nbsp; &nbsp; &nbsp; &nbsp;] },&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Scissors: { e: [ 'Paper'&nbsp; &nbsp;, 'Lizard'&nbsp; &nbsp;], m: [ 'Scissors cuts Paper',&nbsp; &nbsp;'Scissors decapitates Lizard' ] },&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Lizard:&nbsp; &nbsp;{ e: [ 'Paper'&nbsp; &nbsp;, 'Spock'&nbsp; &nbsp; ], m: [ 'Lizard eats Paper',&nbsp; &nbsp; &nbsp;'Lizard poisons Spock'&nbsp; &nbsp; &nbsp; &nbsp; ] },&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Spock:&nbsp; &nbsp; { e: [ 'Rock'&nbsp; &nbsp; , 'Scissors' ], m: [ 'Spock vaporizes Rock',&nbsp; 'Spock smashes Scissors'&nbsp; &nbsp; &nbsp; ] }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }let play&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; = win3&nbsp; // win5 .. win1000...,&nbsp; &nbsp;userScore&nbsp; &nbsp; &nbsp;= 0,&nbsp; &nbsp;computerScore = 0;function game ( userChoice, computerChoice ){&nbsp; if (userChoice == computerChoice )&nbsp; {&nbsp; &nbsp; console.log(' same values , no one score')&nbsp; &nbsp; return&nbsp; }&nbsp; if (play[userChoice].includes(computerChoice) )&nbsp; {&nbsp; &nbsp; userScore++&nbsp; &nbsp; let n = play[userChoice].e.findIndex(e=>e===computerChoice )&nbsp; &nbsp; console.log( play[userChoice].m[n] )&nbsp; }&nbsp; else&nbsp; {&nbsp; &nbsp; computerScore++&nbsp; &nbsp; let n = play[computerChoice].e.findIndex(e=>e===userChoice )&nbsp; &nbsp; console.log( play[computerChoice].m[n] )&nbsp; }}

RISEBY

您可以将两个可能选项之间的关系表示为一棵树:&nbsp; const winsOver = {&nbsp; &nbsp; schaar: ["papier"],&nbsp; &nbsp; steen: ["schaar"],&nbsp; &nbsp; papier: ["steen"],&nbsp;};现在您的比较变得非常简单:&nbsp;if(userChoice === computerChoice) {&nbsp; &nbsp;draw();&nbsp;} else if(winsOver[userChoice].includes(computerChoice)) {&nbsp; &nbsp;win();&nbsp;} else lose();
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript