forked from ChromeGaming/Dot-Box
-
Notifications
You must be signed in to change notification settings - Fork 0
/
game.js
284 lines (229 loc) · 9.11 KB
/
game.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
class Game {
static instance // Singleton instance of Game class
constructor(rows, columns, playersCount) {
if (Game.instance == null) Game.instance = this
this.playersUI = document.querySelector(".players")
this.playerNameUI = document.querySelector(".player-turn .name")
this.playerTurnBgUI = document.querySelector(".player-turn .bg")
this.events = {
edgeFill: [],
boxFill: [],
playerSwitch: [],
playerWin: [],
}
this.players = [
{ name: "Player 1", color: "pink", filledBoxes: 0 },
{ name: "Player 2", color: "skyblue", filledBoxes: 0 },
{ name: "Player 3", color: "lightgreen", filledBoxes: 0 },
{ name: "Player 4", color: "magenta", filledBoxes: 0 },
{ name: "Player 5", color: "yellow", filledBoxes: 0 },
{ name: "Player 6", color: "orange", filledBoxes: 0 }
]
let p = this.players.length - playersCount
for (let i = 0; i < p; i++)
this.players.pop()
this.currentPlayerIndex = 0
this.currentPlayer = this.players[this.currentPlayerIndex]
this.board = new Board(rows, columns)
this.isGameover = false
this.addPlayersUI()
this.updatePlayerNameUI()
this.updateRankingsUI() // Initial call to update the rankings UI
// Adding event listeners for filling box, switching player and winning
this.addEventListener("boxFill", () => this.onBoxFill())
this.addEventListener("playerSwitch", () => this.onPlayerSwitch())
this.addEventListener("playerWin", () => this.onPlayerWin())
}
// End Game
onPlayerWin() {
this.isGameover = true
bgMusic.pause();
let winSound = new Audio('./sounds/win.mp3');
winSound.play();
const player = this.players.reduce((prev, current) => {
return prev.filledBoxes > current.filledBoxes ? prev : current
});
setTimeout(() => {
let play = this.players[0].filledBoxes
// Check for winner
if (this.players.every((p) => p.filledBoxes == play)) {
this.playerNameUI.parentElement.textContent = "Nobody wins"
this.playerTurnBgUI.classList.add("no-win")
this.playerTurnBgUI.style.background = "#eaeaea"
} else {
this.playerNameUI.parentElement.textContent = `${player.name} wins`
this.playerTurnBgUI.classList.add("win")
this.playerTurnBgUI.style.background = player.color
}
}, 500);
}
onPlayerSwitch() {
this.updatePlayerNameUI();
}
// If a box is filled, increment player's score with number of boxes filled by him/her and update UI
onBoxFill() {
this.currentPlayer.filledBoxes++
this.updatePlayerScoreUI();
this.updateRankingsUI(); // Update the rankings whenever a box is filled
}
// Add players to UI
addPlayersUI() {
this.players.forEach((player, index) => {
const div = document.createElement("div")
div.classList.add("player")
// Maintain filled boxes
const b = document.createElement("b")
b.classList.add("filled-boxes")
b.textContent = player.filledBoxes
b.style.background = player.color
this.players[index]["filledBoxesUI"] = b
// Maintain player name
const span = document.createElement("span")
span.textContent = player.name
div.appendChild(b)
div.appendChild(span)
// Adding score and name to the element
this.playersUI.appendChild(div)
});
}
// Update player score UI used while switching player
updatePlayerScoreUI() {
this.currentPlayer.filledBoxesUI.innerText = this.currentPlayer.filledBoxes
}
// Update player name UI used while switching player
updatePlayerNameUI() {
this.playerNameUI.innerText = this.currentPlayer.name
this.playerTurnBgUI.style.background = this.currentPlayer.color
}
updateRankingsUI() {
const rankingBody = document.getElementById('ranking-body');
rankingBody.innerHTML = '';
// Sort players by filledBoxes in descending order
const sortedPlayers = [...this.players].sort((a, b) => b.filledBoxes - a.filledBoxes);
sortedPlayers.forEach((player, index) => {
const row = document.createElement('tr');
const rankCell = document.createElement('td');
const playerCell = document.createElement('td');
const boxesCell = document.createElement('td');
rankCell.textContent = index + 1;
playerCell.textContent = player.name;
boxesCell.textContent = player.filledBoxes;
row.appendChild(rankCell);
row.appendChild(playerCell);
row.appendChild(boxesCell);
rankingBody.appendChild(row);
});
}
eventExist(event) {
return this.events.hasOwnProperty(event)
}
// Add event listeners
addEventListener(event, callback) {
if (!this.eventExist(event)) {
console.error(`${event} event is not defined`)
return
}
this.events[event].push(callback)
}
// Remove event listeners
removeEventListener(event, callback) {
if (!this.eventExist(event)) {
console.error(`${event} event is not defined`)
return
}
this.events[event].splice(this.events[event].indexOf(callback), 1)
}
// Invoke event listeners
invokeEvent(event, args) {
if (!this.eventExist(event)) {
console.error(`${event} event is not defined`)
return
}
this.events[event].forEach((callback) => callback(args))
}
// Switch player
switchPlayer() {
if (!this.isGameover) {
this.currentPlayerIndex = ++this.currentPlayerIndex % this.players.length
this.currentPlayer = this.players[this.currentPlayerIndex]
this.invokeEvent("playerSwitch")
}
}
}
// Selecting the mute button and icon
const muteBtn = document.querySelector(".mute-btn");
const muteIcon = document.querySelector(".mute-btn i");
// Event listener for mute button
muteBtn.addEventListener("click", () => {
if (bgMusic.paused) {
bgMusic.play();
muteIcon.classList.remove("fa-volume-off"); // Remove mute icon
muteIcon.classList.add("fa-volume-up"); // Add unmute icon
} else {
bgMusic.pause();
muteIcon.classList.remove("fa-volume-up"); // Remove unmute icon
muteIcon.classList.add("fa-volume-off"); // Add mute icon
}
});
// Declaring Global Variables
const settingsUI = document.querySelector(".settings")
const rowsInput = document.querySelector("#rows")
const columnsInput = document.querySelector("#columns")
const playersInput = document.querySelector("#players-count")
const startBtn = document.querySelector(".start-btn")
const heading = document.querySelector(".heading")
const bgMusic = new Audio('./sounds/bgMusic.mp3');
const rowsWarning = document.querySelector("#rows-warning");
const columnsWarning = document.querySelector("#columns-warning");
const playersWarning = document.querySelector("#players-warning");
var game = null
// Get warning elements
const warnings = [rowsWarning, columnsWarning, playersWarning];
// Add event listeners to input fields to remove warnings when user starts entering input again
rowsInput.addEventListener("focus", () => {
rowsWarning.style.display = "none";
});
columnsInput.addEventListener("focus", () => {
columnsWarning.style.display = "none";
});
playersInput.addEventListener("focus", () => {
playersWarning.style.display = "none";
});
startBtn.addEventListener("click", () => {
// Get values of inputs
const rows = parseInt(rowsInput.value);
const columns = parseInt(columnsInput.value);
const playersCount = parseInt(playersInput.value);
const inputValues = [rows, columns, playersCount];
// Getting validity of inputs
let validGame = validateForm(inputValues);
// If any input is invalid, prevent starting the game
if (validGame === true) {
// Set background music volume and play
bgMusic.volume = 0.1;
bgMusic.play();
// Start game with valid inputs
game = new Game(rows, columns, playersCount);
settingsUI.style.display = "none";
heading.style.display = "none";
document.getElementById("theme-options").style.display = "none";
document.getElementById("theme-button").style.display = "none";
}
});
function validateForm(inputValues) {
let valid = true;
for (let i = 0; i < 3; i++) {
let value = inputValues[i];
let warning = warnings[i];
let min = (i === 2) ? 2 : 5;
let max = (i === 2) ? 6 : 30;
if (value == null || value < min || value > max) {
warning.style.display = "block";
valid = false;
}
}
return valid;
}
function exitGame() {
window.location.reload();
};