Ir ao conteúdo
  • Cadastre-se

Javascript Jogo da Velha - erro de escopo/lógica


Ir à solução Resolvido por Alexsander Gutierrez,

Posts recomendados

Pessoal, bom dia. Não consigo achar o erro de lógica ou de escopo da minha variável "jogadorAtual" para este jogo simples de jogo da velha. O console do navegador apresenta o seguinte erro: "Uncaught TypeError: jogadorAtual is undefined".

 

Os códigos da página:

HTML:

<!DOCTYPE html>
<html lang="pt-BR">
  <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" />
    <title>Jogo da Velha</title>
    <link
      href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css"
      rel="stylesheet"
      integrity="sha384-aFq/bzH65dt+w6FI2ooMVUpc+21e0SRygnTpmBvdBgSdnuTN7QbdgL+OapgHtvPp"
      crossorigin="anonymous"
    />
    <link rel="stylesheet" href="./style.css" />
    <script
      src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"
      integrity="sha384-qKXV1j0HvMUeCBQ+QVp7JcfGl760yU08IQ+GpUo5hlbpg51QRiuqHAJz8+BrxE/N"
      crossorigin="anonymous"
    ></script>
    <script src="./index.js" defer></script>
  </head>
  <header>
    <nav class="navbar bg-body-tertiary">
      <div class="container-fluid">
        <a
          class="navbar-brand"
          title="Jogo da Velha: Wikipédia, a enciclopédia livre"
          href="#"
          id="jogo_wiki"
        >
          <img
            src="./imagens/hash.svg"
            alt="Logo"
            width="30"
            height="24"
            class="d-inline-block align-text-top"
          />
          Jogo da Velha
        </a>
        <a class="navbar-brand" id="jogadores" href="#">
          <img
            src="./imagens/person-fill.svg"
            alt="Logo"
            width="30"
            height="24"
            class="d-inline-block align-text-top"
          />
          Jogadores
        </a>
        <a class="navbar-brand" id="iniciarJogo" href="#">
          <img
            src="./imagens/play-circle.svg"
            alt="Logo"
            width="30"
            height="24"
            class="d-inline-block align-text-top"
          />
          Iniciar
        </a>
        <a class="navbar-brand" href="#">
          <img
            src="./imagens/repeat.svg"
            alt="Logo"
            width="30"
            height="24"
            class="d-inline-block align-text-top"
          />
          Reiniciar
        </a>
        <a class="navbar-brand" id="pararJogo" href="#">
          <img
            src="./imagens/x-lg.svg"
            alt="Logo"
            width="30"
            height="24"
            class="d-inline-block align-text-top"
          />
          Parar jogo
        </a>
        <a class="navbar-brand" id="is-light" href="#">
          <img
            src="./imagens/sun-fill.svg"
            alt="Logo"
            width="30"
            height="24"
            class="d-inline-block align-text-top"
          />
          Modo Claro
        </a>
        <a class="navbar-brand" id="is-dark" href="#">
          <img
            src="./imagens/moon-fill.svg"
            alt="Logo"
            width="30"
            height="24"
            class="d-inline-block align-text-top"
          />
          Modo Escuro
        </a>
        <a class="navbar-brand" id="info" href="#">
          <img
            src="./imagens/info.svg"
            alt="Logo"
            width="30"
            height="24"
            class="d-inline-block align-text-top"
          />
          Info
        </a>
        <a class="navbar-brand" id="icons" href="#">
          <img
            src="./imagens/images.svg"
            alt="Logo"
            width="30"
            height="24"
            class="d-inline-block align-text-top"
          />
          Icons
        </a>
      </div>
    </nav>
  </header>
  <body>
    <div class="clearfix">
      <img
        src="./imagens/hash.svg"
        class="float-end"
        id="hashtag"
        alt="hashtag"
      />
      <p>
        O jogo da velha (português brasileiro) ou jogo do galo (português
        europeu) ou três em linha é um jogo e/ou passatempo popular. É um jogo
        de regras extremamente simples, que não traz grandes dificuldades para
        seus jogadores e é facilmente aprendido. A origem é desconhecida, com
        indicações de que pode ter começado no antigo Egito, onde foram
        encontrados tabuleiros esculpidos na rocha, que teriam mais de 3.500
        anos. De alguma forma, é um jogo "aparentado" dos "Merels".
      </p>
      <img
        src="./imagens/controller.svg"
        class="float-start"
        id="controller"
        alt="controller"
      />
      <p>
        Algumas lendas urbanas contam que o jogo terá nascido em Portugal, na
        cidade de Almada no ano 545. No entanto, só foi popularizado no ano
        1500, pelo descobridor Pedro Álvares Cabral, que adorava jogar este jogo
        durante as suas viagens. Álvares Cabral terá decidido que este jogo
        seria o primeiro a ser ensinado ao povo indígena no Brasil. O jogo pode
        ser jogado sobre um tabuleiro ou mesmo sendo riscado sobre um pedaço de
        papel ou mesa. O menor tabuleiro do mundo foi feito com DNA.
      </p>
      <p>
        Se os dois jogadores jogarem sempre da melhor forma, o jogo terminará
        sempre em empate. A lógica do jogo é muito simples, de modo que não é
        difícil deduzir ou decorar todas as possibilidades para efetuar a melhor
        jogada - apesar de o número total de possibilidades ser muito grande, a
        maioria delas é simétrica, além de que as regras são simples. Por esse
        motivo, é muito comum que o jogo empate (ou "dê velha").
      </p>
      <br />
      <div class="tresD">
        <div class="front">
          <img src="./imagens/notebook.png" alt="Tecnologia da Informação" />
        </div>
        <div class="back">
          <img src="./imagens/hash.png" alt="Tecnologia da Informação" />
        </div>
      </div>
    </div>
    <div id="jogadorAtual">
      <h3 id="jogadorAtualh3"></h3>
    </div>
    <div id="players">
      <h3>Jogadores</h3>
      <label for="Jogador 1"> Jogador 1: </label>
      <input type="text" id="jogador1" />
      <br />
      <br />
      <label for="Jogador 1"> Jogador 2: </label>
      <input type="text" id="jogador2" />
      <br />
      <br />
      <input type="submit" id="submit" value="Ok" />
    </div>
    <div id="jogo">
      <table cellpadding="0" cellspacing="0" id="table">
        <tr>
          <td
            class="table-data" id="cell0"
          >
            &nbsp;
          </td>

          <td
            class="table-data" id="cell1"
          >
            &nbsp;
          </td>

          <td
            class="table-data" id="cell2"
          >
            &nbsp;
          </td>
        </tr>

        <tr>
          <td
            class="table-data" id="cell3"
          >
            &nbsp;
          </td>

          <td
            class="table-data" id="cell4"
          >
            &nbsp;
          </td>

          <td
            class="table-data" id="cell5"
          >
            &nbsp;
          </td>
        </tr>

        <tr>
          <td
            class="table-data" id="cell6"
          >
            &nbsp;
          </td>

          <td
            class="table-data" id="cell7"
          >
            &nbsp;
          </td>

          <td
            class="table-data" id="cell8"
          >
            &nbsp;
          </td>
        </tr>
      </table>
  </body>
