-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path04_TicTacToe.html
81 lines (73 loc) · 2.49 KB
/
04_TicTacToe.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
<HTML>
<HEAD>
<TITLE>Tic Tac Toe</TITLE>
<SCRIPT LANGUAGE="JavaScript">
var player="X";
var counter=0;
//Inizialize my game board
var table = [];
for (var i=0;i<3;i++)
table[i]=[]; //It is reppresented by a bidimensional array
for (var x=0;x<3;x++)
for (var y=0;y<3;y++)
table[y][x]=0;
function Tic(x, y) { //is called at every click and will update the state
//of the game
if(table[y][x]==0){ //valid move = player choose empty cell
document.getElementById("b"+x+y).value=player;
table[y][x]=player;
counter++;
//Check for all possible winning condition
for (var y=0;y<3;y++)
if((table[y][0]==table[y][1])&&(table[y][0]==table[y][2]))
if(table[y][0]!=0)
endGame(table[y][0]);
for (var x=0;x<3;x++)
if((table[0][x]==table[1][x])&&(table[0][x]==table[2][x]))
if(table[0][x]!=0)
endGame(table[0][x]);
if((table[0][0]==table[1][1])&&(table[0][0]==table[2][2]))
if(table[0][0]!=0)
endGame(table[0][0]);
if((table[0][2]==table[1][1])&&(table[0][2]==table[2][0]))
if(table[0][2]!=0)
endGame(table[0][2]);
if (counter>=9){
//nobody won
alert("No more moves. Try Again!");
window.location.reload(0);
}
if(player=="X") //change player
player="O";
else
player="X";
}
}
function endGame(player){
alert("Player "+player+" won, Congrats!");
window.location.reload(0);
}
</SCRIPT>
</HEAD>
<BODY>
Let's play tic tac toe. Starts player X.
<table>
<tr>
<td><INPUT id="b00" TYPE="button" Value=" " onClick="Tic(0,0)"></td>
<td><INPUT id="b10" TYPE="button" Value=" " onClick="Tic(1,0)"></td>
<td><INPUT id="b20" TYPE="button" Value=" " onClick="Tic(2,0)"></td>
</tr>
<tr>
<td><INPUT id="b01" TYPE="button" Value=" " onClick="Tic(0,1)"></td>
<td><INPUT id="b11" TYPE="button" Value=" " onClick="Tic(1,1)"></td>
<td><INPUT id="b21" TYPE="button" Value=" " onClick="Tic(2,1)"></td>
</tr>
<tr>
<td><INPUT id="b02" TYPE="button" Value=" " onClick="Tic(0,2)"></td>
<td><INPUT id="b12" TYPE="button" Value=" " onClick="Tic(1,2)"></td>
<td><INPUT id="b22" TYPE="button" Value=" " onClick="Tic(2,2)"></td>
</tr>
</table>
<div id="writeHere"></div>
</BODY>
</HTML>