Hi I am new to JavaScript and I'm trying to make a simple game of rock, paper, scissors that loops five times before declaring a winner. Im not understanding why my loop is not working, I've tried a do while loop, while loop, and finally settled with a for loop yet the function does not seem to loop five times like i would want. Im also having a problem with why the game is return a win or loss of 3 instead of one for just one round. I was hoping that someone could help me out with this it would be greatly appreciated.
let computerSelection = computerPlay();
let playerSelection = prompt("Enter your Move");
let roundWinner;
let playerWins = 0;
let computerWins = 0;
let gameWinner;
function computerPlay(computerSelection =3){
let choice = Math.floor(Math.random()*computerSelection) +1;
let answer = "";
if (choice === 1){ answer = "ROCK"} else if (choice === 2){answer ="PAPER"} else {answer = "SCISSORS"}
return answer;}
function round(playerSelection , computerSelection){
if (playerSelection.toUpperCase() === "ROCK" && computerSelection === "SCISSORS") {playerWins += 1}
else if( playerSelection.toUpperCase() === "ROCK" && computerSelection === "PAPER"){computerWins += 1}
else if(playerSelection.toUpperCase() === "SCISSORS" && computerSelection === "PAPER") {playerWins += 1}
else if( playerSelection.toUpperCase() === "SCISSORS" && computerSelection === "ROCK"){computerWins += 1}
else if (playerSelection.toUpperCase() === "PAPER" && computerSelection === "ROCK") {playerWins += 1}
else if( playerSelection.toUpperCase() === "PAPER" && computerSelection === "SCISSORS"){computerWins += 1}
else if( playerSelection !== computerSelection) {roundWinner = "You entered an invalid input, please try again!"}
return (playerWins && computerWins)|| roundWinner;}
function game(){
for ( i = 0; i < 6; i++) {round(playerSelection,computerSelection); if(playerSelection === computerSelection) {i += 0} else {i++};}
if (playerWins > computerWins) {gameWinner =`You win! You won ${playerWins} to ${computerWins}`}
else if (computerWins > playerWins) {gameWinner = `You Lose! You loss ${playerWins} to ${computerWins}`}
else {gameWinner = roundWinner}
return gameWinner;
}
game();
let message = document.querySelector('main');
message.innerHTML = `<h1>${gameWinner} </h1>`;
* {
margin: 0px;
padding: 0px;
border: 0px;
}
h1 {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
height: 500px;
}
<!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">
<link rel="stylesheet" href="style.css">
<title>Rock, Paper, Scissors</title>
</head>
<body>
<main></main>
<script src="game.js"></script>
</body>
</html>
Thanks