I'm new to coding and here is a very basic code for a simple tic tac toe game:
function game(id) {
let round = '';
round = playRound(id, getComputerChoice());
if(round == "win") {
win++;
} else if(round == "lose") {
lose++;
}
score.textContent = "Score is " + win + "-" + lose;
if(win == 5) {
over.textContent = "Game is over, you win!";
} else if(lose == 5) {
over.textContent = "Game is over, you lose!";
}
}
let win = 0;
let lose = 0;
const result = document.querySelector('#results');
const buttons = document.querySelectorAll('button');
const score = document.querySelector('#score');
const over = document.querySelector('#over');
buttons.forEach((button) => {
button.addEventListener('click', () => game(button.id));
});
playRound returns win, lose or tie and getComputerChoice returns random choice for the computer. Once either player gets to 5, I want to use removeEventListener to leave the page as is, but I'm having trouble using it correctly.
Also I don't know if my code is the best way to write this program. Any advice on how to optimize/better ways to write this program would be very much appreciated. Thank you.
I've tried to stick removeEventListener as so, but it is not working as expected:
function game(id) {
...
if(win == 5) {
over.textContent = "Game is over, you win!";
button.removeEventListener('click', () => game(button.id));
} else if(lose == 5) {
over.textContent = "Game is over, you lose!";
button.removeEventListener('click', () => game(button.id));
}
}
I know this is terribly wrong but this is the only way I could come up with. I went on reference pages online but am having trouble understanding. Thanks for any help.