-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtictactoe.js
83 lines (74 loc) · 1.82 KB
/
tictactoe.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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
// @TODO: add inline documentation
(function() {
'use strict';
var
squares = [],
score,
moves,
turn = 'X',
winningScores = [7, 56, 448, 73, 146, 292, 273, 84],
startNewGame = function() {
var i;
turn = 'X';
score = {
'X': 0,
'O': 0
};
moves = 0;
for (i = 0; i < squares.length; i += 1) {
squares[i].firstChild.nodeValue = '';
}
},
checkWin = function(score) {
var i;
for (i = 0; i < winningScores.length; i += 1) {
if ((winningScores[i] & score) === winningScores[i]) {
return true;
}
}
return false;
},
chooseSquare = function() {
if (this.firstChild.nodeValue.trim() !== '') {
alert('Choose a different square.')
return;
}
this.firstChild.nodeValue = turn;
moves += 1;
score[turn] += this.squareScore;
if (moves > 4 && checkWin(score[turn])) {
alert(turn + ' wins!');
startNewGame();
} else if (moves === 9) {
alert('It\'s a tie!');
startNewGame();
} else {
turn = turn === 'X' ? 'O' : 'X';
}
},
createBoard = function() {
var board = document.createElement('table'),
squareScore = 1,
i, j,
row, cell;
board.border = 1;
for (i = 0; i < 3; i += 1) {
row = document.createElement('tr');
board.appendChild(row);
for (j = 0; j < 3; j += 1) {
cell = document.createElement('td');
cell.width = cell.height = 50;
cell.align = cell.valign = 'center';
cell.squareScore = squareScore;
cell.onclick = chooseSquare;
cell.appendChild(document.createTextNode(''));
row.appendChild(cell);
squares.push(cell);
squareScore += squareScore;
}
}
document.getElementById('tictactoe').appendChild(board);
};
createBoard();
startNewGame();
}());