【发布时间】:2021-09-20 14:39:52
【问题描述】:
我正在尝试编写井字游戏逻辑,因此我需要从用户'X 和用户'O 交替获取用户输入。第一个玩家是由随机函数选择的。
const prompt = require('prompt-sync')({ sigint: true });
const ticTacToe = {
board: new Array(9).fill(null),
person: null,
player: function () {
let number = Math.floor(Math.random() * 2);
if (number === 0) {
return this.person = 'X';
}
else {
return this.person = 'O';
}
},
start: function () {
let firstPlayer = this.person;
let count = 0;
while (count <= 9) {
let input;
if (count === 0) {
input = prompt(firstPlayer + ": ");
count = count + 1;
}
else {
let nextPerson = this.nextPlayer();
input = prompt(nextPerson + ": ");
count = count + 1;
}
}
},
nextPlayer: function () {
let next;
if (this.person === 'X') {
return next = 'O';
}
else {
return next = 'X';
}
}
}
当计数达到 9 时,提示没有变化,也没有终止。 输出看起来像-
X: 7
X: 7
5
X: 7
5
0
X: 7
5
0
【问题讨论】:
-
你没有更新
this.person,所以nextPlayer()中的条件总是一样的,它返回的字符串也是一样的。 -
也许你的意思是写
if (this.person === 'X') { return this.person = 'O'; } else { return this.person = 'X'; }。这也可以表示为this.person = {X:'O', O:'X'}[this.person]; -
您是否使用重定向输入运行此程序?例如使用 nodemon?如果是这样,您可能需要检查 prompt_sync 和 nodemon 之间的兼容性。尝试在没有 nodemon 的情况下运行。
-
@Wyck 谢谢,它在没有 nodemon 的情况下工作
-
@Wyck 如何让 nodemon 和 prompt-sync 兼容?
标签: javascript node.js