我正在打井字游戏。我已经使表格单元格成为可单击的,一旦单击它们便运行名为playPVPGame的函数。首先,随机选择O和X首先。我在页面的一角有文字说明该轮到谁了。最初,文本将为“ O优先”或“ X优先”。然后,根据转弯,它将更改为“ X为下一个”或“ O为下一个”。问题是在初始文字之后,转弯不会像我想要的那样来回旋转。
var $ = function(id) {
return document.getElementById(id);
};
var newGameAction = function()
{
//clear table
$("c1").innerHTML = "";
$("c2").innerHTML = "";
$("c3").innerHTML = "";
$("c4").innerHTML = "";
$("c5").innerHTML = "";
$("c6").innerHTML = "";
$("c7").innerHTML = "";
$("c8").innerHTML = "";
$("c9").innerHTML = "";
};
var pVpAction = function(elem)
{
var outputTect;
var turnCounter = 0;
var first_Turn = Math.floor(Math.random() * 2);
$("firstTurn").innerHTML = first_Turn;
first_turn = $("firstTurn").innerHTML;
if(first_turn == 0)
{
message = "O goes first";
}
if(first_turn == 1)
{
message = "X goes first";
}
$("goNext").innerHTML = message;
};
var playPVPGame = function(elem)
{
var turn = $("goNext").innerHTML;
var message;
if(turn == "O goes first")
{
elem.style.backgroundColor = "red";
elem.innerHTML = "O";
turn = "X is next";
$("goNext").innerHTML = turn;
}
if(turn == "X goes first")
{
elem.style.backgroundColor = "blue";
elem.innerHTML = "X";
turn = "O is next";
$("goNext").innerHTML = turn;
}
//does not work
/*if($("goNext").innerHTML = "X is next")
{
$("newGame").disabled = true;
}*/
message = $("goNext").innerHTML;
if(message == "X is next")
{
elem.style.backgroundColor = "blue";
elem.innerHTML = "X";
message = "O is next";
$("goNext").innerHTML = message;
}
if(message == "O is next")
{
elem.style.backgroundColor = "red";
elem.innerHTML = "O";
message = "X is next";
$("goNext").innerHTML = message;
}
};
window.onload = function() {
$("newGame").onclick = newGameAction;
$("playerVplayer").onclick = pVpAction;
};
table {width:100%}
table tr td{border:1px solid #000;height:50px;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<span id="firstTurn"> </span>
<span id= "goNext"> </span>
<table class = "board">
<tr>
<td id = "c1" onclick="playPVPGame(this)" > . </td>
<td id = "c2" onclick="playPVPGame(this)"> . </td>
<td id = "c3" onclick="playPVPGame(this)"> . </td>
</tr>
<tr>
<td id = "c4" onclick="playPVPGame(this)"> . </td>
<td id = "c5" onclick="playPVPGame(this)"> . </td>
<td id = "c6" onclick="playPVPGame(this)"> . </td>
</tr>
<tr>
<td id = "c7" onclick="playPVPGame(this)"> . </td>
<td id = "c8" onclick="playPVPGame(this)">. </td>
<td id = "c9" onclick="playPVPGame(this)"> .</td>
</tr>
</table>
<input type="button"
id= "newGame"
value="New Game"/>
<input type="radio"
id= "playerVplayer"
value="Player vs Player"/>
<input type="radio"
id= "playerVcpu"
value="Player vs CPU"/>
最佳答案
将当前播放器(“ X”或“ O”)存储在变量中,而不是从GUI中读取它。
从GUI读取是一种不好的做法,您不得不问这个问题说明了为什么会这样。
关于javascript - 可点击的HTML表格单元格,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/47248815/