var map = [0,0,0,0,0,0,0,0,0], // Array for the Game and the the Win Check
design = ["td0", "td1", "td2",
"td3", "td4", "td5",
"td6", "td7", "td8"], // Array for the fields of the Table.
Player = true; // true is player Blue, false is player red.
function Game(x) // Game() will be executed when a field in the Table is clicked.
{
switch(Player) // Switch from Player 1 to 2
{
case true:
if(map[x] == 0) // this if is for
{
document.getElementById(design[x]).style.backgroundColor = "blue";
map[x] = 1; // in the 'map' array 1 are Player Blue fields and 2 are Player Red fields
Check(1); // The Win Check for the Game
Player = false; // PlayerChange to Player 1 or 'Red'
}
break;
case false:
if(map[x] == 0)
{
document.getElementById(design[x]).style.backgroundColor = "red";
map[x] = 2;
Check(2);
Player = true; // PlayerChange to Player 2 or 'Blue'
}
}
}
function Check(x)
{
if(map[0] == x && map[1] == x && map[2] == x || // horizontal
map[3] == x && map[4] == x && map[5] == x || // ^
map[6] == x && map[7] == x && map[8] == x || // ^
map[0] == x && map[3] == x && map[6] == x || // vertical
map[1] == x && map[4] == x && map[7] == x || // ^
map[3] == x && map[5] == x && map[8] == x || // ^
map[0] == x && map[4] == x && map[8] == x || // diagonal
map[2] == x && map[4] == x && map[6] == x) // ^
{
alert("Player " + x + " win!"); // Alert for the Player
for(var i=0;i<9;i++)
{
map[i] == 3; // Makes the fields untouchable from User.
}
}
}
td
{
height: 100px;
width: 100px;
border: 1px solid black;
}
<html>
<head>
</head>
<body>
<table>
<tr>
<td id="td0" onclick="Game(0);" />
<td id="td1" onclick="Game(1);" />
<td id="td2" onclick="Game(2);" />
</tr>
<tr>
<td id="td3" onclick="Game(3);" />
<td id="td4" onclick="Game(4);" />
<td id="td5" onclick="Game(5);" />
</tr>
<tr>
<td id="td6" onclick="Game(6);" />
<td id="td7" onclick="Game(7);" />
<td id="td8" onclick="Game(8);" />
</tr>
</table>
</body>
<html>
document.getElementById("id").style.backgroundColor = "color"
, which is 2 lines above this function.