我正在制作一个井字游戏,这些功能对于用户回合来说完美无缺,但是当轮到电脑玩时,功能崩溃并给出意想不到的结果,比如玩了两次,跳过转等等。
谁能告诉我我的代码有什么问题,并帮助我解决这个问题?
const start = document.getElementById('start');
const table = document.getElementById('table');
places = ["one", "two", "three", "four", "five", "six", "seven", 'eight', "nine"];
let move = 0;
start.addEventListener('click', function(){
user();
});
function user(){
table.addEventListener('click', function(event){
let pos = event.target;
let Id = event.target.id;
if (/[1-9]/.test(pos.innerHTML)){
pos.innerHTML = "X";
move += 1;
places.splice(places.indexOf(Id), 1 );
}
if (move > 8){
gameOver();
}
if (move <= 8){
computer();
}
});
}
function gameOver(){
console.log("Game Over");
}
function computer(){
let index = places[Math.floor(Math.random() * places.length)];
let pos = document.getElementById(index);
if (/[1-9]/.test(pos.innerHTML)){
pos.innerHTML = "O";
move += 1;
places.splice(places.indexOf(pos), 1 );
}
if (move > 8){
gameOver();
}
if (move <= 8) {
user();
}
}
<div class="col text-center">
<table class="table text-center">
<tbody id="table">
<tr>
<td id="one">1</td>
<td id="two">2</td>
<td id="three">3</td>
</tr>
<tr>
<td id="four">4</td>
<td id="five">5</td>
<td id="six">6</td>
</tr>
<tr>
<td id="seven">7</td>
<td id="eight">8</td>
<td id="nine">9</td>
</tr>
</tbody>
</table>
<br />
<button class="btn btn-primary" type="button" id="start">Start Game</button>
</div>
最佳答案
让我尝试改写我原来的答案: 当轮到电脑时,你正在执行这段代码
function computer(){
let index = places[Math.floor(Math.random() * places.length)];
let pos = document.getElementById(index);
if (/[1-9]/.test(pos.innerHTML)){
pos.innerHTML = "O";
move += 1;
places.splice(places.indexOf(pos), 1 );
}
if (move > 8){
gameOver();
}
if (move <= 8) {
user();
}
如果 if (/[1-9]/.test(pos.innerHTML)){
返回 false 会怎样? (即该字段已被占用),您的代码只是继续执行,就好像计算机已经采取行动将回合交给用户一样。
所以我的建议是,您需要确保计算机确实进行了移动,一种方法是添加一个 found 变量,该变量初始化为 false,并在实际发现并进行计算机移动时首先设置为 true。
这可以通过将您的方法修改为如下内容来完成:
function computer(){
let foundEmptyField=false;
while(foundEmptyField===false)
{
let index = places[Math.floor(Math.random() * places.length)];
let pos = document.getElementById(index);
if (/[1-9]/.test(pos.innerHTML)){
pos.innerHTML = "O";
move += 1;
places.splice(places.indexOf(pos), 1 );
foundEmptyField = true;
}
if(foundEmptyField===true) {
if (move > 8){
gameOver();
}
if (move <= 8) {
user();
}
}
}
}
如果您查看您的代码,您的 user() 代码中实际上存在完全相同的问题
关于javascript - Tic-Tac-Toe 自动播放无法按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54367492/