-1

I'm trying to write tic-tac-toe game logic, so I need to take user inputs alternatively from user 'X and user 'O. The first player is chosen by a random function.

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';
        }
    }


}


The prompt is not changing and it is not terminating when count reaches 9. The output looks like-

X: 7
X: 7
      5
X: 7
5
         0
X: 7
5
0
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • 1
    You don't update `this.person`, so the condition in `nextPlayer()` is always the same and it returns the same string. – Barmar Sep 20 '21 at 14:50
  • Maybe you meant to write `if (this.person === 'X') { return this.person = 'O'; } else { return this.person = 'X'; }`. This could also be expressed as `this.person = {X:'O', O:'X'}[this.person];` – Wyck Sep 20 '21 at 15:12
  • Are you running this with redirected input? e.g. with **nodemon**? If so, you might want to check compatibility between prompt_sync and nodemon. Try running without nodemon. – Wyck Sep 20 '21 at 15:50
  • 1
    @Wyck Thank you , it's working without nodemon – Nithyashree B L Sep 20 '21 at 16:09
  • @Wyck how to make nodemon and prompt-sync compatible? – Nithyashree B L Sep 20 '21 at 16:12
  • @NithyashreeBL I suspect you could run `nodemon --no-stdin` so that input is passed directly to node. (as per [this suggestion](https://github.com/remy/nodemon/issues/1917#issuecomment-1197069299)) – Wyck Jul 29 '22 at 18:28

1 Answers1

0

Below solution worked for me:

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();
}