-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgame.js
More file actions
1891 lines (1577 loc) · 71.7 KB
/
game.js
File metadata and controls
1891 lines (1577 loc) · 71.7 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
class SpaceInvadersGame {
constructor() {
this.canvas = document.getElementById('gameCanvas');
this.gameWidth = 800;
this.gameHeight = 600;
// ゲーム状態
this.gameState = 'menu'; // menu, preparation, playing, paused, gameOver
this.score = 0;
this.lives = 5;
this.isPaused = false;
// 準備時間用
this.preparationTime = 10; // 10秒の準備時間
this.preparationTimer = 0;
this.preparationStartTime = 0;
// プレイヤー
this.player = {
x: 400,
y: 550,
width: 40,
height: 30,
speed: 5,
invulnerable: false,
invulnerableTime: 0,
// より精密な当たり判定用のコリジョンボックス
collisionBoxes: [
// メインボディ(中央下部)
{ x: -10, y: -8, width: 20, height: 16 },
// コックピット(上部中央)
{ x: -4, y: -12, width: 8, height: 8 },
// 左翼(上部左)
{ x: -14, y: -10, width: 6, height: 8 },
// 右翼(上部右)
{ x: 8, y: -10, width: 6, height: 8 }
]
};
// 弾丸配列
this.playerBullets = [];
this.enemyBullets = [];
// 敵配列
this.enemies = [];
this.bosses = []; // ボス敵を配列で管理
// エフェクト
this.explosions = [];
this.stars = [];
// ボス登場フラグ
this.bossSpawning = false;
// ボス討伐数を追跡
this.bossesDefeated = 0;
// 複数ボス生成中フラグ
this.spawningMultipleBosses = false;
// キー入力
this.keys = {};
// タイミング
this.lastTime = 0;
this.enemyShootTimer = 0;
this.enemyMoveTimer = 0;
this.enemyDirection = 1; // 1: 右, -1: 左
// 時間ベーススコア用
this.gameStartTime = 0;
this.gameTime = 0;
// Bluetooth通信用
this.characteristic = null;
this.device_name = 'ESP32';
this.service_uuid = '12345678-1234-1234-1234-1234567890ab';
this.characteristic_uuid = 'abcdefab-1234-1234-1234-abcdefabcdef';
this.dataArray = [];
this.prevFiltered = 0;
this.alpha = 0.4;
this.beatCount = 0;
this.lastBeatTime = 0;
this.threshold = 1800;
this.aboveThreshold = false;
// デバッグ用
this.showCollisionBoxes = false; // 当たり判定表示フラグ
// BGM用
this.bgmAudio = null;
this.bgmVolume = 0.15; // 音量を10倍に増加
// 効果音用
this.deadSoundAudio = null;
this.damageSoundAudio = null;
this.effectVolume = 0.3; // 効果音用の音量を10倍に増加
// グラフ描画用
this.graphCanvas = null;
this.graphCtx = null;
// ドックンアニメーション用
this.heartCanvas = null;
this.heartCtx = null;
this.heartImages = [];
this.frameCount = 7;
this.frameDelay = 50;
this.init();
}
init() {
this.createStars();
this.setupEventListeners();
this.createPlayer();
this.setupUI();
this.setupCanvases();
this.setupBGM();
}
setupCanvases() {
// グラフキャンバスの設定
this.graphCanvas = document.getElementById('heartDataGraph');
this.graphCtx = this.graphCanvas.getContext('2d');
// ドックンキャンバスの設定
this.heartCanvas = document.getElementById('heartCanvas');
this.heartCtx = this.heartCanvas.getContext('2d');
// ハートのSVG画像を読み込み(簡単な円形で代用)
this.loadHeartImages();
}
setupBGM() {
try {
this.bgmAudio = new Audio('music.mp3');
this.bgmAudio.loop = true; // ループ再生
this.bgmAudio.volume = this.bgmVolume; // 控えめな音量
this.bgmAudio.preload = 'auto'; // 事前読み込み
console.log('BGMセットアップ完了');
} catch (error) {
console.error('BGMセットアップエラー:', error);
}
// 効果音のセットアップ
try {
this.deadSoundAudio = new Audio('dead.mp3');
this.deadSoundAudio.volume = this.effectVolume;
this.deadSoundAudio.preload = 'auto';
this.damageSoundAudio = new Audio('get-damage.mp3');
this.damageSoundAudio.volume = this.effectVolume;
this.damageSoundAudio.preload = 'auto';
console.log('効果音セットアップ完了');
} catch (error) {
console.error('効果音セットアップエラー:', error);
}
}
loadHeartImages() {
// SVGファイルの代わりに、動的に生成したハート画像を使用
for (let i = 0; i < this.frameCount; i++) {
const canvas = document.createElement('canvas');
canvas.width = 256;
canvas.height = 256;
const ctx = canvas.getContext('2d');
// ハート形状を描画(サイズを段階的に変更)
const scale = 0.5 + (i / (this.frameCount - 1)) * 0.5; // 0.5から1.0まで
this.drawHeartShape(ctx, 128, 128, 80 * scale, '#ff6666');
this.heartImages.push(canvas);
}
}
drawHeartShape(ctx, x, y, size, color) {
ctx.save();
ctx.translate(x, y);
ctx.scale(size / 80, size / 80);
ctx.beginPath();
ctx.fillStyle = color;
ctx.shadowColor = color;
ctx.shadowBlur = 10;
// ハート形状の描画
ctx.moveTo(0, 15);
ctx.bezierCurveTo(-50, -40, -90, 10, 0, 50);
ctx.bezierCurveTo(90, 10, 50, -40, 0, 15);
ctx.fill();
ctx.restore();
}
// BGM制御関数
playBGM() {
if (this.bgmAudio) {
this.bgmAudio.play()
.then(() => {
console.log('BGM再生開始');
})
.catch(error => {
console.error('BGM再生エラー:', error);
});
}
}
pauseBGM() {
if (this.bgmAudio && !this.bgmAudio.paused) {
this.bgmAudio.pause();
console.log('BGM一時停止');
}
}
stopBGM() {
if (this.bgmAudio) {
this.bgmAudio.pause();
this.bgmAudio.currentTime = 0;
console.log('BGM停止');
}
}
// 効果音制御関数
playDeadSound() {
if (this.deadSoundAudio) {
this.deadSoundAudio.currentTime = 0; // 最初から再生
this.deadSoundAudio.play()
.then(() => {
console.log('敵撃破音再生');
})
.catch(error => {
console.error('敵撃破音再生エラー:', error);
});
}
}
playDamageSound() {
if (this.damageSoundAudio) {
this.damageSoundAudio.currentTime = 0; // 最初から再生
this.damageSoundAudio.play()
.then(() => {
console.log('ダメージ音再生');
})
.catch(error => {
console.error('ダメージ音再生エラー:', error);
});
}
}
createStars() {
const starsGroup = document.getElementById('stars');
for (let i = 0; i < 100; i++) {
const star = document.createElementNS('http://www.w3.org/2000/svg', 'circle');
star.setAttribute('cx', Math.random() * this.gameWidth);
star.setAttribute('cy', Math.random() * this.gameHeight);
star.setAttribute('r', Math.random() * 1.5 + 0.5);
star.setAttribute('fill', '#ffffff');
star.setAttribute('class', 'star');
star.style.animationDelay = Math.random() * 2 + 's';
starsGroup.appendChild(star);
this.stars.push({
element: star,
x: parseFloat(star.getAttribute('cx')),
y: parseFloat(star.getAttribute('cy')),
speed: Math.random() * 0.5 + 0.1
});
}
}
createPlayer() {
const playerGroup = document.getElementById('player');
const playerSVG = this.createPlayerSVG();
playerGroup.appendChild(playerSVG);
}
createPlayerSVG() {
const g = document.createElementNS('http://www.w3.org/2000/svg', 'g');
g.setAttribute('class', 'player-ship');
g.setAttribute('transform', `translate(${this.player.x - this.player.width/2}, ${this.player.y - this.player.height/2})`);
fetch('svg/player.svg')
.then(response => response.text())
.then(svgText => {
// SVG全体ではなく、<svg>タグの中身だけを抽出
const tempDiv = document.createElement('div');
tempDiv.innerHTML = svgText;
const svgElem = tempDiv.querySelector('svg');
if (svgElem) {
// 元のサイズを取得
const originalWidth = parseFloat(svgElem.getAttribute('width')) || 64;
const originalHeight = parseFloat(svgElem.getAttribute('height')) || 64;
// スケールを計算(プレイヤーのサイズに合わせる)
const scaleX = this.player.width / originalWidth;
const scaleY = this.player.height / originalHeight;
// 内容をコピー
g.innerHTML = svgElem.innerHTML;
// スケール変換を適用
g.setAttribute('transform',
`translate(${this.player.x - this.player.width/2}, ${this.player.y - this.player.height/2}) scale(${scaleX}, ${scaleY})`);
console.log(`プレイヤーSVG読み込み完了 (${originalWidth}x${originalHeight} → ${this.player.width}x${this.player.height})`);
}
})
.catch(error => {
console.error('player.svg読み込みエラー:', error);
// フォールバック:シンプルな図形を作成
g.innerHTML = `
<polygon points="20,0 0,30 40,30" fill="#00ff00" stroke="#00cc00" stroke-width="1"/>
<circle cx="20" cy="15" r="3" fill="#ffffff"/>
`;
});
return g;
}
setupUI() {
this.updateScore();
this.updateLives();
}
createLevel() {
this.enemies = [];
const enemiesGroup = document.getElementById('enemies');
enemiesGroup.innerHTML = '';
// 通常の敵を作成(数を減らす:3×8→2×6)
const rows = 2;
const cols = 6;
const enemyWidth = 40; // サイズを大きく:30→40
const enemyHeight = 35; // サイズを大きく:25→35
const spacing = 80;
const startX = 200;
const startY = 80;
for (let row = 0; row < rows; row++) {
for (let col = 0; col < cols; col++) {
const enemy = {
x: startX + col * spacing,
y: startY + row * spacing,
width: enemyWidth,
height: enemyHeight,
type: row < 1 ? 'weak' : 'normal',
health: 0.5 // 雑魚敵のHPをさらに半分に
};
const enemySVG = this.createEnemySVG(enemy);
enemiesGroup.appendChild(enemySVG);
enemy.element = enemySVG;
this.enemies.push(enemy);
}
}
// ボスは最初は作成しない(雑魚敵が3匹になったら登場)
this.bosses = [];
console.log(`レベル作成完了!初期敵数: ${this.enemies.length}, ボス出現条件: 敵が3匹になったとき`);
}
createEnemySVG(enemy) {
const g = document.createElementNS('http://www.w3.org/2000/svg', 'g');
g.setAttribute('class', 'enemy-ship');
g.setAttribute('transform', `translate(${enemy.x - enemy.width/2}, ${enemy.y - enemy.height/2})`);
// 外部SVGファイルを読み込み
fetch('svg/zako.svg')
.then(response => response.text())
.then(svgText => {
// SVG全体ではなく、<svg>タグの中身だけを抽出
const tempDiv = document.createElement('div');
tempDiv.innerHTML = svgText;
const svgElem = tempDiv.querySelector('svg');
if (svgElem) {
// 元のサイズを取得
const originalWidth = parseFloat(svgElem.getAttribute('width')) || 64;
const originalHeight = parseFloat(svgElem.getAttribute('height')) || 64;
// スケールを計算(敵のサイズに合わせる)
const scaleX = enemy.width / originalWidth;
const scaleY = enemy.height / originalHeight;
// 内容をコピー
g.innerHTML = svgElem.innerHTML;
// スケール変換を適用
g.setAttribute('transform',
`translate(${enemy.x - enemy.width/2}, ${enemy.y - enemy.height/2}) scale(${scaleX}, ${scaleY})`);
console.log(`雑魚敵SVG読み込み完了 (${originalWidth}x${originalHeight} → ${enemy.width}x${enemy.height})`);
}
})
.catch(error => {
console.error('zako.svg読み込みエラー:', error);
// フォールバック:シンプルな図形を作成
g.innerHTML = `
<polygon points="20,0 0,20 7,27 33,27 40,20" fill="#ff4444" stroke="#cc0000" stroke-width="1"/>
<circle cx="10" cy="12" r="2" fill="#ffff00"/>
<circle cx="30" cy="12" r="2" fill="#ffff00"/>
`;
});
return g;
}
createBoss() {
// 最初のボス敵の設定
const bossIndex = this.bosses.length;
const baseShootInterval = 3600;
const shootInterval = baseShootInterval; // 最初のボスは基本間隔
const initialDelay = 1000; // 最初のボスは1秒後に射撃開始
this.bosses.push({
x: this.gameWidth / 2,
y: 100,
width: 80,
height: 60,
health: 8, // HPを半分に:15→8
maxHealth: 8, // 最大HPも調整
moveDirection: 1,
shootTimer: initialDelay,
shootInterval: shootInterval,
bossId: bossIndex
});
const bossSVG = this.createBossSVG();
document.getElementById('enemies').appendChild(bossSVG);
this.bosses[this.bosses.length - 1].element = bossSVG;
console.log(`最初のボス${bossIndex}を作成: 射撃間隔=${shootInterval}ms, 初期遅延=${initialDelay}ms`);
}
createBossSVG() {
const g = document.createElementNS('http://www.w3.org/2000/svg', 'g');
g.setAttribute('class', 'boss-ship');
g.setAttribute('transform', `translate(${this.bosses[this.bosses.length - 1].x - this.bosses[this.bosses.length - 1].width/2}, ${this.bosses[this.bosses.length - 1].y - this.bosses[this.bosses.length - 1].height/2})`);
// PNG画像を読み込み
const image = document.createElementNS('http://www.w3.org/2000/svg', 'image');
image.setAttribute('href', 'svg/boss.png');
image.setAttribute('x', '0');
image.setAttribute('y', '0');
image.setAttribute('width', this.bosses[this.bosses.length - 1].width);
image.setAttribute('height', this.bosses[this.bosses.length - 1].height);
// 画像の読み込み完了を待つ
image.addEventListener('load', () => {
console.log(`ボスPNG読み込み完了 (${this.bosses[this.bosses.length - 1].width}x${this.bosses[this.bosses.length - 1].height})`);
});
image.addEventListener('error', () => {
console.error('boss.png読み込みエラー、フォールバックを使用');
// フォールバック:シンプルな図形を作成
g.innerHTML = `
<polygon points="40,0 10,20 0,30 15,50 25,60 55,60 65,50 80,30 70,20" fill="#ff00ff" stroke="#cc00cc" stroke-width="2"/>
<polygon points="20,30 30,35 50,35 60,30 40,45" fill="#aa00aa"/>
<circle cx="25" cy="20" r="3" fill="#ffff00"/>
<circle cx="55" cy="20" r="3" fill="#ffff00"/>
<circle cx="40" cy="25" r="4" fill="#ff0000"/>
`;
this.addBossHealthBar(g);
console.log('ボスPNGフォールバック使用');
});
g.appendChild(image);
// 体力バーを追加
this.addBossHealthBar(g);
return g;
}
addBossHealthBar(parentG) {
// 体力バーを作成
const healthBarBg = document.createElementNS('http://www.w3.org/2000/svg', 'rect');
healthBarBg.setAttribute('x', '10');
healthBarBg.setAttribute('y', this.bosses[this.bosses.length - 1].height + 5);
healthBarBg.setAttribute('width', '60');
healthBarBg.setAttribute('height', '4');
healthBarBg.setAttribute('fill', '#333');
healthBarBg.setAttribute('stroke', '#fff');
healthBarBg.setAttribute('stroke-width', '0.5');
const healthBar = document.createElementNS('http://www.w3.org/2000/svg', 'rect');
healthBar.setAttribute('class', 'boss-health-bar');
healthBar.setAttribute('x', '10');
healthBar.setAttribute('y', this.bosses[this.bosses.length - 1].height + 5);
healthBar.setAttribute('width', 60 * (this.bosses[this.bosses.length - 1].health / this.bosses[this.bosses.length - 1].maxHealth));
healthBar.setAttribute('height', '4');
healthBar.setAttribute('fill', '#ff0000');
parentG.appendChild(healthBarBg);
parentG.appendChild(healthBar);
}
setupEventListeners() {
// キーボードイベント
document.addEventListener('keydown', (e) => {
this.keys[e.code] = true;
// スペースキーでの射撃を無効化
// if (e.code === 'Space') {
// e.preventDefault();
// this.shoot();
// }
if (e.code === 'KeyP') {
this.togglePause();
}
// デバッグ:当たり判定表示切り替え
if (e.code === 'KeyC') {
this.showCollisionBoxes = !this.showCollisionBoxes;
console.log(`当たり判定表示: ${this.showCollisionBoxes ? 'ON' : 'OFF'}`);
}
// ゲームオーバー時にEnterキーでリスタート
if (e.code === 'Enter' && this.gameState === 'gameOver') {
e.preventDefault();
this.restartGame();
}
});
document.addEventListener('keyup', (e) => {
this.keys[e.code] = false;
});
// ボタンイベント
document.getElementById('startButton').addEventListener('click', () => {
this.startGame();
});
document.getElementById('pauseButton').addEventListener('click', () => {
this.togglePause();
});
document.getElementById('restartButton').addEventListener('click', () => {
this.restartGame();
});
// Bluetoothボタンイベント
document.getElementById('connectBluetoothButton').addEventListener('click', () => {
this.connectToBluetooth();
});
// 通信開始・終了ボタンのイベントリスナーを削除(自動化されているため不要)
// document.getElementById('startCommButton').addEventListener('click', () => {
// this.sendStart();
// });
// document.getElementById('stopCommButton').addEventListener('click', () => {
// this.sendStop();
// });
// しきい値スライダーのイベント
const thresholdSlider = document.getElementById("thresholdSlider");
const thresholdValue = document.getElementById("thresholdValue");
thresholdSlider.addEventListener("input", () => {
this.threshold = parseInt(thresholdSlider.value);
thresholdValue.textContent = this.threshold;
console.log(`しきい値を ${this.threshold} に変更しました`);
});
}
startGame() {
// Bluetooth接続の確認
if (!this.characteristic) {
alert('Bluetooth接続が必要です。');
return;
}
// しきい値の確認
console.log(`現在のしきい値: ${this.threshold} でゲームを開始します`);
// ドックンカウントをリセット
this.beatCount = 0;
this.updateBeatCount();
// ゲーム時間の初期化
this.gameTime = 0;
this.gameStartTime = 0; // 準備時間後に設定
this.score = 0;
this.updateScore(); // スコア表示を更新
console.log('準備時間開始');
// BGM開始
this.playBGM();
this.gameState = 'preparation';
this.preparationStartTime = Date.now();
this.preparationTimer = 0;
document.getElementById('startButton').style.display = 'none';
// 準備時間中はポーズボタンを無効化
const pauseButton = document.getElementById('pauseButton');
pauseButton.style.display = 'inline-block';
pauseButton.textContent = '心拍数上げタイム中...';
pauseButton.disabled = true;
pauseButton.style.opacity = '0.5';
pauseButton.style.cursor = 'not-allowed';
// 準備時間中の表示を開始
this.showPreparationScreen();
// しきい値コントロールはプレイ中も表示したまま
this.updateScore();
this.gameLoop();
}
togglePause() {
// 心拍数上げタイム中はポーズ不可
if (this.gameState === 'preparation') {
console.log('心拍数上げタイム中はポーズできません');
return;
}
if (this.gameState === 'playing') {
this.gameState = 'paused';
this.pauseBGM(); // BGM一時停止
document.getElementById('pauseButton').textContent = '再開';
} else if (this.gameState === 'paused') {
this.gameState = 'playing';
this.playBGM(); // BGM再開
document.getElementById('pauseButton').textContent = 'ポーズ';
this.gameLoop();
}
}
shoot() {
if (this.gameState !== 'playing' && this.gameState !== 'preparation') return;
// 3発連続で発射
for (let i = 0; i < 3; i++) {
setTimeout(() => {
const bullet = {
x: this.player.x + (i - 1) * 8, // 左右に少しずらして発射
y: this.player.y - this.player.height/2,
width: 4,
height: 10,
speed: 8,
damage: 1 // プレイヤーの弾の威力
};
const bulletSVG = this.createBulletSVG(bullet, '#00ff00');
document.getElementById('playerBullets').appendChild(bulletSVG);
bullet.element = bulletSVG;
this.playerBullets.push(bullet);
}, i * 50); // 50msずつ遅らせて発射
}
}
createBulletSVG(bullet, color) {
const rect = document.createElementNS('http://www.w3.org/2000/svg', 'rect');
rect.setAttribute('x', bullet.x - bullet.width/2);
rect.setAttribute('y', bullet.y - bullet.height/2);
rect.setAttribute('width', bullet.width);
rect.setAttribute('height', bullet.height);
rect.setAttribute('fill', color);
rect.setAttribute('class', 'bullet');
rect.style.color = color;
return rect;
}
gameLoop(currentTime = 0) {
if (this.gameState !== 'playing' && this.gameState !== 'preparation') return;
const deltaTime = currentTime - this.lastTime;
this.lastTime = currentTime;
this.update(deltaTime);
this.updateAnimations();
requestAnimationFrame((time) => this.gameLoop(time));
}
update(deltaTime) {
// 準備時間中の処理
if (this.gameState === 'preparation') {
this.updatePreparationTimer();
this.updatePlayer();
this.updatePlayerInvulnerability(deltaTime);
this.updateBullets();
this.updateExplosions();
this.updateStars();
return; // 敵の処理はスキップ
}
// 通常のゲーム処理
this.updatePlayer();
this.updatePlayerInvulnerability(deltaTime);
this.updateBullets();
this.updateEnemies(deltaTime);
this.updateBoss(deltaTime);
this.updateExplosions();
this.updateStars();
this.updateGameTime();
this.checkCollisions();
this.checkBossSpawn();
this.checkWinCondition();
}
updatePlayer() {
// 左移動: 矢印キー左 または Aキー
if ((this.keys['ArrowLeft'] || this.keys['KeyA']) && this.player.x > this.player.width/2) {
this.player.x -= this.player.speed;
}
// 右移動: 矢印キー右 または Dキー
if ((this.keys['ArrowRight'] || this.keys['KeyD']) && this.player.x < this.gameWidth - this.player.width/2) {
this.player.x += this.player.speed;
}
// プレイヤーの位置を更新(スケールも維持)
const playerElement = document.querySelector('#player .player-ship');
if (playerElement) {
const scaleX = this.player.width / 64;
const scaleY = this.player.height / 64;
playerElement.setAttribute('transform',
`translate(${this.player.x - this.player.width/2}, ${this.player.y - this.player.height/2}) scale(${scaleX}, ${scaleY})`);
}
// 当たり判定ボックスの表示を更新
this.updateCollisionBoxes();
}
updateCollisionBoxes() {
if (!this.showCollisionBoxes) {
this.removeCollisionBoxes();
return;
}
// 既存のボックスを削除
this.removeCollisionBoxes();
// 新しいボックスを追加
const collisionGroup = document.createElementNS('http://www.w3.org/2000/svg', 'g');
collisionGroup.setAttribute('id', 'playerCollisionBoxes');
this.player.collisionBoxes.forEach((box, index) => {
const rect = document.createElementNS('http://www.w3.org/2000/svg', 'rect');
rect.setAttribute('x', this.player.x + box.x);
rect.setAttribute('y', this.player.y + box.y);
rect.setAttribute('width', box.width);
rect.setAttribute('height', box.height);
rect.setAttribute('fill', 'rgba(255, 0, 0, 0.3)');
rect.setAttribute('stroke', '#ff0000');
rect.setAttribute('stroke-width', '1');
rect.setAttribute('class', 'collision-box');
collisionGroup.appendChild(rect);
});
document.getElementById('gameCanvas').appendChild(collisionGroup);
}
removeCollisionBoxes() {
const existingBoxes = document.getElementById('playerCollisionBoxes');
if (existingBoxes) {
existingBoxes.remove();
}
}
updatePlayerInvulnerability(deltaTime) {
if (this.player.invulnerable) {
this.player.invulnerableTime += deltaTime;
if (this.player.invulnerableTime > 1000) { // 1秒間無敵
this.player.invulnerable = false;
this.player.invulnerableTime = 0;
}
}
}
updateBullets() {
// プレイヤーの弾
for (let i = this.playerBullets.length - 1; i >= 0; i--) {
const bullet = this.playerBullets[i];
bullet.y -= bullet.speed;
bullet.element.setAttribute('y', bullet.y - bullet.height/2);
if (bullet.y < 0) {
bullet.element.remove();
this.playerBullets.splice(i, 1);
}
}
// 敵の弾
for (let i = this.enemyBullets.length - 1; i >= 0; i--) {
const bullet = this.enemyBullets[i];
// 散弾(velocityがある場合)とそうでない場合を分ける
if (bullet.velocityX !== undefined && bullet.velocityY !== undefined) {
// 散弾の移動
bullet.x += bullet.velocityX;
bullet.y += bullet.velocityY;
bullet.element.setAttribute('x', bullet.x - bullet.width/2);
bullet.element.setAttribute('y', bullet.y - bullet.height/2);
} else {
// 通常の弾の移動
bullet.y += bullet.speed;
bullet.element.setAttribute('y', bullet.y - bullet.height/2);
}
// 画面外に出た弾を削除
if (bullet.y > this.gameHeight || bullet.y < 0 ||
bullet.x < 0 || bullet.x > this.gameWidth) {
bullet.element.remove();
this.enemyBullets.splice(i, 1);
}
}
}
updateEnemies(deltaTime) {
this.enemyMoveTimer += deltaTime;
this.enemyShootTimer += deltaTime;
// 敵の移動
if (this.enemyMoveTimer > 1000) {
this.enemyMoveTimer = 0;
let shouldMoveDown = false;
// 端にいる敵をチェック
for (const enemy of this.enemies) {
if ((this.enemyDirection > 0 && enemy.x > this.gameWidth - 50) ||
(this.enemyDirection < 0 && enemy.x < 50)) {
shouldMoveDown = true;
break;
}
}
if (shouldMoveDown) {
this.enemyDirection *= -1;
this.enemies.forEach(enemy => {
enemy.y += 20;
enemy.element.setAttribute('transform',
`translate(${enemy.x - enemy.width/2}, ${enemy.y - enemy.height/2})`);
});
} else {
this.enemies.forEach(enemy => {
enemy.x += this.enemyDirection * 20;
enemy.element.setAttribute('transform',
`translate(${enemy.x - enemy.width/2}, ${enemy.y - enemy.height/2})`);
});
}
}
// 敵の射撃
if (this.enemyShootTimer > 1500 && this.enemies.length > 0) {
this.enemyShootTimer = 0;
const shootingEnemy = this.enemies[Math.floor(Math.random() * this.enemies.length)];
this.enemyShoot(shootingEnemy);
}
}
updateBoss(deltaTime) {
if (this.bosses.length === 0) return;
// 全てのボス敵を更新
for (let i = 0; i < this.bosses.length; i++) {
const boss = this.bosses[i];
// ボスの移動
boss.x += boss.moveDirection * 1;
if (boss.x <= boss.width/2 || boss.x >= this.gameWidth - boss.width/2) {
boss.moveDirection *= -1;
}
// ボスの射撃(各ボス固有の射撃間隔を使用)
boss.shootTimer += deltaTime;
if (boss.shootTimer > boss.shootInterval) {
boss.shootTimer = 0;
this.bossShoot(boss);
console.log(`ボス${boss.bossId}が射撃しました`);
}
// ボスの位置を更新
boss.element.setAttribute('transform',
`translate(${boss.x - boss.width/2}, ${boss.y - boss.height/2})`);
// 体力バーを更新
const healthBar = boss.element.querySelector('.boss-health-bar');
if (healthBar) {
healthBar.setAttribute('width', 60 * (boss.health / boss.maxHealth));
}
}
}
enemyShoot(enemy) {
const bullet = {
x: enemy.x,
y: enemy.y + enemy.height/2,
width: 4,
height: 8,
speed: 3
};
const bulletSVG = this.createBulletSVG(bullet, '#ff0000');
document.getElementById('enemyBullets').appendChild(bulletSVG);
bullet.element = bulletSVG;
this.enemyBullets.push(bullet);
}
bossShoot(boss) {
// ボスIDに基づいて異なる射撃パターンを設定
const bossId = boss.bossId || 0;
const bulletCount = 5 + (bossId % 2) * 2; // ボス0,2,4は5発、ボス1,3,5は7発
const spreadAngle = Math.PI / 3 + (bossId % 2) * (Math.PI / 6); // 角度も変える
const startAngle = -spreadAngle / 2;
const bulletColor = bossId === 0 ? '#ff00ff' : (bossId % 2 === 0 ? '#ff4400' : '#44ff00');
for (let i = 0; i < bulletCount; i++) {
const angle = startAngle + (spreadAngle / (bulletCount - 1)) * i;
const bullet = {
x: boss.x,
y: boss.y + boss.height/2,
width: 6,
height: 12,
speed: 4,
velocityX: Math.sin(angle) * 4, // X方向の速度
velocityY: Math.cos(angle) * 4 // Y方向の速度
};
const bulletSVG = this.createBulletSVG(bullet, bulletColor);
document.getElementById('enemyBullets').appendChild(bulletSVG);
bullet.element = bulletSVG;
this.enemyBullets.push(bullet);
}
}
// 2匹のボス敵を生成する関数
spawnTwoBosses() {
// 複数ボス生成が既に進行中の場合は実行しない
if (this.spawningMultipleBosses) {
console.log('複数ボス生成が既に進行中です');
return;
}
this.spawningMultipleBosses = true;
console.log('2匹のボス敵を生成します!');
// 警告メッセージを表示
this.showBossMultipleAppearanceEffect();
setTimeout(() => {
// 左側のボス
this.createBossAtPosition(this.gameWidth * 0.25, 100);
// 右側のボス
this.createBossAtPosition(this.gameWidth * 0.75, 100);
this.spawningMultipleBosses = false;
console.log(`2匹のボス敵を生成完了!現在のボス数: ${this.bosses.length}`);
}, 1500);
}
// 指定位置にボス敵を作成
createBossAtPosition(x, y) {
// ボスの番号に基づいて異なる射撃間隔を設定
const bossIndex = this.bosses.length;
const baseShootInterval = 2400;
const shootInterval = baseShootInterval + (bossIndex * 400); // 各ボス400ms間隔をずらす
const initialDelay = bossIndex * 800; // 初期射撃タイミングも大きくずらす
this.bosses.push({
x: x,
y: y,
width: 80,
height: 60,
health: 10,
maxHealth: 10,
moveDirection: Math.random() > 0.5 ? 1 : -1, // ランダムな初期方向
shootTimer: initialDelay, // 初期射撃遅延を大きくずらす
shootInterval: shootInterval, // 各ボス固有の射撃間隔
bossId: bossIndex // ボス識別用ID
});
const bossSVG = this.createBossSVGAtPosition(x, y);
document.getElementById('enemies').appendChild(bossSVG);
this.bosses[this.bosses.length - 1].element = bossSVG;
console.log(`ボス${bossIndex}を作成: 射撃間隔=${shootInterval}ms, 初期遅延=${initialDelay}ms`);
}
// 指定位置にボスSVGを作成
createBossSVGAtPosition(x, y) {
const boss = this.bosses[this.bosses.length - 1];
const g = document.createElementNS('http://www.w3.org/2000/svg', 'g');
g.setAttribute('class', 'boss-ship');
g.setAttribute('transform', `translate(${x - boss.width/2}, ${y - boss.height/2})`);
// PNG画像を読み込み
const image = document.createElementNS('http://www.w3.org/2000/svg', 'image');
image.setAttribute('href', 'svg/boss.png');
image.setAttribute('x', '0');
image.setAttribute('y', '0');