-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
304 lines (245 loc) · 7.9 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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
//OBJECTS ------------------------------------------------
let game = {};
//DOM ELEMENTS
const gameboardDiv = document.getElementById('gameboard');
const turnIndicator = document.getElementById('who-plays');
//Factory functions
/**
*
*/
const squareFactory = () => {
const square = document.createElement('div');
square.classList.add("square", "text-center");
square.addEventListener('click', element => selectSquare(element.currentTarget));
return square;
}
const gameFactory = () => {
const whosTurnItIs = () => movesLeft%2=== 0 ? 'Player 2' : 'Player 1';
const updateMovesLeft = () => {
movesLeft = movesLeft - 1 ;
}
const checkIfPlayerWon = (player) => {
let playerWon = false;
if (movesLeft <= 4) { // Only after 4 turns a game can be won
const playerRowMoves = player.rowMoves;
const playerColMoves = player.colMoves;
const rowWin = playerRowMoves.indexOf(3) != -1;
const colWin = playerColMoves.indexOf(3) != -1;
const diagonalWin = player.getMainDiagonalMoves() == 3 || player.getOppositeDiagonalMoves() == 3;
playerWon = rowWin || colWin || diagonalWin ;
}
return playerWon;
}
const checkIfTie = () => movesLeft === 0;
let board = [];
let movesLeft = 9;
return {board, whosTurnItIs, updateMovesLeft, checkIfPlayerWon, checkIfTie}
}
const playerFactory = (mark) => {
let moves = 0;
let rowMoves = [0,0,0];
let colMoves = [0,0,0];
let mainDiagonalMoves = 0;
let oppositeDiagonalMoves = 0;
const updateMoves = (rowCoordinate, columnCoordinate) =>{
moves = moves + 1;
rowMoves[rowCoordinate]++;
colMoves[columnCoordinate]++;
if (rowCoordinate === columnCoordinate){ //indexes at main diagonal are always the same
mainDiagonalMoves++;
}
if ( (rowCoordinate + columnCoordinate) === 2){ //indexes at opposite diagonal always add up 2
oppositeDiagonalMoves++;
}
} ;
const getMainDiagonalMoves = () => mainDiagonalMoves;
const getOppositeDiagonalMoves = () => oppositeDiagonalMoves;
const getMoves = () => moves;
return {mark, updateMoves, rowMoves, colMoves, getMoves, getMainDiagonalMoves, getOppositeDiagonalMoves}
}
// FUNCTIONS ---------------------------------------------------------------------------
/**
* Whenever a square is clicked, it should display a mark and update the gameboard
* to reflect that it is selected
*
* @param {Node} square where mark is going to appear
*/
function selectSquare(square){
const squareIndex = square.dataset.gameboardIndex; // index to update gameboard array
// This helps determine a winner
const squareColumnCoordinate = Number(square.dataset.column);
const squareRowCoordinate = Number(square.dataset.row);
let whoPlays = game.whosTurnItIs();
let mark = whoPlays === 'Player 1' ? `${playerOne.mark}` : `${playerTwo.mark}`
if (!game.board[squareIndex]){
makeMove(square, mark, squareIndex);
updatePlayerMoves(whoPlays, squareRowCoordinate, squareColumnCoordinate);
const playerWon = checkIfWinner(whoPlays);
if(!playerWon){
const tie = game.checkIfTie();
if (tie){
turnIndicator.textContent = `It's a tie!`;
turnIndicator.classList.add('text-warning');
} else {
updateWhosNext();
}
} else {
//Player WON
turnIndicator.textContent = `${whoPlays} WINS!`.toUpperCase();
turnIndicator.classList.add('text-success');
// Finish game
// Prevent new clicks
// display restart button
}
}
}
/**
* After every player move, check if player wins
*
* @param {String} whoPlayed
*/
function checkIfWinner(whoPlayed){
let playerWon = false;
if (whoPlayed === 'Player 1') {
playerWon = game.checkIfPlayerWon(playerOne);
} else {
playerWon = game.checkIfPlayerWon(playerTwo);
}
return playerWon;
}
/**
* every move a player makes needs to be logged into its personal moves array
*
*/
function updatePlayerMoves(whoPlayed, rowCoordinate, columnCoordinate){
if (whoPlayed === 'Player 1') {
playerOne.updateMoves(rowCoordinate, columnCoordinate);
} else {
playerTwo.updateMoves(rowCoordinate, columnCoordinate);
}
}
/**
* If a square is empty, print player's mark inside it, update gameboard
* and update who will play next
*
* @param {String} mark that will be go inside the selected square
*/
function makeMove(selectedSquare, mark, gameBoardIndex){
game.board[gameBoardIndex] = mark;
selectedSquare.textContent = mark ;
game.updateMovesLeft() ;
}
/**
* After each move, turn indicator should be updated to indicate who's next
* and to allow proper marks to appear on board
*/
function updateWhosNext(){
let whoPlays = game.whosTurnItIs();
turnIndicator.textContent = `${whoPlays} moves`;
}
/**
* Depending on the square position, different classes will be added
* to the element
* @param {int} position of the square in the gameboard
*/
function determineClassesToAdd(position){
let classNames = [];
switch (position) {
case 1:
case 7:
classNames = ["right", "left"];
break;
case 4:
classNames = ["top", "bottom", "left", "right"];
break;
case 3:
case 5:
classNames = ["top", "bottom"];
break;
default:
break;
}
return classNames;
}
/**
* The board is made up of 9 squares
*/
function renderBoard(){
// create board squares
for (let i = 0; i < 9; i++) {
const square = squareFactory();
const classesToAdd = determineClassesToAdd(i);
addClassesToSquare(square, classesToAdd);
setSquareDataAttributes(square, i);
gameboardDiv.appendChild(square);
}
}
/**
* each square will have two data- attributes with its row and column coordinates inside
* the gameboard that will be useful when player selects the square
* @param {int} squarePosition in the gameboard
*/
function setSquareDataAttributes(square, squarePosition){
square.dataset.gameboardIndex = `${squarePosition}`;
square.dataset.row = setRowAttribute(squarePosition);
square.dataset.column = setColAttribute(squarePosition);
}
/**
* Every square will have a data-column attribute that refers to its column inside
* the gameboard matrix
*
* @param {*} markCoordinate
*/
function setColAttribute(markCoordinate){
let firstCol = [0,3,6];
let secondCol = [1,4,7];
let thirdCol = [2,5,8];
let colAttribute = '';
if (firstCol.indexOf(markCoordinate) != -1) {
colAttribute = '0';
}
if (secondCol.indexOf(markCoordinate) != -1) {
colAttribute = '1'
};
if (thirdCol.indexOf(markCoordinate) != -1) {
colAttribute = '2'
};
return colAttribute;
}
/**
* Every square will have a data-row attribute that refers to its row inside
* the gameboard matrix
* @param {*} markCoordinate
*/
function setRowAttribute(markCoordinate){
//set row
let rowAttribute = '';
if (markCoordinate < 3) { // First row
rowAttribute = '0';
}
if (markCoordinate >= 3 && markCoordinate < 6){
rowAttribute = '1';
}
if (markCoordinate >= 6){
rowAttribute = '2';
}
return rowAttribute;
}
/**
*
* @param {Node} square
* @param {Array} classes to add to square
*/
function addClassesToSquare(square, classes){
for (let i = 0; i < classes.length; i++) {
square.classList.add(`${classes[i]}`);
}
}
function initializeGame(){
renderBoard();
game = gameFactory();
playerOne = playerFactory('X');
playerTwo = playerFactory('O');
turnIndicator.textContent = `${game.whosTurnItIs()} starts`;
}
initializeGame();