-
Notifications
You must be signed in to change notification settings - Fork 0
/
tic-tac-toe.html
84 lines (70 loc) · 1.92 KB
/
tic-tac-toe.html
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
84
<html>
<head>
<title>Tic-Tac-Toe</title>
<style>
table button { width: 30px; height: 30px; border:0; }
table { margin: 1em}
</style>
</head>
<body>
<p id="msg">Click to play</p>
<table border=1 cellspacing=0 cellpadding=4>
<tr>
<td><button></button>
<td><button></button>
<td><button></button>
<tr>
<td><button></button>
<td><button></button>
<td><button></button>
<tr>
<td><button></button>
<td><button></button>
<td><button></button>
</table>
<button id=restart>Start over</button>
<script>
var currentPlayer = 'X';
msg = document.querySelector('#msg');
function switchPlayer() {
currentPlayer = (currentPlayer == 'X') ? 'O' : 'X';
msg.innerText = 'Player ' + currentPlayer + ': it is your turn';
}
function detectWin() {
var s = Array.from(squares).map((sq) => sq.innerText);
// rows
if (s[0] && s[0] == s[1] && s[1]== s[2]) return s[0];
if (s[3] && s[3] == s[4] && s[4] == s[5]) return s[5];
if (s[6]&& s[6] == s[7] && s[7]== s[8]) return s[8];
// cols
if (s[0] && s[0] == s[3] && s[3]== s[6]) return s[0];
if (s[1] && s[1] == s[4] && s[4] == s[7]) return s[5];
if (s[2]&& s[2] == s[5] && s[5]== s[8]) return s[8];
// diagonals
if (s[0]&& s[0] == s[4] && s[4]== s[8]) return s[8];
if (s[2]&& s[2] == s[4] && s[4]== s[6]) return s[6];
if (s.filter(sp => sp == '').length == 0)
return 'Cat';
}
function onClick(e) {
var t = e.target;
if (!t.innerText) {
e.target.innerText = currentPlayer;
winner = detectWin();
if (winner) {
msg.innerText = winner + ' has won!';
}
else {
switchPlayer();
}
}
}
var squares = document.querySelectorAll('table button');
squares.forEach((b) => b.addEventListener('click', onClick));
document.querySelector('#restart').addEventListener('click', (e) => {
squares.forEach((s) => s.innerText = '');
switchPlayer();
})
</script>
</body>
</html>