-
Notifications
You must be signed in to change notification settings - Fork 0
/
script.js
337 lines (294 loc) Β· 10.8 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
// 1. get all the elements
// header, player-points, bot-points, grid-items, modal, action-button
const playerPoints = document.querySelector("#player-points");
const botPoints = document.querySelector("#bot-points");
const turn = document.querySelector("#turn");
const gridItems = document.querySelectorAll(".board-grid-items");
const modal = document.querySelector("#modal");
const modalHeader = document.querySelector("#modal-header");
const modalMsg = document.querySelector("#modal-msg");
const modalAction = document.querySelector("#modal-action");
const overlay = document.querySelector("#overlay");
const about = document.querySelector("#about");
// MODEL π
// const board = [...new Array(8).fill([...new Array(8).fill(' ')])];
const board = [
[' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '],
[' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '],
[' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '],
[' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '],
[' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '],
[' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '],
[' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '],
[' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ']
]
let scores = [2, 2];
let playerTurn = 0; // true and false
let cards = ['β‘', 'π₯'];
// let cards = ['π', 'π'];
board[3][3] = cards[0];
board[3][4] = cards[1];
board[4][3] = cards[1];
board[4][4] = cards[0];
// TODO : MODAL data
function switchTurn() {
playerTurn = Number(!playerTurn);
}
// VIEW π»ππβπ¨
// Setting the icon for players
playerPoints.innerText += ` ${cards[0]}`;
botPoints.innerText += ` ${cards[1]}`;
function render() {
turn.innerText = (playerTurn === 0) ? "Player's π turn" : "Bot's π€ turn";
playerPoints.innerText = `Player's ${cards[0]} score: ${scores[0]}`;
botPoints.innerText = `Bot's ${cards[1]} score: ${scores[1]}`;
gridItems.forEach(tile => {
// console.log(parseInt(tile.id.slice(4)));
let [row, column] = idToCord(parseInt(tile.id.slice(4)));
tile.innerText = board[row - 1][column - 1];
})
}
render();
// CONTROLLER HELPERS π€ π
function idToCord(id) {
let row = Math.floor((id - 1) / 8) + 1;
let column = (id - 1) % 8 + 1;
return [row, column];
}
function cordToIndices([row, column]) {
return [row - 1, column - 1];
}
const isValidMove = (id) => {
let [row, column] = idToCord(id);
let tilesToFlip = [];
/// Directions : Top, TRC, RIGHT, BRC, Bottom, BLC, Left, TLC
let directions = [[-1, 0], [-1, 1], [0, 1], [1, 1], [1, 0], [1, -1], [0, -1], [-1, -1]];
let i = row - 1; let j = column - 1;
if (board[i][j] !== ' ') return [];
directions.forEach(dir => {
// explore in the direction till we get ' ' or our card or boundary
i = row - 1; j = column - 1;
i += dir[0]; j += dir[1];
let temp = [];
while (i < 8 && i >= 0 && j < 8 && j >= 0 && board[i][j] === cards[Number(!playerTurn)]) {
temp.push([i, j]);
i += dir[0]; j += dir[1];
}
if (i < 8 && i >= 0 && j < 8 && j >= 0 && board[i][j] === cards[playerTurn]) {
tilesToFlip.push(...temp);
}
})
return tilesToFlip;// this returns an array of corodinate indices [ [i,j], [i,j]...]
}
const getBestMove = async (board) => {
let cloneBoard = await JSON.parse(JSON.stringify(board));
let tilesToFlip = [];
let maxLen = 0;
let bestMove = [];
for (let i = 1; i < 65; i++) {
let [row, column] = idToCord(i);
let [x, y] = [row - 1, column - 1];
if (cloneBoard[x][y] !== ' ') {
continue;
}
let temp = isValidMove(i);
if (temp.length > 0) {
if (temp.length > maxLen) {
maxLen = temp.length;
bestMove = [x, y];
tilesToFlip = temp;
};
}
}
return [tilesToFlip, bestMove];
}
const getValidMoves = async (board) => {
let cloneBoard = await JSON.parse(JSON.stringify(board));
let validMoves = [];
let flipNum = [];
// let maxLen = 0;
// let bestMove = [];
for (let i = 1; i < 65; i++) {
let [row, column] = idToCord(i);
let [x, y] = [row - 1, column - 1];
if (cloneBoard[x][y] !== ' ') {
continue;
}
let temp = isValidMove(i);
if (temp.length > 0) {
validMoves.push([x, y]);
flipNum.push(temp.length);
}
}
return [validMoves, flipNum];
}
// Player's move handler => Part of MODEL : modifies the state.
const playerMoveHandler = (id) => {
let tilesToFlip = isValidMove(id);
if (tilesToFlip.length > 0) {
// first put the player's card to the position
let [row, column] = idToCord(id);
board[row - 1][column - 1] = cards[playerTurn];
// flip the cards to each co-ordinate in tilesToflip
tilesToFlip.forEach(tile => {
board[tile[0]][tile[1]] = cards[playerTurn];
})
switchTurn();
}
else {
alert('π Wrong move (not allowed). Plz play correct move. (See ? : Help)');
return null;
}
}
const updateScore = () => {
let count = [0, 0];
for (let i = 1; i < 65; i++) {
let [row, column] = idToCord(i);
if (board[row - 1][column - 1] === cards[0]) {
count[0]++;
}
else if (board[row - 1][column - 1] === cards[1])
count[1]++;
}
scores[0] = count[0];
scores[1] = count[1];
}
const botMove = async () => {
let [tilesToFlip, bestMove] = await getBestMove(board);
// making actual change to the board state
board[bestMove[0]][bestMove[1]] = cards[playerTurn];
tilesToFlip.forEach(move => {
board[move[0]][move[1]] = cards[playerTurn];
})
// doing click just for that bgcolor effect.
let bestPosId = bestMove[0] * 8 + bestMove[1] + 1;
let el = document.querySelector(`#pos-${bestPosId}`); // turn = 1
el.click();
switchTurn();
}
function resetGame() {
modal.classList.add('active');
overlay.classList.add('active');
if (scores[0] > scores[1]) {
// Player won
modalHeader.innerHTML = `<h3>
You won! <br> ${scores[0]} - ${scores[1]}</h3> <div>πβ¨π π β¨ππ</div> `;
// let gif = `<iframe src="https://giphy.com/embed/111ebonMs90YLu" width="100%" height="100%" style="position:absolute" frameBorder="0" class="giphy-embed" allowFullScreen></iframe>`
let gif = `<iframe src="https://giphy.com/embed/o75ajIFH0QnQC3nCeD" width="100%" height="100%" style="position:absolute" frameBorder="0" class="giphy-embed" allowFullScreen></iframe>`
let message = `${gif}`;
modalMsg.innerHTML = message;
modalAction.innerText = 'Play Again π';
}
else if (scores[1] > scores[0]) {
// Bot has won
modalHeader.innerHTML = `<h3>Bot π€ has defeated you. <br> ${scores[0]} - ${scores[1]} </h3> Try harder πͺ `;
// let gif = `<iframe src="https://giphy.com/embed/mIZ9rPeMKefm0" width="100%" height="100%" style="position:absolute" frameBorder="0" class="giphy-embed" allowFullScreen></iframe>`
let gif = `<iframe src="https://giphy.com/embed/PhR99fbNjhAAzopGnm" width="100%" height="100%" style="position:absolute" frameBorder="0" class="giphy-embed" allowFullScreen></iframe>`
let message = ` ${gif}`;
modalMsg.innerHTML = message;
modalAction.innerText = 'Play Again πͺ';
}
}
function restartGame() {
for (let i = 0; i < 8; i++) {
board[i] = [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '];
}
board[3][3] = cards[0];
board[3][4] = cards[1];
board[4][3] = cards[1];
board[4][4] = cards[0];
playerTurn = 0;
scores = [2, 2];
modalMsg.innerHTML = '';
modal.classList.remove('active')
overlay.classList.remove('active');
render();
}
// CONTROLLER βοΈπ οΈ
const ClickHandler = async (e) => {
if (playerTurn === 0) {
let id = parseInt(e.target.id.slice(4)); // turn =0
if (playerMoveHandler(id) === null) return;
// console.log(board); // turn = 1
updateScore();
render();
turn.click();
// Bot's move
setTimeout(async () => {
let [validMoves, flipNum] = await getValidMoves(board);
let canBotMove = true;
if (validMoves.length > 0) {
await botMove();
// console.log(board);
updateScore(); // turn = 0
render();
turn.click();
}
else {
canBotMove = false;
alert(`Bot has no legal possible moves. `);
switchTurn(); // turn = 0
}
[validMoves, flipNum] = await getValidMoves(board);
// console.log(validMoves);
if (validMoves.length === 0 && canBotMove === false) {
alert('You also have no possible moves. Game ends π');
resetGame();
}
else if (validMoves.length === 0) {
alert('You have no possible moves.');
switchTurn();
[validMoves, flipNum] = await getValidMoves(board);
if (validMoves.length === 0) {
alert('Bot also has no possible moves. Game ends π');
resetGame();
}
}
}, 1500); // 1.5s delay for bot move
}
}
// About handler
const aboutHandler = () => {
modal.classList.add("active");
overlay.classList.add("active");
// 1. Header : built by 2. message: learn how to play. 3. close
modalHeader.innerHTML = `<a href="https://www.youtube.com/watch?v=xDnYEOsjZnM" target="_blank">Learn how to play</a>`;
modalMsg.innerHTML = `<h3>Made by Rahul π</h3>`
modalAction.innerText = 'Close';
modalAction.removeEventListener('click', restartGame);
modalAction.addEventListener('click', closeModal);
}
function closeModal(e) {
modal.classList.remove('active')
overlay.classList.remove('active');
setTimeout(() => {
modalAction.removeEventListener('click', closeModal);
modalAction.addEventListener('click', restartGame);
}, 1000);
}
// Animate the bgcolor if innerContent changes
function changimation(e) {
e.target.classList.add('changimate');
setTimeout(() => {
e.target.classList.remove('changimate')
}, 1000);
}
// Animate the bgcolor if player's turn changes
function sizeanimation(e) {
e.target.classList.add('sizeanimate');
setTimeout(() => {
e.target.classList.remove('sizeanimate')
}, 1000);
}
gridItems.forEach(item => {
// let id = item.id.slice(4);
// console.log(id);
item.addEventListener('click', changimation);
item.addEventListener('click', ClickHandler);
}
);
turn.addEventListener('click', changimation);
modalAction.addEventListener('click', restartGame);
about.addEventListener('click', aboutHandler)
// Test
// modal.classList.add('active');