-
Notifications
You must be signed in to change notification settings - Fork 0
/
script.js
394 lines (332 loc) · 9.34 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
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
function getTilesDOM() {
return Array.from(document.querySelectorAll("td"));
}
const DOM = {
tiles: getTilesDOM(),
// x: "blue", // Image here
// o: "green", // Image here
alert: document.querySelector(".alert"),
boardSizeInput: document.querySelector("#board-size-input"),
boardSizeOutput: document.querySelector("#board-size-output"),
toWinInput: document.querySelector("#to-win-input"),
toWinOutput: document.querySelector("#to-win-output"),
submitButton: document.querySelector("#submit-button"),
board: document.querySelector("tbody"),
continueBtn: document.querySelector("#continue-btn"),
resetBtn: document.querySelector("#reset-btn"),
player: {
x: {
// name: document.querySelector("#player-x-avatar"),
score: document.querySelector("#player-x-score"),
avatar: document.querySelector("#player-x-avatar"),
avatarColorBtn: document.querySelector("#player-x-avatar-color-button"),
avatarImgBtn: document.querySelector("#player-x-avatar-image-button"),
},
o: {
// name: document.querySelector("#player-o-avatar"),
score: document.querySelector("#player-o-score"),
avatar: document.querySelector("#player-o-avatar"),
avatarColorBtn: document.querySelector("#player-o-avatar-color-button"),
avatarImgBtn: document.querySelector("#player-o-avatar-image-button"),
},
},
};
function colorDiv(color) {
return `<span
style="
background-color: ${color};
height: 14px;
width: 14px;
display: inline-block;
"
></span>`;
}
let state = {
currentPlayer: "x",
winner: false,
player: {
x: [],
o: [],
},
color: {
x: "blue",
o: "green",
},
playerName: {
x: colorDiv("blue"), // colorDiv(this.color.x),
o: colorDiv("green"), // colorDiv(this.color.o),
},
point: {
x: 0,
o: 0,
},
boardSize: 3,
toWin: 3,
};
function reverseCoordinate(token) {
if (token === "x") {
return "y";
} else {
return "x";
}
}
function tileEmpty(tile) {
if (
// Photo case: !tile.innerHTML
tile.style.backgroundColor == "" // Background color case
) {
return true;
} else {
return false;
}
}
function tileNotEmptyWarning() {
DOM.alert.innerText = "This tile is not available";
}
function clearWarning() {
DOM.alert.innerText = "";
}
function switchPlayer(prevPlayer) {
state.currentPlayer = prevPlayer === "x" ? "o" : "x";
}
// Converts HTML ID to JavaScript Object for Tile Position
function tileJSPosition(tile) {
const splitTile = tile.split(" ");
return {
x: parseInt(
splitTile[0].split("").slice(1, splitTile[0].split("").length).join("")
),
y: parseInt(
splitTile[1].split("").slice(1, splitTile[1].split("").length).join("")
),
};
}
function addPointsToToken(tileObj) {
winThroughXorY(tileObj, "x");
winThroughXorY(tileObj, "y");
winThroughDiagonalTopLeft(tileObj);
winThroughDiagonalTopRight(tileObj);
}
function mutatePoints(aTile, tileObj, position) {
aTile.point[position] += tileObj.point[position];
tileObj.point[position] = aTile.point[position];
}
function winThroughXorY(tileObj, coordinate) {
state.player[state.currentPlayer].forEach((aTile) => {
if (
aTile.position[reverseCoordinate(coordinate)] ===
tileObj.position[reverseCoordinate(coordinate)] &&
(aTile.position[coordinate] === tileObj.position[coordinate] + 1 ||
aTile.position[coordinate] === tileObj.position[coordinate] - 1)
) {
mutatePoints(aTile, tileObj, coordinate);
if (checkWinner(tileObj.point[coordinate])) declareWinner();
}
});
}
function winThroughDiagonalTopLeft(tileObj) {
state.player[state.currentPlayer].forEach((aTile) => {
if (
// Positive Case
(tileObj.position["x"] === aTile.position["x"] + 1 &&
tileObj.position["y"] === aTile.position["y"] + 1) ||
// Negative Case
(tileObj.position["x"] === aTile.position["x"] - 1 &&
tileObj.position["y"] === aTile.position["y"] - 1)
) {
mutatePoints(aTile, tileObj, "topLeft");
if (checkWinner(tileObj.point["topLeft"])) declareWinner();
}
});
}
function winThroughDiagonalTopRight(tileObj) {
state.player[state.currentPlayer].forEach((aTile) => {
if (
// Positive Case
(tileObj.position["x"] === aTile.position["x"] + 1 &&
tileObj.position["y"] === aTile.position["y"] - 1) ||
// Negative Case
(tileObj.position["x"] === aTile.position["x"] - 1 &&
tileObj.position["y"] === aTile.position["y"] + 1)
) {
mutatePoints(aTile, tileObj, "topRight");
if (checkWinner(tileObj.point["topRight"])) declareWinner();
}
});
}
function checkWinner(point) {
if (point >= state.toWin) {
return true;
}
return false;
}
function checkDraw() {
// Method 1
// let tileCount = 0;
// DOM.tiles.forEach((tile) => {
// if (tileEmpty(tile)) tileCount++;
// });
// if (tileCount === DOM.tiles.length) {
// return true;
// } else {
// return false;
// }
// Method 2
if (state.player.x.length + state.player.o.length === DOM.tiles.length) {
return true;
} else {
return false;
}
}
function declareDraw() {
// Display UI
DOM.alert.innerHTML = `<p>This is a draw</p>`;
gameContinueReset();
}
function gamePlayOff() {
DOM.tiles.forEach((tile) => {
tile.removeEventListener("click", insertToken);
});
}
function declareWinner() {
// Display UI
DOM.alert.innerHTML = `<p>Player ${
state.playerName[state.currentPlayer]
} has won</p>`;
// Add points to user in DB
state.point[state.currentPlayer] += 1;
// Change winning status
state.winner = true;
// Add points to the UI
DOM.player[state.currentPlayer].score.innerText =
state.point[state.currentPlayer];
gameContinueReset();
}
function gameContinueReset() {
// Reset the game
DOM.continueBtn.disabled = false;
// Turn off Game
gamePlayOff();
// Continue
DOM.continueBtn.addEventListener("click", (e) => {
e.preventDefault();
reset();
});
}
function gameResetAll() {
gamePlayOff();
// Clear DB
state.point.x = 0;
state.point.o = 0;
// Clear UI
DOM.player.x.score.innerText = state.point.x;
DOM.player.o.score.innerText = state.point.o;
reset();
}
function reset() {
// Reset winner
state.winner = false;
// Clear the UI
DOM.alert.innerHTML = "";
DOM.tiles.forEach((tile) => {
tile.style.backgroundColor = "";
});
// Clear the DB
state.player.x = [];
state.player.o = [];
// Rerun the game
main();
}
function addTokenToState(tileObj) {
state.player[state.currentPlayer].push({
position: tileObj,
point: {
// X and Y
x: 1,
y: 1,
// Diagonal
topLeft: 1,
topRight: 1,
},
});
}
function insertToken(event) {
clearWarning();
const tile = event.target;
if (tileEmpty(tile)) {
//// Adding placed tile to UI
// Insert photo mode
// tile.insertAdjacentHTML("beforeend", DOM[state.currentPlayer]);
// Colour mode
// tile.style.backgroundColor = DOM[state.currentPlayer];
tile.style.backgroundColor = state.color[state.currentPlayer];
//// Addding placed tile info to database
// Parsing tile from HTML id to JavaScript object
const tileObj = tileJSPosition(tile.id);
// Adding tile to player's move array
addTokenToState(tileObj);
// Adding points to tile's point tracker and check winning condition
addPointsToToken(
state.player[state.currentPlayer][
state.player[state.currentPlayer].length - 1
]
);
if (checkDraw() & !state.winner) declareDraw();
switchPlayer(state.currentPlayer);
} else {
tileNotEmptyWarning();
}
}
function setting() {
gamePlayOff();
const boardSizeNum = parseInt(DOM.boardSizeInput.value);
if (!isNaN(boardSizeNum) && DOM.boardSizeInput.value.trim() != "") {
state.boardSize = boardSizeNum;
DOM.boardSizeOutput.innerHTML = boardSizeNum;
DOM.boardSizeInput.value = "";
DOM.board.innerHTML = "";
for (let i = 0; i < boardSizeNum; i++) {
const boardRow = document.createElement("tr");
boardRow.classList = "x" + (i + 1);
for (let i1 = 0; i1 < boardSizeNum; i1++) {
const boardCell = document.createElement("td");
boardCell.id = boardRow.classList + " " + "y" + (i1 + 1);
boardRow.insertAdjacentElement("beforeend", boardCell);
}
DOM.board.insertAdjacentElement("beforeend", boardRow);
}
}
DOM.tiles = getTilesDOM();
const toWinNum = parseInt(DOM.toWinInput.value);
if (!isNaN(toWinNum) && DOM.toWinInput.value.trim() != "") {
state.toWin = toWinNum;
DOM.toWinOutput.innerHTML = toWinNum;
DOM.toWinInput.value = "";
}
main();
}
function main() {
DOM.tiles.forEach((tile) => {
tile.addEventListener("click", insertToken);
});
DOM.continueBtn.disabled = true;
}
main();
DOM.submitButton.addEventListener("click", (e) => {
e.preventDefault();
setting();
});
DOM.resetBtn.addEventListener("click", (e) => {
e.preventDefault();
gameResetAll();
});
function update(jscolor) {
// 'jscolor' instance can be used as a string
const player = event.target.classList.value.split(" ")[0];
const selectedColour = "#" + jscolor;
state.playerName[player] = colorDiv(selectedColour);
state.color[player] = selectedColour;
DOM.player[player].avatar.style.backgroundColor = selectedColour;
// console.log(state.playerName[player]);
// console.log(DOM.player[player]);
}