【问题标题】:How to take user input in node js?如何在节点 js 中获取用户输入?
【发布时间】: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


【解决方案1】:

以下解决方案对我有用:

node --version
v10.19.0
const readline = require('readline');

const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
});

function readLineAsync(message) {
  return new Promise((resolve, reject) => {
    rl.question(message, (answer) => {
      resolve(answer);
    });
  });
} 

// Leverages Node.js' awesome async/await functionality
async function demoSynchronousPrompt() {
  var promptInput = await readLineAsync("Give me some input >");
  console.log("Won't be executed until promptInput is received", promptInput);
  rl.close();
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-10-26
    • 1970-01-01
    • 2017-05-18
    • 1970-01-01
    • 1970-01-01
    • 2018-03-24
    • 1970-01-01
    相关资源
    最近更新 更多