</html>

 

JavaScript:

let jogadoresAtivos = false;

function cellWins(cell) {
  cell.style.hover = 'transform: scale(1.2);';
}

window.onload = function () {
  document.getElementById('players').style.visibility = 'hidden';
  document.getElementById('jogadorAtual').style.visibility = 'hidden';
  document.getElementById('jogo').style.visibility = 'hidden';
};

const infoBtn = document.getElementById('info');

infoBtn.addEventListener('click', () => {
  alert(
    'Jogo da Velha feito com HTML, CSS e JavaScript\n' +
      'Desenvolvido por: @campanaricarlos\n' +
      'GitHub: https://github.com/ccampa896\n' +
      'LinkedIn: https://www.linkedin.com/in/carlos-campanari-9b4b3b1b3/\n'
  );
});

const iconsBtn = document.getElementById('icons');

iconsBtn.addEventListener('click', () => {
  alert('Icons by https://icons.getbootstrap.com/');
});

function useLightTheme() {
  document.body.style.color = '#212529';
  document.body.style.backgroundColor = '#f1f5f9';
  const hash = document.getElementById('hashtag');
  const controller = document.getElementById('controller');
  hash.style.border = '0px solid #fff';
  controller.style.border = '0px solid #fff';
}

function useDarkTheme() {
  document.body.style.color = '#f1f5f9';
  document.body.style.backgroundColor = '#212529';
  const hash = document.getElementById('hashtag');
  const controller = document.getElementById('controller');
  hash.style.margin = '10px';
  controller.style.margin = '10px';
  hash.style.border = '5px solid #fff';
  controller.style.border = '5px solid #fff';
  hash.style.borderRadius = '10px';
  controller.style.borderRadius = '10px';
}

const lightBtn = document.getElementById('is-light');
const darkBtn = document.getElementById('is-dark');

lightBtn.addEventListener('click', useLightTheme);
darkBtn.addEventListener('click', useDarkTheme);

function jogadores() {
  let elementos = document.querySelectorAll('.tresD');

  elementos.forEach(function (elemento) {
    elemento.remove();
  });

  document.getElementById('players').style.visibility = 'visible';
}

const btnJogadores = document.getElementById('jogadores');
btnJogadores.addEventListener('click', jogadores);

let NomeJogador1 = '';
let NomeJogador2 = '';

const btnSubmit = document.getElementById('submit');
btnSubmit.addEventListener('click', () => {
  NomeJogador1 = document.getElementById('jogador1').value;
  NomeJogador2 = document.getElementById('jogador2').value;
  jogadoresAtivos = true;
  alert(
    'Jogadores cadastrados!\n' +
      'Jogador 1: ' +
      NomeJogador1 +
      '\n' +
      'Jogador 2: ' +
      NomeJogador2
  );

  let elementos = document.querySelectorAll('#players');

  elementos.forEach(function (elemento) {
    elemento.remove();
  });
});

function Jogador(nome, forma) {
  this.nome = nome;
  this.forma = forma;
}

let jogador1, jogador2;

//Jogador da rodada

let jogadorAtual;

let formas = ['X', 'O'];

/*
0 1 2
3 4 5
6 7 8
*/
let tabuleiro = new Array(9);

const setLabelJogadorAtual = function () {
  document.getElementById('jogadorAtualh3').innerHTML =
    'Jogador atual:  ' + jogadorAtual.nome;
};

function iniciarJogo() {
  if (jogadoresAtivos) {
    alert(
      'Para iniciar um novo jogo, clique em "Reiniciar"\n' +
        'Ou clique em "Parar jogo" para finalizar o jogo atual!'
    );
    alert(
      'Jogo iniciado!\n' +
        'Jogador 1: ' +
        NomeJogador1 +
        '\n' +
        'Jogador 2: ' +
        NomeJogador2 +
        '\n' +
        'Boa sorte!'
    );

    jogador1 = new Jogador(NomeJogador1, 0); //X
    jogador2 = new Jogador(NomeJogador2, 1); //O
    jogadorAtual = jogador1;
    setLabelJogadorAtual();

    document.getElementById('jogadorAtual').style.visibility = 'visible';

    document.getElementById('jogo').style.visibility = 'visible';
  } else {
    alert('Você precisa informar os jogadores!');
  }
}

jogadorAtual = jogador1;

const btnIniciarJogo = document.getElementById('iniciarJogo');
btnIniciarJogo.addEventListener('click', iniciarJogo);

/*Verifica se o tabuleiro está completamente preenchido, se estiver, significa que ninguém venceu a rodada*/

tabuleiroIsFilled = function () {
  let preenchidos = 0;

  for (let i = 0; i < tabuleiro.length; i++)
    if (tabuleiro[i] != undefined) preenchidos++;

  return preenchidos == tabuleiro.length;
};

/*Verifica a existência de ocorrências de um mesmo elemento(X ou O) nas linhas do tabuleiro, procurando um vencedor*/

allElementsInSomeLine = function () {
  for (let i = 0; i < 7; i += 3) {
    if (
      tabuleiro[i] == 'X' &&
      tabuleiro[i + 1] == 'X' &&
      tabuleiro[i + 2] == 'X'
    ) {
      alert(jogador1.nome + ' wins!!!');

      pararJogo();
    }

    if (
      tabuleiro[i] == 'O' &&
      tabuleiro[i + 1] == 'O' &&
      tabuleiro[i + 2] == 'O'
    ) {
      alert(jogador2.nome + ' wins!!!');

      pararJogo();
    }
  }
};

/*Verifica a existência de ocorrências de um mesmo elemento(X ou O) nas colunas do tabuleiro, procurando um vencedor*/

allElementsInSomeColumn = function () {
  for (let i = 0; i < 3; i++) {
    if (
      tabuleiro[i] == 'X' &&
      tabuleiro[i + 3] == 'X' &&
      tabuleiro[i + 6] == 'X'
    ) {
      alert(jogador1.nome + ' wins!!!');

      pararJogo();
    }

    if (
      tabuleiro[i] == 'O' &&
      tabuleiro[i + 3] == 'O' &&
      tabuleiro[i + 6] == 'O'
    ) {
      alert(jogador2.nome + ' wins!!!');

      pararJogo();
    }
  }
};

