В настоящее время я пытаюсь создать консольную игру Rock, Paper, Scissors в консоли, но когда я выхожу в эфир, чтобы убедиться, что мой код работает, я продолжаю получать сообщение об ошибке:
index.html:14 Uncaught ReferenceError: game is not defined
at HTMLButtonElement.onclick (index.html:14:32)
Я попытался исправить свои переменные, так как сначала я не определил массив «выборов» в своем коде. Чтобы исправить это, я попытался объявить массив «выборов» и присвоить ему значения «камень», «бумага», «ножницы» перед вызовом функции «выбор компьютера».
Вот обновленный код js:
//this will play the game
//play five rounds
//console based
let choices = ["rock", "paper", "scissors"];
let winners = [];
function game() {
for (let i = 1; i <= 5; i++) {
playRound(i);
}
document.querySelector("button").textContent = "Play New Game";
logWins();
}
function playRound(round) {
const playerSelection = playerChoice();
const computerSelection = computerChoice();
const winner = checkWinner(playerSelection, computerSelection);
winners.push(winner);
logRound(playerSelection, computerSelection, winner, round);
}
function playerChoice() {
//get input from the player
let input = prompt("Type Rock, Paper, or Scissors");
while (input == null) {
input = prompt("Type Rock, Paper or Scissors");
}
}
// this allows no input to show up if misspelled
// a word, or wrote anything in the input prompt
input = input.toLowerCase();
let check = validateInput(input);
console.info(input);
return input;
//get random input from the comp
function computerChoice() {
return choices[Math.floor(Math.random() * choices.length)];
}
function validateInput(choice) {
if (choices.includes(choice)) {
return true;
} else {
return false;
}
}
function checkWinner(choiceP, choiceC) {
if (choiceP === choiceC) {
return "Tie";
} else if (
(choiceP === "rock" && choiceC === "scissors") ||
(choiceP === "paper" && choiceC === "rock") ||
(choiceP === "scissors" && choiceC === "paper")
) {
return "Player";
} else {
return "Computer";
}
}
function logWins() {
let playerWins = winners.filter((item) => item == "Player").length;
let computerWins = winners.filter((item) => item == "Computer").length;
let ties = winners.filter((items) => item == "Ties").length;
console.info("Results:");
console.info("Player Wins", playerWins);
console.info("Computer Wins", computerWins);
console.info("Tie", ties);
}
function logRound(playerChoice, computerChoice, winner, round) {
console.info("Round:", round);
console.info("Player Chose:", playerChoice);
console.info("Computer Chose:", computerChoice);
console.info(winner, "Won the Round!");
console.info("--------------------------");
}
game();
Я также заметил, что в консоли написано index.html, поэтому я попытался изучить это, но мне не хватило разрешений.
вот мой index.html:
<!DOCTYPE html>
<html lang = "en">
<head>
<meta charset = "UTF-8" />
<meta http-equiv = "X-UA-Compatible" content = "IE=edge" />
<meta name = "viewport" content = "width=device-width, initial-scale=1.0" />
<title>Document</title>
<link rel = "stylesheet" href = "styles.css" />
</head>
<body>
<div class = "flex-container">
<h1>Rock Paper Scissors</h1>
<button onclick = "game()">Play New Game</button>
</div>
<p>
Hi! This game is played within the console.
<br />
Instructions to play this game on <br />
Windows/Linux
<br />
press <strong>CTRL</strong> <em>+</em> <strong>SHIFT</strong> <em>+</em>
<strong>J</strong>
<br />
On Mac <br />
press <strong>Option</strong> <em>+</em> <strong>J</strong> <br />
This will open the console so you can start playing!
</p>
<script src = "main.js"></script>
</body>
</html>
Не уверен, в чем проблема, также рассматривал возможность изучения того, как создать эту игру с помощью Python, поскольку она может с большей вероятностью работать.
это была опечатка, когда я писал вопрос.
Вы возвращаетесь за пределы функции, которая вызывает ошибку перед функцией «игры», если она определена.
function playerChoice() {
let input = prompt("Type Rock, Paper, or Scissors");
while (input == null) {
input = prompt("Type Rock, Paper or Scissors");
}
// This part of the code should be inside the "playerChoice" function
input = input.toLowerCase();
let check = validateInput(input);
console.info(input);
return input;
}
Спасибо, я не заметил, что что-то настолько маленькое, как часть моего кода, находится вне функции!
Ваше определение
game()
не требует аргументов, но вы передаете"main.js"
; почему? Кроме того, чтоreturn input;
должен делать? Это не внутри функции; ваш код как есть ошибочен.