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)
{
\t if(map[0] == x && map[1] == x && map[2] == x || // horizontal
\t map[3] == x && map[4] == x && map[5] == x || //^
\t map[6] == x && map[7] == x && map[8] == x || //^
\t map[0] == x && map[3] == x && map[6] == x || // vertical
\t map[1] == x && map[4] == x && map[7] == x || //^
\t map[3] == x && map[5] == x && map[8] == x || //^
\t map[0] == x && map[4] == x && map[8] == x || // diagonal
\t map[2] == x && map[4] == x && map[6] == x) //^
\t \t {
\t \t \t
\t setTimeout(function(){alert("Player " + x + " win!")}, 100);; // Alert for the Player
for(var i=0;i<9;i++)
{
map[i] == 3; // Makes the fields untouchable from User.
}
\t \t }
}
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>
它沒有。如果你把它放在調試器中,它就會像你期望的那樣發生。是否在顯示警報之前預期顏色會發生變化? –
是不是?你是否登錄過你的控制檯,看看這是真的,坐下並不一定是真的。另外,如果您檢查真/假,您最好使用開關。 – somethinghere
由於JavaScript的異步特性。參見[this](http://stackoverflow.com/questions/4559032/easy-to-understand-definition-of-asynchronous-event)。 – casual