-
Notifications
You must be signed in to change notification settings - Fork 0
/
tictactoe.js
106 lines (93 loc) · 2.37 KB
/
tictactoe.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
var prompt = require('prompt');
var board = {
1: ' ',
2: ' ',
3: ' ',
4: ' ',
5: ' ',
6: ' ',
7: ' ',
8: ' ',
9: ' '
};
function markBoard(position, mark) {
board[position] = mark.toUpperCase();
}
function printBoard() {
console.log('\n' +
' ' + board[1] + ' | ' + board[2] + ' | ' + board[3] + '\n' +
' ---------\n' +
' ' + board[4] + ' | ' + board[5] + ' | ' + board[6] + '\n' +
' ---------\n' +
' ' + board[7] + ' | ' + board[8] + ' | ' + board[9] + '\n');
}
function isInt(value) {
var x;
if (isNaN(value)) {
return false;
}
x = parseFloat(value);
return (x | 0) === x;
}
function validateMove(position) {
return (isInt(position) && board[position] === ' ')
}
var winCombinations = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [1, 4, 7],
[2, 5, 8], [3, 6, 9], [1, 5, 9], [3, 5, 7]];
// Determins if the passed in player has three in a row
function checkWin(player) {
var i, j, markCount
for (i = 0; i < winCombinations.length; i++) {
markCount = 0;
for (j = 0; j < winCombinations[i].length; j++) {
if (board[winCombinations[i][j]] === player) {
markCount++;
}
if (markCount === 3) {
return true;
}
}
}
return false;
}
function checkTie() {
for (var i = 1; i <= Object.keys(board).length; i++) {
if (board[i] === ' ') {
return false;
}
}
return true;
}
function playTurn(player) {
console.log('Your turn player: ' + player);
prompt.start();
prompt.get(['position'], function (err, result) {
if (validateMove(result.position) === true) {
markBoard(result.position, player);
printBoard();
if (checkWin(player) === true) {
console.log('Winner Winner!');
return;
}
if (checkTie() === true) {
console.log('Tie Game');
return;
}
if (player === 'X') {
playTurn('O');
} else {
playTurn('X');
}
} else {
console.log('incorrect input please try again...');
playTurn(player);
}
});
}
console.log('Game started: \n' +
' 1 | 2 | 3 \n' +
' --------- \n' +
' 4 | 5 | 6 \n' +
' --------- \n' +
' 7 | 8 | 9 \n');
playTurn('X');