/*Verifica a existência de ocorrências de um mesmo elemento(X ou O) nas diagonais do tabuleiro, procurando um vencedor*/

allElementsInSomeDiagonal = function () {
  if (
    (tabuleiro[0] == 'X' && tabuleiro[4] == 'X' && tabuleiro[8] == 'X') ||
    (tabuleiro[2] == 'X' && tabuleiro[4] == 'X' && tabuleiro[6] == 'X')
  ) {
    alert(jogador1.nome + ' wins!!!');

    pararJogo();
  } else if (
    (tabuleiro[0] == 'O' && tabuleiro[4] == 'O' && tabuleiro[8] == 'O') ||
    (tabuleiro[2] == 'O' && tabuleiro[4] == 'O' && tabuleiro[6] == 'O')
  ) {
    alert(jogador2.nome + ' wins!!!');

    pararJogo();
  }
};

/*Preenche a célula da tabela HTML escolhida pelo usuário ao clicar, além de cuidar do jogador atual da rodada e chamar as funções


de verificação de algum ganhador */

function setOnCeil(cell, pos) {
  if (tabuleiro[pos] == undefined) {
    cell.textContent = jogadorAtual.forma;
    tabuleiro[pos] = jogadorAtual.forma;

    if (jogadorAtual == jogador1) {
      jogadorAtual = jogador2;
    } else {
      jogadorAtual = jogador1;
    }

    setLabelJogadorAtual();
  } else {
    alert('Célula já preenchida! Escolha outra!');
  }

  allElementsInSomeLine();

  allElementsInSomeColumn();

  allElementsInSomeDiagonal();

  if (tabuleiroIsFilled()) {
    alert('Nobody wins! :(. Try Again');

    pararJogo();
  }
}

const btnCell0 = document.getElementById('cell0');
const btnCell1 = document.getElementById('cell1');
const btnCell2 = document.getElementById('cell2');
const btnCell3 = document.getElementById('cell3');
const btnCell4 = document.getElementById('cell4');
const btnCell5 = document.getElementById('cell5');
const btnCell6 = document.getElementById('cell6');
const btnCell7 = document.getElementById('cell7');
const btnCell8 = document.getElementById('cell8');

btnCell0.addEventListener('onclick', setOnCeil(btnCell0, 0));
btnCell1.addEventListener('onclick', setOnCeil(btnCell1, 1));
btnCell2.addEventListener('onclick', setOnCeil(btnCell2, 2));
btnCell3.addEventListener('onclick', setOnCeil(btnCell3, 3));
btnCell4.addEventListener('onclick', setOnCeil(btnCell4, 4));
btnCell5.addEventListener('onclick', setOnCeil(btnCell5, 5));
btnCell6.addEventListener('onclick', setOnCeil(btnCell6, 6));
btnCell7.addEventListener('onclick', setOnCeil(btnCell7, 7));
btnCell8.addEventListener('onclick', setOnCeil(btnCell8, 8));

const pararJogo = function () {
  if (jogadoresAtivos) {
    alert(
      'Jogo finalizado!\n' + 'Obrigado por jogar!\n' + 'Página recarregada!'
    );
    jogadoresAtivos = false;
    document.getElementById('jogador1').value = '';
    document.getElementById('jogador2').value = '';
    window.location.reload();
  } else {
    alert('O jogo não foi iniciado!\n' + 'Comece um novo jogo!');
  }
};

const btnPararJogo = document.getElementById('pararJogo');
btnPararJogo.addEventListener('click', pararJogo);

const btnJogoDaVelha = document.getElementById('jogo_wiki');
btnJogoDaVelha.addEventListener('click', () => {
  alert('Página recarregada!\n' + 'Você será redirecionado para a Wikipédia!');
  window.location.reload();
  window.open('https://pt.wikipedia.org/wiki/Jogo_da_velha');
});

 

CSS:

* {
  padding: 0;
  margin: 0;
  box-sizing: border-box;
}

.clearfix {
  padding: 30px;
  text-align: justify;
}

.float-end {
  padding: 10px;
  height: 150px;
  width: 150px;
}

.float-start {
  padding: 10px;
  height: 150px;
  width: 150px;
}

.tresD {
  height: 400px;
  width: 220px;
  position: relative;
  perspective: 1000px;
  margin: 0 auto;
}

.front,
.back {
  position: absolute;
  backface-visibility: hidden;
  transform-style: preserve-3d;
  transition: all 1s ease;
}

.front {
  transform: rotateY(0deg);
}

.back {
  transform: rotateY(180deg);
}

.tresD:hover .front {
  transform: rotateY(-180deg);
}

.tresD:hover .back {
  transform: rotateY(0deg);
}

#players {
  margin: 0 auto 50px;
  width: 250px;
  border: 2px solid black;
  background-color: #f2f2f2;
  padding: 20px;
  text-align: center;
}

h3 {
  font-size: 24px;
  color: #333;
}

label {
  font-size: 16px;
  color: #666;
}

#submit {
  margin-top: 4px;
  height: 25px;
  width: 150px;
  font-size: 14px;
}

#jogadorAtual {
  margin: 0 auto 50px;
  width: 250px;
  border: 2px solid black;
  background-color: #f2f2f2;
  padding: 20px;
  text-align: center;
  font-weight: bold;
}

#jogadorAtualh3 {
  font-size: 24px;
  color: #333;
}

#table {
  margin: 0 auto;
  width: 400px;
  border: 2px solid black;
  background-color: #f2f2f2;
  padding: 20px;
  text-align: center;
}

#table tr {
  height: 100px;
}

#table td {
  width: 100px;
  border: 1px solid black;
  font-size: 100px;
}

#table td:hover {
  border: 3px solid black;
  cursor: pointer;
}

#jogo {
  padding-bottom: 50px;
}

 

  • Curtir 2
Link para o comentário
Compartilhar em outros sites

  • Solução

Olá boa noite, eu ajustei aqui seu código apenas troquei o onclick event para click e arrow function no seu arquivo js e comentei algumas linhas também alterei seu HTML adicionando a tag script abaixo do body pois como ele acessa elementos do DOM precisa ser carregado depois segue as alterações:

let jogadoresAtivos = false;

function cellWins(cell) {
  cell.style.hover = 'transform: scale(1.2);';
}

window.onload = function () {
  document.getElementById('players').style.visibility = 'hidden';
  document.getElementById('jogadorAtual').style.visibility = 'hidden';
  document.getElementById('jogo').style.visibility = 'hidden';
};

