0

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.

  • For future reference, to remove an event listener, you must pass the same callback function. In your case, you are redeclaring new functions every time: https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/removeEventListener – Chris Hamilton Dec 03 '22 at 20:49

1 Answers1

1

While you could save all 5 handlers in an array of functions and then iterate through them to remove at the end, or use event delegation and have just one event handler to remove - why not just check inside game whether either limit has been reached before continuing?

function game(id) {
  if (win === 5 || lose === 5) {
    return;
  }
  // ...

Other suggestions:

  • playRound returns a string indicating a win or loss - consider naming the variable more precisely to indicate that, such as roundResult
  • Unless you and everyone who'll ever see the code understands the pretty odd behavior of sloppy comparisons with ==, better to use strict equality with ===
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320