odin-rock-paper-scissors/script.js

99 lines
2.6 KiB
JavaScript
Raw Normal View History

2023-11-07 14:52:42 -07:00
let pScore = 0;
let cScore = 0;
let ps;
const buttons = document.querySelectorAll('button');
const msg = document.querySelector("#msg");
const score = document.querySelector("#score");
const player = document.querySelector("#player");
const computer = document.querySelector("#computer");
2023-11-07 21:24:44 -07:00
buttons.forEach((button) => {
button.addEventListener('click', () => {
ps = button.id; // Assign the button's id to the external variable
game(); // Start the game when the user makes a choice
});
});
2023-11-07 21:24:44 -07:00
2023-09-30 10:23:21 -06:00
function getComputerChoice(){
let compAnswer = Math.floor(Math.random() * 3) + 1;
if (compAnswer === 1) {
return "rock";
} else if (compAnswer === 2) {
return "paper";
} else {
return "scissors"
}
2023-09-30 10:23:21 -06:00
}
2023-09-30 10:23:21 -06:00
function playRound(playerSelection, computerSelection){
p = playerSelection.toLowerCase();
c = computerSelection.toLowerCase();
2023-09-30 10:23:21 -06:00
2023-09-30 10:52:40 -06:00
if (p === c) {
//console.log("It's a tie!")
return "tie";
2023-09-30 10:52:40 -06:00
} else if (p === "rock") {
if (c === "paper") {
return "player loses";
} else { //scissors
2023-09-30 10:52:40 -06:00
return "player wins";
}
2023-09-30 10:52:40 -06:00
} else if (p === "paper") {
if (c === "scissors") {
return "player loses";
} else { //rock
2023-09-30 10:52:40 -06:00
return "player wins";
}
2023-09-30 10:52:40 -06:00
} else if (p === "scissors") {
2023-09-30 12:33:29 -06:00
if (c === "rock") {
2023-09-30 10:52:40 -06:00
return "player loses";
2023-09-30 12:33:29 -06:00
} else { //paper
2023-09-30 10:52:40 -06:00
return "player wins";
}
}
2023-09-30 10:23:21 -06:00
}
function game() {
if (pScore < 5 && cScore < 5) {
const cs = getComputerChoice();
play = playRound(ps, cs);
switch (play) {
case "player loses":
cScore += 1;
computer.textContent = cScore;
msg.textContent = "You lose! " + cs + " beats " + ps + ". You: " + pScore + " Computer: " + cScore;
break;
case "player wins":
pScore += 1;
player.textContent = pScore;
msg.textContent = "You lose! " + ps + " beats " + cs + ". You: " + pScore + " Computer: " + cScore;
break;
2023-11-07 21:58:19 -07:00
default:
msg.textContent = "It's a tie! " + "You: " + pScore + " Computer: " + cScore;
break;
}
}
2023-11-07 21:24:44 -07:00
if (pScore === 5 || cScore === 5) {
2023-11-07 22:10:15 -07:00
endGame();
2023-11-07 21:24:44 -07:00
}
}
2023-11-07 21:24:44 -07:00
function endGame(){
2023-11-07 22:10:15 -07:00
let winner = (pScore > cScore) ? true : false;
2023-09-30 10:23:21 -06:00
if (winner) {
msg.textContent = "You won the game " + pScore + " to " + cScore + "! Great job!";
} else {
2023-11-07 22:10:15 -07:00
msg.textContent = "You lost the game " + pScore + " to " + cScore + ". Better luck next time!";
}
2023-11-07 21:24:44 -07:00
}