const infoBtn = document.getElementById('info');

infoBtn.addEventListener('click', () => {
  alert(
    'Jogo da Velha feito com HTML, CSS e JavaScript\n' +
      'Desenvolvido por: @campanaricarlos\n' +
      'GitHub: https://github.com/ccampa896\n' +
      'LinkedIn: https://www.linkedin.com/in/carlos-campanari-9b4b3b1b3/\n'
  );
});

const iconsBtn = document.getElementById('icons');

iconsBtn.addEventListener('click', () => {
  alert('Icons by https://icons.getbootstrap.com/');
});

function useLightTheme() {
  document.body.style.color = '#212529';
  document.body.style.backgroundColor = '#f1f5f9';
  const hash = document.getElementById('hashtag');
  const controller = document.getElementById('controller');
  hash.style.border = '0px solid #fff';
  controller.style.border = '0px solid #fff';
}

function useDarkTheme() {
  document.body.style.color = '#f1f5f9';
  document.body.style.backgroundColor = '#212529';
  const hash = document.getElementById('hashtag');
  const controller = document.getElementById('controller');
  hash.style.margin = '10px';
  controller.style.margin = '10px';
  hash.style.border = '5px solid #fff';
  controller.style.border = '5px solid #fff';
  hash.style.borderRadius = '10px';
  controller.style.borderRadius = '10px';
}

const lightBtn = document.getElementById('is-light');
const darkBtn = document.getElementById('is-dark');

lightBtn.addEventListener('click', useLightTheme);
darkBtn.addEventListener('click', useDarkTheme);

function jogadores() {
  let elementos = document.querySelectorAll('.tresD');

  elementos.forEach(function (elemento) {
    elemento.remove();
  });

  document.getElementById('players').style.visibility = 'visible';
}

const btnJogadores = document.getElementById('jogadores');
btnJogadores.addEventListener('click', jogadores);

let NomeJogador1 = '';
let NomeJogador2 = '';

const btnSubmit = document.getElementById('submit');
btnSubmit.addEventListener('click', () => {
  NomeJogador1 = document.getElementById('jogador1').value;
  NomeJogador2 = document.getElementById('jogador2').value;
  jogadoresAtivos = true;
  alert(
    'Jogadores cadastrados!\n' +
      'Jogador 1: ' +
      NomeJogador1 +
      '\n' +
      'Jogador 2: ' +
      NomeJogador2
  );

  let elementos = document.querySelectorAll('#players');

  elementos.forEach(function (elemento) {
    elemento.remove();
  });
});

function Jogador(nome, forma) {
  this.nome = nome;
  this.forma = forma;
}

let jogador1, jogador2;

//Jogador da rodada

let jogadorAtual;

let formas = ['X', 'O'];

/*
0 1 2
3 4 5
6 7 8
*/
let tabuleiro = new Array(9);

const setLabelJogadorAtual = function () {
  document.getElementById('jogadorAtualh3').innerHTML =
    'Jogador atual:  ' + jogadorAtual.nome;
};

function iniciarJogo() {
  if (jogadoresAtivos) {
    alert(
      'Para iniciar um novo jogo, clique em "Reiniciar"\n' +
        'Ou clique em "Parar jogo" para finalizar o jogo atual!'
    );
    alert(
      'Jogo iniciado!\n' +
        'Jogador 1: ' +
        NomeJogador1 +
        '\n' +
        'Jogador 2: ' +
        NomeJogador2 +
        '\n' +
        'Boa sorte!'
    );

    jogador1 = new Jogador(NomeJogador1, 0); //X
    jogador2 = new Jogador(NomeJogador2, 1); //O
    jogadorAtual = jogador1;
    setLabelJogadorAtual();

    document.getElementById('jogadorAtual').style.visibility = 'visible';

    document.getElementById('jogo').style.visibility = 'visible';
  } else {
    alert('Você precisa informar os jogadores!');
  }
}

jogadorAtual = jogador1;

const btnIniciarJogo = document.getElementById('iniciarJogo');
btnIniciarJogo.addEventListener('click', iniciarJogo);

/*Verifica se o tabuleiro está completamente preenchido, se estiver, significa que ninguém venceu a rodada*/

tabuleiroIsFilled = function () {
  let preenchidos = 0;

  for (let i = 0; i < tabuleiro.length; i++)
    if (tabuleiro[i] != undefined) preenchidos++;

  return preenchidos == tabuleiro.length;
};

/*Verifica a existência de ocorrências de um mesmo elemento(X ou O) nas linhas do tabuleiro, procurando um vencedor*/

allElementsInSomeLine = function () {
  for (let i = 0; i < 7; i += 3) {
    if (
      tabuleiro[i] == 'X' &&
      tabuleiro[i + 1] == 'X' &&
      tabuleiro[i + 2] == 'X'
    ) {
      alert(jogador1.nome + ' wins!!!');

      pararJogo();
    }

    if (
      tabuleiro[i] == 'O' &&
      tabuleiro[i + 1] == 'O' &&
      tabuleiro[i + 2] == 'O'
    ) {
      alert(jogador2.nome + ' wins!!!');

      pararJogo();
    }
  }
};

/*Verifica a existência de ocorrências de um mesmo elemento(X ou O) nas colunas do tabuleiro, procurando um vencedor*/

allElementsInSomeColumn = function () {
  for (let i = 0; i < 3; i++) {
    if (
      tabuleiro[i] == 'X' &&
      tabuleiro[i + 3] == 'X' &&
      tabuleiro[i + 6] == 'X'
    ) {
      alert(jogador1.nome + ' wins!!!');

      pararJogo();
    }

    if (
      tabuleiro[i] == 'O' &&
      tabuleiro[i + 3] == 'O' &&
      tabuleiro[i + 6] == 'O'
    ) {
      alert(jogador2.nome + ' wins!!!');

      pararJogo();
    }
  }
};

/*Verifica a existência de ocorrências de um mesmo elemento(X ou O) nas diagonais do tabuleiro, procurando um vencedor*/

allElementsInSomeDiagonal = function () {
  if (
    (tabuleiro[0] == 'X' && tabuleiro[4] == 'X' && tabuleiro[8] == 'X') ||
    (tabuleiro[2] == 'X' && tabuleiro[4] == 'X' && tabuleiro[6] == 'X')
  ) {
    alert(jogador1.nome + ' wins!!!');

    pararJogo();
  } else if (
    (tabuleiro[0] == 'O' && tabuleiro[4] == 'O' && tabuleiro[8] == 'O') ||
    (tabuleiro[2] == 'O' && tabuleiro[4] == 'O' && tabuleiro[6] == 'O')
  ) {
    alert(jogador2.nome + ' wins!!!');

    pararJogo();
  }
};

