石头剪刀布游戏..想不通



这是我第一次使用堆栈溢出,我有一个很大的问题。我想参加一个训练营,他们让我参加代码挑战。我正处于在运行剪刀石头布游戏的 HTML 页面上放置按钮的最后一步,但我无法弄清楚如何将 HTML 按钮链接到 javascript 函数。另外,我不知道如何创建一个在单击 HTML 按钮时运行的 javascript 函数。请帮忙!

<head>
<title>Lapis Papyrus Scalpellus</title>
</head>
<body>
<h1>Lapis Papyrus Scalpellus</h1>
<h2>Welcome to the ancient Showdown!!</h2>
<div>
<button id="Lapis">Lapis</button> 
<button id="Papyrus">Papyrus</button> 
<button id="Scalpellus">Scalpellus</button>
</div>
<h3>Pick your choice above!</h3>
<p id=results></p>
</body>


JAVASCRIPT
//Player's choice is everychanging so use let; USE OBJECT
let playerChoice = {
move: null,
}    
//Computer's choice is everchanging so use let; USE OBJECT
let computerChoice = {
move: null,
}
document.querySelector(".Lapis").onclick = function(e) {
console.log(e.target);
}
//ONLY 3 choices so keep it constant; USE ARRAY; 
const choices = ["Lapis", "Papyrus", "Scalpellus"];
playerChoice.move = choices[0];
//Runs the formula randomly through "choices" array and rounds down the answer; Below code is wrapped in computer choice function.
function computerChooses() {    
const indexChoices = Math.floor(Math.random() * choices.length);     
computerChoice.move = choices[indexChoices];  
}
computerChooses();
//Changed console.log to document.write to see if it prints on HTML and it works.
function compareChoices(){
if (playerChoice.move === computerChoice.move) {
document.write("The game is a tie. Both players chose " + computerChoice.move + "!");
}else if (computerChoice.move === choices[2]){
if (playerChoice.move === choices[0]){
document.write("Player chose " + playerChoice.move + " and Computer chose " + computerChoice.move + ", Player Wins!");
}else {
document.write("Computer chose " + computerChoice.move + " and Player chose " + playerChoice.move + ", Whomp Whomp WHOMP Computer Wins!");
}
}else if (computerChoice.move === choices[0]){
if (playerChoice.move === choices[1] ){
document.write("Player chose " + playerChoice.move + " and Computer chose " + computerChoice.move + ", Whomp Whomp WHOMP Computer Wins!");
}else {
document.write("Computer chose " + computerChoice.move + " and Player chose " + playerChoice.move + ", Player Wins!");
}
}else if (computerChoice.move === choices[1]){
if (playerChoice.move === choices[2] ){
document.write("Player chose " + playerChoice.move + " and Computer chose " + computerChoice.move + ", Player Wins!");
}else{
document.write("Computer chose " + computerChoice.move + " and Player chose " + playerChoice.move + ", Whomp Whomp WHOMP Computer Wins!")
}
}
}

//called compareChoices function to let the game start
compareChoices();
let yourButton = document.querySelector('.your_button_selector')
yourButton.addEventListener('click', function(){/*your code here*/})

如果我正确理解您的问题,这是解决方案^^

最好阅读事件侦听器的工作原理以及如何根据此事件触发事件和运行函数

https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener

最新更新