RPS
unknown
javascript
a year ago
3.2 kB
15
Indexable
// Initialize the score of the computer and the human globally
let ComputerScore = 0;
let HumanScore = 0;
let TieCounter = 0;
function getRandomInt(max) {
return Math.floor(Math.random() * max);
}
function getComputerChoice() {
// Use getRandomInt to make the computer randomly choose.
const choices = ["rock", "paper", "scissors"];
return choices[getRandomInt(3)];
}
// Create a function that determines the winner.
function CheckWinner(ComputerChoice, HumanChoice) {
if (ComputerChoice === HumanChoice) {
return "Tie";
} else {
if (ComputerChoice === "rock") {
if (HumanChoice === "paper") {
return "Human";
} else if (HumanChoice === "scissors") {
return "Computer";
}
} else if (ComputerChoice === "paper") {
if (HumanChoice === "rock") {
return "Computer";
} else if (HumanChoice === "scissors") {
return "Human";
}
} else if (ComputerChoice === "scissors") {
if (HumanChoice === "rock") {
return "Human";
} else if (HumanChoice === "paper") {
return "Computer";
}
}
}
}
function playRound(HumanChoice) {
const ComputerChoice = getComputerChoice();
const winner = CheckWinner(ComputerChoice, HumanChoice);
console.log(`Computer chose: ${ComputerChoice}`);
console.log(`Human chose: ${HumanChoice}`);
console.log(`Winner: ${winner}`);
if (winner === "Computer") {
ComputerScore++;
} else if (winner === "Human") {
HumanScore++;
} else {
TieCounter++;
}
// Update scores after each round
console.log(`Scores - Computer: ${ComputerScore}, Human: ${HumanScore}, Tie: ${TieCounter}`);
}
function updateGameResult(result) {
const gameResultElement = document.getElementById('gameresult');
gameResultElement.textContent = result;
}
function playGame() {
// Reset scores before starting a new game
ComputerScore = 0;
HumanScore = 0;
TieCounter = 0;
for (let i = 0; i < 5; i++) {
// Get HumanChoice from the event listener
playRound(HumanChoice); // Pass HumanChoice to playRound
}
// Determine the game result after all rounds
if (HumanScore > ComputerScore) {
updateGameResult('Game over! You win!');
} else if (ComputerScore > HumanScore) {
updateGameResult('Game over! Computer Wins!');
} else {
updateGameResult('Game over! Tie!');
}
}
const rock = document.querySelector('#rock');
const paper = document.querySelector('#paper');
const scissors = document.querySelector('#scissors');
let HumanChoice; // Declare HumanChoice as a global variable
rock.addEventListener('click', function() {
HumanChoice = 'rock';
});
paper.addEventListener('click', function() {
HumanChoice = 'paper';
});
scissors.addEventListener('click', function() {
HumanChoice = 'scissors';
});
// Define a function to get the human's choice.
// function getHumanChoice() {
// return HumanChoice;
// }
// Call playGame after setting up event listeners
playGame();
Editor is loading...
Leave a Comment