-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.js
645 lines (521 loc) · 18.8 KB
/
main.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
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
// factory for creating players
const playerFactory = (name, mark) => {
return { name, mark, isAI: false };
};
// factory for creating AI
const AIFactory = (name, mark, difficulty, opponentMark) => {
// make a move based on difficulty
const makeMove = () => {
switch (difficulty) {
case 'easy':
// 30% chance to play best move instead of random move
_chanceBestMove(30);
break;
case 'medium':
// 50% chance to play best move instead of random move
_chanceBestMove(50);
break;
case 'impossible':
_bestMove();
break;
default:
break;
}
// render the gameboard
displayController.render();
};
// place a best move based on chance else play a random move
const _chanceBestMove = (chance) => {
// get a random number between 0 and 100 exclusive
const randomNumber = Math.random() * 100;
// if randomNumber is below chance, best move is played
if (randomNumber < chance) {
_bestMove();
} else {
_randomMove();
}
};
// play a random possible move
const _randomMove = () => {
// get all available postions to place a mark
const availablePositions = gameBoard.getEmptyCellsIndexes();
// get a random available position
const randomAvailablePosition = gameController.getRandomArrayElement(availablePositions);
// place mark at a random available position
gameBoard.editGameBoard(randomAvailablePosition, mark);
};
// play the best possible move
const _bestMove = () => {
// get all available postions to place a mark
const availablePositions = gameBoard.getEmptyCellsIndexes();
let bestScore = -Infinity;
let move;
// iterate over available positions
availablePositions.forEach(index => {
// place a mark at available position
gameBoard.editGameBoard(index, mark);
// get the score of the new gameboard with the above position marked
let score = _minimax(false);
// remove mark from gameboard
gameBoard.editGameBoard(index, '');
// if this move has a higher score than the current bestScore
// set the bestScore to this score and set the move to the index
if (score > bestScore) {
bestScore = score;
move = index;
};
});
// make the best move
gameBoard.editGameBoard(move, mark);
};
// returns best score of all possible moves of the game
const _minimax = (isMaximizing) => {
// get the result of the game
const result = gameController.getGameResult();
// return a score if the game is over
if (result !== null) {
// scores based on the AI's mark
const scores = {
'win: X': mark === 'X' ? 10 : -10,
'win: O': mark === 'O' ? 10 : -10,
draw: 0,
};
return scores[result.status];
}
// get all available postions to place a mark
const availablePositions = gameBoard.getEmptyCellsIndexes();
// if the move is the maximizing player
if (isMaximizing) {
let bestScore = -Infinity;
// iterate over available positions
availablePositions.forEach(index => {
// place a mark at available position
gameBoard.editGameBoard(index, mark);
// get the score of the new gameboard with the above position marked
let score = _minimax(false);
// remove mark from gameboard
gameBoard.editGameBoard(index, '');
// update bestScore to equal score if score is higher than bestscore
bestScore = Math.max(score, bestScore);
});
return bestScore;
} else {
let bestScore = Infinity;
// iterate over available positions
availablePositions.forEach(index => {
// place a mark at available position
gameBoard.editGameBoard(index, opponentMark);
// get the score of the new gameboard with the above position marked
let score = _minimax(true);
// remove mark from gameboard
gameBoard.editGameBoard(index, '');
// update bestScore to equal score if score is lower than bestscore
bestScore = Math.min(score, bestScore);
});
return bestScore;
}
};
return {
name,
mark,
isAI: true,
makeMove,
};
};
// module for storing and returning DOM elements
const domElems = (() => {
const _gameBoardElem = document.querySelector('.gameboard');
const gameBoardCells = [..._gameBoardElem.querySelectorAll('div')];
const announcerElem = document.querySelector('.announcer');
const modeSelectbtns = document.getElementById('mode-select-btns');
const gameForm = document.getElementById('game-form');
const gameFormElems = {
p1Input: gameForm.querySelector('#p1-name-input'),
p1Label: gameForm.querySelector('label[for="p1-name-input"]'),
p2Input: gameForm.querySelector('#p2-name-input'),
p2Label: gameForm.querySelector('label[for="p2-name-input"]'),
startBtn: gameForm.querySelector('#start-btn'),
backBtn: gameForm.querySelector('#back-btn')
};
const formGrid = document.querySelector('.form-grid');
return {
gameBoardCells,
announcerElem,
modeSelectbtns,
gameForm,
gameFormElems,
formGrid
};
})();
// module for manipulating the DOM
const displayController = (() => {
// render gameboard array to screen
const render = () => {
domElems.gameBoardCells.forEach(cell => {
cell.textContent =
gameBoard.getValue(cell.dataset.index);
});
};
// set textContent of a element
const setTextContent = (element, text) => {
element.textContent = text;
};
// show an element
const showElement = (element) => {
element.classList.add('is-visible');
};
// hide an element
const hideElement = (element) => {
element.classList.remove('is-visible');
};
// add class to elements
const addClassToElements = (elements, htmlClass) => {
elements.forEach(element => element.classList.add(`${htmlClass}`))
};
// remove class to elements
const removeClassFromElements = (elements, htmlClass) => {
elements.forEach(element => element.classList.remove(`${htmlClass}`))
};
// show who's turn it is
const showCurrentPlayer = (currentPlayer) => {
const text = `${currentPlayer.name}'s Turn - ${currentPlayer.mark}`;
setTextContent(domElems.announcerElem, text);
}
const showInputs = (gamemode) => {
displayController.showElement(domElems.gameFormElems.p1Label);
if (gamemode === 'mp') {
displayController.showElement(domElems.gameFormElems.p2Label);
}
};
const hideInputs = (gamemode) => {
displayController.hideElement(domElems.gameFormElems.p1Label);
if (gamemode === 'mp') {
displayController.hideElement(domElems.gameFormElems.p2Label);
}
};
const hideBackButton = () => {
// make form block
domElems.formGrid.style.display = 'block';
// hide back button
displayController.hideElement(domElems.gameFormElems.backBtn);
};
const showBackButton = () => {
// make form grid
domElems.formGrid.style.display = 'grid';
// show back button
displayController.showElement(domElems.gameFormElems.backBtn);
};
return {
render,
setTextContent,
showElement,
hideElement,
addClassToElements,
removeClassFromElements,
showCurrentPlayer,
showInputs,
hideInputs,
hideBackButton,
showBackButton
};
})();
// module for manipulating gameboard
const gameBoard = (() => {
let _gameBoardArray = [
'', '', '',
'', '', '',
'', '', ''
];
// return value of array element
const getValue = (index) => _gameBoardArray[index];
// change value of array element
const editGameBoard = (index, newValue) => {
_gameBoardArray[index] = newValue;
};
// set all array elements to empty string
const clearGameBoard = () => {
_gameBoardArray.fill('');
displayController.render();
};
// get empty cells indexs on gameboard
const getEmptyCellsIndexes = () => {
let emptyCellsIndexs = [];
_gameBoardArray.forEach((value, index) => {
if (value === '') emptyCellsIndexs.push(index);
});
return emptyCellsIndexs;
};
// return true if cell is empty, else false
const isCellEmpty = (index) => _gameBoardArray[index] === '';
return {
getValue,
editGameBoard,
clearGameBoard,
getEmptyCellsIndexes,
isCellEmpty,
};
})();
// module for controlling the game
const gameController = (() => {
const _marks = ['X', 'O'];
let _players = null;
let _currentPlayer = null;
let _gamemode = null;
let _gameActive = false;
let _difficulty = null;
// all possible winning combinations (lines)
const _winningCombinations = [
[0, 1, 2],
[3, 4, 5],
[6, 7, 8],
[0, 3, 6],
[1, 4, 7],
[2, 5, 8],
[0, 4, 8],
[2, 4, 6]
];
// proccess the click event on a cell
const _handeCellClick = (event) => {
// return if game not active or
// clicked cell is not empty or
// current player is AI
if (
!_gameActive ||
!gameBoard.isCellEmpty(event.target.dataset.index) ||
_currentPlayer.isAI
) return;
// get the click cell index
const cellIndex = event.target.dataset.index;
// place current players mark in the clicked cell
gameBoard.editGameBoard(cellIndex, _currentPlayer.mark);
// render the gameboard
displayController.render();
// announce if winner or draw, else next turn
_handleWinnerOrDraw();
};
const _handleWinnerOrDraw = () => {
// get result
const result = getGameResult();
// if theres a result announce it and end the game, else play next turn
if (result !== null) {
if (result.status.includes('win')) {
displayController.addClassToElements(result.winner.winningCells, 'highlight');
}
_announce(result);
_endGame();
} else {
_nextTurn();
}
};
const _nextTurn = () => {
_switchPlayer();
// show who's turn it is
displayController.showCurrentPlayer(_currentPlayer);
// if AI is current player AI take turn
_handleAITurn();
};
// switch current player
const _switchPlayer = () => {
_currentPlayer = _currentPlayer === _players[0] ?
_players[1] : _players[0];
};
const _endGame = () => {
// stop the game
_gameActive = false;
// change text of start game button
displayController.setTextContent(domElems.gameFormElems.startBtn, 'Start Game');
// show back button
displayController.showBackButton();
// show player name inputs
displayController.showInputs(_gamemode);
};
// reset game settings
const _reset = () => {
// reset players and current player
_players = null;
_currentPlayer = null;
// reset gameboard
gameBoard.clearGameBoard();
// hide announcement msg
displayController.hideElement(domElems.announcerElem);
// remove color from winning cells
displayController.removeClassFromElements(domElems.gameBoardCells, 'highlight');
};
// get players
const _getPlayers = () => {
// get player names from text inputs
const player1Name = domElems.gameFormElems.p1Input.value || 'player1';
const player2Name = domElems.gameFormElems.p2Input.value || 'player2';
// get random mark for each player
const player1Mark = getRandomArrayElement(_marks);
const player2Mark = player1Mark === 'X' ? 'O' : 'X';
// create new player from factory
const player1 = playerFactory(player1Name, player1Mark);
// if singleplayer player2 is computer, else is a new player from factory
let player2 = null;
if (_gamemode === 'sp') {
player2 = AIFactory('computer', player2Mark, _difficulty, player1Mark);
} else {
player2 = playerFactory(player2Name, player2Mark);
}
return [player1, player2];
};
// get winning cell dom elements
const _getWinningCells = (winningCombination) => {
return winningCombination.map(index => {
return domElems.gameBoardCells[index];
});
};
// check if there is a winnner
const _getWinner = () => {
let winner = null;
const equals3 = (a, b, c) => {
return gameBoard.getValue(a) === gameBoard.getValue(b) &&
gameBoard.getValue(b) === gameBoard.getValue(c) &&
gameBoard.getValue(a) !== '';
};
// return a winner if player has three marks in a row
_winningCombinations.forEach(combination => {
if (equals3(combination[0], combination[1], combination[2])) {
const winningMark = gameBoard.getValue(combination[0]);
const winningPlayer = _players.find(player => player.mark === winningMark);
winner = winningPlayer;
winner.winningCells = _getWinningCells(combination)
}
});
return winner;
};
// its a draw if theres no empty cells left
const _isDraw = () => gameBoard.getEmptyCellsIndexes().length === 0;
// announce winner or draw
const _announce = (result) => {
const announcerElem = domElems.announcerElem;
if (result.status.includes('win')) {
const winMessage = `${result.winner.name} wins with ${result.winner.mark}s!`;
displayController.setTextContent(announcerElem, winMessage);
} else {
const drawMessage = 'Draw!';
displayController.setTextContent(announcerElem, drawMessage);
}
};
const _handleAITurn = () => {
const aiMoveTimer = 1000;
if (_currentPlayer.isAI) {
setTimeout(() => {
// AI make a move
_currentPlayer.makeMove();
// announce if winner or draw, else next turn
_handleWinnerOrDraw();
}, aiMoveTimer);
}
};
const startGame = () => {
_reset();
// get players
_players = _getPlayers();
// get a random starting player
_currentPlayer = getRandomArrayElement(_players);
// change text of start game button
displayController.setTextContent(domElems.gameFormElems.startBtn, 'Restart Game');
// show player name inputs
displayController.hideInputs(_gamemode);
// hide back button
displayController.hideBackButton();
// set announcer element text
displayController.showCurrentPlayer(_currentPlayer);
// show announcer element
displayController.showElement(domElems.announcerElem);
// add click event listener on cells
eventController.addEvent(
domElems.gameBoardCells,
'click',
_handeCellClick
);
// activate game
_gameActive = true;
// if AI is current player AI take turn
_handleAITurn();
};
const handleModeSelect = (event) => {
// set gamemode
_gamemode = event.target.dataset.mode;
// if singleplayer set difficulty
if (_gamemode === 'sp') {
_difficulty = event.target.dataset.difficulty;
}
// hide mode select btns
displayController.hideElement(domElems.modeSelectbtns);
// show player name inputs
displayController.showInputs(_gamemode);
// show form
displayController.showElement(domElems.gameForm);
};
const backToModeSelect = () => {
// reset game settings
_reset();
// hide player name inputs
displayController.hideInputs(_gamemode);
// reset gamemode
_gamemode = null;
// reset difficulty
_difficulty = null;
// hide form
displayController.hideElement(domElems.gameForm);
// show mode select btns
displayController.showElement(domElems.modeSelectbtns);
};
const getGameResult = () => {
let result = {};
// get winner if there is one
const winner = _getWinner();
// announce if theres a winner or draw and end the game, else next round
if (winner) {
result.winner = winner;
result.status = `win: ${winner.mark}`;
} else if (_isDraw()) {
result.status = 'draw';
} else {
result = null;
}
return result;
};
// return a random array element
const getRandomArrayElement = (array) => {
return array[Math.floor(Math.random() * array.length)];
};
return {
startGame,
handleModeSelect,
backToModeSelect,
getGameResult,
getRandomArrayElement
};
})();
// module for creating event listeners
const eventController = (() => {
// add event listener
const addEvent = (target, type, listener, options) => {
if (target instanceof Array) {
target.forEach(element => {
element.addEventListener(`${type}`, listener, options);
});
} else {
target.addEventListener(`${type}`, listener, options);
}
};
// remove event listener
const removeEvent = (target, type, listener) => {
if (target instanceof Array) {
target.forEach(element => {
element.removeEventListener(`${type}`, listener);
});
} else {
target.removeEventListener(`${type}`, listener);
}
};
return { addEvent, removeEvent };
})();
// add click events to UI elements
eventController.addEvent(domElems.modeSelectbtns, 'click', gameController.handleModeSelect);
eventController.addEvent(domElems.gameFormElems.startBtn, 'click', gameController.startGame);
eventController.addEvent(domElems.gameFormElems.backBtn, 'click', gameController.backToModeSelect);