-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmyScript.js
More file actions
710 lines (626 loc) · 25 KB
/
Copy pathmyScript.js
File metadata and controls
710 lines (626 loc) · 25 KB
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
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
/** Comments here are both for my own understanding and for anyone else who looks at the code later.
* I'm learning JavasScript as I do this so this code might not be the most efficient - Aaron */
// --- GOOGLE FIREBASE SETUP --- \\
// Import Firebase SDK (Software Development Kit) modules directly from Google's CDN
//This gives us functions to connect to our Firebase project and talk to the Realtime Database for the health tracker
import { initializeApp } from "https://www.gstatic.com/firebasejs/12.8.0/firebase-app.js";
import {
getDatabase,
ref,
onValue,
set,
update,
remove,
} from "https://www.gstatic.com/firebasejs/12.8.0/firebase-database.js";
//Import the anonymous authentication functions we need
import {
getAuth,
signInAnonymously,
} from "https://www.gstatic.com/firebasejs/12.8.0/firebase-auth.js";
// Confirguration object for our specific Firebase project
// These values come from the Firebase console and identity which project we want to connect to. In this case "SkuffleTest"
const firebaseConfig = {
apiKey: "AIzaSyAXUdeglgszb0WflC5o8VuXBuO1V3OzHWQ", // This is a public api key, it's not a secret and is safe to include. Ignore Githubs warning about this.
authDomain: "skuffletest.firebaseapp.com",
databaseURL:
"https://skuffletest-default-rtdb.europe-west1.firebasedatabase.app",
projectId: "skuffletest",
storageBucket: "skuffletest.firebasestorage.app",
messagingSenderId: "656546117071",
appId: "1:656546117071:web:25437409b3c2e155fa8eba",
measurementId: "G-E5H5Q8STFE",
};
// Const are variables that we can't and don't want to reassign
// Creates a Firebase app instance using the config from above
// From this, we can connect to our Realtime Database
const app = initializeApp(firebaseConfig);
const database = getDatabase(app); // Main handle to interact with the Realtime Database
// Create a reference to the "players" node in our realtime database
// All player data will be stored under this path: /players
const playersRef = ref(database, "players");
//Get a handle to Firebase Authentication so we can sign in anonymously
const auth = getAuth(app);
//This variable will hold the current user's unique ID once they're signed in
//It starts as null because sign-in hasn't happened yet when the page first loads
let currentUID = null;
// --- ANONYMOUS SIGN-IN --- \\
// signInAnonymously returns a Promise - meaning it goes off and does its work and calls the .then() function when it's done, without freezing the page
// a promise is just a placeholder for a value that will be available in the future
signInAnonymously(auth)
.then((userCredential) => {
// Sign-in succeeded - userCredential contains info about this "ghost account"
// We pull out just the uid (unique ID) and store it in our currentUID variable
currentUID = userCredential.user.uid;
console.log("Signed in anonymously, UID:", currentUID); // Useful for debugging, shows the UID in the console
// Re-check the players once after sign-in
// This matters because the database listener may have loaded before currentUID was ready
onValue(
playersRef,
(snapshot) => {
const data = snapshot.val();
displayPlayers(data);
},
{ onlyOnce: true },
);
})
.catch((error) => {
console.error("Anonymous sign-in failed:", error); // catches the error
});
// --- CHARACTER SOUND LOGIC --- \\
// Plays specific sound for each character
// soundType is either "increase", "decrease", or "ability" depending on the action being taken. We create an array later on containing all the different effect
window.playCharacterSound = function (characterName, soundType) {
const characterSound = characterSounds[characterName];
if (!characterSound) {
console.warn(`No sound found for character: ${characterName}`);
return;
}
const sound = characterSound[soundType];
if (!sound) {
console.warn("No", soundType, "sound found for:", characterName);
return;
}
sound.currentTime = 0; // starts sound at begining
sound.play().catch((error) => {
console.error("Could not play sound:", error);
});
};
// --- HEALTH CHANGE LOGIC --- \\
// Change a player's health by a certain amount (positive or negative)
// playerId is the database key for that player
window.changeHealth = function (playerId, change) {
// Get a reference to the specific player in the database using their unique ID: /players/<playerId>
const playerRef = ref(database, "players/" + playerId);
// Read the current player data once from the database
onValue(
playerRef,
(snapshot) => {
const player = snapshot.val();
if (!player) return;
// Calculate the new health by adding the change. ex. 20 + (-1) = 19
let newHealth = player.health + change;
// Constrain the health so it can't go below 0 or above 20
newHealth = Math.max(0, Math.min(20, newHealth));
// Write the updated health value back to the database
update(playerRef, { health: newHealth });
},
{ onlyOnce: true },
); // onlyOnce: true means this listener will run once and then stop
};
// --- SPECIAL ABILITY BANK --- \\
const characterData = {
// This stores the special ability info for each character to be called upon later, so type of ability, name and the numbers
Cowboy: {
specialName: "Bullets",
specialType: "number",
specialValue: 6,
specialMin: 0,
specialMax: 6,
},
"Were-Lobster": {
specialName: "Tide",
specialType: "toggle",
specialValue: "Low", // Starting tide
toggleOptions: ["Low", "High"], // Swap between the two tides
},
"Goe Bling": {
specialName: "Steal",
specialType: "number",
specialValue: 0,
specialMin: 0,
specialMax: 10,
},
"Salary Man": {
specialName: "Money",
specialType: "number",
specialValue: 4,
specialMin: 0,
specialMax: 100,
},
Alien: {
specialName: "Dodge",
specialType: "number",
specialValue: 3,
specialMin: 0,
specialMax: 3,
},
Margritte: {
// Doesn't have special ability so everthing is null
specialName: null,
specialType: null,
specialValue: null,
specialMin: null,
specialMax: null,
},
};
// --- CHARACTER IMAGE BANK --- \\
// This is for the "Hero" section of the health tracker
const characterImages = {
Cowboy: "img/character/Cabarello (Medium).png",
"Were-Lobster": "img/character/Lawrence (Medium).png",
"Goe Bling": "img/character/Goe (Medium).png",
"Salary Man": "img/character/Sal (Medium).png",
Alien: "img/character/Alan (Medium).png",
Margritte: "img/character/Margritte (Medium).png",
};
// --- CHARACTER COLOUR BANK --- \\
// This is for the health tracker and the character bios
const characterThemes = {
Cowboy: {
border: "#561300",
background: "#ad8c83",
text: "#000000",
},
"Were-Lobster": {
border: "#18163b",
background: "#a1d0fc",
text: "#18163b",
},
"Goe Bling": {
border: "#223323",
background: "#466948",
text: "#ffffff",
},
"Salary Man": {
border: "#393939",
background: "#d9d9d9",
text: "#393939",
},
Alien: {
border: "#fc6fe7",
background: "#efeacd",
text: "#fc6fe7",
},
Margritte: {
border: "#541037",
background: "#f2bb5b",
text: "#541037",
},
};
// --- CHARACTER SOUND BANK --- \\
// For health tracker, when taking damage, using ability and healing
const characterSounds = {
Cowboy: {
increase: new Audio("audio/cowboy_health_up.wav"),
decrease: new Audio("audio/cowboy_health_down.wav"),
ability: new Audio("audio/cowboy_skill.wav"),
},
"Were-Lobster": {
increase: new Audio("audio/warelobster_health_up.wav"),
decrease: new Audio("audio/warelobster_health_down.wav"),
ability: new Audio("audio/warelobster_skill.wav"),
},
"Goe Bling": {
increase: new Audio("audio/goblin_health_up.wav"),
decrease: new Audio("audio/goblin_health_down.wav"),
ability: new Audio("audio/goblin_skill.wav"),
},
"Salary Man": {
increase: new Audio("audio/salary_health_up.wav"),
decrease: new Audio("audio/salary_health_down.wav"),
ability: new Audio("audio/salary_skill.wav"),
},
Alien: {
increase: new Audio("audio/alien_health_up.wav"),
decrease: new Audio("audio/alien_health_down.wav"),
ability: new Audio("audio/alien_skill.wav"),
},
Margritte: {
increase: new Audio("audio/wizard_health_up.wav"),
decrease: new Audio("audio/wizard_health_down.wav"),
ability: null, // Margritte doesn't have an ability, therefore no audio
},
};
// --- SPECIAL ABILITY LOGIC --- \\
// This is essentially the same as the health change logic, just switched up a bit
// Change a player's special value by a certain amount (positive or negative)
// This is for the "number" abilities
window.changeSpecial = function (playerId, change) {
const playerRef = ref(database, "players/" + playerId);
// Read the current player data once from the database
onValue(
playerRef,
(snapshot) => {
const player = snapshot.val();
if (!player) return;
if (player.specialType === "number") {
let newSpecial = player.specialValue + change;
newSpecial = Math.max(
player.specialMin,
Math.min(player.specialMax, newSpecial),
); //constrains the special values for each unique character
update(playerRef, { specialValue: newSpecial });
}
},
{ onlyOnce: true },
); // onlyOnce: true means this listener will run once and then stop
};
// This is for the toggle ability (Were-Lobster)
window.toggleSpecial = function (playerId) {
const playerRef = ref(database, "players/" + playerId);
// Read the current player data once from the database
onValue(
playerRef,
(snapshot) => {
const player = snapshot.val();
if (!player) return;
if (player.specialType === "toggle" && player.toggleOptions) {
const currentIndex = player.toggleOptions.indexOf(player.specialValue); // set the currentIndex to what the current value is, so for the Were-Lobster it starts with Low Tide
const nextIndex = (currentIndex + 1) % player.toggleOptions.length; // Moves along the index in the array to the next value, being high tide. Loops back after that.
const newSpecialValue = player.toggleOptions[nextIndex];
update(playerRef, { specialValue: newSpecialValue });
}
},
{ onlyOnce: true },
); // onlyOnce: true means this listener will run once and then stop
};
// --- REMOVE SINGLE PLAYER --- \\
// Allows user to remove their own character
window.removePlayer = function (playerId) {
if (
confirm(
"Are you sure you want to remove your player? This cannot be undone.",
)
) {
const playerRef = ref(database, "players/" + playerId);
remove(playerRef)
.then(() => {
console.log("Player removed successfully");
})
.catch((error) => {
console.error("Error removing player:", error);
});
}
};
// --- CHARACTER SELECTION STATE --- \\
// This variable stores which character the user has currently picked in the dropdown
// It is used when creating a new player
let selectedCharacter = null;
// Attach click event listeners to all links in the character dropdown
// When a link is clicked, we remember the chosen character and update the button text
document.querySelectorAll(".character-option").forEach((a) => {
a.addEventListener("click", (e) => {
e.preventDefault(); // Stop the link from navigating anywhere since it's just a dropdown option, we don't want to move or change pages
// Read the character name from the element's data-character attribute, and assign it to the char variable (constant)
const char = a.dataset.character;
//Save the selected character in our selectedCharacter variable
selectedCharacter = char;
// Update the button label so the user sees which character they've chosen
document.getElementById("character-chosen").textContent = char;
});
});
// --- REAL-TIME DATABASE LISTENER --- \\
// Listen for any change under /players in the database
// This runs whenever players are added, updated (health/character), or removed
onValue(playersRef, (snapshot) => {
const data = snapshot.val(); // snapshot.val() gets the current data at the 'players' location
displayPlayers(data); // Update the display with the new data
});
// --- RENDER PLAYERS ON THE PAGE --- \\
// This function decides how the tracker page should look based on who owns what character
// The current user's character becomes the hero card
// Everyone else appears in the smaller grid
function displayPlayers(players) {
const setupPanel = document.getElementById("setup-panel");
const gameArea = document.getElementById("game-area");
const heroPanel = document.getElementById("hero-panel");
const playersGrid = document.getElementById("players-grid");
// Clear the hero and grid each time before rebuilding them
// This avoids duplicate cards appearing whenever Firebase updates
heroPanel.innerHTML = "";
playersGrid.innerHTML = "";
//If there are no players yet, show the setup panel and hide the game area
if (!players) {
setupPanel.classList.remove("hidden");
gameArea.classList.add("hidden");
updateCharacterDropdown(players);
return;
}
// This will store the current users player, if we find one
let myPlayer = null;
let myPlayerId = null;
//Loop through all players and check if any of them belong to the current browser/user
for (let id in players) {
const player = players[id];
if (player.ownerUID === currentUID) {
myPlayer = player;
myPlayerId = id;
break;
}
}
// If this browser/user has not made a player yet;
// show the setup panel and hide the game area
if (!myPlayer) {
setupPanel.classList.remove("hidden");
gameArea.classList.add("hidden");
updateCharacterDropdown(players);
return;
}
// If this browser/user does have player
// hide the setup panel and show the game area
setupPanel.classList.add("hidden");
gameArea.classList.remove("hidden");
//Render the current user's character as the hero
renderHeroPlayer(myPlayerId, myPlayer);
// Render all other players as small cards in the grid
for (let id in players) {
//Skip the current user's own player because it is already shown as the hero
if (id === myPlayerId) continue;
const player = players[id];
renderOtherPlayer(id, player);
}
// Update dropdown options so already-taken characters are faded/disbaled
updateCharacterDropdown(players);
}
// This makes it so each individual sees themselves as the hero
// --- RENDER CURRENT USER'S HERO ID --- \\
// This creates the large hero card for the player owned by the browser/user
function renderHeroPlayer(playerId, player) {
const heroPanel = document.getElementById("hero-panel");
// Get characters image
const imagePath =
characterImages[player.character] || "img/character/Group.png"; // Fallback to group image if character not found
const theme = characterThemes[player.character] || {
border: "#ccc",
background: "#ffffff",
text: "#000000",
};
// This builds the hero section using the themes created earlier on
// Build special ability controls
let specialHTML = "";
if (player.specialName && player.specialType) {
if (player.specialType === "number") {
// This is for the number abilties
specialHTML = `
<div class="hero-control">
<strong>${player.specialName}:</strong>
<button onclick="changeSpecial('${playerId}', -1); playCharacterSound('${player.character}', 'ability')">-</button>
<span class="hero-value">${player.specialValue}</span>
<button onclick="changeSpecial('${playerId}', 1); playCharacterSound('${player.character}', 'ability')">+</button>
</div>
`;
} else if (player.specialType === "toggle") {
// This is for the toggle abilities
specialHTML = `
<div class="hero-control">
<strong>${player.specialName}:</strong>
<button class="toggle-button" onclick="toggleSpecial('${playerId}'); playCharacterSound('${player.character}', 'ability')">
${player.specialValue}</button></div>
`;
}
}
// Create the full hero card using the theme colours, image, buttons, HP/Abilities and audio
heroPanel.innerHTML = `
<div class="hero-card" style="
--card-border: ${theme.border};
--card-bg: ${theme.background};
--card-text: ${theme.text};
">
<img src="${imagePath}" alt="${player.character}" width="280" height="280">
<div class="hero-info">
<h2>${player.name}</h2>
<p>${player.character}</p>
<div class="hero-control">
<strong>Health:</strong>
<button onclick="changeHealth('${playerId}', -1); playCharacterSound('${player.character}', 'decrease')">-</button>
<span class="hero-value">${player.health}</span>
<button onclick="changeHealth('${playerId}', 1); playCharacterSound('${player.character}', 'increase')">+</button>
</div>
${specialHTML}
<button class="remove-player-button" onclick="removePlayer('${playerId}')">
Remove Player
</button>
</div>
</div>
`;
}
// --- RENDER OTHER PLAYERS --- \\
// This creates smaller cards for everyone in a grid who is not the current user
function renderOtherPlayer(playerId, player) {
const playersGrid = document.getElementById("players-grid");
const theme = characterThemes[player.character] || {
border: "#ccc",
background: "#ffffff",
text: "#000000",
};
const playerCard = document.createElement("div");
playerCard.className = "other-player-card";
playerCard.style.setProperty("--card-border", theme.border);
playerCard.style.setProperty("--card-bg", theme.background);
playerCard.style.setProperty("--card-text", theme.text);
//again using the theme colours set earlier on
let specialText = "";
if (player.specialName && player.specialValue !== null) {
specialText = `<p>${player.specialName}: ${player.specialValue}</p>`;
}
playerCard.innerHTML = `
<h3>${player.name}</h3>
<p>${player.character}</p>
<p>Health: ${player.health}</p>
${specialText}
`;
playersGrid.appendChild(playerCard);
}
// --- UPDATE CHARACTER DROPDOWN --- \\
// This fades/disables characters in the dropdown that are already taken by existing players
function updateCharacterDropdown(players) {
const takenCharacters = new Set();
if (players) {
for (let id in players) {
const player = players[id];
if (player.character) {
takenCharacters.add(player.character);
}
}
}
document.querySelectorAll(".character-option").forEach((a) => {
const char = a.dataset.character;
if (takenCharacters.has(char)) {
a.style.pointerEvents = "none";
a.style.opacity = "0.4"; // not selectable
} else {
a.style.pointerEvents = "auto";
a.style.opacity = "1"; // means they're selectable
}
});
}
// --- ADDING NEW PLAYERS --- \\
// When the "Add player" button is clicked, create a new player in the database
document.getElementById("add-player").addEventListener("click", () => {
const nameInput = document.getElementById("player-name");
const name = nameInput.value.trim(); // Remove any extra spaces from start/end of name
// Do not add if the name field is empty, and show an alert
if (!name) {
alert("Please enter a name.");
return;
}
// Enforce that a character must be chosen before adding a player
if (!selectedCharacter) {
alert("Please select a character first.");
return;
}
// Wait till UID is assigned
if (!currentUID) {
alert("Still signing in, please wait a moment and try again.");
return;
}
// Read the current list of players once so we can:
// - check how many players exist
// - ensure the selected character is not already taken
onValue(
playersRef,
(snapshot) => {
const players = snapshot.val();
// Count how many players we currently have
// If players is null, there are 0 players; otherwise count the keys
const playerCount = players ? Object.keys(players).length : 0;
// Enforce a maximum of 6 players in total
if (playerCount >= 6) {
alert(
"Maximum of 6 players has been reached! Please remove players before adding any more",
);
return; // Stops it here and doesn't add the new player
}
// This isn't neccessarily needed as we only have 6 selectable characters, this is from when I first created the database without any characters, but there's probably no harm keeping it in as people may find workaround
// If there are existing players, ensure the chosen character is still free
if (players) {
for (let id in players) {
if (players[id].character === selectedCharacter) {
alert(
"This character is already taken! Please select a different character.",
);
return; // Stop if someone has already picked the character
}
}
}
// If we reach this point:
// - There are less than 6 players
// - The selected character is not taken
// Now we create a new player entry in the database
// Use Date.now() as a simple unique ID for the player node
const newPlayerRef = ref(database, "players/" + Date.now());
// Lookup the special data for chosen Character
const specialData = characterData[selectedCharacter];
// Build the player data object to save in the realtime database
const newPlayerData = {
name: name,
health: 20,
character: selectedCharacter,
specialName: specialData.specialName,
specialType: specialData.specialType,
specialValue: specialData.specialValue,
//store who created this player
ownerUID: currentUID,
};
// Add type-specific data for the different abilites
if (specialData.specialType === "number") {
newPlayerData.specialMin = specialData.specialMin;
newPlayerData.specialMax = specialData.specialMax;
} else if (specialData.specialType === "toggle") {
newPlayerData.toggleOptions = specialData.toggleOptions;
}
// Save the new player object with player data
set(newPlayerRef, newPlayerData).then(() => {
// Hide the setup panel immediately after Firebase saves the player
document.getElementById("setup-panel").classList.add("hidden");
// Show the game area immediately
document.getElementById("game-area").classList.remove("hidden");
});
// Clear the name input and reset the character selection in the UI
nameInput.value = "";
selectedCharacter = null;
document.getElementById("character-chosen").textContent =
"Choose Character";
},
{ onlyOnce: true },
); // We only need to check this data once, not a continuous listener
});
// --- CLEAR ALL PLAYERS --- \\
// When the "Clear All Players" is clicked, remove every player from the database
// This is needed for debugging and exhibition purposes
document.getElementById("clear-all").addEventListener("click", () => {
// Ask for confirmation before deleting everything
if (
confirm(
"Are you sure you want to clear all players? This cannot be undone and will permanently delete all player data.",
)
) {
remove(playersRef)
.then(() => {
// Resets character selection state
selectedCharacter = null;
document.getElementById("character-chosen").textContent =
"Choose Character";
document.querySelectorAll(".character-option").forEach((a) => {
a.style.pointerEvents = "auto"; // Re-enables clicking
a.style.opacity = "1"; // Resets opacity
});
console.log("All players cleared successfully");
})
.catch((error) => {
console.error("Error clearing players:", error);
});
}
});
// --- Select Character Dropdown --- \\
// This is useful for mobile, so when a character is selected it'll close the dropdown without needing extra inputs
const dropdown = document.querySelector(".dropdown");
const characterButton = document.getElementById("character-chosen");
const characterOptions = document.querySelectorAll(".character-option");
characterButton.addEventListener("click", function (event) {
event.preventDefault();
dropdown.classList.toggle("open");
});
//Tapping the button open/closes the dropdown
characterOptions.forEach(function (option) {
option.addEventListener("click", function () {
dropdown.classList.remove("open");
});
});
//Tapping a character closes it immediately
document.addEventListener("click", function (event) {
if (!dropdown.contains(event.target)) {
dropdown.classList.remove("open");
}
});
//Tapping outside also closes it