/*Preenche a célula da tabela HTML escolhida pelo usuário ao clicar, além de cuidar do jogador atual da rodada e chamar as funções


de verificação de algum ganhador */

function setOnCeil(cell, pos) {
  if (tabuleiro[pos] == undefined) {
    cell.textContent = jogadorAtual.forma;
    tabuleiro[pos] = jogadorAtual.forma;

    if (jogadorAtual == jogador1) {
      jogadorAtual = jogador2;
    } else {
      jogadorAtual = jogador1;
    }

    setLabelJogadorAtual();
  } else {
    alert('Célula já preenchida! Escolha outra!');
  }

  allElementsInSomeLine();

  allElementsInSomeColumn();

  allElementsInSomeDiagonal();

  if (tabuleiroIsFilled()) {
    alert('Nobody wins! :(. Try Again');

    pararJogo();
  }
}

const btnCell0 = document.getElementById('cell0');
const btnCell1 = document.getElementById('cell1');
const btnCell2 = document.getElementById('cell2');
const btnCell3 = document.getElementById('cell3');
const btnCell4 = document.getElementById('cell4');
const btnCell5 = document.getElementById('cell5');
const btnCell6 = document.getElementById('cell6');
const btnCell7 = document.getElementById('cell7');
const btnCell8 = document.getElementById('cell8');

btnCell0.addEventListener('click', () => setOnCeil(btnCell0, 0));
btnCell1.addEventListener('click', () => setOnCeil(btnCell1, 1));
btnCell2.addEventListener('click', () => setOnCeil(btnCell2, 2));
btnCell3.addEventListener('click', () => setOnCeil(btnCell3, 3));
btnCell4.addEventListener('click', () => setOnCeil(btnCell4, 4));
btnCell5.addEventListener('click', () => setOnCeil(btnCell5, 5));
btnCell6.addEventListener('click', () => setOnCeil(btnCell6, 6));
btnCell7.addEventListener('click', () => setOnCeil(btnCell7, 7));
btnCell8.addEventListener('click', () => setOnCeil(btnCell8, 8));

const pararJogo = function () {
  if (jogadoresAtivos) {
    alert(
      'Jogo finalizado!\n' + 'Obrigado por jogar!\n' + 'Página recarregada!'
    );
    jogadoresAtivos = false;
    // document.getElementById('jogador1').value = '';
    // document.getElementById('jogador2').value = '';
    window.location.reload();
  } else {
    alert('O jogo não foi iniciado!\n' + 'Comece um novo jogo!');
  }
};

const btnPararJogo = document.getElementById('pararJogo');
btnPararJogo.addEventListener('click', pararJogo);

const btnJogoDaVelha = document.getElementById('jogo_wiki');
btnJogoDaVelha.addEventListener('click', () => {
  alert('Página recarregada!\n' + 'Você será redirecionado para a Wikipédia!');
  window.location.reload();
  window.open('https://pt.wikipedia.org/wiki/Jogo_da_velha');
});
<!DOCTYPE html>
<html lang="pt-BR">

<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" />
  <title>Jogo da Velha</title>
  <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet"
    integrity="sha384-aFq/bzH65dt+w6FI2ooMVUpc+21e0SRygnTpmBvdBgSdnuTN7QbdgL+OapgHtvPp" crossorigin="anonymous" />
  <link rel="stylesheet" href="./style.css" />
  <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"
    integrity="sha384-qKXV1j0HvMUeCBQ+QVp7JcfGl760yU08IQ+GpUo5hlbpg51QRiuqHAJz8+BrxE/N"
    crossorigin="anonymous"></script>

</head>

<body>
  <header>
    <nav class="navbar bg-body-tertiary">
      <div class="container-fluid">
        <a class="navbar-brand" title="Jogo da Velha: Wikipédia, a enciclopédia livre" href="#" id="jogo_wiki">
          <img src="./imagens/hash.svg" alt="Logo" width="30" height="24" class="d-inline-block align-text-top" />
          Jogo da Velha
        </a>
        <a class="navbar-brand" id="jogadores" href="#">
          <img src="./imagens/person-fill.svg" alt="Logo" width="30" height="24"
            class="d-inline-block align-text-top" />
          Jogadores
        </a>
        <a class="navbar-brand" id="iniciarJogo" href="#">
          <img src="./imagens/play-circle.svg" alt="Logo" width="30" height="24"
            class="d-inline-block align-text-top" />
          Iniciar
        </a>
        <a class="navbar-brand" href="#">
          <img src="./imagens/repeat.svg" alt="Logo" width="30" height="24" class="d-inline-block align-text-top" />
          Reiniciar
        </a>
        <a class="navbar-brand" id="pararJogo" href="#">
          <img src="./imagens/x-lg.svg" alt="Logo" width="30" height="24" class="d-inline-block align-text-top" />
          Parar jogo
        </a>
        <a class="navbar-brand" id="is-light" href="#">
          <img src="./imagens/sun-fill.svg" alt="Logo" width="30" height="24" class="d-inline-block align-text-top" />
          Modo Claro
        </a>
        <a class="navbar-brand" id="is-dark" href="#">
          <img src="./imagens/moon-fill.svg" alt="Logo" width="30" height="24" class="d-inline-block align-text-top" />
          Modo Escuro
        </a>
        <a class="navbar-brand" id="info" href="#">
          <img src="./imagens/info.svg" alt="Logo" width="30" height="24" class="d-inline-block align-text-top" />
          Info
        </a>
        <a class="navbar-brand" id="icons" href="#">
          <img src="./imagens/images.svg" alt="Logo" width="30" height="24" class="d-inline-block align-text-top" />
          Icons
        </a>
      </div>
    </nav>
  </header>

  <div class="clearfix">
    <img src="./imagens/hash.svg" class="float-end" id="hashtag" alt="hashtag" />
    <p>
      O jogo da velha (português brasileiro) ou jogo do galo (português
      europeu) ou três em linha é um jogo e/ou passatempo popular. É um jogo
      de regras extremamente simples, que não traz grandes dificuldades para
      seus jogadores e é facilmente aprendido. A origem é desconhecida, com
      indicações de que pode ter começado no antigo Egito, onde foram
      encontrados tabuleiros esculpidos na rocha, que teriam mais de 3.500
      anos. De alguma forma, é um jogo "aparentado" dos "Merels".
    </p>
    <img src="./imagens/controller.svg" class="float-start" id="controller" alt="controller" />
    <p>
      Algumas lendas urbanas contam que o jogo terá nascido em Portugal, na
      cidade de Almada no ano 545. No entanto, só foi popularizado no ano
      1500, pelo descobridor Pedro Álvares Cabral, que adorava jogar este jogo
      durante as suas viagens. Álvares Cabral terá decidido que este jogo
      seria o primeiro a ser ensinado ao povo indígena no Brasil. O jogo pode
      ser jogado sobre um tabuleiro ou mesmo sendo riscado sobre um pedaço de
      papel ou mesa. O menor tabuleiro do mundo foi feito com DNA.
    </p>
    <p>
      Se os dois jogadores jogarem sempre da melhor forma, o jogo terminará
      sempre em empate. A lógica do jogo é muito simples, de modo que não é
      difícil deduzir ou decorar todas as possibilidades para efetuar a melhor
      jogada - apesar de o número total de possibilidades ser muito grande, a
      maioria delas é simétrica, além de que as regras são simples. Por esse
      motivo, é muito comum que o jogo empate (ou "dê velha").
    </p>
    <br />
    <div class="tresD">
      <div class="front">
        <img src="./imagens/notebook.png" alt="Tecnologia da Informação" />
      </div>
      <div class="back">
        <img src="./imagens/hash.png" alt="Tecnologia da Informação" />
      </div>
    </div>
  </div>
  <div id="jogadorAtual">
    <h3 id="jogadorAtualh3"></h3>
  </div>
  <div id="players">
    <h3>Jogadores</h3>
    <label for="Jogador 1"> Jogador 1: </label>
    <input type="text" id="jogador1" />
    <br />
    <br />
    <label for="Jogador 1"> Jogador 2: </label>
    <input type="text" id="jogador2" />
    <br />
    <br />
    <input type="submit" id="submit" value="Ok" />
  </div>
  <div id="jogo">
    <table cellpadding="0" cellspacing="0" id="table">
      <tr>
        <td class="table-data" id="cell0">
          &nbsp;
        </td>

        <td class="table-data" id="cell1">
          &nbsp;
        </td>

        <td class="table-data" id="cell2">
          &nbsp;
        </td>
      </tr>

      <tr>
        <td class="table-data" id="cell3">
          &nbsp;
        </td>

        <td class="table-data" id="cell4">
          &nbsp;
        </td>

        <td class="table-data" id="cell5">
          &nbsp;
        </td>
      </tr>

      <tr>
        <td class="table-data" id="cell6">
          &nbsp;
        </td>

        <td class="table-data" id="cell7">
          &nbsp;
        </td>

        <td class="table-data" id="cell8">
          &nbsp;
        </td>
      </tr>
    </table>
  </div>
  <script src="./index.js"></script>
