2
This is an old game created in JS. is working right. I want to change the color every time I click on the squares. for example: when I click on the square the 'X' turns red, when I click on another the 'O' frame turns green. I tried to change the field in JS nextPlayer function, but I’m not getting it. Could you help me?
HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<div></div>
<table></table>
<button onclick="Game.start();">Restart</button>
<style>
table,td, tr{
border: 1px solid black;
text-align: center;
}
td{
width: 50px;
height: 50px;
}
</style>
<script src="./scripts.js"></script>
</body>
</html>
JS
var divElement = document.querySelector('div'),
tableElement = document.querySelector('table')
var Game ={
start(){
this.field = [
['','',''],
['','',''],
['','','']
];
this.currentPlayer = 'X';
this.isFinished = false;
this.round = 0;
this.render();
},
nextPlayer(){
if(this.currentPlayer ==='X'){
document.querySelector("td").style.color="red"
document.getElementById('CC').style.backgroundColor = 'Green'
}
this.currentPlayer = this.currentPlayer ==='X' ? 'O' : 'X';
},
setField(line,column){
if(!this.isFinished && this.field[line][column]===''){
this.field[line][column] = this.currentPlayer;
this.nextPlayer();
this.round++;
this.render();
}
},
isGameOver(){
var field = this.field,
rows =3,
cols =3,
totalRow = 0,
totalCol = 0;
for(var i =0; i<rows; i++){
totalRow = 0,
totalCol = 0;
for(var j = 0; j< cols; j++){
if(field[i][j] ==='X'){
totalRow++;
}
if(field[i][j] ==='O'){
totalRow--;
}
if(field[j][i] ==='X'){
totalCol++;
}
if(field[j][i] ==='O'){
totalCol--;
}
}
if(totalRow ===3 || totalCol ===3){
return 'X'
}
if(totalRow ===-3 || totalCol ===-3){
return 'O'
}
}
if(field[0][0] !=='' && field[0][0] === field[1][1] && field[1][1] ==field[2][2]){
return field[0][0];
}
if(field[0][2] !=='' && field[0][2] === field[1][1] && field[1][1] ==field[2][0]){
return field[0][2];
}
if(this.round === 9){
return 'Ninguem'
}
},
render(){
var winner = this.isGameOver();
divElement.textContent = winner ? `Winner: ${winner}` : `Current Player: ${this.currentPlayer}`
if(winner){
this.isFinished = true;
}
var template = '';
this.field.forEach((line, lineIndex) => {
template +='<tr>';
line.forEach((column,columnIndex)=>{
template += `<td id = "CC" onclick = "Game.setField(${lineIndex}, ${columnIndex})">${column}</td>`
})
template+='</tr>'
})
tableElement.innerHTML = template;
}
}
Game.start();
was worth, that’s what I really wanted to do.
– vitJS
good. a suggestion would run the render the first time, and go just updating on the click, but as it is quite small the table has no problem. don’t forget to mark the answer if it helped resolve :)
– Ricardo Pontual