-
Notifications
You must be signed in to change notification settings - Fork 0
/
script.js
278 lines (260 loc) · 10.4 KB
/
script.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
// object that represents the board
const gameBoard = (() => {
const fieldArray = [" "," "," "," "," "," "," "," "," "];
return {fieldArray}
})();
// factory function that creates the players
const player = (name) => {
this.name = name;
this.score = 0;
return {name, score}
}
const player1 = player("Fred");
const player2 = player("Johannes");
// this private module contains all functions relating to game logic and DOM manipulation
// this demonstrates the concept of closure: every function retains the scope of its creation (displayControl) and can only be called outside of this function if we return it
const displayControl = (() => {
const gameFields = document.querySelectorAll(".gameField")
const modal = document.querySelector(".modal")
const resultMessage = document.querySelector(".resultMessage")
const scoreX = document.querySelector(".scoreX")
const scoreY = document.querySelector(".scoreY")
const addEvents = () => {
// make a "x" on the users click
let makeMark = function(field, index){
return function curriedFunc(e){
if(gameBoard.fieldArray[index]===" "){
field.textContent= "x"
gameBoard.fieldArray[index] = "x"
field.classList.add("filled")
// check for win or draw
if(checkForWin()==="x"){
activateModal("x")
}
else if(checkForWin()==="o"){
activateModal("o")
}
else if(checkForDraw()==="draw"){
activateModal("draw")
}
else{
// decide between impossible mode and easy mode
let mode = document.querySelector("#mode")
if(mode.value === "easy"){
// random computer move
setTimeout(robotMoves, 500);
}
else if(mode.value === "impossible"){
// optimal computer move
setTimeout(unbeatableMoves, 500);
}
}
}
}
}
gameFields.forEach((field, index) => field.addEventListener("click", makeMark(field, index)))
}
const checkForWin = () =>{
if(
// horizontal x
(gameBoard.fieldArray[0]==="x"&&gameBoard.fieldArray[1]==="x"&&gameBoard.fieldArray[2]==="x")||
(gameBoard.fieldArray[3]==="x"&&gameBoard.fieldArray[4]==="x"&&gameBoard.fieldArray[5]==="x")||
(gameBoard.fieldArray[6]==="x"&&gameBoard.fieldArray[7]==="x"&&gameBoard.fieldArray[8]==="x")||
// vertical x
(gameBoard.fieldArray[0]==="x"&&gameBoard.fieldArray[3]==="x"&&gameBoard.fieldArray[6]==="x")||
(gameBoard.fieldArray[1]==="x"&&gameBoard.fieldArray[4]==="x"&&gameBoard.fieldArray[7]==="x")||
(gameBoard.fieldArray[2]==="x"&&gameBoard.fieldArray[5]==="x"&&gameBoard.fieldArray[8]==="x")||
// diagonal x
(gameBoard.fieldArray[0]==="x"&&gameBoard.fieldArray[4]==="x"&&gameBoard.fieldArray[8]==="x")||
(gameBoard.fieldArray[6]==="x"&&gameBoard.fieldArray[4]==="x"&&gameBoard.fieldArray[2]==="x")){
return "x"
}
else if(
// horizontal o
(gameBoard.fieldArray[0]==="o"&&gameBoard.fieldArray[1]==="o"&&gameBoard.fieldArray[2]==="o")||
(gameBoard.fieldArray[3]==="o"&&gameBoard.fieldArray[4]==="o"&&gameBoard.fieldArray[5]==="o")||
(gameBoard.fieldArray[6]==="o"&&gameBoard.fieldArray[7]==="o"&&gameBoard.fieldArray[8]==="o")||
// vertical o
(gameBoard.fieldArray[0]==="o"&&gameBoard.fieldArray[3]==="o"&&gameBoard.fieldArray[6]==="o")||
(gameBoard.fieldArray[1]==="o"&&gameBoard.fieldArray[4]==="o"&&gameBoard.fieldArray[7]==="o")||
(gameBoard.fieldArray[2]==="o"&&gameBoard.fieldArray[5]==="o"&&gameBoard.fieldArray[8]==="o")||
// diagonal o
(gameBoard.fieldArray[0]==="o"&&gameBoard.fieldArray[4]==="o"&&gameBoard.fieldArray[8]==="o")||
(gameBoard.fieldArray[6]==="o"&&gameBoard.fieldArray[4]==="o"&&gameBoard.fieldArray[2]==="o")){
return "o"
}
return null // no winner
}
const checkForDraw = () => {
let drawCounter = 0
for(let i=0; i<gameBoard.fieldArray.length; i++){
if(gameBoard.fieldArray[i]!==" "){
drawCounter++
}
}
if(drawCounter === 9){
return "draw"
}
return null
}
const activateModal = (result) => {
// activate modal
modal.classList.add("modalActive")
resultMessage.classList.add("modalActive")
// enter win/loss/draw message
if(result==="x"){
resultMessage.textContent = `x wins!`
player1.score++
}
else if(result==="o"){
resultMessage.textContent = `o wins!`
player2.score++
}
else if(result==="draw"){
resultMessage.textContent = `It's a draw!`
}
displayScore()
}
const restartGame = () => {
// empty array
gameBoard.fieldArray = [" "," "," "," "," "," "," "," "," "];
// empty fields
gameFields.forEach((field) => {
field.textContent = ""
field.classList.remove("filled")
})
// deactivate modal
modal.classList.remove("modalActive")
resultMessage.classList.remove("modalActive")
}
modal.addEventListener("click", restartGame)
resultMessage.addEventListener("click", restartGame)
// function for displaying score
const displayScore = () => {
scoreX.textContent = player1.score
scoreY.textContent = player2.score
}
// computer plays random moves
const robotMoves = () => {
// random move: choose num between 0 and 8
// if illegal, choose again
let randomMove;
do{
randomMove = Math.floor(Math.random() * 8) + 1
}while(gameBoard.fieldArray[randomMove]!==" ")
// add move to array
gameBoard.fieldArray[randomMove] = "o"
// make move in DOM
gameFields[randomMove].textContent = "o"
gameFields[randomMove].classList.add("filled")
// check for win or draw
if(checkForWin()==="x"){
activateModal("x")
}
else if(checkForWin()==="o"){
activateModal("o")
}
else if(checkForDraw()==="draw"){
activateModal("draw")
}
}
// computer plays optimally
const unbeatableMoves = () => {
// save bestScore in a variable
let bestScore = Infinity
// save bestMove in a variable
let bestMove;
// go through all possible moves
for(let i=0; i<gameBoard.fieldArray.length; i++){
// check if field is available
if(gameBoard.fieldArray[i]===" "){
// computer makes a move, to be evaluated
gameBoard.fieldArray[i]="o"
// find best possible move (for x, maximizing)
let score = minimax(0, true)
// undo the tested move
gameBoard.fieldArray[i]=" "
// update bestMove and bestScore
if(score < bestScore){
bestScore=score
bestMove=i
}
}
}
gameBoard.fieldArray[bestMove]="o"
// make move in DOM
gameFields[bestMove].textContent = "o"
gameFields[bestMove].classList.add("filled")
// check for win + activate modal
if(checkForWin()==="x"){
activateModal("x")
}
else if(checkForWin()==="o"){
activateModal("o")
}
else if(checkForDraw()==="draw"){
activateModal("draw")
}
}
// translate the game results into minimax scores
let scores = {
x : 1,
o : -1,
draw : 0,
}
const minimax = (depth, isMaximizing) => {
// terminating condition: if leaf node is reached(win, loss or draw) return a corresponding score (1,-1, 0)
let result = checkForWin()
if(result !== null){
return scores[result]
}
let drawCheck = checkForDraw()
if(drawCheck !== null){
return scores[drawCheck]
}
// choose the next move
if(isMaximizing){
let bestScore = -Infinity
for(let i=0; i<gameBoard.fieldArray.length; i++){
// check if field is available
if(gameBoard.fieldArray[i]===" "){
// x makes a move, to be evaluated
gameBoard.fieldArray[i]="x"
// find next, best possible move for o
let score = minimax(depth + 1, false)
// undo the tested move
gameBoard.fieldArray[i]=" "
// update bestMove and bestScore
bestScore = Math.max(score, bestScore)
}
}
return bestScore
} else { // is minimizing
let bestScore = Infinity
for(let i=0; i<gameBoard.fieldArray.length; i++){
// check if field is available
if(gameBoard.fieldArray[i]===" "){
// ai(o) makes a move, to be evaluated
gameBoard.fieldArray[i]="o"
// find next, best possible move for x
let score = minimax(depth + 1, true)
// undo the tested move
gameBoard.fieldArray[i]=" "
// update bestMove and bestScore
bestScore = Math.min(score, bestScore)
}
}
return bestScore;
}
}
return {addEvents, checkForDraw, checkForWin, unbeatableMoves, minimax}
})();
displayControl.addEvents()
/*
create mode selector: random, depth varied difficulty, unbeatable
highlight the winning combination?
make the ai play to lose
invert depth to apply different skill levels
style the select element
is the curried function necessary?
*/