</body>

</html>

 

  • Curtir 1
  • Amei 1
Link para o comentário
Compartilhar em outros sites

Muito obrigado @Alexsander Gutierrez, realmente o que estava faltando é o arrow function.

 

Porém esbarrei em outro problema. O primeiro foi adicionar o evento, e agora quero retirar. 😅

 

Após ser declarado o jogador vencedor, os eventos de adicionar elementos no tabuleiro continua funcionando. Eu quero deixar sem eventos, após declarado o vencedor. Porém, a minha função "removeClicks" adicionada após a declaração dos vencedores não funciona. Pesquisei usando até o ChatGPT e não localizo o erro, pois ele retorna que está tudo certo. Sabe orientar onde está o erro?

 

let jogadoresAtivos = false;

function removeClicks() {
  const btnClick = document.querySelectorAll('.table-data');

  btnClick.forEach(function (elemento) {
    elemento.removeEventListener('click', setOnCeil);
  });
}

function cellWins(cell) {
  cell.style.border = '8px solid #F94A29';
  cell.style.backgroundColor = '#FC7300';
}

window.onload = function () {
  document.getElementById('players').style.visibility = 'hidden';
  document.getElementById('jogadorAtual').style.visibility = 'hidden';
  document.getElementById('jogo').style.visibility = 'hidden';
};

const infoBtn = document.getElementById('info');

infoBtn.addEventListener('click', () => {
  alert(
    'Jogo da Velha feito com HTML, CSS e JavaScript\n' +
      'Desenvolvido por: @campanaricarlos\n' +
      'GitHub: https://github.com/ccampa896\n' +
      'LinkedIn: https://www.linkedin.com/in/carlos-campanari-9b4b3b1b3/\n'
  );
});

const iconsBtn = document.getElementById('icons');

iconsBtn.addEventListener('click', () => {
  alert('Icons by https://icons.getbootstrap.com/');
});

function useLightTheme() {
  document.body.style.color = '#212529';
  document.body.style.backgroundColor = '#f1f5f9';
  const hash = document.getElementById('hashtag');
  const controller = document.getElementById('controller');
  hash.style.border = '0px solid #fff';
  controller.style.border = '0px solid #fff';
}

function useDarkTheme() {
  document.body.style.color = '#f1f5f9';
  document.body.style.backgroundColor = '#212529';
  const hash = document.getElementById('hashtag');
  const controller = document.getElementById('controller');
  hash.style.margin = '10px';
  controller.style.margin = '10px';
  hash.style.border = '5px solid #fff';
  controller.style.border = '5px solid #fff';
  hash.style.borderRadius = '10px';
  controller.style.borderRadius = '10px';
}

const lightBtn = document.getElementById('is-light');
const darkBtn = document.getElementById('is-dark');

lightBtn.addEventListener('click', useLightTheme);
darkBtn.addEventListener('click', useDarkTheme);

function jogadores() {
  let elementos = document.querySelectorAll('.tresD');

  elementos.forEach(function (elemento) {
    elemento.remove();
  });

  document.getElementById('players').style.visibility = 'visible';
}

const btnJogadores = document.getElementById('jogadores');
btnJogadores.addEventListener('click', jogadores);

let NomeJogador1 = '';
let NomeJogador2 = '';

const btnSubmit = document.getElementById('submit');
btnSubmit.addEventListener('click', () => {
  NomeJogador1 = document.getElementById('jogador1').value;
  NomeJogador2 = document.getElementById('jogador2').value;
  jogadoresAtivos = true;
  alert(
    'Jogadores cadastrados!\n' +
      'Jogador 1: ' +
      NomeJogador1 +
      '\n' +
      'Jogador 2: ' +
      NomeJogador2
  );

  let elementos = document.querySelectorAll('#players');
  document.getElementById('jogador1').value = '';
  document.getElementById('jogador2').value = '';

  elementos.forEach(function (elemento) {
    elemento.remove();
  });
});

function Jogador(nome, forma) {
  this.nome = nome;
  this.forma = forma;
}

let jogador1, jogador2;

