You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript井字棋(ticTacToe)如何判定获胜并停止prompt输入请求

问题原因
  • 棋盘数据结构是长度为9的一维数组,但computerWinner方法中错误按照二维数组格式this.board[i][j]读取元素,永远无法拿到正确值,导致获胜判断全部失败
  • computerWinner的判断逻辑错误:每一行/列只要不匹配就立刻return null,不会继续检查后续的行、列、对角线,哪怕已经存在获胜组合也检测不到
  • 首次落子(count=1分支)后没有加入获胜判断逻辑,存在逻辑完整性缺失
  • moves方法里的循环完全冗余,无需遍历整个数组只为单个位置赋值
修复后的完整代码
const prompt = require('prompt-sync')({ sigint: true });

const ticTacToe = {
    board: new Array(9).fill(null),
    person: '',
    winner: '',
    randomPlayer: function () {
        let number = Math.floor(Math.random() * 2);
        return this.person = number === 0 ? 'X' : 'O';
    },

    start: function () {
        let firstPlayer = this.person;
        let count = 1;
        while (count <= 9) {
            let input;
            if (count === 1) {
                input = Number(prompt(firstPlayer + ":"));
                this.moves(input);
                // 首次落子后补充获胜判断,保持逻辑统一
                this.winner = this.computerWinner(this.person);
                if (this.winner !== null) {
                    console.log("Winner is : " + this.winner);
                    return this.winner;
                }
                count += 1;
            }
            else {
                this.person = this.nextPlayer();
                input = Number(prompt(this.person + ":"));
                this.moves(input);
                this.winner = this.computerWinner(this.person);
                if (this.winner !== null) {
                    console.log("Winner is : " + this.winner);
                    return this.winner;
                }
                count = count + 1;
            }
        }
        // 9步走完无人获胜返回平局
        return '平局';
    },
    nextPlayer: function () {
        return this.person = this.person === 'X' ? 'O' : 'X';
    },
    moves: function (number) {
        // 移除冗余循环,直接给对应位置赋值
        this.board[number - 1] = this.person;
    },

    computerWinner: function (player) {
        // 直接枚举所有获胜组合的索引,适配一维数组结构,避免索引计算错误
        const winLines = [
            [0,1,2], [3,4,5], [6,7,8], // 横向获胜组合
            [0,3,6], [1,4,7], [2,5,8], // 纵向获胜组合
            [0,4,8], [2,4,6] // 对角线获胜组合
        ];
        // 遍历所有获胜组合,匹配到就直接返回获胜玩家
        for (let line of winLines) {
            if (this.board[line[0]] === player && this.board[line[1]] === player && this.board[line[2]] === player) {
                return player;
            }
        }
        // 所有组合都不匹配才返回null
        return null;
    }
}

console.log(ticTacToe.randomPlayer());
console.log(ticTacToe.start());
console.log(ticTacToe.board);
修复说明
  • 获胜判断逻辑改为直接枚举所有获胜索引组合,适配一维数组的存储结构,避免索引计算错误
  • 调整获胜判断的返回逻辑,遍历完全部获胜组合都不满足才返回null,不会中途跳出判断
  • 移除moves方法里的冗余循环
  • 补齐首次落子后的获胜判断逻辑,同时增加了平局的返回值,避免9步走完返回undefined的问题

内容的提问来源于stack exchange,提问作者Nithyashree B L

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 09:45:04