新手求助:如何实现「Lapis, Papyrus, Scalpellus」游戏的按钮交互?
解决Lapis, Papyrus, Scalpellus游戏的玩家选择按钮功能问题
修改后的完整代码
HTML代码
<html> <style> </style> <body> <h1>Lapis, Papyrus, Scalpellus!</h1> <h2>Join the game of centuries and see if you can be a conqueror like Ancient Rome in this original version of Rock, Paper, Scissors.</h2> <h3>Make Your Choice</h3> <div class="buttons"> <button id="lapis">Lapis</button> <button id="papyrus">Papyrus</button> <button id="scalpellus">Scalpellus</button> </div> <div id="result-container"></div> </body> <script> const player = { currentChoice: null }; const computer = { currentChoice: null }; let choices = ["Lapis", "Papyrus", "Scalpellus"]; const resultContainer = document.getElementById('result-container'); function computerChooses() { const randomIndex = Math.floor(Math.random() * choices.length); computer.currentChoice = choices[randomIndex]; } function compareChoices() { computerChooses(); let result; if (computer.currentChoice === player.currentChoice) { result = "Tie. Both Choose " + computer.currentChoice; } else if (computer.currentChoice === choices[0]) { if (player.currentChoice === choices[1]) { result = "Player Wins! " + player.currentChoice + " Beats " + computer.currentChoice + "."; } else { result = "Computer Wins! " + computer.currentChoice + " Beats " + player.currentChoice + "."; } } else if (computer.currentChoice === choices[1]) { if (player.currentChoice === choices[2]) { result = "Player Wins! " + player.currentChoice + " Beats " + computer.currentChoice + "."; } else { result = "Computer Wins! " + computer.currentChoice + " Beats " + player.currentChoice + "."; } } else if (computer.currentChoice === choices[2]) { if (player.currentChoice === choices[0]) { result = "Player Wins! " + player.currentChoice + " Beats " + computer.currentChoice + "."; } else { result = "Computer Wins! " + computer.currentChoice + " Beats " + player.currentChoice + "."; } } displayResults(result); } function displayResults(result) { resultContainer.innerHTML = ''; const resultText = document.createElement("p"); resultText.innerText = result; resultContainer.appendChild(resultText); } document.getElementById('lapis').addEventListener('click', () => { player.currentChoice = choices[0]; compareChoices(); }); document.getElementById('papyrus').addEventListener('click', () => { player.currentChoice = choices[1]; compareChoices(); }); document.getElementById('scalpellus').addEventListener('click', () => { player.currentChoice = choices[2]; compareChoices(); }); </script> </html>
关键修改说明
- 绑定按钮点击事件:通过
getElementById获取每个按钮,用addEventListener绑定click事件。点击时设置对应玩家选择,再触发胜负判断逻辑。 - 移除固定玩家选择:删掉了
player.currentChoice = choices[0];,让玩家选择完全由按钮操作决定。 - 修正拼写错误:原代码最后分支里的
currentChoices是笔误,改为正确的currentChoice。 - 优化结果展示:新增
result-container容器,每次显示结果前清空容器,避免页面堆积重复内容。
内容的提问来源于stack exchange,提问作者Fuzzy Volpitta
相关产品推荐
相关产品推荐

