我创建了一个Rock Paper Scissors游戏,在游戏机中玩了5轮,我现在正试图通过使用DOM操作的按钮重构它以使用按钮。
按钮和圆形功能是:
rock_btn.addEventListener('click',function(){
round('rock');
})
paper_btn.addEventListener('click',function(){
round('paper');
})
scissors_btn.addEventListener('click',function(){
round('scissors');
})
function round (playerSelection) {
let computerSelection = computerPlay();
if (playerSelection === 'rock' && computerSelection === 'scissors') {
playerScore++
userScore_span.innerHTML = playerScore;
result_div.innerHTML = 'You Win\! Rock beats Scissors\!';
} else if (playerSelection === 'scissors' && computerSelection === 'rock') {
computerScore++;
compScore_span.innerHTML = computerScore;
result_div.innerHTML = 'You Lose\! Rock beats Scissors\!';
} else if(playerSelection === 'paper' && computerSelection === 'rock') {
playerScore++;
userScore_span.innerHTML = playerScore;
result_div.innerHTML ='You Win\! Paper beats Rock\!';
} else if(playerSelection === 'rock' && computerSelection === 'paper') {
computerScore++;
compScore_span.innerHTML = computerScore;
result_div.innerHTML = 'You Lose\! Paper beats Rock\!';
} else if(playerSelection === 'scissors' && computerSelection === 'paper') {
playerScore++;
userScore_span.innerHTML = playerScore;
result_div.innerHTML ='You Win\! Scissors beats Paper\!';
} else if(playerSelection === 'paper' && computerSelection === 'scissors') {
computerScore++;
compScore_span.innerHTML = computerScore;
result_div.innerHTML = 'You Lose\! Scissors beats Paper\!';
} else {
result_div.innerHTML = ('A draw! Please play again!');
}
}
游戏函数用于计算在控制台中调用时轮次的工作但现在没有效果:
let playerScore = 0;
let computerScore = 0;
function game () {
while (playerScore <= 5 || computerScore <= 5) {
round();
if(playerScore === 5) {
result_div.innerHTML = 'Player Wins!!!';
}
if(computerScore === 5) {
result_div.innerHTML = 'Computer Wins!!!';
}
}
}
有人可以告诉我如何将游戏功能插入到序列中以便计数器有效吗?
答案 0 :(得分:1)
欢迎使用Stackoverflow。
由于您依赖于使用DOM上的按钮进行游戏,因此您应该检查round
功能结束时的获胜条件:
胜利条件:
function win_condition () {
if(playerScore === 5) {
result_div.innerHTML = 'Player Wins!!!';
}
if(computerScore === 5) {
result_div.innerHTML = 'Computer Wins!!!';
}
}
在您的round
函数中:
...
else if(playerSelection === 'paper' && computerSelection === 'scissors') {
computerScore++;
compScore_span.innerHTML = computerScore;
result_div.innerHTML = 'You Lose\! Scissors beats Paper\!';
} else {
result_div.innerHTML = ('A draw! Please play again!');
}
win_condition();
}
你可以通过DRYing来重构你的一些代码,也许可以将规则抽象出来(即岩石胜过剪刀而是输掉纸张等等)
我在另一篇文章中做了类似的事情。 See this CodePen:
请注意,它位于ReactJS中,因此您需要稍微改变它,但原则仍然存在:抽象逻辑并干掉您的代码。
(顺便说一句:全球可变状态最终会让你感到害怕,你making your functions pure会大量改进你的代码)