首页 > 解决方案 > 初学者首先尝试编码摇滚,纸..游戏。不断返回“纸质胜利”

问题描述

当我选择“摇滚”时,我不断获得“纸上奖”。

function game() {
  pChoice = prompt('What is your play?');
  cChoice = ['rock','paper','scissor'];
  
  let compChoice = [Math.floor(Math.random() * cChoice.length)];
  console.log(compChoice);

  function compare(pChoice, compChoice) {
    if (pChoice === compChoice) {
      alert( "It's a tie" );
    }

    if (pChoice === 'rock') {
      if (compChoice === 'scissor') {
        return 'rock wins';
      } else {
        return 'paper wins';    
      }
    }
    else if (pChoice === 'paper') {
      if (compChoice === 'rock') {
        return 'paper wins';
      } else {
        return 'scissor wins';
      }
    }
    else if (pChoice === 'scissor') {
      if (compChoice === 'paper') {
        return 'scissor wins';
      } else {
        return 'rock wins';
      }
    }
  }

  var result = compare(pChoice, compChoice);
  console.log(compare(pChoice, compChoice));
}

game();

标签: javascript

解决方案


您永远不会将 cChoice 分配给一个值,而是将其分配给一个包含数字的数组。

例如:

// Assigning to [number]
let compChoice = [Math.floor(Math.random() * cChoice.length)];
// Assigning to string inside of array cChoice
let compChoice = cChoice[Math.floor(Math.random() * cChoice.length)];

推荐阅读