forked from CombustibleToast/StratagemHeroOnline
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript.js
564 lines (474 loc) · 16.6 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
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
// Load stratagem data
var stratagems = undefined;
var xhr = new XMLHttpRequest();
xhr.open(method='GET', url='./data/HD2-Sequences.json', async=false); // false indicates synchronous request
xhr.send();
if (xhr.status === 200) {
stratagems = xhr.responseText;
} else {
console.error('Error reading file:', xhr.statusText);
}
stratagems = JSON.parse(stratagems);
// console.log(stratagems);
// Install keypress listener
function mainGameKeyDownListener(event) {
if (event.isComposing || event.code === 229) {
return;
}
keypress(event.code);
}
addMainGameListener();
// Set gamepad polling
let gpPollInterval;
const gpPollRate = 1000;
const gpButtonToKeyMap = {
12: "KeyW", // Up
13: "KeyS", // Down
14: "KeyA", // Left
15: "KeyD" // Right
};
// Poll for gamepad connection
gpPollInterval = setInterval(pollGamepads, gpPollRate);
function pollGamepads() {
const gamepads = navigator.getGamepads();
// If any gamepad is connected, start the gamepad loop
if (gamepads[0] || gamepads[1] || gamepads[2] || gamepads[3]) {
gamepadLoop();
clearInterval(gpPollInterval);
}
}
// Gamepad input handling
let prevButtons = new Array(16).fill(false);
function gamepadLoop() {
const gamepads = navigator.getGamepads();
// Get the first non-null gamepad
const gp = gamepads[0] || gamepads[1] || gamepads[2] || gamepads[3];
if (!gp) {
return;
}
for (let i in gpButtonToKeyMap) {
if (gp.buttons[i].pressed && !prevButtons[i]) {
keypress(gpButtonToKeyMap[i]);
}
}
// Update previous buttons state
for (let i = 0; i < gp.buttons.length; i++) {
prevButtons[i] = gp.buttons[i].pressed;
}
requestAnimationFrame(gamepadLoop);
}
// Load SFX
var sfxDown = new Audio("./data/Sounds/1_D.mp3");
var sfxLeft = new Audio("./data/Sounds/2_L.mp3");
var sfxRight = new Audio("./data/Sounds/3_R.mp3");
var sfxUp = new Audio("./data/Sounds/4_U.mp3");
var sfxGameOver = [new Audio("./data/Sounds/GameOver1.mp3"), new Audio("./data/Sounds/GameOver2.mp3")]
// Create global tracking variables
var gameState = "initial" //initial, running, hitlag, over
var currentSequenceIndex = 0;
var currentRefreshIndex = 0;
var currentArrowSequenceTags = undefined;
var refreshArrowSequenceTags;
const TOTAL_TIME = 10000;
const COUNTDOWN_STEP = 10;
const NEW_STRATEGEM_TIMEOUT = 200;
const CORRECT_TIME_BONUS = 500;
const FAILURE_SHAKE_TIME = 200;
var timeRemaining = TOTAL_TIME;
var completedStrategemsList = [];
const CURRENT_STRATAGEM_LIST_LENGTH = 4; //dependent on the html, don't change without modifying html too
var currentStratagemsList = [];
var lastCheckedTime = undefined;
var CONFIGPOPUP = document.getElementById('game-config-popup');
var TEMPARROWKEYS = {};
// initial state of custom config
const storedArrowKeysConfig = localStorage.getItem("CONFIG.arrowKeys") ? JSON.parse(localStorage.getItem("CONFIG.arrowKeys")) : false;
const CONFIG = {};
if(storedArrowKeysConfig) {
CONFIG.arrowKeys = storedArrowKeysConfig;
} else {
CONFIG.arrowKeys = {
up:"KeyW",
down:"KeyS",
left:"KeyA",
right:"KeyD"
}
}
// Show directional buttons if user is on mobile
if(userIsMobile())
showMobileButtons();
// Load first stratagems
for(let i = 0; i < CURRENT_STRATAGEM_LIST_LENGTH; i++){
currentStratagemsList.push(pickRandomStratagem());
}
// Show stratagems
refreshStratagemDisplay();
// Bootstrap countdown timer
countDown();
//~~~//
function keypress(keyCode){
// Ignore invalid keypresses
let sfx;
switch(keyCode){
case "ArrowUp":
case CONFIG.arrowKeys.up:
sfx = sfxUp;
keyCode = "KeyW";
break;
case "ArrowDown":
case CONFIG.arrowKeys.down:
sfx = sfxDown;
keyCode = "KeyS";
break;
case "ArrowLeft":
case CONFIG.arrowKeys.left:
sfx = sfxLeft;
keyCode = "KeyA";
break;
case "ArrowRight":
case CONFIG.arrowKeys.right:
sfx = sfxRight;
keyCode = "KeyD";
break;
default:
return;
}
//b
//Route keypress to proper handling function
switch(gameState){
case "initial":
gameState = "running";
// Exclusion of `break;` here is intentional. The first keypress of the game should apply to the sequence
case "running":
checkGameKeypress(keyCode, sfx);
break;
case "over":
checkRefreshKeypress(keyCode, sfx);
break;
case "hitlag":
break;
}
}
function checkGameKeypress(keyCode, sfx){
// Check the keypress against the current sequence
if(keyCode == currentArrowSequenceTags[currentSequenceIndex].code){
//Success, apply the success
currentSequenceIndex++;
//Check if that success completes the entire sequence.
if(currentSequenceIndex == currentArrowSequenceTags.length){
//Add time bonus and pause the countdown for the delay time
timeRemaining += CORRECT_TIME_BONUS;
gameState = "hitlag";
//Add completed stratagem to completed list and remove from active list
completedStrategemsList.push(currentStratagemsList.shift());
//Add a new stratagem to the active list
currentStratagemsList.push(pickRandomStratagem());
//Set a delay for when the timer should unpause and the next stratagem should be loaded
setTimeout(() => {
currentSequenceIndex = 0;
refreshStratagemDisplay();
gameState = "running";
}, NEW_STRATEGEM_TIMEOUT);
}
}
else if (keyCode == currentArrowSequenceTags[0].code){
//Edge case; if they're wrong but their input is the same as the first code, reset to first.
currentSequenceIndex = 1;
//Play failure animation
shakeArrows(FAILURE_SHAKE_TIME);
}
else{
//Failure, reset progress
currentSequenceIndex = 0;
//Play failure animation
shakeArrows(FAILURE_SHAKE_TIME);
}
updateArrowFilters(currentArrowSequenceTags, currentSequenceIndex);
// Play/replay sound
sfx.paused ? sfx.play() : sfx.currentTime = 0;
}
function checkRefreshKeypress(keyCode, sfx){
// Check the keypress against the current sequence
if(keyCode == refreshArrowSequenceTags[currentRefreshIndex].code){
//Success, apply the success
currentRefreshIndex++;
//If that completes the entire sequence, reload the window after a short delay
if(currentRefreshIndex == refreshArrowSequenceTags.length){
setTimeout(() => {
window.location.reload()
}, 300);
}
}
updateArrowFilters(refreshArrowSequenceTags, currentRefreshIndex);
// Play/replay sound
sfx.paused ? sfx.play() : sfx.currentTime = 0;
}
function updateArrowFilters(arrowTags, index){
for(i = 0; i < arrowTags.length; i++){
arrowTags[i].setAttribute("class", i < index ? "arrow-complete-filter" : "arrow-incomplete-filter")
}
}
function shakeArrows(time){
document.getElementById("arrows-container").setAttribute("style", `animation: shake ${time/1000}s;`);
setTimeout(() => {
document.getElementById("arrows-container").removeAttribute("style");
}, 200);
}
function refreshStratagemDisplay(){
for(let i in currentStratagemsList){
// Show the stratagem's picture in the correct slot
if (currentStratagemsList[i].image) {
document.getElementById(`stratagem-icon-${i}`).src = `./data/Images/Stratagem\ Icons/hd2/${currentStratagemsList[i].image}`;
}
else {
document.getElementById(`stratagem-icon-${i}`).src = `./data/Images/Stratagem\ Icons/hd2/placeholder.png`;
}
}
// Show arrow icons for the current active stratagem
currentArrowSequenceTags = showArrowSequence(currentStratagemsList[0].sequence);
// Show active stratagem name
document.getElementById("stratagem-name").innerHTML = currentStratagemsList[0].name;
}
function pickRandomStratagem(){
return stratagems[Math.floor(Math.random() * stratagems.length)];
}
function showArrowSequence(arrowSequence, arrowsContainer){
if(arrowsContainer == undefined)
arrowsContainer = document.getElementById("arrows-container");
// Remove all table elements of old arrows
arrowsContainer.innerHTML = '';
//Create new arrow elements
let arrowTags = [];
for(arrow of arrowSequence){
let td = document.createElement("td");
let img = document.createElement("img");
td.appendChild(img);
img.setAttribute("src", `./data/Images/Arrows/${arrow}.png`);
img.setAttribute("class", `arrow-incomplete-filter`);
// Map filename to keycode
switch(arrow){
case "U":
img.code = "KeyW";
break;
case "D":
img.code = "KeyS";
break;
case "L":
img.code = "KeyA";
break;
case "R":
img.code = "KeyD";
break;
}
arrowsContainer.appendChild(td);
arrowTags.push(img);
}
return arrowTags;
}
function gameOver(){
//Stop the game
gameState = "over";
// Write score to readout
let scoreReadout = document.getElementById("score-readout");
scoreReadout.innerHTML = `SCORE: ${completedStrategemsList.length}`
// Write completed strategems to readout
let stratagemReadout = document.getElementById("completed-strategems-readout");
stratagemReadout.innerHTML = stratagemListToString(true);
// Show refresh arrow sequence
let sequence = ["U", "D", "R", "L", "U"];
let container = document.getElementById("refresh-arrows-container");
refreshArrowSequenceTags = showArrowSequence(sequence, container);
// Hide the game
let game = document.getElementById("interactable-center-container");
game.setAttribute("hidden", "hidden");
game.style.visibility = "invisible";
// Show the popup
let popup = document.getElementById("game-over-popup");
popup.removeAttribute("hidden");
popup.style.visibility = "visible";
// Play game over sfx
sfxGameOver[Math.floor(Math.random() * sfxGameOver.length)].play();
}
function stratagemListToString(html, spamless){
// Set direction characters based on argument
let up = "🡅", down = "🡇", left = "🡄", right = "🡆";
if(userIsMobile()){
up = "⬆️", down = "⬇️", left = "⬅️", right = "➡️";
}
if(spamless){
up = "U", down = "D", left = "L", right = "R";
}
let re = "";
for(let stratagem of completedStrategemsList){
let line = `${stratagem.name}: `;
//Put arrows
for(let direction of stratagem.sequence){
switch(direction){
case "U":
line += up;
break;
case "D":
line += down;
break;
case "L":
line += left;
break;
case "R":
line += right;
break;
}
}
line += html ? "<br>" : "\n";
re += line;
}
return re;
}
function copyShare(spamless){
// Gather text and write to clipboard
let output = `## My Stratagem Hero Online Score: ${completedStrategemsList.length}\n`
output += stratagemListToString(false, spamless);
output += "Do your part! Play Stratagem Hero Online: https://combustibletoast.github.io/"
navigator.clipboard.writeText(output);
//Change button's text
let buttonElement = document.getElementById(`share-button${spamless ? "-spamless" : ""}`);
let buttonOriginalText = buttonElement.innerHTML;
buttonElement.innerHTML = "Copied!";
//Set timeout to change it back
//Doesn't work, unable to pass in original text
setTimeout(() => {
buttonElement.innerHTML = buttonOriginalText;
}, 3000);
}
async function countDown(){
if(gameState == "over")
return;
if(timeRemaining <= 0){
gameOver();
return;
}
//Calculate the true delta time since last check
//This should fix #2
if(lastCheckedTime == undefined)
lastCheckedTime = Date.now();
let now = Date.now();
let trueDeltaT = now-lastCheckedTime;
lastCheckedTime = now;
// Immediately Set timeout for next countdown step
setTimeout(() => {
countDown();
// console.log(timeRemaining)
}, COUNTDOWN_STEP);
// Apply countdown if it's not paused
if(gameState != "hitlag" && gameState != "initial")
timeRemaining -= trueDeltaT;
updateTimeBar();
}
function updateTimeBar(){
let bar = document.getElementById("time-remaining-bar");
let width = (timeRemaining/TOTAL_TIME) * 100;
// console.log(width);
bar.style.width = `${width}%`;
}
async function sleep(ms){
await new Promise(r => setTimeout(r, ms));
}
function userIsMobile() {
return navigator.userAgent.match(/Android/i)
|| navigator.userAgent.match(/webOS/i)
|| navigator.userAgent.match(/iPhone/i)
|| navigator.userAgent.match(/iPad/i)
|| navigator.userAgent.match(/iPod/i)
|| navigator.userAgent.match(/BlackBerry/i)
|| navigator.userAgent.match(/Windows Phone/i);
}
function showMobileButtons() {
container = document.getElementById("mobile-button-container");
container.removeAttribute("hidden");
container.style.visibility = "visible";
}
function configPopupInputListener(event) {
//this limits the input charater length to 1 char
event.target.value = event.data.toUpperCase();
}
function configPopupButtonListener(event) {
let actionTypes = ["game-config--save", "game-config--close", "game-config--open"];
let foundType = actionTypes.find(actionType => {
return event.target.closest(`[data-action-type="${actionType}"]`);
});
let foundButton = event.target.closest(`[data-action-type="${foundType}"]`);
if (foundButton) {
switch (foundButton.dataset.actionType) {
case "game-config--save":
//save controls
configSaveArrowKeys();
//NOTE: This is a intentional missing break as i want both the save and the popup close to happen due to there not being any more settings here
case "game-config--close":
case "game-config--open":
//close popup
toggleConfigPopup();
break;
}
}
}
function configSaveArrowKeys() {
CONFIG.arrowKeys = TEMPARROWKEYS;
localStorage.setItem("CONFIG.arrowKeys", JSON.stringify(CONFIG.arrowKeys));
}
function configPopupKeydownListener(event) {
let activeElement = document.activeElement;
if (activeElement.tagName == "INPUT") {
let excludedKeys = ["TAB", "ALT"];
if (!excludedKeys.find((keyCode) => event.code.toUpperCase().includes(keyCode))) {
TEMPARROWKEYS[activeElement.name] = event.code;
}
}
}
let configPopupEvents = [
["input", configPopupInputListener],
["keydown", configPopupKeydownListener]
];
function addConfigPopupListener() {
configPopupEvents.forEach((event)=>{
addEventListener(event[0], event[1]);
})
}
function removeConfigPopupListener() {
configPopupEvents.forEach((event)=>{
removeEventListener(event[0], event[1]);
})
}
function addMainGameListener() {
addEventListener("keydown", mainGameKeyDownListener);
addEventListener("click", configPopupButtonListener);
}
function removeMainGameListener() {
removeEventListener("keydown", mainGameKeyDownListener);
}
function toggleConfigPopup() {
let popupCurrentState = CONFIGPOPUP.classList.contains('active');
if (popupCurrentState == true) {
CONFIGPOPUP.classList.remove('active');
addMainGameListener();
removeConfigPopupListener();
} else {
CONFIGPOPUP.classList.add('active');
initaliseConfigPopupInputs();
removeMainGameListener();
addConfigPopupListener();
TEMPARROWKEYS = Object.assign({}, CONFIG.arrowKeys);
}
}
function getConfigPopupInputs() {
return CONFIGPOPUP.querySelectorAll('input[name][type=text]');
}
function initaliseConfigPopupInputs() {
let inputs = getConfigPopupInputs();
inputs.forEach((input)=>{
let inputKey = Object.keys(CONFIG.arrowKeys).find((key)=>{
return key.toLowerCase() == input.name.toLowerCase();
});
if (inputKey) {
input.value = CONFIG.arrowKeys[inputKey].slice(-1).toUpperCase();
}
})
}