JS摇滚,纸,剪刀。 HTML输出

时间:2016-08-30 18:22:50

标签: javascript html

我有一个带有摇滚,纸张,剪刀游戏和按钮的Javascript代码,以供用户选择。游戏本身就像现在一样,它在用户选择和计算机选择的HTML元素中打印出来。我对如何调用比较函数感到茫然,并让它显示我在那里写的结果。

HTML:

  <button id ="rock"> Rock </button>
  <button id ="paper"> Paper </button>
  <button id ="scissors"> Scissors </button>

 <p id="output" onclick="user()">  </p>

JS:

document.getElementById('rock').onclick = user;
document.getElementById('paper').onclick = user;
document.getElementById('scissors').onclick = user;





var computerChoice = Math.random();
     if (computerChoice < 0.34) {
         computerChoice = "rock";
      }else if(computerChoice <= 0.67) {
         computerChoice = "paper";
      }else{
         computerChoice = "scissors";
      }; 

console.log("Computer: " + computerChoice);

console.log(compare(userChoice, computerChoice)); 

function compare(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 {
              return "scissors wins";
          }
         }

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


    }

}

 function user(){
 var userChoice = this.id;
 document.getElementById("output").innerHTML = ("User: " + userChoice + ". "         
+ "Computer: "+ computerChoice);
}

0 个答案:

没有答案