JSFiddle - React, Tailwind, and code Playground

by Joshua_David

HTML

<table id="table"></table>
<input type="number" id="sizeinput" value="8" />
<br />
<button id="undo">Undo</button>
<button id="reset">Reset</button>

CSS

table {
    border-collapse: collapse;
}
td {
    border: 1px solid black;
    height: 30px;
    width: 30px;
    line-height: 30px;
    font-size: 30px;
    text-align: center;
}
tr:nth-child(2n + 1) td:nth-child(2n),
tr:nth-child(2n) td:nth-child(2n + 1) {
    background: #777777;
}

JavaScript

var moves = [], board = [], size, k;
reset.onclick = function newGame() {
    table.innerHTML = "";
    var size = sizeinput.value;
    for(var y = 0; y < size; y++) {
        board[y] = [];
        var row = table.appendChild(document.createElement('tr'));
        for(var x = 0; x < size; x++) {
            var cell = board[y][x] = row.appendChild(document.createElement('td'));
            cell.x = x, cell.y = y;
        }
    }
    k = board[0][0];
    k.innerHTML = "&#9816;";
    table.onclick = function(e) {
        var t = e.target;
        if(Math.pow(t.x-k.x,2)+Math.pow(t.y-k.y,2)==5 && !t.innerHTML) {
            board[k.y][k.x].innerHTML = 'X';
            moves.push(k), k = t;
            k.innerHTML = "&#9816;";
            if(table.textContent.length == size * size) table.innerHTML+="You win!";
        }
    };
};
reset.onclick();
undo.onclick = function() {
    k.innerHTML = '';
    k = moves.pop();
    k.innerHTML = "&#9816;";
};