//Jogador da rodada

let jogadorAtual;

let formas = ['X', 'O'];

/*
0 1 2
3 4 5
6 7 8
*/
let tabuleiro = new Array(9);

const setLabelJogadorAtual = function () {
  document.getElementById('jogadorAtualh3').innerHTML =
    'Jogador atual:  ' + jogadorAtual.nome;
};

function iniciarJogo() {
  if (jogadoresAtivos) {
    alert(
      'Para iniciar um novo jogo, clique em "Reiniciar"\n' +
        'Ou clique em "Parar jogo" para finalizar o jogo atual!'
    );
    alert(
      'Jogo iniciado!\n' +
        'Jogador 1: ' +
        NomeJogador1 +
        '\n' +
        'Jogador 2: ' +
        NomeJogador2 +
        '\n' +
        'Boa sorte!'
    );

    jogador1 = new Jogador(NomeJogador1, 0); //X
    jogador2 = new Jogador(NomeJogador2, 1); //O
    jogadorAtual = jogador1;
    setLabelJogadorAtual();

    document.getElementById('jogadorAtual').style.visibility = 'visible';

    document.getElementById('jogo').style.visibility = 'visible';
  } else {
    alert('Você precisa informar os jogadores!');
  }
}

const btnIniciarJogo = document.getElementById('iniciarJogo');
btnIniciarJogo.addEventListener('click', iniciarJogo);

/*Verifica se o tabuleiro está completamente preenchido, se estiver, significa que ninguém venceu a rodada*/

tabuleiroIsFilled = function () {
  let preenchidos = 0;

  for (let i = 0; i < tabuleiro.length; i++)
    if (tabuleiro[i] != undefined) preenchidos++;

  return preenchidos == tabuleiro.length;
};

/*Verifica a existência de ocorrências de um mesmo elemento(X ou O) nas linhas do tabuleiro, procurando um vencedor*/
const table_datas = document.querySelectorAll('.table-data');

allElementsInSomeLine = function () {
  for (let i = 0; i < 7; i += 3) {
    if (
      tabuleiro[i] == 'X' &&
      tabuleiro[i + 1] == 'X' &&
      tabuleiro[i + 2] == 'X'
    ) {
      cellWins(table_datas[i]);
      cellWins(table_datas[i + 1]);
      cellWins(table_datas[i + 2]);
      alert(jogador1.nome + ' wins!!!');
      removeClicks();
    }
    if (
      tabuleiro[i] == 'O' &&
      tabuleiro[i + 1] == 'O' &&
      tabuleiro[i + 2] == 'O'
    ) {
      cellWins(table_datas[i]);
      cellWins(table_datas[i + 1]);
      cellWins(table_datas[i + 2]);
      alert(jogador2.nome + ' wins!!!');
      removeClicks();
    }
  }
};

/*Verifica a existência de ocorrências de um mesmo elemento(X ou O) nas colunas do tabuleiro, procurando um vencedor*/

allElementsInSomeColumn = function () {
  for (let i = 0; i < 3; i++) {
    if (
      tabuleiro[i] == 'X' &&
      tabuleiro[i + 3] == 'X' &&
      tabuleiro[i + 6] == 'X'
    ) {
      cellWins(table_datas[i]);
      cellWins(table_datas[i + 3]);
      cellWins(table_datas[i + 6]);
      alert(jogador1.nome + ' wins!!!');
      removeClicks();
      if (
        tabuleiro[i] == 'O' &&
        tabuleiro[i + 3] == 'O' &&
        tabuleiro[i + 6] == 'O'
      ) {
        cellWins(table_datas[i]);
        cellWins(table_datas[i + 3]);
        cellWins(table_datas[i + 6]);
        alert(jogador2.nome + ' wins!!!');
        removeClicks();
      }
    }
  }
};
/*Verifica a existência de ocorrências de um mesmo elemento(X ou O) nas diagonais do tabuleiro, procurando um vencedor*/

allElementsInSomeDiagonal = function () {
  if (tabuleiro[0] == 'X' && tabuleiro[4] == 'X' && tabuleiro[8] == 'X') {
    alert(jogador1.nome + ' wins!!!');
    cellWins(table_datas[0]);
    cellWins(table_datas[4]);
    cellWins(table_datas[8]);
    removeClicks();
  } else if (
    tabuleiro[2] == 'X' &&
    tabuleiro[4] == 'X' &&
    tabuleiro[6] == 'X'
  ) {
    alert(jogador1.nome + ' wins!!!');
    cellWins(table_datas[2]);
    cellWins(table_datas[4]);
    cellWins(table_datas[6]);
    removeClicks();
  } else if (
    tabuleiro[0] == 'O' &&
    tabuleiro[4] == 'O' &&
    tabuleiro[8] == 'O'
  ) {
    alert(jogador2.nome + ' wins!!!');
    cellWins(table_datas[0]);
    cellWins(table_datas[4]);
    cellWins(table_datas[8]);
    removeClicks();
  } else if (
    tabuleiro[2] == 'O' &&
    tabuleiro[4] == 'O' &&
    tabuleiro[6] == 'O'
  ) {
    alert(jogador2.nome + ' wins!!!');
    cellWins(table_datas[2]);
    cellWins(table_datas[4]);
    cellWins(table_datas[6]);
    removeClicks();
  }
};

const btnCell0 = document.getElementById('cell0');
const btnCell1 = document.getElementById('cell1');
const btnCell2 = document.getElementById('cell2');
const btnCell3 = document.getElementById('cell3');
const btnCell4 = document.getElementById('cell4');
const btnCell5 = document.getElementById('cell5');
const btnCell6 = document.getElementById('cell6');
const btnCell7 = document.getElementById('cell7');
const btnCell8 = document.getElementById('cell8');

/*Preenche a célula da tabela HTML escolhida pelo usuário ao clicar, além de cuidar do jogador atual da rodada e chamar as funções


de verificação de algum ganhador */

function setOnCeil(cell, pos) {
  if (tabuleiro[pos] == undefined) {
    cell.innerText = formas[jogadorAtual.forma];
    tabuleiro[pos] = formas[jogadorAtual.forma];

    if (jogadorAtual == jogador1) {
      jogadorAtual = jogador2;
    } else {
      jogadorAtual = jogador1;
    }

    setLabelJogadorAtual();
  } else {
    alert('Célula já preenchida! Escolha outra!');
  }

  allElementsInSomeLine();

  allElementsInSomeColumn();

  allElementsInSomeDiagonal();

  if (tabuleiroIsFilled()) {
    alert('Nobody wins! :(. Try Again');

    pararJogo();
  }
}

