Error in logic game in old game in JavaScript?

0

I'm learning JavaScript and want to make a game of the old one to train. The game is not working and I think it might be a logic bug.

  

function verificar(elemento) {
  var teste = document.getElementById(elemento).innerHTML;

  if (teste == "") {
    teste = "X";
  } else {
    teste = "Y";
  }
}
.container {
  max-width: 130px;
}

.tab {
  float: left;
  height: 30px;
  width: 30px;
  border: solid green 2px;
}
<div class="container">
  <div class="tab" id="q1" onlick="verificar(this.id);"></div>
  <div class="tab" id="q2" onlick="verificar(this.id);"></div>
  <div class="tab" id="q3" onlick="verificar(this.id);"></div>
  <div class="tab" id="q4" onlick="verificar(this.id);"></div>
  <div class="tab" id="q5" onlick="verificar(this.id);"></div>
  <div class="tab" id="q6" onlick="verificar(this.id);"></div>
  <div class="tab" id="q7" onlick="verificar(this.id);"></div>
  <div class="tab" id="q8" onlick="verificar(this.id);"></div>
  <div class="tab" id="q9" onlick="verificar(this.id);"></div>
</div>
    
asked by anonymous 12.12.2018 / 12:45

1 answer

2

Correcting just what you've already set up.

function verificar(elemento) {
  if(elemento.innerHTML == "") {
    elemento.innerHTML = "X";
  } else {
    elemento.innerHTML = "Y";
  }
}
.container {
  max-width: 130px;
}

.tab {
  float: left;
  height: 30px;
  width: 30px;
  border: solid green 2px;
}
<div class="container">
  <div class="tab" id="q1" onclick="verificar(this);"></div>
  <div class="tab" id="q2" onclick="verificar(this);"></div>
  <div class="tab" id="q3" onclick="verificar(this);"></div>
  <div class="tab" id="q4" onclick="verificar(this);"></div>
  <div class="tab" id="q5" onclick="verificar(this);"></div>
  <div class="tab" id="q6" onclick="verificar(this);"></div>
  <div class="tab" id="q7" onclick="verificar(this);"></div>
  <div class="tab" id="q8" onclick="verificar(this);"></div>
  <div class="tab" id="q9" onclick="verificar(this);"></div>
</div>

First, as Anderson pointed out, you wrote "onlick" instead of onclick . I also left your code a bit simpler by taking this.id and replacing with only this that will pass the entire div to the function, then just refer to it by element without having to do any kind of DOM query. Another thing pointed out by Anderson in the comments is that you were modifying the value of the variable rather than the innerHTML of the element, so it was not going as it wanted.

There are more problems in this game to be really a game of the old one, for example, when clicking on a square already with X it becomes Y, but does not return to X if clicked again, outside that the game should not allow someone clicked on an already occupied square. It also needs to be validated if the person wins, lost, or has a tie.

    
12.12.2018 / 12:59