-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
1670 lines (1510 loc) · 84.1 KB
/
Copy pathscript.js
File metadata and controls
1670 lines (1510 loc) · 84.1 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
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
// ─── Space Invaders ───────────────────────────────────────────────────────────
// Logical resolution : 480 × 640
// Modes : Solo | Versus Local 1v1 | Online 1v1 | Online Co-op
// Online engine : engine/online.js (PeerJS P2P, no backend)
const W = 480, H = 640;
// ── Palette ──────────────────────────────────────────────────────────────────
const C = {
bg: '#05050f',
grid: 'rgba(255,255,255,0.03)',
player: '#00e5ff',
playerG: '#007a8a',
p2: '#ff9800',
bullet: '#00e5ff',
p2bullet: '#ffa726',
alien0: '#ff4081',
alien1: '#ff9800',
alien2: '#76ff03',
alienP2: '#e040fb', // alien-player skin 4 (última vida)
shield: '#00bcd4',
ufo: '#e040fb',
ufoBomb: '#ff1744',
star: '#ffffff',
hud: '#e0e0e0',
accent: '#00e5ff',
dim: 'rgba(0,0,0,0.55)',
};
// ── Alien sprite data (11×8 px bitmask, 3 tipos × 2 frames) ──────────────────
const SPRITES = {
0: [
[0b00100000100,0b01100011000,0b11111111110,0b10111010101,0b11111111110,0b00100000100,0b01000000010,0b00100000100],
[0b00100000100,0b00100000100,0b11111111110,0b10111010101,0b11111111110,0b01100011000,0b10000000001,0b01000000010],
],
1: [
[0b00100000100,0b00100000100,0b01111111110,0b11011010110,0b11111111111,0b01110111010,0b10000000001,0b01000000010],
[0b00100000100,0b10100000101,0b01111111110,0b11011010110,0b11111111111,0b01110111010,0b01010001010,0b10000000001],
],
2: [
[0b00111100000,0b01111111100,0b11011011010,0b11111111110,0b01001001010,0b10111111101,0b10100000101,0b01011101010],
[0b00111100000,0b01111111100,0b11011011010,0b11111111110,0b01001001010,0b10111111101,0b10100000101,0b01000000010],
],
};
// Skin del alien-jugador según vidas restantes: 4→tipo2, 3→tipo1, 2→tipo0, 1→special(ufo-like)
const ALIEN_P2_SKIN = (lives) => {
if (lives >= 4) return 2;
if (lives === 3) return 1;
if (lives === 2) return 0;
return -1; // skin especial (UFO) para última vida
};
const ALIEN_SCORES = [30, 20, 10];
const ALIEN_COLORS = [C.alien0, C.alien1, C.alien2];
// ── Button helpers ────────────────────────────────────────────────────────────
// ── Helpers ───────────────────────────────────────────────────────────────────
function makeStars(n) {
const s = [];
for (let i = 0; i < n; i++)
s.push({ x: Math.random()*W, y: Math.random()*H, r: Math.random()*1.2+0.3, spd: Math.random()*8+4 });
return s;
}
function drawAlien(ctx, type, frame, x, y, size, color) {
const rows = SPRITES[type][frame];
const px = size / 11;
ctx.fillStyle = color;
for (let row = 0; row < rows.length; row++) {
const bits = rows[row];
for (let col = 0; col < 11; col++) {
if (bits & (1 << (10 - col)))
ctx.fillRect(x + col*px, y + row*px, Math.ceil(px), Math.ceil(px));
}
}
}
function makeShield(cx, y) {
const blocks = [], cols = 6, rows = 4, bsz = 8;
const ox = cx - (cols * bsz) / 2;
for (let r = 0; r < rows; r++)
for (let c = 0; c < cols; c++) {
if (r === 0 && (c === 0 || c === cols - 1)) continue;
blocks.push({ x: ox + c*bsz, y: y + r*bsz, sz: bsz, hp: 3 });
}
return blocks;
}
// ─────────────────────────────────────────────────────────────────────────────
// GAME OBJECT
// States: 'menu' | 'online-setup' | 'lobby' |
// 'playing' | 'playing-local' | 'playing-online' |
// 'gameover' | 'win'
// Modes: 'solo' | 'local' | 'online-1v1' | 'online-coop'
// ─────────────────────────────────────────────────────────────────────────────
const game = {
state: 'menu',
mode: 'solo',
onlineRole: null, // 'host'|'guest'
onlinePlayerNum: 1, // 1 = P1 (shooter), 2 = P2 (alien-jugador) - asignado en online 1v1
_onlineSubMode: '1v1',
stars: [],
// ── P1 (shooter) ──────────────────────────────────────────────────────────
score: 0, hi: 0, lives: 3, level: 1,
px: W/2, py: H-50, pspd: 220,
pbullets: [], pCooldown: 0, pW: 36, pH: 18,
// ── P2 - alien-jugador en modo 1v1 ────────────────────────────────────────
// En local: P2 controla un alien en zona superior
// p2x/p2y = posición del alien-jugador
// p2lives = 4 vidas, skin cambia con cada vida perdida
// p2bullets = bombas del alien hacia abajo
p2score: 0, p2lives: 4,
p2x: W/2, p2y: 80,
p2spd: 200,
p2bullets: [], p2Cooldown: 0,
p2W: 36, p2H: 26, // tamaño del alien-jugador
P2_ZONE_BOTTOM: 240, // límite inferior de la zona del alien
// ── Online rival display ───────────────────────────────────────────────────
rivalScore: 0, rivalLives: 3,
// ── Aliens NPC ────────────────────────────────────────────────────────────
aliens: [], aFrame: 0, aFrameTimer: 0, aFrameInterval: 0.6,
aDir: 1, aSpeedX: 20, aDropAmt: 16,
aBullets: [], aShootTimer: 0, aShootInterval: 1.8,
// ── UFO ──────────────────────────────────────────────────────────────────
ufo: null, ufoTimer: 0, ufoInterval: 18,
// ── Shields ───────────────────────────────────────────────────────────────
shields: [],
// ── UI ───────────────────────────────────────────────────────────────────
_btns: {}, _hover: {},
flashMsg: '', flashTimer: 0,
// ── Particles ─────────────────────────────────────────────────────────────
_particles: [],
// ── Touch ─────────────────────────────────────────────────────────────────
// P1 touch (solo/online/local-p1)
_touchLeft: false, _touchRight: false, _touchFire: false, _touchFirePressed: false,
// P2 touch (local-p2)
_touch2Left: false, _touch2Right: false, _touch2Up: false, _touch2Down: false,
_touch2Fire: false, _touch2FirePressed: false,
_touchBtnLayout: null,
// ── Online sync ───────────────────────────────────────────────────────────
_onlineSyncTimer: 0,
// ── Online 1v1 alien state (para sincronizar el alien-jugador remoto) ─────
_remoteAlienX: W/2, _remoteAlienY: 80, _remoteAlienLives: 4,
_remoteAlienBullets: [], // balas del alien remoto para renderizar
// ─────────────────────────────────────────────────────────────────────────
// INIT
// ─────────────────────────────────────────────────────────────────────────
init() {
this.stars = makeStars(80);
this._buildMenuBtns();
this._synthSounds();
this._setupOnlineUI();
},
_synthSounds() {
Audio.synth('shoot', 'square', 880, 0.08, 0.15);
Audio.synth('shoot2', 'saw', 330, 0.10, 0.20); // sonido bala alien-P2
Audio.synth('hit', 'noise', 200, 0.12, 0.3);
Audio.synth('explode', 'noise', 80, 0.35, 0.5);
Audio.synth('ufo', 'square', 440, 0.5, 0.2, 220);
Audio.synth('die', 'saw', 200, 0.4, 0.4, 50);
Audio.synth('levelup', 'sine', 660, 0.4, 0.3, 1320);
Audio.synth('alienhit', 'sine', 220, 0.20, 0.4, 110); // alien-P2 recibe daño
},
// ─────────────────────────────────────────────────────────────────────────
// BUTTON MAPS
// ─────────────────────────────────────────────────────────────────────────
_buildMenuBtns() {
const bw = 244, bh = 54, cx = W/2 - bw/2;
this._btns = {
solo: { x: cx, y: 395, w: bw, h: bh, label: '▶ SOLO' },
local: { x: cx, y: 460, w: bw, h: bh, label: 'VERSUS LOCAL' },
online: { x: cx, y: 525, w: bw, h: bh, label: 'MULTIJUGADOR' },
restart: null,
};
this._hover = {};
},
_buildOnlineSetupBtns() {
const bw = 212, bh = 52, cx = W/2 - bw/2;
this._btns = {
mode1v1: { x: W/2-150, y: 300, w: 132, h: 44, label: '🎯 1 vs 1' },
modeCoop: { x: W/2+18, y: 300, w: 132, h: 44, label: '🤝 CO-OP' },
hostRoom: { x: cx, y: 374, w: bw, h: bh, label: 'Crear Sala' },
joinRoom: { x: cx, y: 438, w: bw, h: bh, label: 'Unirse a Sala' },
onlineBack: { x: cx, y: 512, w: bw, h: 42, label: '← Volver' },
restart: null,
};
this._hover = {};
},
// ─────────────────────────────────────────────────────────────────────────
// ONLINE HTML UI
// ─────────────────────────────────────────────────────────────────────────
_setupOnlineUI() {
OnlineLobby.onCancel(() => {
this._buildOnlineSetupBtns();
this.state = 'online-setup';
});
OnlineLobby.wireDefaultJoin((code) => {
OnlineLobby.setStatus('Conectando...');
Online.join(code);
});
},
_showOnlineUI(view) {
if (view === 'host') {
OnlineLobby.showHostPanel('------');
} else if (view === 'join') {
OnlineLobby.showJoinPanel();
} else {
OnlineLobby.show();
}
},
_hideOnlineUI() {
OnlineLobby.hide();
},
// ─────────────────────────────────────────────────────────────────────────
// ONLINE CALLBACKS
// ─────────────────────────────────────────────────────────────────────────
_setupOnlineCallbacks() {
Online.on('onHostReady', (code) => {
OnlineLobby.setCode(code);
OnlineLobby.setStatus('Esperando rival...');
});
Online.on('onConnected', (role) => {
this.onlineRole = role;
OnlineLobby.setStatus('¡Conectado! Iniciando...');
setTimeout(() => {
this._hideOnlineUI();
if (role === 'host') {
let p1role = 'shooter', p2role = 'alien';
const is1v1 = (!this._onlineSubMode || this._onlineSubMode === '1v1' || this._onlineSubMode !== 'coop');
if (is1v1 && Math.random() < 0.5) {
p1role = 'alien'; p2role = 'shooter';
}
console.log(`[1v1 Online] Host role: ${p1role}, Guest role: ${p2role}`);
Online.send({ type: 'game_init', mode: this._onlineSubMode || '1v1', guestRole: p2role });
const myRole = p1role;
this._startOnlineGame(role, this._onlineSubMode || '1v1', myRole);
}
}, 600);
});
Online.on('onData', (data) => this._handleOnlineData(data));
Online.on('onDisconnect', () => {
if (this.state === 'playing-online') {
this.rivalLives = 0;
this._flash('RIVAL DESCONECTADO');
setTimeout(() => {
if (this.state === 'playing-online') this.state = 'gameover';
}, 2500);
} else {
this._hideOnlineUI();
this._buildMenuBtns();
this.state = 'menu';
}
});
Online.on('onError', (err) => {
OnlineLobby.setStatus(`Error: ${err.type || String(err)}`);
OnlineLobby.enableJoin(true);
});
},
// ─────────────────────────────────────────────────────────────────────────
// ONLINE DATA HANDLER
// ─────────────────────────────────────────────────────────────────────────
_handleOnlineData(data) {
if (data.type === 'game_init') {
const subMode = data.mode || '1v1';
this._onlineSubMode = subMode;
this._hideOnlineUI();
// Guest recibe su rol (siempre P2 en coop, asignado aleatoriamente en 1v1)
const myRole = subMode === 'coop' ? 'shooter' : data.guestRole;
console.log(`[1v1 Online] Guest role received: ${myRole}`);
this._startOnlineGame('guest', subMode, myRole);
return;
}
if (this.state !== 'playing-online') return;
switch (data.type) {
// ── CO-OP: status sync ────────────────────────────────────────────
case 'status':
this.rivalScore = data.score;
this.rivalLives = data.lives;
break;
// ── CO-OP: kill sync ──────────────────────────────────────────────
case 'kill': {
if (this.mode !== 'online-coop') break;
const a = this.aliens[data.idx];
if (a && a.alive) {
a.alive = false;
this._spawnParticles(a.x + a.w/2, a.y + a.h/2, ALIEN_COLORS[a.type]);
}
break;
}
// ── 1v1: posición del alien-jugador remoto ────────────────────────
case 'alien_move':
this._remoteAlienX = data.x;
this._remoteAlienY = data.y;
this._remoteAlienLives = data.lives;
if (data.score !== undefined) this.rivalScore = data.score;
break;
// ── 1v1: posición del shooter remoto ──────────────────────────────
case 'shooter_move':
this._remoteAlienX = data.x; // Reusamos esta variable para la pos del rival (shooter)
this.rivalScore = data.score;
this.rivalLives = data.lives;
break;
// ── 1v1: bala del alien-jugador remoto ────────────────────────────
case 'alien_shoot':
// El alien dispara bombas hacia abajo (desde la perspectiva del shooter local)
this._remoteAlienBullets.push({ x: data.x, y: data.y });
break;
// ── 1v1: bala del shooter remoto ──────────────────────────────────
case 'shooter_shoot':
// Si yo soy el alien, recibo las balas del shooter remoto
if (this.onlinePlayerNum === 2) {
this.aBullets.push({ x: data.x, y: data.y, fromShooter: true });
}
break;
// ── 1v1: Alien llegó abajo ────────────────────────────────────────
case 'alien_reached_bottom':
this.state = 'gameover';
break;
// ── Rival terminó ─────────────────────────────────────────────────
case 'gameover':
this.rivalLives = 0;
if (this.mode === 'online-1v1') this._flash('¡RIVAL ELIMINADO!');
this.state = 'gameover';
break;
}
},
// ─────────────────────────────────────────────────────────────────────────
// START MODES
// ─────────────────────────────────────────────────────────────────────────
_startSolo() {
this.mode = 'solo';
this.score = 0; this.lives = 3; this.level = 1;
this._btns.restart = null; this._hover = {};
this._initLevel();
this.px = W/2; this.py = H-50;
this.state = 'playing';
},
// LOCAL: P1=shooter abajo, P2=alien-jugador arriba
_startLocal() {
this.mode = 'local';
this.score = 0; this.p2score = 0;
this.lives = 3; this.p2lives = 4;
this.level = 1;
this._btns.restart = null; this._hover = {};
this._initLevelLocal();
this.px = W / 2; this.py = H - 50;
this.p2x = W / 2; this.p2y = 80;
this.state = 'playing-local';
},
_startOnlineGame(role, subMode, myGameRole) {
this.mode = subMode === 'coop' ? 'online-coop' : 'online-1v1';
this.onlineRole = role;
// myGameRole: 'shooter' | 'alien' (solo en 1v1)
// En coop: siempre shooter. En 1v1: asignado aleatoriamente.
// onlinePlayerNum: 1=shooter, 2=alien
this.onlinePlayerNum = (subMode === 'coop') ? (role === 'host' ? 1 : 2) : (myGameRole === 'shooter' ? 1 : 2);
this.score = 0; this.lives = 3; this.level = 1;
this.p2lives = 4;
this.p2x = W/2; this.p2y = 80;
this.rivalScore = 0; this.rivalLives = (subMode === '1v1') ? 4 : 3;
this._remoteAlienX = W/2; this._remoteAlienY = 80; this._remoteAlienLives = 4;
this._remoteAlienBullets = [];
this._btns.restart = null; this._hover = {};
if (subMode === '1v1') {
this._initLevelLocal(); // Sin NPC aliens en 1v1
} else {
this._initLevel();
}
this.px = W/2; this.py = H-50;
this.state = 'playing-online';
this._onlineSyncTimer = 0;
},
// ─────────────────────────────────────────────────────────────────────────
// LEVEL INIT
// ─────────────────────────────────────────────────────────────────────────
_initLevel() {
const cols = 11, rows = 5;
const aw = 32, ah = 24, padX = 6, padY = 10;
const totalW = cols * (aw + padX) - padX;
const startX = (W - totalW) / 2;
const startY = 80;
this.aliens = [];
for (let r = 0; r < rows; r++) {
const type = r === 0 ? 0 : r <= 2 ? 1 : 2;
for (let c = 0; c < cols; c++) {
this.aliens.push({
x: startX + c * (aw + padX),
y: startY + r * (ah + padY),
w: aw, h: ah, type, alive: true,
});
}
}
this.aDir = 1;
this.aSpeedX = 20 + (this.level - 1) * 5;
this.aShootInterval = Math.max(0.6, 1.8 - (this.level - 1) * 0.12);
this.aFrame = 0; this.aFrameTimer = 0;
this.aFrameInterval = Math.max(0.2, 0.6 - (this.level - 1) * 0.04);
this.pbullets = []; this.p2bullets = []; this.aBullets = [];
this.ufo = null; this.ufoTimer = 0; this.ufoInterval = 15;
this.pCooldown = 0; this.p2Cooldown = 0;
this.shields = [];
for (const sx of [90, 185, 295, 390]) this.shields.push(...makeShield(sx, H - 130));
},
// Local 1v1: sin aliens NPC - sólo el alien-P2 y el shooter-P1
_initLevelLocal() {
this.aliens = []; // no hay horda NPC
this.aFrame = 0; this.aFrameTimer = 0; this.aFrameInterval = 0.4;
this.pbullets = []; this.p2bullets = []; this.aBullets = [];
this.ufo = null; this.ufoTimer = 0;
this.pCooldown = 0; this.p2Cooldown = 0;
this.shields = [];
for (const sx of [90, 185, 295, 390]) this.shields.push(...makeShield(sx, H - 130));
},
// ─────────────────────────────────────────────────────────────────────────
// UPDATE DISPATCHER
// ─────────────────────────────────────────────────────────────────────────
update(dt) {
for (const s of this.stars) {
s.y += s.spd * dt;
if (s.y > H) { s.y = 0; s.x = Math.random() * W; }
}
switch (this.state) {
case 'menu': this._updateMenu(dt); break;
case 'online-setup': this._updateOnlineSetup(dt); break;
case 'lobby': break;
case 'playing': this._updatePlaying(dt); break;
case 'playing-local': this._updatePlayingLocal(dt); break;
case 'playing-online': this._updatePlayingOnline(dt);break;
case 'gameover':
case 'win': this._updateOver(dt); break;
}
},
// ── Menu update ───────────────────────────────────────────────────────────
_updateMenu(dt) {
const m = Input.getMouse();
const gm = Engine.toGame(m.x, m.y);
this._hover.solo = UICanvas.hitTest(gm.x, gm.y, this._btns.solo);
this._hover.local = UICanvas.hitTest(gm.x, gm.y, this._btns.local);
this._hover.online = UICanvas.hitTest(gm.x, gm.y, this._btns.online);
const check = (gx, gy) => {
if (UICanvas.hitTest(gx, gy, this._btns.solo)) { this._startSolo(); return; }
if (UICanvas.hitTest(gx, gy, this._btns.local)) { this._startLocal(); return; }
if (UICanvas.hitTest(gx, gy, this._btns.online)) {
this._buildOnlineSetupBtns();
this.state = 'online-setup';
}
};
if (Input.isMousePressed()) check(gm.x, gm.y);
if (Input.isTouchStarted()) {
const t = Input.getTouch(0);
if (t) { const gt = Engine.toGame(t.x, t.y); check(gt.x, gt.y); }
}
},
// ── Online-setup update ───────────────────────────────────────────────────
_updateOnlineSetup(dt) {
const m = Input.getMouse();
const gm = Engine.toGame(m.x, m.y);
for (const k of ['mode1v1','modeCoop','hostRoom','joinRoom','onlineBack'])
if (this._btns[k]) this._hover[k] = UICanvas.hitTest(gm.x, gm.y, this._btns[k]);
const check = (gx, gy) => {
if (this._btns.mode1v1 && UICanvas.hitTest(gx, gy, this._btns.mode1v1)) { this._onlineSubMode = '1v1'; return; }
if (this._btns.modeCoop && UICanvas.hitTest(gx, gy, this._btns.modeCoop)) { this._onlineSubMode = 'coop'; return; }
if (this._btns.onlineBack && UICanvas.hitTest(gx, gy, this._btns.onlineBack)) {
this._buildMenuBtns(); this.state = 'menu'; return;
}
if (this._btns.hostRoom && UICanvas.hitTest(gx, gy, this._btns.hostRoom)) {
this._setupOnlineCallbacks();
this._showOnlineUI('host');
OnlineLobby.setStatus('Iniciando servidor...');
Online.host(code => {
OnlineLobby.setCode(code);
OnlineLobby.setStatus('Esperando rival...');
});
this.state = 'lobby';
return;
}
if (this._btns.joinRoom && UICanvas.hitTest(gx, gy, this._btns.joinRoom)) {
this._setupOnlineCallbacks();
this._showOnlineUI('join');
OnlineLobby.setStatus('Introduce el código de sala');
this.state = 'lobby';
return;
}
};
if (Input.isMousePressed()) check(gm.x, gm.y);
if (Input.isTouchStarted()) {
const t = Input.getTouch(0);
if (t) { const gt = Engine.toGame(t.x, t.y); check(gt.x, gt.y); }
}
},
// ── Gameover update ───────────────────────────────────────────────────────
_updateOver(dt) {
if (!this._btns.restart) {
const bw = 220, bh = 50;
this._btns.restart = { x: W/2-bw/2, y: H/2+60, w: bw, h: bh, label: '▶ MENÚ' };
}
const m = Input.getMouse();
const gm = Engine.toGame(m.x, m.y);
this._hover.restart = UICanvas.hitTest(gm.x, gm.y, this._btns.restart);
const doMenu = () => {
Online.destroy();
this._btns.restart = null;
this._buildMenuBtns();
this.state = 'menu';
};
if (Input.isMousePressed() && this._hover.restart) doMenu();
if (Input.isTouchStarted()) {
const t = Input.getTouch(0);
if (t) {
const gt = Engine.toGame(t.x, t.y);
if (this._btns.restart && UICanvas.hitTest(gt.x, gt.y, this._btns.restart)) doMenu();
}
}
if (Input.isPressed('Space') || Input.isPressed('Enter')) doMenu();
},
// ── Playing: Solo ─────────────────────────────────────────────────────────
_updatePlaying(dt) {
this._updatePlayerSolo(dt);
this._updateAliens(dt);
this._updateBullets(dt, 'solo');
this._updateUFO(dt);
this._updateCollisionsSolo();
this._checkWinLose();
if (this.flashTimer > 0) this.flashTimer -= dt;
},
// ── Playing: Local 1v1 ────────────────────────────────────────────────────
_updatePlayingLocal(dt) {
this._updatePlayerP1Local(dt);
this._updateAlienP2Local(dt);
this._updateBullets(dt, 'local');
this._updateCollisionsLocal1v1();
this.aFrameTimer += dt;
if (this.aFrameTimer >= this.aFrameInterval) { this.aFrameTimer = 0; this.aFrame = 1 - this.aFrame; }
if (this.flashTimer > 0) this.flashTimer -= dt;
},
// ── Playing: Online ───────────────────────────────────────────────────────
_updatePlayingOnline(dt) {
if (this.mode === 'online-coop') {
this._updatePlayerSolo(dt);
this._updateAliens(dt);
this._updateBullets(dt, 'solo');
this._updateUFO(dt);
this._updateCollisionsOnline();
this._checkWinLoseOnline();
} else {
// 1v1 online
this._updateOnline1v1(dt);
}
this._onlineSyncTimer -= dt;
if (this._onlineSyncTimer <= 0) {
this._onlineSyncTimer = 0.1; // sync frecuente en 1v1
if (this.mode === 'online-coop') {
Online.send({ type: 'status', score: this.score, lives: this.lives });
} else {
// Enviar posición del alien o del shooter
if (this.onlinePlayerNum === 2) {
Online.send({ type: 'alien_move', x: this.p2x, y: this.p2y, lives: this.p2lives, score: this.p2score });
} else {
Online.send({ type: 'shooter_move', x: this.px, score: this.score, lives: this.lives });
}
}
}
if (this.flashTimer > 0) this.flashTimer -= dt;
},
// ─────────────────────────────────────────────────────────────────────────
// ONLINE 1v1 UPDATE
// ─────────────────────────────────────────────────────────────────────────
_updateOnline1v1(dt) {
this.aFrameTimer += dt;
if (this.aFrameTimer >= this.aFrameInterval) { this.aFrameTimer = 0; this.aFrame = 1 - this.aFrame; }
if (this.onlinePlayerNum === 1) {
// Soy el SHOOTER
const oldBullets = this.pbullets.length;
this._updatePlayerSolo(dt);
if (this.pbullets.length > oldBullets) {
// A new bullet was fired!
const b = this.pbullets[this.pbullets.length - 1];
Online.send({ type: 'shooter_shoot', x: b.x, y: b.y });
}
// Muevo balas P1 hacia arriba
for (const b of this.pbullets) b.y -= 420 * dt;
this.pbullets = this.pbullets.filter(b => b.y > -10);
// Balas remotas del alien (vienen desde arriba, bajan)
for (const b of this._remoteAlienBullets) b.y += 200 * dt;
this._remoteAlienBullets = this._remoteAlienBullets.filter(b => b.y < H + 10);
// Colisiones: mis balas vs alien remoto
for (const b of this.pbullets) {
const ax = this._remoteAlienX, ay = this._remoteAlienY;
if (b.x > ax - this.p2W/2 && b.x < ax + this.p2W/2 &&
b.y > ay && b.y < ay + this.p2H) {
b.y = -9999;
this.score += 50;
Audio.play('alienhit');
}
}
// Balas remotas del alien vs yo
for (const b of this._remoteAlienBullets) {
if (Math.abs(b.x - this.px) < this.pW/2 && b.y > this.py - this.pH && b.y < this.py + 4) {
b.y = 9999;
this._playerHit(1);
}
}
} else {
// Soy el ALIEN-JUGADOR
this._updateAlienP2Online(dt);
// Balas del alien (van hacia abajo desde la perspectiva del shooter)
for (const b of this.p2bullets) b.y += 200 * dt;
this.p2bullets = this.p2bullets.filter(b => b.y < H + 10);
// Balas remotas del shooter (suben desde abajo)
for (const b of this.aBullets) {
if (b.fromShooter) b.y -= 420 * dt;
}
this.aBullets = this.aBullets.filter(b => b.fromShooter ? b.y > -10 : b.y < H + 10);
// Mis balas vs shooter remoto (evalúo impacto local para sumar puntos)
for (const b of this.p2bullets) {
if (Math.abs(b.x - this._remoteAlienX) < this.pW/2 && b.y > H - 50 - this.pH && b.y < H - 50 + 4) {
b.y = 9999;
this.p2score += 30; // Yo, alien, anoto puntos
}
}
// Balas del shooter remoto vs yo (alien)
for (const b of this.aBullets) {
if (!b.fromShooter) continue;
if (b.x > this.p2x - this.p2W/2 && b.x < this.p2x + this.p2W/2 &&
b.y > this.p2y && b.y < this.p2y + this.p2H) {
b.y = -9999;
this.p2lives--;
Audio.play('alienhit');
this._spawnParticles(this.p2x, this.p2y, C.alienP2, 8);
if (this.p2lives <= 0) {
Online.send({ type: 'gameover' });
this.state = 'gameover';
}
}
}
}
// Shields (para AMBOS jugadores)
this._updateShieldCollisions1v1(dt);
// Check si el alien llegó abajo (alien gana)
if (this.onlinePlayerNum === 1 && this._remoteAlienY + this.p2H >= H - 70) {
this.state = 'gameover';
}
if (this.onlinePlayerNum === 2 && this.p2y + this.p2H >= H - 70) {
Online.send({ type: 'alien_reached_bottom' });
this.state = 'gameover'; // alien ganó
}
},
_updateShieldCollisions1v1(dt) {
const upBullets = this.onlinePlayerNum === 1 ? this.pbullets : this.aBullets;
const downBullets = this.onlinePlayerNum === 1 ? this._remoteAlienBullets : this.p2bullets;
for (const b of upBullets) {
for (const sh of this.shields) {
if (sh.hp <= 0) continue;
if (b.x > sh.x && b.x < sh.x+sh.sz && b.y > sh.y && b.y < sh.y+sh.sz)
{ sh.hp--; b.y = -9999; }
}
}
for (const b of downBullets) {
for (const sh of this.shields) {
if (sh.hp <= 0) continue;
if (b.x > sh.x && b.x < sh.x+sh.sz && b.y > sh.y && b.y < sh.y+sh.sz)
{ sh.hp--; b.y = 9999; }
}
}
},
// ─────────────────────────────────────────────────────────────────────────
// PLAYER UPDATES
// ─────────────────────────────────────────────────────────────────────────
_updatePlayerSolo(dt) {
const left = Input.isDown('ArrowLeft') || Input.isDown('KeyA');
const right = Input.isDown('ArrowRight') || Input.isDown('KeyD');
const fire = Input.isPressed('Space') || Input.isPressed('ArrowUp') || Input.isPressed('KeyW');
const tLeft = this._touchLeft, tRight = this._touchRight;
const tFire = this._touchFirePressed; this._touchFirePressed = false;
if (left || tLeft) this.px = Math.max(this.pW/2, this.px - this.pspd*dt);
if (right || tRight) this.px = Math.min(W - this.pW/2, this.px + this.pspd*dt);
this.pCooldown -= dt;
if ((fire || tFire) && this.pCooldown <= 0) {
this.pbullets.push({ x: this.px, y: this.py - this.pH/2 - 4 });
this.pCooldown = 0.25;
Audio.play('shoot');
}
},
// P1 en Local 1v1: Arrow keys + Space
_updatePlayerP1Local(dt) {
const l1 = Input.isDown('ArrowLeft') || this._touchLeft;
const r1 = Input.isDown('ArrowRight') || this._touchRight;
const f1 = (Input.isPressed('Space') || Input.isPressed('ArrowUp') || this._touchFirePressed);
this._touchFirePressed = false;
if (l1) this.px = Math.max(this.pW/2, this.px - this.pspd*dt);
if (r1) this.px = Math.min(W - this.pW/2, this.px + this.pspd*dt);
this.pCooldown -= dt;
if (f1 && this.pCooldown <= 0) {
this.pbullets.push({ x: this.px, y: this.py - this.pH/2 - 4 });
this.pCooldown = 0.25; Audio.play('shoot');
}
},
// P2 alien-jugador en Local 1v1: WASD + movimiento vertical + E/Tab para disparar
_updateAlienP2Local(dt) {
const l2 = Input.isDown('KeyA') || this._touch2Left;
const r2 = Input.isDown('KeyD') || this._touch2Right;
const u2 = Input.isDown('KeyW') || this._touch2Up;
const d2 = Input.isDown('KeyS') || this._touch2Down;
const f2 = (Input.isPressed('KeyE') || Input.isPressed('Tab') || this._touch2FirePressed);
this._touch2FirePressed = false;
if (l2) this.p2x = Math.max(this.p2W/2, this.p2x - this.p2spd*dt);
if (r2) this.p2x = Math.min(W - this.p2W/2, this.p2x + this.p2spd*dt);
if (u2) this.p2y = Math.max(40, this.p2y - this.p2spd*dt);
if (d2) this.p2y = Math.min(this.P2_ZONE_BOTTOM, this.p2y + this.p2spd*dt);
this.p2Cooldown -= dt;
if (f2 && this.p2Cooldown <= 0) {
// El alien dispara hacia ABAJO
this.p2bullets.push({ x: this.p2x, y: this.p2y + this.p2H/2 + 4 });
this.p2Cooldown = 0.4; Audio.play('shoot2');
}
},
// Alien-jugador online
_updateAlienP2Online(dt) {
const l2 = Input.isDown('ArrowLeft') || Input.isDown('KeyA') || this._touchLeft;
const r2 = Input.isDown('ArrowRight') || Input.isDown('KeyD') || this._touchRight;
const u2 = Input.isDown('ArrowUp') || Input.isDown('KeyW') || this._touch2Up;
const d2 = Input.isDown('ArrowDown') || Input.isDown('KeyS') || this._touch2Down;
const f2 = Input.isPressed('Space') || this._touchFirePressed || this._touch2FirePressed;
this._touchFirePressed = false; this._touch2FirePressed = false;
if (l2) this.p2x = Math.max(this.p2W/2, this.p2x - this.p2spd*dt);
if (r2) this.p2x = Math.min(W - this.p2W/2, this.p2x + this.p2spd*dt);
if (u2) this.p2y = Math.max(40, this.p2y - this.p2spd*dt);
if (d2) this.p2y = Math.min(H/2 - this.p2H, this.p2y + this.p2spd*dt); // No puede pasar la mitad
this.p2Cooldown -= dt;
if (f2 && this.p2Cooldown <= 0) {
const bx = this.p2x, by = this.p2y + this.p2H/2 + 4;
this.p2bullets.push({ x: bx, y: by });
this.p2Cooldown = 0.4; Audio.play('shoot2');
// Notificar al shooter
Online.send({ type: 'alien_shoot', x: bx, y: by });
}
},
// ─────────────────────────────────────────────────────────────────────────
// ALIENS NPC, BULLETS, UFO (solo en solo/coop)
// ─────────────────────────────────────────────────────────────────────────
_updateAliens(dt) {
this.aFrameTimer += dt;
if (this.aFrameTimer >= this.aFrameInterval) { this.aFrameTimer = 0; this.aFrame = 1 - this.aFrame; }
const alive = this.aliens.filter(a => a.alive);
if (alive.length === 0) return;
const speedMult = 1 + (1 - alive.length / 55) * 1.8;
const dx = this.aDir * this.aSpeedX * speedMult * dt;
let minX = Infinity, maxX = -Infinity;
for (const a of alive) { if (a.x < minX) minX = a.x; if (a.x + a.w > maxX) maxX = a.x + a.w; }
let drop = false;
if (maxX + dx > W - 8) { drop = true; this.aDir = -1; }
if (minX + dx < 8) { drop = true; this.aDir = 1; }
for (const a of alive) { if (drop) a.y += this.aDropAmt; else a.x += dx; }
this.aShootTimer -= dt;
if (this.aShootTimer <= 0) {
this.aShootTimer = this.aShootInterval * (0.7 + Math.random() * 0.6);
const cols = {};
for (const a of alive) {
const col = Math.round(a.x);
if (!cols[col] || a.y > cols[col].y) cols[col] = a;
}
const shooters = Object.values(cols);
const shooter = shooters[Math.floor(Math.random() * shooters.length)];
if (shooter) this.aBullets.push({ x: shooter.x + shooter.w/2, y: shooter.y + shooter.h });
}
},
_updateBullets(dt, who) {
const pspd = 420, aspd = 200;
if (who !== 'local-p2only') for (const b of this.pbullets) b.y -= pspd * dt;
if (who === 'local') {
// p2bullets van hacia abajo (bombas del alien)
for (const b of this.p2bullets) b.y += aspd * dt;
}
for (const b of this.aBullets) b.y += aspd * dt;
this.pbullets = this.pbullets.filter(b => b.y > -10);
if (who === 'local') this.p2bullets = this.p2bullets.filter(b => b.y < H + 10);
this.aBullets = this.aBullets.filter(b => b.y < H + 10);
},
_updateUFO(dt) {
this.ufoTimer -= dt;
if (this.ufoTimer <= 0 && !this.ufo) {
this.ufoTimer = this.ufoInterval + Math.random() * 10;
const dir = Math.random() < 0.5 ? 1 : -1;
this.ufo = { x: dir === 1 ? -40 : W + 40, y: 38, dir, spd: 110 };
Audio.play('ufo');
}
if (this.ufo) {
this.ufo.x += this.ufo.dir * this.ufo.spd * dt;
if (this.ufo.x < -60 || this.ufo.x > W + 60) this.ufo = null;
}
},
// ─────────────────────────────────────────────────────────────────────────
// COLLISIONS
// ─────────────────────────────────────────────────────────────────────────
_updateCollisionsSolo() {
for (const b of this.pbullets) {
for (const a of this.aliens) {
if (!a.alive) continue;
if (b.x > a.x && b.x < a.x+a.w && b.y > a.y && b.y < a.y+a.h) {
a.alive = false; b.y = -9999;
this.score += ALIEN_SCORES[a.type];
Audio.play('hit'); this._spawnParticles(a.x+a.w/2, a.y+a.h/2, ALIEN_COLORS[a.type]);
}
}
if (this.ufo) {
const u = this.ufo;
if (b.x > u.x-20 && b.x < u.x+20 && b.y > u.y-8 && b.y < u.y+8) {
const bonus = (Math.floor(Math.random()*6)+1)*50;
this.score += bonus; this._flash(`+${bonus}!`);
this.ufo = null; b.y = -9999; Audio.play('explode');
}
}
for (const sh of this.shields) {
if (sh.hp <= 0) continue;
if (b.x > sh.x && b.x < sh.x+sh.sz && b.y > sh.y && b.y < sh.y+sh.sz) { sh.hp--; b.y = -9999; }
}
}
for (const b of this.aBullets) {
if (Math.abs(b.x-this.px) < this.pW/2 && b.y > this.py-this.pH && b.y < this.py+4)
{ b.y = 9999; this._playerHit(1); }
for (const sh of this.shields) {
if (sh.hp <= 0) continue;
if (b.x > sh.x && b.x < sh.x+sh.sz && b.y > sh.y && b.y < sh.y+sh.sz) { sh.hp--; b.y = 9999; }
}
}
for (const a of this.aliens) {
if (a.alive && a.y+a.h >= H-70) {
if (this.score > this.hi) this.hi = this.score;
this.state = 'gameover'; Audio.play('explode'); return;
}
}
},
// Local 1v1: P1 (shooter) vs P2 (alien-jugador)
_updateCollisionsLocal1v1() {
// Balas de P1 (suben) vs alien-P2
for (const b of this.pbullets) {
// Colisión con alien-P2
if (b.x > this.p2x - this.p2W/2 && b.x < this.p2x + this.p2W/2 &&
b.y > this.p2y && b.y < this.p2y + this.p2H) {
b.y = -9999;
this.p2lives--;
this.score += 50; // P1 anota puntos por golpe
Audio.play('alienhit');
this._spawnParticles(this.p2x, this.p2y + this.p2H/2, C.alienP2, 10);
if (this.p2lives <= 0) {
const best = Math.max(this.score, this.p2score);
if (best > this.hi) this.hi = best;
this.state = 'gameover'; Audio.play('explode'); return;
}
}
// Shields
for (const sh of this.shields) {
if (sh.hp <= 0) continue;
if (b.x > sh.x && b.x < sh.x+sh.sz && b.y > sh.y && b.y < sh.y+sh.sz) { sh.hp--; b.y = -9999; }
}
}
// Balas de P2-alien (bajan) vs P1-shooter
for (const b of this.p2bullets) {
if (Math.abs(b.x - this.px) < this.pW/2 && b.y > this.py - this.pH && b.y < this.py + 4) {
b.y = 9999;
this.p2score += 30; // P2 anota puntos por golpe
this._playerHit(1);
}
for (const sh of this.shields) {
if (sh.hp <= 0) continue;
if (b.x > sh.x && b.x < sh.x+sh.sz && b.y > sh.y && b.y < sh.y+sh.sz) { sh.hp--; b.y = 9999; }
}
}
// Si el alien-P2 llega abajo, P2 gana
if (this.p2y + this.p2H >= H - 70) {
const best = Math.max(this.score, this.p2score);
if (best > this.hi) this.hi = best;
this.p2score += 200; // bonus por llegar
this.state = 'gameover'; Audio.play('explode'); return;
}
},
// Online CO-OP
_updateCollisionsOnline() {
for (const b of this.pbullets) {
for (let i = 0; i < this.aliens.length; i++) {
const a = this.aliens[i];
if (!a.alive) continue;
if (b.x > a.x && b.x < a.x+a.w && b.y > a.y && b.y < a.y+a.h) {
a.alive = false; b.y = -9999;
this.score += ALIEN_SCORES[a.type];
Audio.play('hit'); this._spawnParticles(a.x+a.w/2, a.y+a.h/2, ALIEN_COLORS[a.type]);
Online.send({ type: 'kill', idx: i });
}
}
if (this.ufo) {
const u = this.ufo;
if (b.x > u.x-20 && b.x < u.x+20 && b.y > u.y-8 && b.y < u.y+8) {
const bonus = (Math.floor(Math.random()*6)+1)*50;
this.score += bonus; this._flash(`+${bonus}!`);
this.ufo = null; b.y = -9999; Audio.play('explode');
}
}
for (const sh of this.shields) {
if (sh.hp <= 0) continue;
if (b.x > sh.x && b.x < sh.x+sh.sz && b.y > sh.y && b.y < sh.y+sh.sz) { sh.hp--; b.y = -9999; }
}
}
for (const b of this.aBullets) {
if (Math.abs(b.x-this.px) < this.pW/2 && b.y > this.py-this.pH && b.y < this.py+4)
{ b.y = 9999; this._playerHit(1); }
for (const sh of this.shields) {