btnCell0.addEventListener('click', () => {
  setOnCeil(btnCell0, 0);
});
btnCell1.addEventListener('click', () => {
  setOnCeil(btnCell1, 1);
});
btnCell2.addEventListener('click', () => {
  setOnCeil(btnCell2, 2);
});
btnCell3.addEventListener('click', () => {
  setOnCeil(btnCell3, 3);
});
btnCell4.addEventListener('click', () => {
  setOnCeil(btnCell4, 4);
});
btnCell5.addEventListener('click', () => {
  setOnCeil(btnCell5, 5);
});
btnCell6.addEventListener('click', () => {
  setOnCeil(btnCell6, 6);
});
btnCell7.addEventListener('click', () => {
  setOnCeil(btnCell7, 7);
});
btnCell8.addEventListener('click', () => {
  setOnCeil(btnCell8, 8);
});

function pararJogo() {
  if (jogadoresAtivos) {
    alert(
      'Jogo finalizado!\n' + 'Obrigado por jogar!\n' + 'Página recarregada!'
    );
    jogadoresAtivos = false;
    window.location.reload();
  } else {
    alert('O jogo não foi iniciado!\n' + 'Comece um novo jogo!');
  }
}

const btnPararJogo = document.getElementById('pararJogo');
btnPararJogo.addEventListener('click', pararJogo);

const btnJogoDaVelha = document.getElementById('jogo_wiki');
btnJogoDaVelha.addEventListener('click', () => {
  alert('Página recarregada!\n' + 'Você será redirecionado para a Wikipédia!');
  window.location.reload();
  window.open('https://pt.wikipedia.org/wiki/Jogo_da_velha');
});

const btnResetarJogo = document.getElementById('reset');
btnResetarJogo.addEventListener('click', () => {
  alert('Página recarregada!\n' + 'Jogo resetado!');
  window.location.reload();
});

 

  • Curtir 2
Link para o comentário
Compartilhar em outros sites

Olá boa tarde, você pode atribuir um método no evento de click pela propriedade onclick e depois para remover definir como undefined, ou utilizando o removeEventListener você precisa ter a função declarada no código que seriam nove funções, e passar cada referencia dessa função para o removeEventListener de cada botão, segue os exemplos:

com o onclick:

const btnCell0 = document.getElementById('cell0');
const btnCell1 = document.getElementById('cell1');
const btnCell2 = document.getElementById('cell2');
const btnCell3 = document.getElementById('cell3');
const btnCell4 = document.getElementById('cell4');
const btnCell5 = document.getElementById('cell5');
const btnCell6 = document.getElementById('cell6');
const btnCell7 = document.getElementById('cell7');
const btnCell8 = document.getElementById('cell8');

btnCell1.onclick = () => setOnCeil(btnCell1, 1);
btnCell2.onclick = () => setOnCeil(btnCell2, 2);
btnCell3.onclick = () => setOnCeil(btnCell3, 3);
btnCell4.onclick = () => setOnCeil(btnCell4, 4);
btnCell5.onclick = () => setOnCeil(btnCell5, 5);
btnCell6.onclick = () => setOnCeil(btnCell6, 6);
btnCell7.onclick = () => setOnCeil(btnCell7, 7);
btnCell8.onclick = () => setOnCeil(btnCell8, 8);

function removeClicks = () => {
    btnCell0.onclick = undefined;
    btnCell1.onclick = undefined;
    btnCell2.onclick = undefined;
    btnCell3.onclick = undefined;
    btnCell4.onclick = undefined;
    btnCell5.onclick = undefined;
    btnCell6.onclick = undefined;
    btnCell7.onclick = undefined;
    btnCell8.onclick = undefined;
}

 

com o removeEventListener:

 

const btnCell0 = document.getElementById('cell0');
const btnCell1 = document.getElementById('cell1');
const btnCell2 = document.getElementById('cell2');
const btnCell3 = document.getElementById('cell3');
const btnCell4 = document.getElementById('cell4');
const btnCell5 = document.getElementById('cell5');
const btnCell6 = document.getElementById('cell6');
const btnCell7 = document.getElementById('cell7');
const btnCell8 = document.getElementById('cell8');

const setCell0 = () => setOnCeil(btnCell0, 0);
const setCell1 = () => setOnCeil(btnCell1, 1);
const setCell2 = () => setOnCeil(btnCell2, 2);
const setCell3 = () => setOnCeil(btnCell3, 3);
const setCell4 = () => setOnCeil(btnCell4, 4);
const setCell5 = () => setOnCeil(btnCell5, 5);
const setCell6 = () => setOnCeil(btnCell6, 6);
const setCell7 = () => setOnCeil(btnCell7, 7);
const setCell8 = () => setOnCeil(btnCell8, 8);

btnCell0.addEventListener('click', setCell0);
btnCell1.addEventListener('click', setCell1);
btnCell2.addEventListener('click', setCell2);
btnCell3.addEventListener('click', setCell3);
btnCell4.addEventListener('click', setCell4);
btnCell5.addEventListener('click', setCell5);
btnCell6.addEventListener('click', setCell6);
btnCell7.addEventListener('click', setCell7);
btnCell8.addEventListener('click', setCell8);

function removeClicks() {
  btnCell0.removeEventListener('click', setCell0);
  btnCell1.removeEventListener('click', setCell1);
  btnCell2.removeEventListener('click', setCell2);
  btnCell3.removeEventListener('click', setCell3);
  btnCell4.removeEventListener('click', setCell4);
  btnCell5.removeEventListener('click', setCell5);
  btnCell6.removeEventListener('click', setCell6);
  btnCell7.removeEventListener('click', setCell7);
  btnCell8.removeEventListener('click', setCell8);
}

 

qualquer duvidas estou a disposição!

  • Curtir 1
  • Amei 1
Link para o comentário
Compartilhar em outros sites

Crie uma conta ou entre para comentar

Você precisa ser um usuário para fazer um comentário

Criar uma conta

Crie uma nova conta em nossa comunidade. É fácil!

Crie uma nova conta

Entrar

Já tem uma conta? Faça o login.

Entrar agora

Sobre o Clube do Hardware

No ar desde 1996, o Clube do Hardware é uma das maiores, mais antigas e mais respeitadas comunidades sobre tecnologia do Brasil. Leia mais

Direitos autorais

Não permitimos a cópia ou reprodução do conteúdo do nosso site, fórum, newsletters e redes sociais, mesmo citando-se a fonte. Leia mais

×
×
  • Criar novo...

Ebook grátis: Aprenda a ler resistores e capacitores!

EBOOK GRÁTIS!

CLIQUE AQUI E BAIXE AGORA MESMO!