javascript - 开关转功能在井字游戏中不起作用
问题描述
(如果可能,请使用基本方法来解决这个问题。我仍然是一个绝对的初学者,所以我不想混淆自己)我正在尝试创建一个名为 changeturns 的函数,以便当我在 startGame 函数中运行此函数时转可以自动在X和O之间切换。但是轮数只有在单人玩一轮后才会改变(即只有在O获胜后才切换到X)。
var arrayx = [];
var turn = "O";
var scoreX = 0;
var scoreO = 0;
function refresh() {
for (var cell = 0; cell < 9; cell++) {
document.getElementById("cell" + cell).innerHTML = " ";
}
}
function changeturns(turn) {
}
function startGame(cell) {
document.getElementById("cell" + cell).innerHTML = turn;
checkwin(turn);
}
function checkwin(turn) {
}
startGame(); // should not be called here
body {
font-family: helvetica, arial, sans-serif;
margin: 2em;
}
h1 {
font-style: italic;
color: #373fdd;
}
table {
border-collapse:collapse;
position:absolute;
left:50%;
margin-left:-155px;
top:50px;
background-color:pink;
}
td{
border:2px solid#333;
height:100px;
width:100px;
text-align:center;
vertical-align:middle;
font-family:"Comic Sans MS",cursive;
font size: 70px;
cursor: pointer;
}
table tr:first-child td{
border-top:0;
}
table tr:last-child td{
border-bottom:0;
}
table tr td:first-child{
border-left:0;
}
table tr td:last-child{
border-right:0;
}
.endgame{
display:none;
width:200px;
top:120px;
color:white;
font size:2em;
background-color:rgba(304,144,66,0.7)
}
<h1>Wanna Play Tic Tac Toe?</h1>
<p id="qiguai">
<b>O player scoreboard</b>
</p>
<p id="roundannouncer">
</p>
<p id="qiguai2">
<b>X player scoreboard</b>
</p>
<p id="roundannouncer2">
</p>
<table id="myTable" width="400" height="400">
<tr>
<td class="cell" id="cell0" onclick="startGame(0)"></td>
<td class="cell" id="cell1" onclick="startGame(1)"></td>
<td class="cell" id="cell2" onclick="startGame(2)"></td>
</tr>
<tr>
<td class="cell" id="cell3" onclick="startGame(3)"></td>
<td class="cell" id="cell4" onclick="startGame(4)"></td>
<td class="cell" id="cell5" onclick="startGame(5)"></td>
</tr>
<tr>
<td class="cell" id="cell6" onclick="startGame(6)"></td>
<td class="cell" id="cell7" onclick="startGame(7)"></td>
<td class="cell" id="cell8" onclick="startGame(8)"></td>
</tr>
</table>
<div class="endgame">
<div class="text">
</div>
</div>
<button onclick="refresh()"> Replay </button>
我试图在 startGame 函数内部和外部调用该函数,但都不起作用。
解决方案
问题是该checkwin
函数再次调用startGame
,因此转弯也再次切换。然后发生错误,因为startGame
在没有参数的情况下调用。
你永远不应该调用startGame
你现在在代码中的位置。删除这两个实例。唯一可以调用的地方startGame
是单击事件处理程序(您已在 HTMLclick
属性中定义)。
请注意,名称startGame
令人困惑,因为它实际上并没有开始游戏,而是下棋。这可能也是您引入此错误的原因。为函数(和变量)使用好的名称很重要。
推荐阅读
- python - 在带有 groupby 的 dask 数据帧上使用 pd.DataFrame.sample
- javascript - 如何在 Flask 下拉菜单中获取和发布数据
- c# - 如何使用 c# 成功停止服务?
- azure - 无法在 Azure Batch 中解压缩应用程序包
- html - 如何让css动画缩放到适当的屏幕尺寸
- c# - C# Confluent.Apache.Avro - GenericRecord.Add(schema) 在模式中有枚举
- php - 将 Stripe 结帐会话与订阅 webhook 关联
- c++ - 我怎样才能在循环中做减法?
- ibm-mq - 可以在两个远程 qmgrs 中使用具有相同 CN 的证书吗?
- vue.js - 图例未显示使用 Echarts 的 vue.js 项目