-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
110 lines (99 loc) · 3.24 KB
/
index.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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
var prompt = require('prompt-sync')();
class TikTakToe {
constructor() {
this.array = [];
this.isGameOver = false;
this.turn = 1;
for (let i = 0; i < 9; i++) {
this.array[i] = i;
}
}
startGmae() {
let counter = 0;
while (!this.isGameOver && counter < 9) {
this.printGame();
this.input();
this.printGame();
this.check();
this.changeTurn();
counter++;
}
if (this.isGameOver) {
console.log(`player ${this.turn == 1 ? 2 : 1} win!`);
console.log('Game Over');
} else {
console.log("Game is draw!");
}
var x = prompt('would you like to replay Y/N : ');
if (x == 'y' || x == 'Y') {
this.isGameOver = false;
this.turn = 1;
for (let i = 0; i < 9; i++) {
this.array[i] = i;
}
this.startGmae();
} else {
process.exit();
}
}
printGame() {
console.clear();
console.log('Enter "q" to quite the game.');
console.log('player 1 : ✓');
console.log('player 2 : ⨉');
console.log(`turn : ${this.turn == 1 ? 1 : 2}`);
console.log();
console.log(`${this.array[0]} | ${this.array[1]} | ${this.array[2]}`);
console.log(`---------`);
console.log(`${this.array[3]} | ${this.array[4]} | ${this.array[5]}`);
console.log(`---------`);
console.log(`${this.array[6]} | ${this.array[7]} | ${this.array[8]}`);
console.log();
}
changeTurn() {
this.turn == 1 ? this.turn = 2 : this.turn = 1;
}
input() {
var isValid = false;
var x = prompt('please enter a number : ');
if (x == 'q') {
process.exit();
}
while ((x > 8 || x < 0) || isNaN(x)) {
x = prompt('please enter a valid number : ');
}
if (this.array[x] == '✓' || this.array[x] == '⨉') {
x = prompt('Box is already used please, enter another number : ');
} else {
this.array[x] = this.turn == 1 ? '✓' : '⨉';
}
}
check() {
if (this.array[0] == this.array[1] && this.array[0] == this.array[2]) {
this.isGameOver = true;
}
if (this.array[3] == this.array[4] && this.array[3] == this.array[5]) {
this.isGameOver = true;
}
if (this.array[6] == this.array[7] && this.array[6] == this.array[8]) {
this.isGameOver = true;
}
if (this.array[0] == this.array[3] && this.array[0] == this.array[6]) {
this.isGameOver = true;
}
if (this.array[1] == this.array[4] && this.array[1] == this.array[7]) {
this.isGameOver = true;
}
if (this.array[2] == this.array[5] && this.array[2] == this.array[8]) {
this.isGameOver = true;
}
if (this.array[0] == this.array[4] && this.array[0] == this.array[8]) {
this.isGameOver = true;
}
if (this.array[2] == this.array[4] && this.array[2] == this.array[6]) {
this.isGameOver = true;
}
}
}
const game = new TikTakToe();
game.startGmae();