Node.js如何获取用户输入?井字棋玩家切换及循环终止问题排查
井字棋代码问题修复方案
问题根因
- 玩家身份未切换:
nextPlayer方法仅返回了下一个玩家的标识,没有更新存储当前玩家的person属性,每次调用判断的都是初始的先手身份,所以输入提示一直不变;同时原代码没有主动调用初始化先手的方法,person初始为null也会导致逻辑异常。 - 循环不终止:井字棋最多走9步,原代码设置的循环条件为
count <=9,count从0开始计数时最多会执行10次循环,且没有输入合法性校验逻辑,输入不符合要求时count不会累加,就会出现无限循环的情况。
修复后可运行代码
const prompt = require('prompt-sync')({ sigint: true }); const ticTacToe = { board: new Array(9).fill(null), currentPlayer: null, // 随机生成先手玩家 initFirstPlayer: function () { const randomNum = Math.floor(Math.random() * 2); this.currentPlayer = randomNum === 0 ? 'X' : 'O'; }, // 切换当前玩家 switchPlayer: function () { this.currentPlayer = this.currentPlayer === 'X' ? 'O' : 'X'; }, // 胜负判断逻辑 checkWin: function () { 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) { const [a, b, c] = line; if (this.board[a] && this.board[a] === this.board[b] && this.board[a] === this.board[c]) { return this.board[a]; } } return null; }, start: function () { this.initFirstPlayer(); let stepCount = 0; while (stepCount < 9) { const input = prompt(`${this.currentPlayer}: `); const position = Number(input.trim()) - 1; // 输入合法性校验 if (position >= 0 && position < 9 && this.board[position] === null) { this.board[position] = this.currentPlayer; stepCount++; // 每走一步校验是否有玩家获胜 const winner = this.checkWin(); if (winner) { console.log(`玩家${winner}获胜!`); break; } this.switchPlayer(); } else { console.log('输入无效,请输入1-9之间未被占用的位置数字'); } } if (stepCount === 9) { console.log('平局!'); } console.log('游戏结束'); } } // 启动游戏 ticTacToe.start();
内容的提问来源于stack exchange,提问作者Nithyashree B L
相关产品推荐
相关产品推荐

