-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.html
1146 lines (1025 loc) · 33.4 KB
/
index.html
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
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<style>
html,
body {
width: 100%;
height: 100%;
margin: 0px;
border: 0;
overflow: hidden;
/* Disable scrollbars */
display: block;
/* No floating content on sides */
}
#topbar {
background-color: black;
}
#namediv {
display: none;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background-color: blue;
font-family: courier;
width: 600px;
height: 100px;
padding: 20px;
border: 1px solid white;
}
#leaderboard,
tr {
background-color: black;
color: green;
font-family: courier;
}
#gamearea {
z-index: 0;
}
#animation {
z-index: 1;
}
#namediv {
z-index: 2;
}
</style>
</head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bodymovin/5.12.2/lottie.min.js" integrity="sha512-jEnuDt6jfecCjthQAJ+ed0MTVA++5ZKmlUcmDGBv2vUI/REn6FuIdixLNnQT+vKusE2hhTk2is3cFvv5wA+Sgg==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<body id="bodyid">
<div id="gamediv">
<canvas id="topbar" style='position:absolute; left:0px; top:0px; width: 100%; height: 10%'></canvas>
<div id="animation" style='position:absolute; left:0px; top:5%; width: 80%; height: 100%'></div>
<canvas id="gamearea" style='position:absolute; left:0px; top:10%; width: 80%; height: 90%'></canvas>
<div id="leaderboard" style='position:absolute; left:80%; top:10%; width: 50%; height: 100%'></div>
</div>
</div>
<div id="namediv">
You got a high score! Enter your name: <input id="player_name" value="" />
</div>
<script>
let high_score_checked = false;
let has_high_score = false;
let high_score_index = 0;
let cur_high_score_letter = 0;
let high_score_name_letters = [];
let submit_high_score = false;
let start_explosion_anim = true;
let start_intro_anim = true;
let intro_anim = {};
let start_outro_anim = true;
let outro_anim = {};
let outro_complete = 0;
let sprites = [];
let module = {};
let leaderboard_table = {};
let leaderboard = [];
let local_score = {};
let local_id = "";
let playername = "";
const gamepadsByIndex = {};
const controllerTemplate = `
<div>
<div class="head"><div class="index"></div><div class="id"></div></div>
<div class="info"><div class="label">connected:</div><span class="connected"></span></div>
<div class="info"><div class="label">mapping:</div><span class="mapping"></span></div>
<div class="inputs">
<div class="axes"></div>
<div class="buttons"></div>
</div>
</div>
`;
const axisTemplate = `
<svg viewBox="-2.2 -2.2 4.4 4.4" width="128" height="128">
<circle cx="0" cy="0" r="2" fill="none" stroke="#888" stroke-width="0.04" />
<path d="M0,-2L0,2M-2,0L2,0" stroke="#888" stroke-width="0.04" />
<circle cx="0" cy="0" r="0.22" fill="red" class="axis" />
<text text-anchor="middle" fill="#CCC" x="0" y="2">0</text>
</svg>
`
const buttonTemplate = `
<svg viewBox="-2.2 -2.2 4.4 4.4" width="64" height="64">
<circle cx="0" cy="0" r="2" fill="none" stroke="#888" stroke-width="0.1" />
<circle cx="0" cy="0" r="0" fill="none" fill="red" class="button" />
<text class="value" dominant-baseline="middle" text-anchor="middle" fill="#CCC" x="0" y="0">0.00</text>
<text class="index" alignment-baseline="hanging" dominant-baseline="hanging" text-anchor="start" fill="#CCC" x="-2" y="-2">0</text>
</svg>
`;
const buttonids = {
FACE_1: 0, // Face (main) buttons
FACE_2: 1,
FACE_3: 2,
FACE_4: 3,
LEFT_SHOULDER: 4, // Top shoulder buttons
RIGHT_SHOULDER: 5,
LEFT_SHOULDER_BOTTOM: 6, // Bottom shoulder buttons
RIGHT_SHOULDER_BOTTOM: 7,
SELECT: 8,
START: 9,
LEFT_ANALOGUE_STICK: 10, // Analogue sticks (if depressible)
RIGHT_ANALOGUE_STICK: 11,
PAD_TOP: 12, // Directional (discrete) pad
PAD_BOTTOM: 13,
PAD_LEFT: 14,
PAD_RIGHT: 15
};
function applyDeadZone(number, threshold){
percentage = (Math.abs(number) - threshold) / (1 - threshold);
if(percentage < 0)
percentage = 0;
return percentage * (number > 0 ? 1 : -1);
}
function addGamepad(gamepad) {
console.log('add:', gamepad.index);
const elem = document.createElement('div');
elem.innerHTML = controllerTemplate;
const axesElem = elem.querySelector('.axes');
const buttonsElem = elem.querySelector('.buttons');
const axes = [];
for (let ndx = 0; ndx < gamepad.axes.length; ndx += 2) {
const div = document.createElement('div');
div.innerHTML = axisTemplate;
axesElem.appendChild(div);
axes.push({
axis: div.querySelector('.axis'),
value: div.querySelector('text'),
});
}
const buttons = [];
for (let ndx = 0; ndx < gamepad.buttons.length; ++ndx) {
const div = document.createElement('div');
div.innerHTML = buttonTemplate;
buttonsElem.appendChild(div);
div.querySelector('.index').textContent = ndx;
buttons.push({
circle: div.querySelector('.button'),
value: div.querySelector('.value'),
});
}
gamepadsByIndex[gamepad.index] = {
gamepad,
elem,
axes,
buttons,
index: elem.querySelector('.index'),
id: elem.querySelector('.id'),
mapping: elem.querySelector('.mapping'),
connected: elem.querySelector('.connected'),
};
}
function removeGamepad(gamepad) {
const info = gamepadsByIndex[gamepad.index];
if (info) {
delete gamepadsByIndex[gamepad.index];
info.elem.parentElement.removeChild(info.elem);
}
}
function addGamepadIfNew(gamepad) {
const info = gamepadsByIndex[gamepad.index];
if (!info) {
addGamepad(gamepad);
} else {
// This broke sometime in the past. It used to be
// the same gamepad object was returned forever.
// Then Chrome only changed to a new gamepad object
// is returned every frame.
info.gamepad = gamepad;
}
}
function addNewPads() {
const gamepads = navigator.getGamepads();
for (let i = 0; i < gamepads.length; i++) {
const gamepad = gamepads[i]
if (gamepad) {
addGamepadIfNew(gamepad);
}
}
}
function handleConnect(e) {
console.log('connect');
addGamepadIfNew(e.gamepad);
}
function handleDisconnect(e) {
console.log('disconnect');
removeGamepad(e.gamepad);
}
function get_value_from_cookie(key) {
var value;
var row = document.cookie
.split('; ')
.find(row => row.startsWith(key));
if (typeof row != "undefined") {
value = row.split('=')[1];
} else {
value = "";
}
return value;
}
function updateTable(table, index, fields, local) {
let newRow = table.insertRow(index);
for (var i = 0; i < fields.length; ++i) {
let newCell = newRow.insertCell(i);
if (local)
newCell.style.color = "rgb(200, 0, 0)";
let newText = document.createTextNode(fields[i]);
newCell.appendChild(newText);
}
}
function update_leaderboard_entry(table, index, rank, score, name, local) {
updateTable(table, index, [rank, name, score], local);
}
/*
Flow is:
/new_session to get id
/update_listing to update score
these get leaderboard entries
/around_me
/topten
*/
// I think we need to keep local score and name better
function render_leaderboard(table, lb, name) {
table.innerHTML = "";
var tbdy = document.createElement('tbody');
var rendered_local = false;
table.appendChild(tbdy);
var i = 0;
var lastrank = 1;
lb.forEach(entry => {
update_leaderboard_entry(table, i, i+1, entry.score, entry.name, entry.id == local_id);
lastrank = entry.rank;
i += 1;
});
var header = table.createTHead();
var row = header.insertRow(0);
var cell = row.insertCell(0);
cell.innerHTML = "<b>" + name + "</b>";
}
function is_in_top_ten(lb) {
var ret = true;
var count = 1;
lb.every(entry => {
if (count > 10) {
ret = false;
return false;
}
if (entry.name != "Kiosk Player") {
count++;
if (local_score.score > entry.score) {
ret = true;
return false;
}
}
return true;
});
return ret;
}
function check_for_high_score() {
high_score_checked = false;
has_high_score = false;
high_score_index = 0;
cur_high_score_letter = 0;
high_score_name_letters = [];
var leaderboard_req = new XMLHttpRequest();
leaderboard_req.onload = function (oEvent) {
var entries = JSON.parse(leaderboard_req.response);
leaderboard = [];
entries.forEach((entry, i) => {
leaderboard[i] = entry;
});
if (is_in_top_ten(leaderboard)) {
has_high_score = true;
} else {
has_high_score = false;
}
high_score_checked = true;
}
leaderboard_req.open("GET", "https://leaderboard.edgecompute.app/global", true);
leaderboard_req.send();
}
function get_leaderboard_entries() {
var leaderboard_req = new XMLHttpRequest();
leaderboard_req.onload = function (oEvent) {
var entries = JSON.parse(leaderboard_req.response);
leaderboard = [];
let eindex = 0;
entries.forEach((entry, i) => {
if (entry.id == local_id) {
leaderboard[i] = entry;
}
if (entry.name != "Kiosk Player" && eindex < 10) {
leaderboard[i] = entry;
eindex++;
}
});
render_leaderboard(leaderboard_table, leaderboard, "Global");
}
leaderboard_req.open("GET", "https://leaderboard.edgecompute.app/global", true);
leaderboard_req.send();
}
// Returns an object containing resources that will be used later for drawing
function resources() {
let res = {
player: document.createElement('canvas'),
fastly_player: document.createElement('canvas'),
bullet: document.createElement('canvas'),
player_bullet: document.createElement('canvas'),
player_bomb: document.createElement('canvas'),
particle: document.createElement('canvas'),
shields: {},
shield_hit: gamearea.getContext("2d").createImageData(40, 40), // TODO scale shields
title_img: new Image(),
game_over_img: new Image(),
}
res.title_img.src = 'title.png';
res.title_img.alt = 'Bug Invaders Title Screen';
res.game_over_img.src = 'game_over_w_score.png';
res.game_over_img.alt = 'Bug Invaders Game Over Screen';
// Particle
res.particle.width = 20;
res.particle.height = 20;
// Bullet
res.bullet.width = 6;
res.bullet.height = 6;
let bCtx = res.bullet.getContext('2d');
bCtx.fillStyle = "white";
bCtx.beginPath();
bCtx.arc(3, 3, 3, 0, 2 * Math.PI);
bCtx.fill();
res.player_bullet.width = 4;
res.player_bullet.height = 40;
let bpCtx = res.player_bullet.getContext('2d');
bpCtx.fillStyle = "green";
bpCtx.beginPath();
bpCtx.lineTo(2, 40);
bpCtx.lineTo(4, 0);
bpCtx.lineTo(0, 0);
bpCtx.fill();
res.player_bomb.width = 20;
res.player_bomb.height = 80;
let bombCtx = res.player_bomb.getContext('2d');
bombCtx.fillStyle = "red";
bombCtx.beginPath();
bombCtx.lineTo(10, 80);
bombCtx.lineTo(20, 0);
bombCtx.lineTo(0, 0);
bombCtx.fill();
// Player
res.player.width = 40;
res.player.height = 32;
let plCtx = res.player.getContext('2d');
plCtx.fillStyle = "green";
plCtx.beginPath();
plCtx.lineTo(40, 16);
plCtx.lineTo(0, 32);
plCtx.lineTo(0, 0);
plCtx.fill();
res.fastly_player.width = 40;
res.fastly_player.height = 32;
let pfCtx = res.fastly_player.getContext('2d');
pfCtx.fillStyle = "red";
pfCtx.beginPath();
pfCtx.lineTo(40, 16);
pfCtx.lineTo(0, 32);
pfCtx.lineTo(0, 0);
pfCtx.fill();
leaderboard_table = document.createElement('table');
leaderboard_table.style.width = '30%';
var tbdy = document.createElement('tbody');
leaderboard_table.appendChild(tbdy);
return res;
}
// We create this here because it will be used from within `imports`
let gamearea = document.getElementById('gamearea');
let leaderboardglobal_elem = document.getElementById('leaderboard');
let topbar = document.getElementById('topbar');
// Returns an object containing functions that will be linked to our wasm model
// This means that they can be called from Rust
function imports() {
const res = resources();
var ctx = gamearea.getContext("2d");
var topbar_ctx = topbar.getContext("2d");
function new_session() {
show_game_end_screen = false;
start_explosion_anim = true;
start_intro_anim = true;
start_outro_anim = true;
outro_complete = 0;
intro_anim.stop();
intro_anim.destroy();
document.getElementById('animation').style.display = 'none';
var session_req = new XMLHttpRequest();
session_req.onload = function (oEvent) {
local_id = session_req.response;
get_leaderboard_entries();
}
session_req.open("GET", "https://leaderboard.edgecompute.app/new_session", true);
session_req.send();
}
function clear_screen() {
ctx.fillStyle = "black";
ctx.fillRect(0, 0, gamearea.width, gamearea.height);
topbar_ctx.fillStyle = "black";
topbar_ctx.fillRect(0, 0, topbar.width, topbar.height);
}
// player is 33x33
function draw_player(x, y, angle, fastly) {
draw_sprite(98, 0, x-16, y);
}
function draw_ufo(x, y) {
ctx.putImageData(sprites[99][0].image_data, x, y);
}
function draw_bullet(x, y) {
ctx.drawImage(res.bullet, x - 3, y - 3);
}
function draw_player_bullet(x, y, rotate, bomb) {
if (bomb) {
ctx.drawImage(res.player_bomb, x - 3, y - 3);
} else {
ctx.translate(x-3,y-3);
ctx.rotate(rotate);
ctx.drawImage(res.player_bullet, 0, 0);
}
ctx.setTransform(1, 0, 0, 1, 0, 0);
}
function draw_particle(x, y, radius, color) {
let pCtx = res.particle.getContext('2d');
if (color == 1) {
pCtx.fillStyle = "blue";
} else if (color == 2) {
pCtx.fillStyle = "red";
} else if (color == 3) {
pCtx.fillStyle = "green";
} else {
pCtx.fillStyle = "white";
}
pCtx.beginPath();
pCtx.arc(10, 10, 10, 0, 2 * Math.PI);
pCtx.fill();
ctx.drawImage(res.particle, x - radius, y - radius, 2 * radius, 2 * radius);
}
function draw_intro() {
if (start_intro_anim) {
document.getElementById('animation').style.display = 'block';
intro_anim = bodymovin.loadAnimation({
container: document.getElementById('animation'),
path: 'intro.json',
render: 'canvas',
loop: true,
autoplay: true,
name: 'intro_anim'
});
// setTimeout(() => {
// anim.stop();
// },500);
start_intro_anim = false;
}
}
function check_high_score() {
outro_anim.stop();
outro_anim.destroy();
check_for_high_score();
}
function wait_high_score() {
if (high_score_checked) {
if (has_high_score) {
return 2;
} else {
return 1;
}
}
return 0;
}
function handle_game_over(score) {
if (submit_high_score) {
let name = "";
for (i=0;i<high_score_name_letters.length;++i) {
name = name.concat(String.fromCharCode(65 + high_score_name_letters[i]));
}
var listing_req = new XMLHttpRequest();
listing_req.open("POST", "https://leaderboard.edgecompute.app/update_listing", true);
listing_req.setRequestHeader("id", local_id);
listing_req.setRequestHeader("name", name);
listing_req.setRequestHeader("score", local_score.score);
listing_req.send();
listing_req.onload = function (oEvent) {
get_leaderboard_entries();
}
submit_high_score = false;
}
}
function draw_hud(score, lives, wave) {
// draw hud
topbar_ctx.fillStyle = "red";
topbar_ctx.textBaseline = "top";
topbar_ctx.font = "20px courier";
topbar_ctx.fillText("Score: " + score, 20, 20);
topbar_ctx.fillText("Wave: " + wave, 200, 20);
// draw leaderboard
leaderboardglobal_elem.appendChild(leaderboard_table);
}
function draw_name_picker(letter_index, cur_letter) {
if (letter_index != high_score_index) {
high_score_name_letters[high_score_index] = cur_high_score_letter;
}
high_score_index = letter_index;
cur_high_score_letter = cur_letter;
ctx.fillStyle = "red";
ctx.font = "20px courier";
ctx.fillText("You got a high score! Enter your initials", 300,300);
ctx.font = "30px courier";
for (li = 0; li < letter_index+1; ++li) {
let letter_offset = li * 110;
ctx.strokeStyle = "red";
ctx.beginPath();
ctx.moveTo(letter_offset + 450, 400);
ctx.lineTo(letter_offset + 500, 400);
ctx.lineTo(letter_offset + 500, 450);
ctx.lineTo(letter_offset + 450, 450);
ctx.lineTo(letter_offset + 450, 400);
ctx.stroke();
ctx.beginPath();
ctx.moveTo(letter_offset + 440, 410);
ctx.lineTo(letter_offset + 430, 420);
ctx.lineTo(letter_offset + 440, 430);
ctx.stroke();
ctx.beginPath();
ctx.moveTo(letter_offset + 510, 410);
ctx.lineTo(letter_offset + 520, 420);
ctx.lineTo(letter_offset + 510, 430);
ctx.stroke();
if (li == letter_index) {
high_score_name_letters[high_score_index] = cur_high_score_letter;
let letter = String.fromCharCode(65 + cur_high_score_letter);
ctx.fillText(letter, letter_offset + 465,425);
} else {
let letter = String.fromCharCode(65 + high_score_name_letters[li]);
ctx.fillText(letter, letter_offset + 465, 425);
}
}
submit_high_score = true;
}
function draw_condition_warning(condition,x,y) {
ctx.fillStyle = "red";
ctx.textBaseline = "top";
ctx.font = "20px courier";
// if (condition == 1) {
// ctx.fillText("Shields Low; activating Fastly Shields", x,y);
// } else if (condition == 2) {
// ctx.fillText("Bots closing in; activating Bot Bomb", x,y);
// } else if (condition == 3) {
// ctx.fillText("Bots speeding up; activating Bot Seeking", x,y);
// }
let text = "Starting Wave " + condition;
ctx.fillText(text, x, y);
}
function wait_outro_complete() {
return outro_complete;
}
// as t nears 0 the screen should get more red
function draw_fastly_treatment(t) {
// let opacity = 0.6*t + 0.4;
// let gamearea = document.getElementById('bodyid');
// gamearea.style.opacity = opacity;
// gamearea.style.backgroundColor = "red";
if (start_explosion_anim) {
document.getElementById('animation').style.display = 'block';
let anim = bodymovin.loadAnimation({
container: document.getElementById('animation'),
path: 'data.json',
render: 'canvas',
loop: false,
autoplay: true,
name: 'explosion'
});
setTimeout(() => {
anim.stop();
anim.destroy();
start_outro_anim = true;
},500);
start_explosion_anim = false;
}
if (start_outro_anim) {
outro_anim = bodymovin.loadAnimation({
container: document.getElementById('animation'),
path: 'outro.json',
render: 'canvas',
loop: false,
autoplay: true,
name: 'explosion'
});
outro_anim.addEventListener('complete', () => {
outro_complete = 1;
});
start_outro_anim = false;
}
}
function reset_fastly_treatment() {
let gamearea = document.getElementById('bodyid');
gamearea.style.opacity = 1;
bodymovin.destroy();
}
function draw_bounds(x1, y1, x2, y2) {
ctx.strokeStyle = "orange";
ctx.beginPath();
ctx.moveTo(x1, y1);
ctx.lineTo(x2, y1);
ctx.lineTo(x2, y2);
ctx.lineTo(x1, y2);
ctx.lineTo(x1, y1);
ctx.stroke();
}
function draw_line(x1, y1, x2, y2, color) {
if (color == 1) {
ctx.strokeStyle = "blue";
} else if (color == 2) {
pCtx.strokeStyle = "red";
} else if (color == 3) {
pCtx.strokeStyle = "green";
} else {
pCtx.strokeSTyle = "white";
}
ctx.strokeStyle = "orange";
ctx.beginPath();
ctx.moveTo(x1, y1);
ctx.lineTo(x2, y2);
ctx.stroke();
}
function console_log_int(value) {
console.log(value);
}
function console_log_double(value) {
console.log(value);
}
function init_shield(id) {
res.shields[id] = [];
}
function add_shield_state(id, index, state) {
res.shields[id][index] = state;
}
function update_shield(id, index, state) {
if (res.shields[id] != "undefined")
res.shields[id][index] = state;
}
function draw_shield(id, x, y, dim, fastly) {
for (var i = 0; i < 25; ++i) {
var state = res.shields[id][i];
var xoffset = (i % 5) * dim;
var yoffset = Math.trunc(i / 5) * dim;
if (fastly) {
if (state == 1) { // BlockState::Hit
ctx.fillStyle = "darkred";
ctx.fillRect(x + xoffset, y + yoffset, dim, dim);
} else if (state == 2) { // BlockState::Full
ctx.fillStyle = "red";
ctx.fillRect(x + xoffset, y + yoffset, dim, dim);
}
} else {
if (state == 1) { // BlockState::Hit
ctx.fillStyle = "darkgreen";
ctx.fillRect(x + xoffset, y + yoffset, dim, dim);
} else if (state == 2) { // BlockState::Full
ctx.fillStyle = "green";
ctx.fillRect(x + xoffset, y + yoffset, dim, dim);
}
}
}
}
function draw_sprite(sprite_id, frame_index, x, y) {
if (sprites[sprite_id] != "undefined" && sprites[sprite_id][frame_index] != "undefined") {
ctx.putImageData(sprites[sprite_id][frame_index].image_data, x, y);
}
}
function update_local_score(score) {
local_score.score = score;
var listing_req = new XMLHttpRequest();
listing_req.onload = function (oEvent) {
get_leaderboard_entries();
}
listing_req.open("POST", "https://leaderboard.edgecompute.app/update_listing", true);
listing_req.setRequestHeader("id", local_id);
listing_req.setRequestHeader("name", local_score.name);
listing_req.setRequestHeader("score", score);
listing_req.send();
}
// The real loading and running of our wasm starts here
let imports = { console_log_int, console_log_double, clear_screen, draw_condition_warning, draw_fastly_treatment, reset_fastly_treatment, draw_name_picker, check_high_score, wait_outro_complete, wait_high_score, draw_player, draw_bullet, draw_player_bullet, draw_particle, draw_hud, draw_line, draw_bounds, draw_intro, handle_game_over, draw_sprite, init_shield, add_shield_state, update_shield, draw_shield, draw_ufo, update_local_score, new_session };
imports.Math_atan = Math.atan;
imports.sin = Math.sin;
imports.cos = Math.cos;
return imports;
}
// Copy a nul-terminated string from the buffer pointed to.
// Consumes the old data and thus deallocated it.
function copyCStr(module, ptr) {
let orig_ptr = ptr;
const collectCString = function* () {
let memory = new Uint8Array(module.memory.buffer);
while (memory[ptr] !== 0) {
if (memory[ptr] === undefined) { throw new Error("Tried to read undef mem") }
yield memory[ptr]
ptr += 1
}
}
const buffer_as_u8 = new Uint8Array(collectCString())
const utf8Decoder = new TextDecoder("UTF-8");
const buffer_as_utf8 = utf8Decoder.decode(buffer_as_u8);
module.dealloc_str(orig_ptr);
return buffer_as_utf8
}
// Fetch and instantiate our wasm module
fetch("space_invaders.wasm").then(response =>
response.arrayBuffer()
).then(bytes =>
WebAssembly.instantiate(bytes, { env: imports() })
).then(results => {
let mod = results.instance;
module.update = mod.exports.update;
module.key_pressed = mod.exports.key_pressed;
module.toggle_fire = mod.exports.toggle_fire;
module.toggle_left = mod.exports.toggle_left;
module.toggle_right = mod.exports.toggle_right;
module.toggle_alt = mod.exports.toggle_alt;
module.resize = mod.exports.resize;
module.draw = mod.exports.draw;
module.init = mod.exports.init;
module.alloc = mod.exports.alloc;
module.dealloc = mod.exports.dealloc;
module.dealloc_str = mod.exports.dealloc_str;
module.memory = mod.exports.memory;
module.init();
local_score.name = "Kiosk Player"; // TODO add unique id to this?
document.getElementById('gamediv').style.display = 'block';
document.getElementById('namediv').style.display = 'none';
local_score.score = 0;
get_leaderboard_entries();
// TODO set timer for get_leaderboard_entries
// Input processing
const keys = ['index', 'id', 'connected', 'mapping', /*'timestamp'*/];
function processController(info) {
const {elem, gamepad, axes, buttons} = info;
const lines = [`gamepad : ${gamepad.index}`];
for (const key of keys) {
info[key].textContent = gamepad[key];
}
let v = applyDeadZone(gamepad.axes[0], 0.1);
let direction = false;
if (v < 0.0) {
module.toggle_left(true);
module.toggle_right(false);
direction = true;
} else if (v > 0.0) {
module.toggle_left(false);
module.toggle_right(true);
direction = true;
}
let all_released = true;
buttons.forEach(({circle, value}, ndx) => {
const button = gamepad.buttons[ndx];
if (ndx == buttonids.PAD_LEFT) {
if (button.pressed) {
module.toggle_left(true);
module.toggle_right(false);
direction = true;
}
} else if (ndx == buttonids.PAD_RIGHT) {
if (button.pressed) {
module.toggle_left(false);
module.toggle_right(true);
direction = true;
}
} else if (ndx != buttonids.PAD_TOP && ndx != buttonids.PAD_BOTTOM ) {
if (button.pressed) {
module.key_pressed(" ", true);
module.toggle_fire(true);
all_released = false;
}
}
circle.setAttributeNS(null, 'r', button.value * 2);
circle.setAttributeNS(null, 'fill', button.pressed ? 'red' : 'gray');
value.textContent = `${button.value.toFixed(2)}`;
});
if (all_released) {
module.toggle_fire(false);
module.key_pressed(" ", false);
}
if (!direction) {
module.toggle_left(false);
module.toggle_right(false);
}
}
function processKey(key, b) {
switch (key) {
case "ArrowLeft":
module.toggle_left(b);
break;
case "ArrowRight":
module.toggle_right(b);
break;
case " ":
module.toggle_fire(b);
break;
case "s":
module.toggle_alt(b);
break;
}
module.key_pressed(key, b);
}
document.addEventListener('keydown', e => processKey(e.key, true));
document.addEventListener('keyup', e => processKey(e.key, false));
window.addEventListener('gamepadconnected', e => handleConnect(e));
window.addEventListener('gamepaddisconnected', e => handleDisconnect);
/*
Sprites are 12x12, and the enemy game radius is 24
So we double the sprites when we init, and then when we render we need to scale by game to screen
*/
function init_sprites(scale) {
let enemy0_0 = [
0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0,
0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0,
0, 1, 0, 1, 1, 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