Sorry i couldn't be specific in the question title ill try to explain better here, It maybe a really dumb question but I just started javascript a few days ago and now I'm trying to implement a small rock paper scissors game with a UI,
basically there is a function gameRound(playerInput, computerInput) when i run this function it returns 0,1 or -1 depending on who won this round and if its a tie.
I need to run this function ONLY when a click event is triggered on a button on my page so initially this is what I did:
const btns = document.querySelectorAll(".buttons");
btns.forEach(btn => btn.addEventListener("click", () => {
(gameRound(btn.id,computerPlay()))
}));
in my html:
<button id="Rock" class="buttons"><strong>Rock</strong></button>
<button id="Paper" class="buttons"><strong>Paper</strong></button>
<button id="Scissors" class="buttons"><strong>Scissors</strong></button>
This code works for individual rounds but I'm supposed to declare a winner that reaches 5 wins first so i have another function mainGame that tracks the number of wins for the player and the computer in a while loop like this:
function mainGame(){
let roundNum = 0;
let playerWins = 0;
let computerWins = 0;
while(playerWins < 5 && computerWins < 5){
const btns = document.querySelectorAll(".buttons");
btns.forEach(btn => btn.addEventListener("click", () => {
(gameRound(btn.id,computerPlay()))
}));
//let thisRound = gameRound(playerInput, computerPlay());
if (thisRound > 0){
playerWins ++;
roundNum ++;
}else if (thisRound < 0){
computerWins ++;
roundNum ++;
}else{
roundNum ++;
}
console.log(`Round: ${roundNum} \nPlayer: ${playerWins} \nComputer: ${computerWins}`);
}
const final = document.querySelector('#results-container');
if(playerWins > computerWins){
final.textContent = "You Won!";
}else{
final.textContent = "You Lose!";
}
}
mainGame();
But now i cant access the return value of the gameRound function without running it a second time and I'm stuck, is there an easy obvious fix that I can't see or do I have to change my whole logic for this game?
Thanks!