2016-08-30 40 views
0

我有JS的基本「岩石,紙,剪刀」遊戲的代碼。它與Promt一起工作,但我希望能夠使用按鈕進行選擇。我想使用「getElementById」和「addEventListener(」click「)」。任何人都可以將我指向正確的方向嗎?JS - 岩石,紙,剪,按鈕而不是提示

HTML:

<button id ="rock"> Rock </button> 

紙 剪刀

的JavaScript:

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"; 
} console.log("Computer: " + computerChoice); 


var compare = function (choice1, choice2) { 
if (choice1 === choice2) { 
    return "The result is a tie!"; 
    } 

    else 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 if (choice2 === "paper") { 
      return "scissors wins"; 
     } 
     } 
     } 
     } 
    } 
    compare (userChoice, computerChoice); 

回答

2

使用在幾個街區的onclick事件處理(documentation)是這樣的:

document.getElementById('rock').onclick = function(e){ 
    userChoice = 'rock' 
} 
1

下面是一個例子(單擊 「運行的代碼片斷」):

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

 

 
function user(){ 
 
    var userChoice = this.id; 
 
    console.log("User: " + userChoice) 
 

 
    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) { 
 
    
 
\t \t  if (choice1 === choice2) { 
 
      return "The result is a tie!"; 
 
     } 
 
    
 
     if (choice1 === "rock") { 
 
      if (choice2 === "scissors") { 
 
       return "rock wins"; 
 
      }else{ 
 
       return "paper wins"; 
 
      } 
 
\t \t \t \t } 
 
    
 
     if (choice1 === "paper") { 
 
      if (choice2 === "rock") { 
 
       return "paper wins"; 
 
       } else { 
 
        return "scissors wins"; 
 
       } 
 
\t \t  } 
 
\t \t 
 
\t \t  if (choice1 === "scissors") { 
 
      if (choice2 === "rock") { 
 
       return "rock wins"; 
 
      } else { 
 
       return "scissors wins"; 
 
      } 
 
     } 
 
    } 
 
}
<button id="rock">Rock</button> 
 
<button id="paper">Paper</button> 
 
<button id="scissors">Scissor</button>

PS:你的函數compare是返回undefined一些情況。

+0

我明白了,謝謝你指出,我可以問一下,你將如何代表HTML的輸出而不是控制檯? – Sergi

+0

http://www.w3schools.com/jsref/prop_html_innerhtml.asp –