JSFiddle - React, Tailwind, and code Playground
by minitech
HTML
<button id="reset">Reset</button>
CSS
.cell {
border: 1px solid black;
display: inline-block;
line-height: 2;
height: 2em;
margin: 0.2em;
text-align: center;
vertical-align: middle;
width: 2em;
}
.row {
line-height: 1;
}
JavaScript
function check(cells) {
for(var i = 0; i < 3; i++) {
if(cells[i][0] && cells[i][0] === cells[i][1] && cells[i][0] === cells[i][2])
return cells[i][0];
if(cells[0][i] && cells[0][i] === cells[1][i] && cells[0][i] === cells[2][i])
return cells[0][i];
}
if(cells[0][0] && cells[0][0] === cells[1][1] && cells[0][0] === cells[2][2])
return cells[0][0];
if(cells[0][2] && cells[0][2] === cells[1][1] && cells[0][2] === cells[2][0])
return cells[0][2];
return null;
}
function createBoard() {
var board = $('<div class="board">');
var cells = [[], [], []];
var won = false;
for(var y = 0; y < 3; y++) {
var row = $('<div class="row">');
for(var x = 0; x < 3; x++) {
(function(x, y) {
var cell = $('<div class="cell">');
cell.click(function(e) {
if(!won && !cells[y][x]) {
cells[y][x] = 'X';
cell.text('X');
if(check(cells)) {
won = true;
alert('You win!');
}
}
e.preventDefault();
});
row.append(cell);
})(x, y);
}
board.append(row);
}
return {
element: board,
reset: function() {
won = false;
cells = [[], [], []];
board.find('.cell').empty();
}
};
}
$(document).ready(function() {
var board = createBoard();
$('body').prepend(board.element);
$('#reset').click(function(e) {
board.reset();
e.preventDefault();
});
});