Ad

Trying To Change Cell Image Once Clicked, Doesnt Change Upon Click

- 1 answer

I m trying to change the img on the cell once i click on it, however that does not happen, an explanation and a solution would be nice.

I am manually setting gBoard[0][0].isFlagged to true, and then clicking the cell, the img does not change.

html

<!DOCTYPE html>
<html>
<head>
    <meta content="width=device-width, initial-scale=1.0" name="viewport">
    <meta content="ie=edge" http-equiv="X-UA-Compatible">
    <title>Document</title>
    <link target="_blank" rel="nofollow noreferrer" href="css/game.css" rel="stylesheet">
</head>
<body onload="init()">
    <h1>Welcome to minesweeper</h1>
    <div class="board-container"></div><button class="restart-Btn" onclick="restartGame(this)">restartGame</button> 
    <script src="js/utils.js">
    </script> 
    <script src="js/game.js">
    </script>
</body>
</html>

script

const TILE = '<img src="/img/tile.png" >'
const TWO = '<img src="/img/2.png" >'

function printMat(mat, selector) {
    var strHTML = '<table border="1"><tbody>';
    for (var i = 0; i < mat.length; i++) {
        strHTML += '<tr>';
        for (var j = 0; j < mat[0].length; j++) {
            var className = `cell-${i}-${j}`
            strHTML +=
                `<td class="${className}" 
              onclick="cellClicked(this, ${i}, ${j})">
                <img src="${mat[i][j].image}" >
            </td>`
        }
        strHTML += '</tr>'
    }
    strHTML += '</tbody></table>';
    var elContainer = document.querySelector(selector);
    elContainer.innerHTML = strHTML;
}

function createBoard(size) {
    var board = []
    for (var i = 0; i < size; i++) {
        board[i] = []
        for (var j = 0; j < size; j++) {
            board[i][j] = creatCell()
        }
    }
    return board
}

function creatCell() {
    return {
        isBomb: false,
        isFlagged: false,
        isClicked: false,
        isOpen: false,
        image: "/img/tile.png"
    }
}
function cellClicked(elCell, i, j) {

    if (gBoard[i][j].image === TILE && gBoard[i][j].isFlagged === true) {

        elCell.innerHTML = TWO
    }
}
Ad

Answer

If you check out the cellClicked() function, the first comparison is not right. TILE holds a string with the entire <img>element but gBoard[i][j].image is just the value of the src attribute, so this comparison:

gBoard[i][j].image === TILE

Is really comparing:

'<img src="/img/tile.png" >' === '/img/tile.png'

Which won't ever be true.

I got it to work by setting up a new variable, tileSrc:

const TILE = '<img src="/img/tile.png" >'
const tileSrc = '/img/tile.png';

Then in the conditional in cellClicked(), test against that:

if (gBoard[i][j].image === tileSrc && gBoard[i][j].isFlagged === true)

You can see it working here: Tiles App

Ad
source: stackoverflow.com
Ad