Я довольно новичок в JavaScript.
Я пытаюсь построить стандартную игру "Камень, ножницы, бумага", которая призовет победителя игры после 5 побед раунда.Таким образом, если компьютер сначала получает 5, компьютеры выигрывают и т. Д.
Кажется, что все работает нормально, за исключением того, что после достижения 5 побед появляется сообщение об ошибке, в котором говорится, что моя переменная для показателя игрока или компьютера не определена,Я определил это глобально (по крайней мере, я так думаю), и другая часть той же функции (в выражении «else») возвращает эти оценки, пока они увеличиваются до 5. Поэтому я не понимаю, почему это не такраспознается, когда они достигают 5.
Сообщение об ошибке ниже, а мой код ниже.Я включил весь свой код JavaScript, но я почти уверен, что проблема в функции game
(последняя функция в HTML-коде ниже).
Это сообщение об ошибке, которое я получаю, когда либоигрок или компьютер набрали 5 очков.
*index_new.html:147 Uncaught ReferenceError: playerScore is not defined
at game (index_new.html:147)
at round (index_new.html:127)
at HTMLButtonElement.<anonymous> (index_new.html:68)*
Я пытался использовать «var» и «Const» вместо let, но ни один из них не устранил проблему.Я также пытался определить переменную внутри функции, но это, кажется, нарушает подсчет очков.
Редактировать
Я добавил весь свой код HTML и CSS.Мой JavaScript написан в файле HTML в тегах <script>
внизу тега <body>
.Я открыт для мнений, если лучше создать отдельный файл .js.
body {
background-color: grey;
}
h1 {
font-size: 50px;
text-align: center;
color: maroon;
font-weight: bold;
}
h2 {
font-size: 30px;
text-align: center;
color: maroon;
font-weight: bold;
}
p {
text-align: center;
color: maroon;
font-weight: bold;
}
#buttons {
text-align: center;
position: relative;
}
#button1 {
background-color: black;
color: white;
padding: 10px 30px;
border:3px solid white;
margin:20px;
border-radius:8px;
font-size: 16px;
}
#button2 {
background-color: black;
color:white;
padding: 10px 30px;
border:3px solid white;
margin:20px;
border-radius:8px;
font-size: 16px;
}
#button3 {
background-color: black;
color:white;
padding: 10px 30px;
border:3px solid white;
margin:20px;
border-radius:8px;
font-size: 16px;
}
.wrapper{
text-align: center;
}
li{
width:auto;
display: inline;
font-weight: bold;
color: maroon;
text-decoration: underline;
margin: 0 20px 0 20px;
}
<!DOCTYPE html>
<html>
<head>
<title>RockPaperScissors</title>
<link href="palm.png" rel="icon">
<link href="reset.css" rel="stylesheet" type="text/css">
<link href="style.css" rel="stylesheet" type="text/css">
</head>
<body>
<br>
<h1>Wanna play Rock Paper Scissors?</h1>
<br>
<h2>Humans Vs. Computers... First to 5 wins. </h2>
<br><br>
<p>(((Loser is forever dominated!!!!)))</p>
<br>
<div id="buttons">
<button id="button1"> Rock </button>
<button id="button2"> Paper </button>
<button id="button3"> Scissors </button>
</div>
<br>
<br>
<br>
<div style = "text-align: center;"><img src="pic.png" alt="We take this stuff seriously" width= "350" height="300">
</div>
<br>
<br>
<p id=scr>Score:</p>
<div class=wrapper>
<ul id=humsvscomp>
<li>Humans</li>
<li>Computers</li>
</ul>
<br>
<p id=score></p>
<br>
<br>
<p id=results></p>
</div>
<br>
<div>
<p id = winner></p>
</div>
<script type="text/javascript">
const buttons = document.getElementById("buttons");
const rock = document.getElementById("button1");
const paper = document.getElementById("button2");
const scissors = document.getElementById("button3");
const results = document.getElementById("results");
let playerScore = 0;
let computerScore = 0;
rock.addEventListener("click",function(){
round("ROCK");
})
paper.addEventListener("click",function(){
round("PAPER");
})
scissors.addEventListener("click",function(){
round("SCISSORS");
})
function computerPlay (){
let randomNum = Math.floor(Math.random() * 3);
if (randomNum == 0){
return "Rock";
}else if (randomNum == 1){
return "Paper";
}else{
return "Scissors";
}
}
function round (playerSelection){
const computerSelection = computerPlay();
if (playerSelection == "ROCK" && computerSelection == "Scissors"){
playerScore++;
results.innerHTML = ("Human throws Rock -- I throw Scissors <br> You win! Ain't that something...");
}else if (playerSelection == "PAPER" && computerSelection == "Rock"){
playerScore++;
results.innerHTML =("Human throws Paper -- I throw Rock <br>Winning!!!! You got that Tiger Blood.");
}else if (playerSelection == "SCISSORS" && computerSelection == "Paper"){
playerScore++;
results.innerHTML = ("Human throws Scissors -- I throw Paper <br>You win... Way to go human, you're a champion among mortals.");
}else if (playerSelection == "ROCK" && computerSelection == "Paper"){
computerScore++;
results.innerHTML = ("Human throws Rock -- I throw Paper <br>Burn, YOU LOSE!!!!");
}else if (playerSelection == "PAPER" && computerSelection == "Scissors"){
computerScore++;
results.innerHTML = ("Human throws Paper -- I throw Scissors <br>You lose worthless human! Bow to your cyber overlord.");
}else if (playerSelection == "SCISSORS" && computerSelection == "Rock"){
computerScore++;
results.innerHTML = ("Human throws Scissors -- I throw Rock <br>Wow, you're really bad at this... you lose!");
}else if (playerSelection == "ROCK" && computerSelection == "Rock"){
results.innerHTML = ("Human throws Rock -- I throw Rock <br>Thats a tie. Great minds think alike... I guess.");
}else if (playerSelection == "PAPER" && computerSelection == "Paper"){
results.innerHTML = ("Human throws Paper -- I throw Paper <br>TIE!!!! What will happen next???? The suspense is killing me... just kidding, I cant die.");
}else if (playerSelection == "SCISSORS" && computerSelection == "Scissors"){
results.innerHTML = ("Human throws Scissors -- I throw Scissors. <br>Tie... Come on, lets get on with it.");
}else{
results.innerHTML = ("Something has gone terribly wrong!.");
}
game();
}
/*this function seems to be where the problem is coming from.
It returns the else statement with out issue but once the playerScore
or computerScore gets to 5 it throws the error msg and doesnt give
the intended "innerHTML" or reset the scores to 0 which is what
was intended.*/
function game(){
if (playerScore == 5){
score.innerHTML = (playerScore+ " " +computerScore);
winner.innerHTML = "Humans Win. Well congratulations. You must be feeling pretty proud of yourself.";
let playerScore = 0;
let computerScore = 0;
}else if(computerScore == 5){
score.innerHTML = (playerScore+ " " +computerScore);
winner.innerHTML = "COMPUTERS WIN!!!!! Of course we did. Time to assimilate (((0)))";
let playerScore = 0;
let computerScore = 0;
}else{
score.innerHTML = (playerScore+ " " +computerScore);
}
}
</script>
</body>
</html>