今回はゲームクリア画面とゲームオーバー画面からゲームを再開する処理を書きます。
ただ、割と書き換えています。
書き換えるところを抜粋して書きます。
function draw() {
if (gameState === "start") {
showStartScreen(); // スタート画面を表示
} else if (gameState === "play") {
showandmove();
if (areAllEnemiesDefeated(Enemy)) {
gameState = "clear"; // ゲームクリア状態にする
}
if (!player.isAlive) {
gameState = "gameover"; // ゲームオーバー状態にする
}
time_limit();
fill(0);
textSize(24);
text("Score: " + score, 10, 30);
}else if (gameState === "clear" || gameState === "gameover") {
textSize(32);
textAlign(CENTER, CENTER);
fill(0);
text("Press ENTER to Restart", width / 2, height / 2);
}
}
function time_limit(){
let elapsedTime = millis() - startTime; // 経過時間を計算
let remainingTime = timeLimit - elapsedTime; // 残り時間を計算
if (remainingTime > 0) {
// ゲームのロジックをここに記述
textSize(32);
fill(0);
text("残り時間: " + floor(remainingTime / 1000), 10, 70); // 残り時間を秒で表示
} else {
gameState = "gameover";
}
}
// キーボードイベントを処理する関数
function keyPressed() {
if ((gameState === "start" || gameState === "clear" || gameState === "gameover") && keyCode === ENTER) {
resetGame(); // ゲームをリセットする
} else if (gameState === "play" && key === ' ') {
let bullet = new Bullet(player.x + 20, player.y);
bullets.push(bullet);
}
}
function resetGame() {
gameState = "play"; // ゲームの状態をプレイ中に戻す
score = 0;
startTime = millis(); // 開始時の時間をリセット
// オブジェクトをリセット
player = new Mine(width / 2, height - 40, gridSize);
player.isAlive = true;
bullets = [];
enemy_bullets = [];
enemies = [];
// 敵を再生成し、ランダムな発射タイミングと待機時間を設定
for (let row = 0; row < rows; row++) {
for (let col = 0; col < cols; col++) {
let x = col * (enemyWidth + spacing) + 50;
let y = row * (enemyHeight + spacing) + 50;
let enemy = new Enemy(x, y, enemyWidth, enemyHeight, enemySpeed);
enemies.push(enemy);
}
}
}
ただ、このままだと再開したときに敵が一斉に弾を発射します。
少し難易度が下がりますが、開始直後のちょっとの間は弾を発射しないようにします。
// 敵クラス
class Enemy {
constructor(x, y, w, h, speed) {
this.x = x;
this.y = y;
this.w = w;
this.h = h;
this.speed = speed;
this.lastShotTime = frameCount; // 発射タイミングの初期化
this.shootInterval = random(60, 480); // 発射間隔
this.shootDelay = random(120, 480); // 初回発射までの待機時間をランダムに設定
}
// 敵を描画
show() {
fill(255, 0, 0);
rect(this.x, this.y, this.w, this.h);
}
// 敵を移動させる
move(direction) {
this.x += direction * enemySpeed;
}
// 敵を下に移動させる
shiftDown() {
this.y += 20;
}
tryShoot() {
// 待機時間が経過してから発射
if (frameCount > this.lastShotTime + this.shootDelay &&
frameCount - this.lastShotTime > this.shootInterval) {
let e_bullet = new Enemy_Bullet(this.x + this.w / 2, this.y);
enemy_bullets.push(e_bullet);
this.lastShotTime = frameCount;
this.shootInterval = random(60, 480); // 次の発射間隔をランダムに再設定
}
}
}
shootDelay変数を追加しました。
tryShoot()メソッドのところで使って以前のif文の処理に追加する形でランダムで値が決まったshootDelay変数とlastShotTime変数を足した数がframeCountより小さかったら弾を発射するといった処理になっています
コメント