-
Notifications
You must be signed in to change notification settings - Fork 2
/
tictactoe6.js
68 lines (58 loc) · 1.49 KB
/
tictactoe6.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
// game 6 will
// start with an empty board in the html and generate the board dynamically
// have an on load listener to generate the first board
var nextPlayer = true;
var boardState = [
[null, null, null],
[null, null, null],
[null, null, null]
];
function play(box) {
var row = box.parentElement.getAttribute('row');
var column = box.getAttribute('column');
if(boardState[row][column] == null) {
if(nextPlayer) {
boardState[row][column] = 'x';
} else {
boardState[row][column] = 'o';
}
nextPlayer = !nextPlayer;
// did someone win?
// if they did, change the state and redraw
populateBoard();
} else {
alert('grow up. you can\'t do that')
};
};
function populateBoard() {
var board = document.getElementById('ticTacBoard').children[0].children;
var row;
var column;
for(var i = 0; i < 3; i++) {
row = board[i].children;
for(var j = 0; j < 3; j++) {
column = row[j];
column.innerHTML = boardState[i][j];
};
};
};
function buildBoard() {
var board = document.getElementById('ticTacBoard');
var row;
var cell;
for(var i = 0; i < 3; i++) {
row = board.insertRow(i);
row.setAttribute('row', i);
for(var j = 0; j < 3; j++) {
cell = row.insertCell(j);
// why not set it to null directly?
// because what if you want to finish a saved game?
cell.innerHTML = boardState[i][j];
cell.setAttribute('column', j);
cell.setAttribute('onclick', 'play(this)');
};
};
};
window.addEventListener('DOMContentLoaded', function() {
buildBoard();
});