Tic-tac-toe
Working on an interview
by Augustus Yuan
HTML
<header>
<h1>Tic Tac Toe</h1>
</header>
<div class="tic-tac-toe">
<div class="tile row-0 col-0"></div>
<div class="tile row-0 col-1"></div>
<div class="tile row-0 col-2"></div>
<div class="tile row-1 col-0"></div>
<div class="tile row-1 col-1"></div>
<div class="tile row-1 col-2"></div>
<div class="tile row-2 col-0"></div>
<div class="tile row-2 col-1"></div>
<div class="tile row-2 col-2"></div>
</div>
CSS
body {
font-family: Helvetica, Arial, sans-serif;
}
.tic-tac-toe {
width: 150px;
}
.tile {
display: inline-block;
width: 45px;
height: 45px;
border: 1px solid black;
}
JavaScript
function indexToCoords(index, gridSize) {
//var row = Math.floor(( index ) / gridSize);
var coords = [
[0,0],
[0,1],
[0,2],
[1,0],
[1,1],
[1,2],
[2,0],
[2,1],
[2,2]
];
return coords[index];
}
console.log(indexToCoords(4, 3));
var tiles = document.querySelectorAll('.tile');
tiles.forEach(function(tile, i) {
tile.addEventListener('click', function(e) {
alert(indexToCoords(i));
});
})