odin-rps/index.js

56 lines
2.0 KiB
JavaScript
Raw Normal View History

'use strict';
2024-01-03 18:36:00 +00:00
const choices = ["rock", "paper", "scissors"];
function getComputerChoice() {
return choices[Math.floor(Math.random() * 3)];
}
function playRound(playerChoice, computerChoice) {
let playerChoiceCapital = playerChoice.slice(0,1).toUpperCase() + playerChoice.slice(1,playerChoice.length)
let computerChoiceCapital = computerChoice.slice(0,1).toUpperCase() + computerChoice.slice(1,computerChoice.length)
if (playerChoice == computerChoice) {
points.playerAddPoints();
points.computerAddPoints();
return `It's a tie! ${playerChoiceCapital} vs ${computerChoiceCapital}.`;
} else if ((playerChoice == "rock" && computerChoice == "paper")
|| (playerChoice == "paper" && computerChoice == "scissors")
|| (playerChoice == "scissors" && computerChoice == "rock")) {
points.computerAddPoints();
return `You lost! ${computerChoiceCapital} beats ${playerChoiceCapital}.`;
} else if ((playerChoice == "rock" && computerChoice == "scissors")
|| (playerChoice == "paper" && computerChoice == "rock")
|| (playerChoice == "scissors" && computerChoice == "paper")) {
points.playerAddPoints();
return `You won! ${playerChoiceCapital} beats ${computerChoiceCapital}.`;
}
}
const points = (() => {
this.player = 0;
this.computer = 0;
function playerAddPoints() {
player++;
}
function computerAddPoints() {
computer++;
}
function reset() {
player = 0;
computer = 0
}
return {get player() {return player},
get computer() {return computer},
playerAddPoints, computerAddPoints, reset};
})()
const buttons = document.querySelectorAll("button.choose");
const resultDiv = document.querySelector("div#result");
buttons.forEach(button => {
button.addEventListener("click", () => {
let result = playRound(button.value, getComputerChoice());
resultDiv.textContent = `Result: ${result}`;
});
});