石头剪刀布项目分数递增问题求助:如何正确累加玩家与电脑分数
石头剪刀布分数递增问题修复方案
核心问题分析
- 分数变量作用域错误:
getPlayerPoints和getComputerPoints在按钮点击事件内部声明,每次点击都会重置为0,导致无法累计分数。 - 重复DOM元素添加:每次点击按钮时,都会重复将分数容器添加到结果容器,再把结果容器添加到页面,造成冗余DOM元素。
- 递增顺序错误:使用
getPlayerPoints++后置递增时,会先将当前值赋值给textContent,再执行递增,导致分数显示滞后一次。
修正后的代码
const startGame = document.querySelector('#startGame'); const container = document.querySelector('#container'); //Start The Game startGame.addEventListener('click', (e) => { e.target.setAttribute('class', 'hidden'); const buttons = ['Rock', 'Paper', 'Scissor']; const buttonContainer = document.createElement('div'); buttonContainer.setAttribute('class', 'buttonContainer'); const resultContainer = document.createElement('div'); resultContainer.setAttribute('id', 'resultContainer'); const playerScoreContainer = document.createElement('div'); playerScoreContainer.setAttribute('id', 'playerScoreContainer'); const computerScoreContainer = document.createElement('div'); computerScoreContainer.setAttribute('id', 'computerScoreContainer'); // 初始化分数并显示 let getPlayerPoints = 0; let getComputerPoints = 0; playerScoreContainer.textContent = `玩家分数: ${getPlayerPoints}`; computerScoreContainer.textContent = `电脑分数: ${getComputerPoints}`; // 一次性添加容器到页面,避免重复添加 resultContainer.append(playerScoreContainer, computerScoreContainer); container.appendChild(buttonContainer); container.appendChild(resultContainer); for (const button of buttons) { const createButton = document.createElement('button'); createButton.textContent = button; createButton.setAttribute('name', `${button}`); buttonContainer.appendChild(createButton); createButton.addEventListener('click', (e) => { const playerSelection = e.target.getAttribute('name'); const computerSelection = buttons[Math.floor(Math.random() * buttons.length)]; let gameTie = ''; switch (true) { case (playerSelection === computerSelection): gameTie = 'Tie'; break; case ( (playerSelection === 'Rock' && computerSelection === 'Scissor') || (playerSelection === 'Scissor' && computerSelection === 'Paper') || (playerSelection === 'Paper' && computerSelection === 'Rock') ): getPlayerPoints++; playerScoreContainer.textContent = `玩家分数: ${getPlayerPoints}`; break; case ( (computerSelection === 'Rock' && playerSelection === 'Scissor') || (computerSelection === 'Scissor' && playerSelection === 'Paper') || (computerSelection === 'Paper' && playerSelection === 'Rock') ): getComputerPoints++; computerScoreContainer.textContent = `电脑分数: ${getComputerPoints}`; break; } // 可选:显示当前回合结果 if (gameTie) { console.log(gameTie); // 也可以添加到页面显示 } }) } });
关键修改点
- 将分数变量
getPlayerPoints和getComputerPoints移到按钮点击事件外部,确保每次点击能累计分数。 - 初始化时直接设置分数容器的文本内容,一次性将所有容器添加到页面,避免重复DOM操作。
- 先执行分数递增,再更新容器的文本内容,保证显示的是最新分数。
- 优化了分数显示的可读性,添加了分数标签说明。
内容的提问来源于stack exchange,提问作者Muhammad Huzaifa
相关产品推荐
相关产品推荐

