-2
I’m doing an old game and added an eventListenner to each space, so that as soon as I clicked, the image would change. But it’s not working and I can’t understand why.
Follow js, HTML, CSS and images
const player1 ="X";
const player2 ="O";
var playTime = player1;
var gameOver = false;
updateDisplay();
initiateSpaces();
function updateDisplay(){
if(gameOver){
return;
}
if (playTime == player1)
{
var player =document.querySelectorAll("div.display img")[0];
player.setAttribute("src", "./Assets/images/X.png");
}
else{
var player = document.querySelectorAll("div.display img")[0];
player.setAttribute("src","Assets/images/circle.png");
}
}
function initiateSpaces(){
var spaces = document.getElementsByClassName("space");
//Adicionando um EventListner para cada Espaço
for (let index = 0; index < spaces.length; index++) {
spaces[index].addEventListener("click",function(){
if (gameOver){
return;
}
//Adicionando a condição para o click
if(this.getElementsByTagName("img").length ==0){
if(playTime == player1){
this.innerHtml = "<img src ='./Assets/images/X.png'>"
this.setAttribute("jogada",player1);
playTime = player2;
}
if(playTime ==player2){
this.innerHtml = "<img src ='./Assets/images/circle.png'>"
this.setAttribute("jogada",player2);
playTime = player1;
}
updateDisplay();
}
});
}
}
.game{
display: flex;
justify-content: center;
align-items: center;
flex-direction: column;
}
.game > .table >.space{
width: 80px;
height: 65px;
border:2px solid black;
float: left;
text-align:center;
padding-top: 15px;
}
.table{
width:calc(84*3px);
}
.display{
margin-top:30px;
margin-bottom:20px;
display: flex;
align-items: center;
}
.image{
margin-right: 200px;
}
.game > .table > .a-line{
border-top: none;
}
.game > .table > .c-line{
border-bottom:none;
}
.game > .table > .column-1{
border-left:none;
}
.game > .table > .column-3{
border-right:none;
}
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8'>
<meta http-equiv='X-UA-Compatible' content='IE=edge'>
<title>Page Title</title>
<meta name='viewport' content='width=device-width, initial-scale=1'>
<link rel='stylesheet' type='text/css' media='screen' href='./Assets/CSS/index.css'>
</head>
<body>
<div class="game">
<div class="display">
<p style="float: left;">Vez do Jogador: </p>
<img src="" height="50" >
</div>
<div class="table">
<div id="a1" class="space a-line column-1" jogada="">
<img src="" alt="">
</div>
<div id="a2" class="space a-line column-2" jogada="">
</div>
<div id="a3" class="space a-line column-3" jogada="">
</div>
<div id="b1" class="space b-line column-1" jogada="">
</div>
<div id="b2" class="space b-line column-2" jogada ="">
</div>
<div id="b3" class="space b-line column-3" jogada ="">
</div>
<div id="c1" class="space c-line column-1" jogada ="">
</div>
<div id="c2" class="space c-line column-2" jogada ="">
</div>
<div id="c3" class="space c-line column-3" jogada ="">
</div>
</div>
</div>
<script type="text/javascript" src="./Assets/JS/main.js"></script>
</body>
</html>