-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtic-tac-toe-computerRandom.js
59 lines (53 loc) · 1.31 KB
/
tic-tac-toe-computerRandom.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
const Board = require("./board");
const GameUI = require("./gameUI");
const board = new Board();
const gameUI = new GameUI(board);
const readline = require("readline").createInterface({
input: process.stdin,
output: process.stdout,
});
const getPlayerInput = (question) => {
return new Promise((resolve, reject) => {
readline.question(question, (answer) => {
resolve(answer);
});
});
};
let player = "X";
const gamePlay = async (player) => {
let position;
while (!board.gameOver()) {
if (player === "X") {
position = await getPlayerInput(`What's your move X?`);
position = parseInt(position);
} else {
position = getRandomInt();
console.log(`Computer moved to position ${position}`);
}
try {
board.write(position, player);
if (player === "X") {
player = "0";
} else {
player = "X";
}
l;
} catch (error) {
if (player === "X") {
gameUI.displayErrorMessage(error);
}
}
gameUI.renderBoard();
if (board.gameOver()) {
gameUI.displayWinner();
return readline.close();
}
}
};
gameUI.initialize();
gamePlay(player);
function getRandomInt() {
min = 1;
max = 10;
return Math.floor(Math.random() * (max - min)) + min; //The maximum is exclusive and the minimum is inclusive
}