为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

素胚勾勒不出你 2021-07-01 09:00:09
我想在玩石头剪刀布游戏(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 choicefunction 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 声明。
查看完整描述

3 回答

?
函数式编程

TA贡献1807条经验 获得超9个赞

您链接的文章为您提供了这种剪刀石头布的逻辑方法:


泛化 对于 n >= 3 和 n 奇数:


令 d = (n + a - b) % n。然后:


如果 d = 0 => 平局


如果 d % 2 = 1 => a 获胜


如果 d % 2 = 0 => b 获胜


你可以这样实现:


// convert names to numbers

const options = {

  rock: 0,

  paper: 1,

  scissors: 2

}


// length of object

const length = Object.keys(options).length


// user input

const user = options[prompt().toLowerCase()]


// randomly generate input for opponent

const comp = Math.floor(Math.random() * Math.floor(length));


// debug

console.log(user, comp)


// conditions

const win = () => console.log('win')

const lose = () => console.log('lose')

const tie = () => console.log('tie')


// calculate output

const d = (length + user - comp) % length


// d = 0 -> tie

// d % 2 = 1 -> win

// d % 2 = 0 -> lose

d ? d % 2 ? win() : lose() : tie()

这种方法是自动扩展的;您可以在对象中再添加两个条目,代码将自动适应它。我将代码提取到一个函数中,让它更像一个游戏:


// convert names to numbers

const options = {

  rock: 0,

  paper: 1,

  scissors: 2,

  spock: 3,

  lizard: 4

}


const condition = (input, comp, condition) => {

  switch (condition) {

    case 'win':

      order = [input, comp]

      break

    case 'lose':

      order = [comp, input]

      break

    case 'tie':

      order = [input]

      break

  }

  

  console.log(`You chose ${input}, and the opponent chose ${comp},`)


  order.length > 1

    ? console.log(`${order[0]} beats ${order[1]}.`)

    : console.log(`${order[0]} cannot beat iself.`)

    

  console.log(`You ${condition}.`)

  

}



const play = (input, options) => {

  input = options[input.toLowerCase()]


  var length = Object.keys(options).length

  var comp = Math.floor(Math.random() * Math.floor(length))

  var d = (length + input - comp) % length

  

  input = Object.keys(options)[input]

  comp = Object.keys(options)[comp]

  

  condition(input, comp, d ? d % 2 ? 'win' : 'lose' : 'tie')

}



const input = prompt()

play(input, options)


查看完整回答
反对 回复 2021-07-08
?
肥皂起泡泡

TA贡献1829条经验 获得超6个赞

我和乔纳斯威尔姆斯有同样的想法,但它让我有更多时间详细说明


const win3 = { Rock:     { e: [ 'Scissors' ], m: [ 'Rock crushes Scissors'] }

,              Paper:    { e: [ 'Rock' ],     m: ['Paper cover Rock']       }

,              Scissors: { e: [ 'Paper'],     m: ['Scissors cuts Paper']    }

            }


const win5 = { Rock:     { e: [ 'Scissors', 'Lizard'   ], m: [ 'Rock crushes Scissors', 'Rock crushes Lizard'         ] }

,              Paper:    { e: [ 'Rock'    , 'Spock'    ], m: [ 'Paper cover Rock',      'Paper disproves Spock'       ] }

,              Scissors: { e: [ 'Paper'   , 'Lizard'   ], m: [ 'Scissors cuts Paper',   'Scissors decapitates Lizard' ] }

,              Lizard:   { e: [ 'Paper'   , 'Spock'    ], m: [ 'Lizard eats Paper',     'Lizard poisons Spock'        ] }

,              Spock:    { e: [ 'Rock'    , 'Scissors' ], m: [ 'Spock vaporizes Rock',  'Spock smashes Scissors'      ] }

            }



let play          = win3  // win5 .. win1000...

,   userScore     = 0

,   computerScore = 0

;

function game ( userChoice, computerChoice )

{

  if (userChoice == computerChoice )

  {

    console.log(' same values , no one score')

    return

  }

  if (play[userChoice].includes(computerChoice) )

  {

    userScore++

    let n = play[userChoice].e.findIndex(e=>e===computerChoice )

    console.log( play[userChoice].m[n] )

  }

  else

  {

    computerScore++

    let n = play[computerChoice].e.findIndex(e=>e===userChoice )

    console.log( play[computerChoice].m[n] )

  }

}


查看完整回答
反对 回复 2021-07-08
?
RISEBY

TA贡献1856条经验 获得超5个赞

您可以将两个可能选项之间的关系表示为一棵树:


  const winsOver = {

    schaar: ["papier"],

    steen: ["schaar"],

    papier: ["steen"],

 };

现在您的比较变得非常简单:


 if(userChoice === computerChoice) {

   draw();

 } else if(winsOver[userChoice].includes(computerChoice)) {

   win();

 } else lose();


查看完整回答
反对 回复 2021-07-08
  • 3 回答
  • 0 关注
  • 177 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信