How to change the color when clicking?

Asked

Viewed 117 times

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();

1 answer

4


You can create two css classes: classeX, with background-color: greenand classeO with background-color: green, and, in Function render(), which is the one that generates the table, add the class according to the variable "column" which in this case is "X" or "O":

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)=>{
                var classeCor = "fundo" + column;
                
                template += `<td class="${classeCor}" id = "CC" onclick = "Game.setField(${lineIndex}, ${columnIndex})">${column}</td>`

            })
            template+='</tr>'
        })
        tableElement.innerHTML = template;
    }
}

Game.start();
table,td, tr{
            border: 1px solid black;
            text-align: center;
        }
        td{
            width: 50px;
            height: 50px;
        }
        
        .fundo {
          background-color: #fff
        }
        .fundoX {
          background-color: green
        }
        .fundoO {
          background-color: red
        }
 <div></div>
 <table></table>
 <button onclick="Game.start();">Restart</button>

  • was worth, that’s what I really wanted to do.

  • 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 :)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.