ToroVerse

作品:シューティングゲーム

この回でできるようになること

自機を動かし、弾を撃ち、次々に現れる敵を、倒す。最後には、大きなボスが、待っている。シューティングゲームを、最初から最後まで、作り上げます。絵のアニメーション、効果音と音楽、爆発、何種類もの敵、ハイスコアの保存。これまでに身に付けたものを、1つの作品に、組み上げる回です。

sketch.js
let ships;
let bossImage;
let shootSound;
let boomSound;
let bgm;
let bgmPlaying = false;

let scene = 'title';
let message = '';

let player;
let bullets = [];
let enemyBullets = [];
let enemies = [];
let particles = [];

let score = 0;
let highScore = 0;
let lives = 3;
let timer = 0;
let bossAppeared = false;
let shootWait = 0;
let boomWait = 0;

async function setup() {
  createCanvas(400, 500);
  ships = await loadImage('ships.png');
  bossImage = await loadImage('boss.png');
  shootSound = await loadSound('shoot.wav');
  boomSound = await loadSound('boom.wav');
  bgm = await loadSound('bgm.wav');
  bgm.loop();
  bgm.amp(0.25);
  shootSound.amp(0.4);

  let saved = getItem('shooter_highScore');
  if (saved !== null) {
    highScore = saved;
  }
  player = new Player();
}

function draw() {
  background(10, 10, 30);
  drawStars();

  if (scene === 'title') {
    drawTitle();
  } else if (scene === 'play') {
    updateGame();
    drawGame();
  } else if (scene === 'result') {
    drawGame();
    drawResult();
  }
}

// 流れる星。位置は、番号から計算する
function drawStars() {
  noStroke();
  fill(255, 255, 255, 150);
  for (let i = 0; i < 40; i++) {
    let x = (i * 97) % 400;
    let y = (i * 53 + frameCount * (1 + i % 3)) % 500;
    circle(x, y, 1 + i % 3);
  }
}

function startGame() {
  player = new Player();
  bullets = [];
  enemyBullets = [];
  enemies = [];
  particles = [];
  score = 0;
  lives = 3;
  timer = 0;
  bossAppeared = false;
  shootWait = 0;
}

function updateGame() {
  timer += 1;
  if (shootWait > 0) {
    shootWait -= 1;
  }
  if (boomWait > 0) {
    boomWait -= 1;
  }

  player.update();

  // 弾を撃つ
  if (keyIsDown(' ') && shootWait === 0) {
    bullets.push(new Bullet(player.x, player.y - 24, -9));
    shootSound.play();
    shootWait = 10;
  }

  // 敵を出す。1500フレームたったら、ボスを出す
  if (bossAppeared === false) {
    let interval = max(20, 50 - floor(timer / 300) * 6);
    if (timer % interval === 0) {
      spawnEnemy();
    }
    if (timer > 1500) {
      enemies.push(new Boss());
      bossAppeared = true;
    }
  }

  // 自分の弾
  for (let i = bullets.length - 1; i >= 0; i--) {
    bullets[i].update();
    if (bullets[i].isGone()) {
      bullets.splice(i, 1);
    }
  }

  // 敵の弾。自機に当たったら、消す
  for (let i = enemyBullets.length - 1; i >= 0; i--) {
    enemyBullets[i].update();
    if (dist(enemyBullets[i].x, enemyBullets[i].y, player.x, player.y) < 18) {
      hitPlayer();
      enemyBullets.splice(i, 1);
    } else if (enemyBullets[i].isGone()) {
      enemyBullets.splice(i, 1);
    }
  }

  // 敵
  for (let i = enemies.length - 1; i >= 0; i--) {
    let enemy = enemies[i];
    enemy.update();

    // 自分の弾との当たり
    for (let j = bullets.length - 1; j >= 0; j--) {
      if (enemy.hp > 0 && dist(bullets[j].x, bullets[j].y, enemy.x, enemy.y) < enemy.r) {
        enemy.hp -= 1;
        bullets.splice(j, 1);
        explode(enemy.x, enemy.y + enemy.r * 0.5, 3);
      }
    }

    // 自機との当たり
    if (dist(player.x, player.y, enemy.x, enemy.y) < enemy.r + 14) {
      hitPlayer();
    }

    if (enemy.hp <= 0) {
      score += enemy.points;
      explode(enemy.x, enemy.y, enemy.r);
      if (enemy.isBoss) {
        finish('クリア!');
      }
      enemies.splice(i, 1);
    } else if (enemy.isGone()) {
      enemies.splice(i, 1);
    }
  }

  // 爆発の粒
  for (let i = particles.length - 1; i >= 0; i--) {
    particles[i].update();
    if (particles[i].isDead()) {
      particles.splice(i, 1);
    }
  }
}

function spawnEnemy() {
  let x = random(40, 360);
  let pick = random(1);
  if (pick < 0.55) {
    enemies.push(new Enemy(x));
  } else if (pick < 0.85) {
    enemies.push(new ZigZag(x));
  } else {
    enemies.push(new Tank(x));
  }
}

// 自機が、敵や、敵の弾に当たった
function hitPlayer() {
  if (player.safeTime === 0) {
    lives -= 1;
    player.safeTime = 90;
    explode(player.x, player.y, 20);
    if (lives <= 0) {
      finish('ゲームオーバー');
    }
  }
}

// 爆発。粒をまき、音を鳴らす
function explode(x, y, count) {
  for (let i = 0; i < count; i++) {
    particles.push(new Particle(x, y));
  }
  if (count >= 10 && boomWait === 0) {
    boomSound.play();
    boomWait = 6;
  }
}

// ゲームを終わらせ、ハイスコアを保存する
function finish(text) {
  message = text;
  scene = 'result';
  if (score > highScore) {
    highScore = score;
    storeItem('shooter_highScore', highScore);
  }
}

function drawGame() {
  for (let i = 0; i < bullets.length; i++) {
    bullets[i].show();
  }
  for (let i = 0; i < enemyBullets.length; i++) {
    enemyBullets[i].show();
  }
  for (let i = 0; i < enemies.length; i++) {
    enemies[i].show();
  }
  for (let i = 0; i < particles.length; i++) {
    particles[i].show();
  }
  if (lives > 0) {
    player.show();
  }

  noStroke();
  fill(255);
  textAlign(LEFT, BASELINE);
  textSize(16);
  text(`スコア: ${score}`, 12, 24);
  text(`ハイスコア: ${highScore}`, 150, 24);
  text(`残り: ${lives}`, 330, 24);
}

function drawTitle() {
  player.show();
  noStroke();
  fill(255);
  textAlign(CENTER, CENTER);
  textSize(32);
  text('シューティング', 200, 160);
  textSize(16);
  text('← → ↑ ↓: 動く   スペース: 撃つ', 200, 230);
  text('エンターキーで、スタート', 200, 290);
  text(`ハイスコア: ${highScore}`, 200, 340);
}

function drawResult() {
  noStroke();
  fill(0, 0, 0, 150);
  rect(0, 0, 400, 500);
  fill(255);
  textAlign(CENTER, CENTER);
  textSize(32);
  text(message, 200, 190);
  textSize(22);
  text(`スコア: ${score}`, 200, 245);
  textSize(16);
  text('エンターキーで、タイトルへ', 200, 310);
}

function keyPressed() {
  if (key === 'Enter') {
    if (scene === 'title') {
      // 最初の操作で、音を出す準備をして、音楽を流す
      userStartAudio();
      if (bgmPlaying === false) {
        bgm.play();
        bgmPlaying = true;
      }
      startGame();
      scene = 'play';
    } else if (scene === 'result') {
      scene = 'title';
    }
  }
}

class Player {
  constructor() {
    this.x = 200;
    this.y = 440;
    this.safeTime = 0;
  }

  update() {
    if (keyIsDown(LEFT_ARROW)) {
      this.x -= 5;
    }
    if (keyIsDown(RIGHT_ARROW)) {
      this.x += 5;
    }
    if (keyIsDown(UP_ARROW)) {
      this.y -= 4;
    }
    if (keyIsDown(DOWN_ARROW)) {
      this.y += 4;
    }
    this.x = max(24, min(376, this.x));
    this.y = max(60, min(470, this.y));

    if (this.safeTime > 0) {
      this.safeTime -= 1;
    }
  }

  show() {
    // 当たった直後は、点滅させる
    if (this.safeTime === 0 || frameCount % 6 < 3) {
      let frame = floor(frameCount / 4) % 2;
      image(ships, this.x - 32, this.y - 32, 64, 64, frame * 64, 0, 64, 64);
    }
  }
}

class Bullet {
  constructor(x, y, speedY) {
    this.x = x;
    this.y = y;
    this.speedY = speedY;
  }

  update() {
    this.y += this.speedY;
  }

  isGone() {
    return this.y < -20 || this.y > 520;
  }

  show() {
    noStroke();
    if (this.speedY < 0) {
      fill(255, 240, 150);
      rect(this.x - 2, this.y - 8, 4, 16, 2);
    } else {
      fill(255, 110, 140);
      circle(this.x, this.y, 10);
    }
  }
}

// 敵の、親クラス。まっすぐ、下へ進む
class Enemy {
  constructor(x) {
    this.x = x;
    this.y = -30;
    this.speed = 2;
    this.hp = 1;
    this.r = 22;
    this.points = 10;
    this.row = 1;
    this.isBoss = false;
  }

  update() {
    this.y += this.speed;
  }

  isGone() {
    return this.y > 540;
  }

  show() {
    let frame = floor(frameCount / 10) % 2;
    image(ships, this.x - 32, this.y - 32, 64, 64, frame * 64, this.row * 64, 64, 64);
  }
}

// 左右に、行ったり来たりしながら、進む敵
class ZigZag extends Enemy {
  constructor(x) {
    super(x);
    this.row = 2;
    this.points = 20;
    this.dir = 3;
  }

  update() {
    super.update();
    this.x += this.dir;
    if (this.x < 30 || this.x > 370) {
      this.dir = -this.dir;
    }
  }
}

// 遅いが、何発も当てないと、倒せない敵
class Tank extends Enemy {
  constructor(x) {
    super(x);
    this.row = 3;
    this.speed = 1;
    this.hp = 4;
    this.r = 24;
    this.points = 50;
  }
}

// ボス。上のほうで、左右に動きながら、弾を撃つ
class Boss extends Enemy {
  constructor() {
    super(200);
    this.y = -60;
    this.hp = 40;
    this.r = 48;
    this.points = 500;
    this.dir = 2;
    this.isBoss = true;
  }

  update() {
    if (this.y < 100) {
      this.y += 1;
    } else {
      this.x += this.dir;
      if (this.x < 70 || this.x > 330) {
        this.dir = -this.dir;
      }
      if (frameCount % 45 === 0) {
        enemyBullets.push(new Bullet(this.x - 40, this.y + 30, 4));
        enemyBullets.push(new Bullet(this.x, this.y + 40, 5));
        enemyBullets.push(new Bullet(this.x + 40, this.y + 30, 4));
      }
    }
  }

  show() {
    let frame = floor(frameCount / 15) % 2;
    image(bossImage, this.x - 64, this.y - 48, 128, 96, frame * 128, 0, 128, 96);

    // 残りの体力
    noStroke();
    fill(80, 80, 100);
    rect(100, 40, 200, 8);
    fill(255, 90, 120);
    rect(100, 40, this.hp * 5, 8);
  }
}

class Particle {
  constructor(x, y) {
    this.x = x;
    this.y = y;
    this.speedX = random(-4, 4);
    this.speedY = random(-4, 4);
    this.life = 30;
  }

  update() {
    this.x += this.speedX;
    this.y += this.speedY;
    this.speedX *= 0.92;
    this.speedY *= 0.92;
    this.life -= 1;
  }

  isDead() {
    return this.life <= 0;
  }

  show() {
    noStroke();
    fill(255, 150 + this.life * 3, 60, this.life * 8);
    circle(this.x, this.y, this.life / 4);
  }
}

一度、キャンバスをクリックしてから、エンターキーを押すと、始まります。音が出ますので、音量に、気を付けてください。

キー 操作
←、→、↑、↓ 自機を動かす
スペース 押している間、弾を撃つ

敵は、3種類です。赤い敵は、まっすぐ、下りてきます。紫の敵は、左右に、行ったり来たりします。緑の敵は、遅いけれど、何発も当てないと、倒せません。しばらく戦うと、ボスが、現れます。倒すと、クリアです。3回、当たると、ゲームオーバーです。


この回が終わると、次のことができるようになります。

  • 大きな作品を、部品に分けて、順番に組み上げる
  • 自機、弾、敵、爆発を、それぞれクラスにして、配列で管理する
  • 継承を使って、動きの違う敵を、少ない手間で増やす
  • スプライト、効果音、音楽、保存を、ゲームに組み込む
  • 複数の配列の間で、当たり判定をする

全体を、設計する

大きな作品は、いきなり、書き始めません。まず、何があるかを、書き出します。

登場するもの

もの クラス 数 管理の仕方
自機 Player 1 変数
自分の弾 Bullet たくさん 配列 bullets
敵の弾 Bullet たくさん 配列 enemyBullets
敵(3種類と、ボス) Enemy と、その子クラス たくさん 配列 enemies
爆発の粒 Particle たくさん 配列 particles

たくさんあるものは、どれも、生まれて、動いて、消えるという、同じ一生を、たどります。そこで、どのクラスにも、同じ名前のメソッドを、持たせます。

メソッド 役割
update() 1フレーム分、動く
show() 自分を描く
isGone()、isDead() もう、消えるべきかを、返す

ゲームの流れ

場面 すること
タイトル 題名と、遊び方を見せる。エンターキーで、始まる
プレイ ゲームを進め、描く
結果 ゲームオーバーか、クリアかを見せる。ハイスコアを、保存する

当たり判定の、組み合わせ

「何と、何が、当たるか」を、先に、決めておきます。

当たるもの 当たると
自分の弾 と 敵 敵の体力が減る。0 になったら、爆発して、消える。弾も、消える
敵 と 自機 自機が、やられる
敵の弾 と 自機 自機が、やられる。弾は、消える

自分の弾と、敵の弾は、当たりません。敵どうしも、当たりません。必要な組み合わせだけを、調べます。

作る順番

順番 作るもの
1 自機と、弾
2 敵、当たり判定、爆発
3 継承で、敵の種類を増やす
4 ボス、敵の弾、自機のやられ
5 音、場面の切り替え、ハイスコア

遊びの中心から、作ります。「動かして、撃つ」が、気持ちよくなってから、次へ、進みます。

使う素材

ファイル 中身
ships.png 自機と、3種類の敵の絵。64 × 64 のコマが、横に2つ、縦に4つ
boss.png ボスの絵。128 × 96 のコマが、横に2つ
shoot.wav 弾を撃つ音
boom.wav 爆発の音
bgm.wav 繰り返して流す、音楽

ships.png は、行ごとに、別のキャラクターが、並んでいます。

行 キャラクター
0 自機
1 赤い敵
2 紫の敵
3 緑の敵

横の2コマは、少しずつ違う絵です。交互に表示して、動いているように、見せます。

ステップ1:自機と、弾

自機を、矢印キーで動かし、スペースキーで、弾を撃ちます。

sketch.js
let ships;
let player;
let bullets = [];
let shootWait = 0;

async function setup() {
  createCanvas(400, 500);
  ships = await loadImage('ships.png');
  player = new Player();
}

function draw() {
  background(10, 10, 30);

  if (shootWait > 0) {
    shootWait -= 1;
  }
  player.update();

  // 弾を撃つ
  if (keyIsDown(' ') && shootWait === 0) {
    bullets.push(new Bullet(player.x, player.y - 24, -9));
    shootWait = 10;
  }

  for (let i = bullets.length - 1; i >= 0; i--) {
    bullets[i].update();
    bullets[i].show();
    if (bullets[i].isGone()) {
      bullets.splice(i, 1);
    }
  }

  player.show();
}

class Player {
  constructor() {
    this.x = 200;
    this.y = 440;
    this.safeTime = 0;
  }

  update() {
    if (keyIsDown(LEFT_ARROW)) {
      this.x -= 5;
    }
    if (keyIsDown(RIGHT_ARROW)) {
      this.x += 5;
    }
    if (keyIsDown(UP_ARROW)) {
      this.y -= 4;
    }
    if (keyIsDown(DOWN_ARROW)) {
      this.y += 4;
    }
    this.x = max(24, min(376, this.x));
    this.y = max(60, min(470, this.y));

    if (this.safeTime > 0) {
      this.safeTime -= 1;
    }
  }

  show() {
    // 当たった直後は、点滅させる
    if (this.safeTime === 0 || frameCount % 6 < 3) {
      let frame = floor(frameCount / 4) % 2;
      image(ships, this.x - 32, this.y - 32, 64, 64, frame * 64, 0, 64, 64);
    }
  }
}

class Bullet {
  constructor(x, y, speedY) {
    this.x = x;
    this.y = y;
    this.speedY = speedY;
  }

  update() {
    this.y += this.speedY;
  }

  isGone() {
    return this.y < -20 || this.y > 520;
  }

  show() {
    noStroke();
    if (this.speedY < 0) {
      fill(255, 240, 150);
      rect(this.x - 2, this.y - 8, 4, 16, 2);
    } else {
      fill(255, 110, 140);
      circle(this.x, this.y, 10);
    }
  }
}

キャンバスをクリックしてから、矢印キーと、スペースキーを、押してください。自機の下で、炎が、ちらちらと、動いています。

自機のクラス

javascript
update() {
  if (keyIsDown(LEFT_ARROW)) {
    this.x -= 5;
  }
  // 右、上、下も、同じ
  this.x = max(24, min(376, this.x));
  this.y = max(60, min(470, this.y));
}

max(24, min(376, this.x)) は、x を、24 から 376 の範囲に、収めます。内側の min で、376 より大きくならないようにし、外側の max で、24 より小さくならないように、しています。

スプライトを、コマ送りで描く

sketch.js
let frame = floor(frameCount / 4) % 2;
image(ships, this.x - 32, this.y - 32, 64, 64, frame * 64, 0, 64, 64);

frame は、4 フレームごとに、0 と 1 が、入れ替わります。image の、後ろの4つの数字で、シートの中の、どのコマを切り出すかを、決めています。frame * 64 が、切り出す x。0 が、切り出す y(0 行目)です。


this.x、this.y は、自機の中心です。絵は 64 × 64 なので、32 ずつ引いて、左上の角を、求めています。

連射の間隔

sketch.js
if (keyIsDown(' ') && shootWait === 0) {
  bullets.push(new Bullet(player.x, player.y - 24, -9));
  shootWait = 10;
}

スペースキーを、押している間、弾を撃ちます。ただし、毎フレーム撃つと、1秒に 60 発も出て、弾が、つながった線に、なってしまいます。


shootWait は、「次に撃てるまでの、残りフレーム数」です。撃ったら、10 にします。毎フレーム、1 ずつ減らし、0 のときだけ、撃てます。1秒に、6 発です。

弾のクラス

弾は、縦に、まっすぐ進みます。speedY が、マイナスなら、上へ。プラスなら、下へ。自分の弾にも、敵の弾にも、同じクラスを、使います。

sketch.js
isGone() {
  return this.y < -20 || this.y > 520;
}

画面の外へ出たら、true を返します。draw の中で、それを見て、配列から、取り除きます。取り除かないと、見えない弾が、配列に、たまり続けます。

ステップ2:敵と、当たり判定と、爆発

敵を出し、弾を当てて、倒せるようにします。

敵のクラス

javascript
class Enemy {
  constructor(x) {
    this.x = x;
    this.y = -30;
    this.speed = 2;
    this.hp = 1;
    this.r = 22;
    this.points = 10;
    this.row = 1;
    this.isBoss = false;
  }
}
プロパティ 意味
x、y 位置。画面の上の外(y = −30)から、現れる
speed 下りてくる速さ
hp 体力。弾が当たるたびに、1 減る
r 当たり判定の半径
points 倒したときに入る点
row スプライトシートの、何行目の絵を使うか
isBoss ボスかどうか

速さ、体力、点、絵。敵の個性は、すべて、プロパティに、入っています。あとで、種類を増やすとき、これが、効いてきます。

弾と敵の、当たり判定

敵の配列と、弾の配列。2つの配列の、すべての組み合わせを、調べます。

sketch.js
for (let i = enemies.length - 1; i >= 0; i--) {
  let enemy = enemies[i];
  enemy.update();
  enemy.show();

  // 自分の弾との当たり
  for (let j = bullets.length - 1; j >= 0; j--) {
    if (enemy.hp > 0 && dist(bullets[j].x, bullets[j].y, enemy.x, enemy.y) < enemy.r) {
      enemy.hp -= 1;
      bullets.splice(j, 1);
      explode(enemy.x, enemy.y + enemy.r * 0.5, 3);
    }
  }

  if (enemy.hp <= 0) {
    score += enemy.points;
    explode(enemy.x, enemy.y, enemy.r);
    enemies.splice(i, 1);
  } else if (enemy.isGone()) {
    enemies.splice(i, 1);
  }
}

外側のループで、敵を1体ずつ、取り出します。内側のループで、その敵と、すべての弾を、比べます。


弾と、敵の中心との距離が、敵の半径 r より小さければ、当たりです。

当たったら すること
敵 体力を、1 減らす
弾 配列から、取り除く
見た目 小さな爆発(粒を 3 つ)を出す

どちらのループも、後ろから前へ、回しています。途中で、要素を取り除くからです。

すぐには、敵を取り除かない

弾が当たった瞬間に、敵を配列から取り除くのでは、ありません。体力を減らすだけに、しておきます。


内側のループが終わったあとで、体力が 0 以下かを調べ、そこで、取り除きます。


内側のループの途中で、敵を取り除くと、enemy が、もう配列にいないのに、残りの弾と、比べ続けることに、なります。条件の enemy.hp > 0 は、「もう倒れた敵には、それ以上、弾を当てない」ためのものです。2発が、同時に当たっても、余分な弾は、消えずに、先へ、飛んでいきます。

爆発

倒したとき、粒を、まき散らします。

sketch.js
function explode(x, y, count) {
  for (let i = 0; i < count; i++) {
    particles.push(new Particle(x, y));
  }
}

粒は、でたらめな向きへ飛び出し、だんだん遅くなり、30 フレームで、消えます。random(最小, 最大) は、その範囲の、でたらめな数を返す関数です。


弾が当たっただけのときは、粒を 3 つ。倒したときは、敵の半径と同じ数(22 個)を、出します。同じ関数を、数を変えて、使い回しています。

sketch.js
let ships;
let player;
let bullets = [];
let enemies = [];
let particles = [];
let score = 0;
let shootWait = 0;

async function setup() {
  createCanvas(400, 500);
  ships = await loadImage('ships.png');
  player = new Player();
}

function draw() {
  background(10, 10, 30);

  if (shootWait > 0) {
    shootWait -= 1;
  }
  player.update();

  if (keyIsDown(' ') && shootWait === 0) {
    bullets.push(new Bullet(player.x, player.y - 24, -9));
    shootWait = 10;
  }

  // 50フレームごとに、敵を出す
  if (frameCount % 50 === 0) {
    enemies.push(new Enemy(random(40, 360)));
  }

  for (let i = bullets.length - 1; i >= 0; i--) {
    bullets[i].update();
    bullets[i].show();
    if (bullets[i].isGone()) {
      bullets.splice(i, 1);
    }
  }

  for (let i = enemies.length - 1; i >= 0; i--) {
    let enemy = enemies[i];
    enemy.update();
    enemy.show();

    // 自分の弾との当たり
    for (let j = bullets.length - 1; j >= 0; j--) {
      if (enemy.hp > 0 && dist(bullets[j].x, bullets[j].y, enemy.x, enemy.y) < enemy.r) {
        enemy.hp -= 1;
        bullets.splice(j, 1);
        explode(enemy.x, enemy.y + enemy.r * 0.5, 3);
      }
    }

    if (enemy.hp <= 0) {
      score += enemy.points;
      explode(enemy.x, enemy.y, enemy.r);
      enemies.splice(i, 1);
    } else if (enemy.isGone()) {
      enemies.splice(i, 1);
    }
  }

  for (let i = particles.length - 1; i >= 0; i--) {
    particles[i].update();
    particles[i].show();
    if (particles[i].isDead()) {
      particles.splice(i, 1);
    }
  }

  player.show();

  noStroke();
  fill(255);
  textSize(16);
  text(`スコア: ${score}`, 12, 24);
}

function explode(x, y, count) {
  for (let i = 0; i < count; i++) {
    particles.push(new Particle(x, y));
  }
}

class Player {
  constructor() {
    this.x = 200;
    this.y = 440;
    this.safeTime = 0;
  }

  update() {
    if (keyIsDown(LEFT_ARROW)) {
      this.x -= 5;
    }
    if (keyIsDown(RIGHT_ARROW)) {
      this.x += 5;
    }
    if (keyIsDown(UP_ARROW)) {
      this.y -= 4;
    }
    if (keyIsDown(DOWN_ARROW)) {
      this.y += 4;
    }
    this.x = max(24, min(376, this.x));
    this.y = max(60, min(470, this.y));

    if (this.safeTime > 0) {
      this.safeTime -= 1;
    }
  }

  show() {
    // 当たった直後は、点滅させる
    if (this.safeTime === 0 || frameCount % 6 < 3) {
      let frame = floor(frameCount / 4) % 2;
      image(ships, this.x - 32, this.y - 32, 64, 64, frame * 64, 0, 64, 64);
    }
  }
}

class Bullet {
  constructor(x, y, speedY) {
    this.x = x;
    this.y = y;
    this.speedY = speedY;
  }

  update() {
    this.y += this.speedY;
  }

  isGone() {
    return this.y < -20 || this.y > 520;
  }

  show() {
    noStroke();
    if (this.speedY < 0) {
      fill(255, 240, 150);
      rect(this.x - 2, this.y - 8, 4, 16, 2);
    } else {
      fill(255, 110, 140);
      circle(this.x, this.y, 10);
    }
  }
}

// 敵の、親クラス。まっすぐ、下へ進む
class Enemy {
  constructor(x) {
    this.x = x;
    this.y = -30;
    this.speed = 2;
    this.hp = 1;
    this.r = 22;
    this.points = 10;
    this.row = 1;
    this.isBoss = false;
  }

  update() {
    this.y += this.speed;
  }

  isGone() {
    return this.y > 540;
  }

  show() {
    let frame = floor(frameCount / 10) % 2;
    image(ships, this.x - 32, this.y - 32, 64, 64, frame * 64, this.row * 64, 64, 64);
  }
}

class Particle {
  constructor(x, y) {
    this.x = x;
    this.y = y;
    this.speedX = random(-4, 4);
    this.speedY = random(-4, 4);
    this.life = 30;
  }

  update() {
    this.x += this.speedX;
    this.y += this.speedY;
    this.speedX *= 0.92;
    this.speedY *= 0.92;
    this.life -= 1;
  }

  isDead() {
    return this.life <= 0;
  }

  show() {
    noStroke();
    fill(255, 150 + this.life * 3, 60, this.life * 8);
    circle(this.x, this.y, this.life / 4);
  }
}

赤い敵が、上から、下りてきます。弾を当てると、爆発して、消え、スコアが入ります。

ステップ3:継承で、敵の種類を増やす

敵が、1種類だけでは、すぐに、飽きます。動きの違う敵を、足します。

違うところだけを、書く

新しい敵は、赤い敵と、ほとんど同じです。位置があり、体力があり、下りてきて、絵を描く。違うのは、ほんの一部です。


Enemy を、親クラスにして、違うところだけを、子クラスに、書きます。

数字だけが違う敵

sketch.js
class Tank extends Enemy {
  constructor(x) {
    super(x);
    this.row = 3;
    this.speed = 1;
    this.hp = 4;
    this.r = 24;
    this.points = 50;
  }
}

Tank は、遅くて、固い敵です。super(x); で、親クラスのコンストラクタを、呼び出します。これで、Enemy と同じプロパティが、すべて、用意されます。そのあとで、違う値だけを、上書きします。


update() も、show() も、isGone() も、書いていません。親クラスのものが、そのまま、使われます。絵の行(row)を、3 に変えたので、show() は、同じプログラムのまま、緑の敵の絵を、描きます。

動きが違う敵

sketch.js
class ZigZag extends Enemy {
  constructor(x) {
    super(x);
    this.row = 2;
    this.points = 20;
    this.dir = 3;
  }

  update() {
    super.update();
    this.x += this.dir;
    if (this.x < 30 || this.x > 370) {
      this.dir = -this.dir;
    }
  }
}

ZigZag は、左右に動きながら、下りてきます。update() を、書き直しています。


super.update(); で、親クラスの update()(下へ進む)を、まず、実行します。そのあとに、横の動きを、足しています。下へ進む処理を、もう一度、書く必要は、ありません。

配列は、1つのまま

3種類の敵を、同じ配列 enemies に、入れます。

sketch.js
if (pick < 0.55) {
  enemies.push(new Enemy(x));
} else if (pick < 0.85) {
  enemies.push(new ZigZag(x));
} else {
  enemies.push(new Tank(x));
}

そして、draw の中の、敵を扱う部分は、1行も、変えていません。

sketch.js
enemy.update();
enemy.show();

enemy が、どの種類であっても、update() と show() を、呼び出すだけです。どう動くかは、それぞれのクラスが、知っています。当たり判定も、enemy.r、enemy.hp、enemy.points を、見ているだけなので、そのまま、動きます。

sketch.js
let ships;
let player;
let bullets = [];
let enemies = [];
let particles = [];
let score = 0;
let shootWait = 0;

async function setup() {
  createCanvas(400, 500);
  ships = await loadImage('ships.png');
  player = new Player();
}

function draw() {
  background(10, 10, 30);

  if (shootWait > 0) {
    shootWait -= 1;
  }
  player.update();

  if (keyIsDown(' ') && shootWait === 0) {
    bullets.push(new Bullet(player.x, player.y - 24, -9));
    shootWait = 10;
  }

  // 50フレームごとに、敵を出す
  if (frameCount % 50 === 0) {
    let x = random(40, 360);
    let pick = random(1);
    if (pick < 0.55) {
      enemies.push(new Enemy(x));
    } else if (pick < 0.85) {
      enemies.push(new ZigZag(x));
    } else {
      enemies.push(new Tank(x));
    }
  }

  for (let i = bullets.length - 1; i >= 0; i--) {
    bullets[i].update();
    bullets[i].show();
    if (bullets[i].isGone()) {
      bullets.splice(i, 1);
    }
  }

  for (let i = enemies.length - 1; i >= 0; i--) {
    let enemy = enemies[i];
    enemy.update();
    enemy.show();

    // 自分の弾との当たり
    for (let j = bullets.length - 1; j >= 0; j--) {
      if (enemy.hp > 0 && dist(bullets[j].x, bullets[j].y, enemy.x, enemy.y) < enemy.r) {
        enemy.hp -= 1;
        bullets.splice(j, 1);
        explode(enemy.x, enemy.y + enemy.r * 0.5, 3);
      }
    }

    if (enemy.hp <= 0) {
      score += enemy.points;
      explode(enemy.x, enemy.y, enemy.r);
      enemies.splice(i, 1);
    } else if (enemy.isGone()) {
      enemies.splice(i, 1);
    }
  }

  for (let i = particles.length - 1; i >= 0; i--) {
    particles[i].update();
    particles[i].show();
    if (particles[i].isDead()) {
      particles.splice(i, 1);
    }
  }

  player.show();

  noStroke();
  fill(255);
  textSize(16);
  text(`スコア: ${score}`, 12, 24);
}

function explode(x, y, count) {
  for (let i = 0; i < count; i++) {
    particles.push(new Particle(x, y));
  }
}

class Player {
  constructor() {
    this.x = 200;
    this.y = 440;
    this.safeTime = 0;
  }

  update() {
    if (keyIsDown(LEFT_ARROW)) {
      this.x -= 5;
    }
    if (keyIsDown(RIGHT_ARROW)) {
      this.x += 5;
    }
    if (keyIsDown(UP_ARROW)) {
      this.y -= 4;
    }
    if (keyIsDown(DOWN_ARROW)) {
      this.y += 4;
    }
    this.x = max(24, min(376, this.x));
    this.y = max(60, min(470, this.y));

    if (this.safeTime > 0) {
      this.safeTime -= 1;
    }
  }

  show() {
    // 当たった直後は、点滅させる
    if (this.safeTime === 0 || frameCount % 6 < 3) {
      let frame = floor(frameCount / 4) % 2;
      image(ships, this.x - 32, this.y - 32, 64, 64, frame * 64, 0, 64, 64);
    }
  }
}

class Bullet {
  constructor(x, y, speedY) {
    this.x = x;
    this.y = y;
    this.speedY = speedY;
  }

  update() {
    this.y += this.speedY;
  }

  isGone() {
    return this.y < -20 || this.y > 520;
  }

  show() {
    noStroke();
    if (this.speedY < 0) {
      fill(255, 240, 150);
      rect(this.x - 2, this.y - 8, 4, 16, 2);
    } else {
      fill(255, 110, 140);
      circle(this.x, this.y, 10);
    }
  }
}

// 敵の、親クラス。まっすぐ、下へ進む
class Enemy {
  constructor(x) {
    this.x = x;
    this.y = -30;
    this.speed = 2;
    this.hp = 1;
    this.r = 22;
    this.points = 10;
    this.row = 1;
    this.isBoss = false;
  }

  update() {
    this.y += this.speed;
  }

  isGone() {
    return this.y > 540;
  }

  show() {
    let frame = floor(frameCount / 10) % 2;
    image(ships, this.x - 32, this.y - 32, 64, 64, frame * 64, this.row * 64, 64, 64);
  }
}

// 左右に、行ったり来たりしながら、進む敵
class ZigZag extends Enemy {
  constructor(x) {
    super(x);
    this.row = 2;
    this.points = 20;
    this.dir = 3;
  }

  update() {
    super.update();
    this.x += this.dir;
    if (this.x < 30 || this.x > 370) {
      this.dir = -this.dir;
    }
  }
}

// 遅いが、何発も当てないと、倒せない敵
class Tank extends Enemy {
  constructor(x) {
    super(x);
    this.row = 3;
    this.speed = 1;
    this.hp = 4;
    this.r = 24;
    this.points = 50;
  }
}

class Particle {
  constructor(x, y) {
    this.x = x;
    this.y = y;
    this.speedX = random(-4, 4);
    this.speedY = random(-4, 4);
    this.life = 30;
  }

  update() {
    this.x += this.speedX;
    this.y += this.speedY;
    this.speedX *= 0.92;
    this.speedY *= 0.92;
    this.life -= 1;
  }

  isDead() {
    return this.life <= 0;
  }

  show() {
    noStroke();
    fill(255, 150 + this.life * 3, 60, this.life * 8);
    circle(this.x, this.y, this.life / 4);
  }
}

3種類の敵が、混ざって、現れます。緑の敵は、4発、当てないと、倒せません。

クラス 書いたもの 親から、そのまま使うもの
Enemy すべて
Tank コンストラクタ(値の上書き) update、show、isGone
ZigZag コンストラクタ、update show、isGone

クイズ

ZigZag の update() の中の、super.update(); を、書き忘れたとします。紫の敵は、どう動くでしょう?

▶ 答えを確認する

下りてこなくなります。画面の上の外(y = −30)で、左右に、行ったり来たりするだけです。


下へ進む処理(this.y += this.speed;)は、親クラスの update() の中に、あります。子クラスで、update() を書くと、親クラスのものは、置き換えられて、呼ばれなくなります。super.update(); と書いて、はじめて、親の処理も、実行されます。


敵は、画面の外にいるので、見えません。弾も、届きません。isGone() も、true に、なりません。見えない敵が、配列に、たまり続けることに、なります。

ステップ4:ボスと、敵の弾と、自機のやられ

ここからは、完成したプログラムの、該当する部分を、見ていきます。

ボスも、敵の一種

ボスも、Enemy の、子クラスです。

javascript
class Boss extends Enemy {
  constructor() {
    super(200);
    this.y = -60;
    this.hp = 40;
    this.r = 48;
    this.points = 500;
    this.dir = 2;
    this.isBoss = true;
  }
}

体力が 40、当たり判定の半径が 48 の、大きな敵です。enemies の配列に、ほかの敵と、いっしょに、入れます。だから、弾との当たり判定は、何も足さなくても、働きます。


update() と show() は、ボス専用に、書き直しています。

メソッド 内容
update() y が 100 になるまで、下りてくる。そのあとは、左右に動きながら、45 フレームごとに、弾を3つ撃つ
show() ボスの絵(別のファイル)を描き、上に、残りの体力の棒を描く

ボスが、弾を生む

sketch.js
enemyBullets.push(new Bullet(this.x - 40, this.y + 30, 4));
enemyBullets.push(new Bullet(this.x, this.y + 40, 5));
enemyBullets.push(new Bullet(this.x + 40, this.y + 30, 4));

ボスの update() の中で、enemyBullets という配列に、弾を、足しています。同じ Bullet クラスですが、速度が、プラス(下向き)です。


自分の弾と、敵の弾を、別の配列にしているのは、当たる相手が、違うからです。自分の弾は、敵と。敵の弾は、自機と、比べます。配列を分けておけば、「この弾は、どちらのものか」を、いちいち、調べずに済みます。

ボスが出たら、ほかの敵を止める

javascript
if (bossAppeared === false) {
  // ふつうの敵を出す
  if (timer > 1500) {
    enemies.push(new Boss());
    bossAppeared = true;
  }
}

timer が 1500(25 秒)を超えたら、ボスを、1体だけ、出します。bossAppeared を true にして、それ以降は、新しい敵を出さないように、しています。

自機が、やられたとき

sketch.js
function hitPlayer() {
  if (player.safeTime === 0) {
    lives -= 1;
    player.safeTime = 90;
    explode(player.x, player.y, 20);
    if (lives <= 0) {
      finish('ゲームオーバー');
    }
  }
}

敵に当たったときも、敵の弾に当たったときも、同じ関数を、呼びます。


safeTime は、無敵の、残り時間です。やられた直後の 90 フレーム(1.5 秒)は、もう一度、当たっても、何も起きません。これがないと、敵に重なっている間、毎フレーム、残りが減って、一瞬で、ゲームオーバーに、なります。


無敵の間は、自機を、点滅させます。

javascript
if (this.safeTime === 0 || frameCount % 6 < 3) {
  // 自機を描く
}

無敵でなければ、いつも、描く。無敵の間は、6 フレームのうち、3 フレームだけ、描く。「いまは、当たらない」ことが、目で、わかります。

ステップ5:音、場面、ハイスコア

音を、読み込んで、準備する

sketch.js
shootSound = await loadSound('shoot.wav');
boomSound = await loadSound('boom.wav');
bgm = await loadSound('bgm.wav');
bgm.loop();
bgm.amp(0.25);
shootSound.amp(0.4);

音楽は、loop() で、繰り返すように、設定しておきます。音量は、音楽を小さく、効果音が、埋もれないように、します。撃つ音は、何度も鳴るので、少し、控えめにします。

最初の操作で、音を始める

ブラウザは、見ている人の操作があるまで、音を、出させません。タイトルで、エンターキーが押されたときに、音を出す準備をし、音楽を、流し始めます。

sketch.js
userStartAudio();
if (bgmPlaying === false) {
  bgm.play();
  bgmPlaying = true;
}

bgmPlaying で、「もう、流しているか」を、覚えます。2回目のプレイで、もう一度 play() を呼ぶと、音楽が、最初に、戻ってしまうからです。

同じ音を、続けて鳴らしすぎない

爆発は、同じフレームに、いくつも、起きることが、あります。同じ音の play() を、同じ瞬間に、2回、呼び出すと、エラーに、なります。

sketch.js
if (count >= 10 && boomWait === 0) {
  boomSound.play();
  boomWait = 6;
}

boomWait は、弾の連射と、同じ仕組みです。爆発の音を鳴らしたら、6 フレームの間は、次を、鳴らしません。粒の数が 10 以上の、大きな爆発のときだけ、鳴らします。弾が当たっただけの、小さな爆発では、鳴らしません。

終わり方を、1つの関数にまとめる

ゲームが終わるのは、やられたときと、ボスを倒したときの、2通りです。どちらも、同じ関数を、呼びます。

sketch.js
function finish(text) {
  message = text;
  scene = 'result';
  if (score > highScore) {
    highScore = score;
    storeItem('shooter_highScore', highScore);
  }
}

表示する言葉を、引数で、受け取ります。場面を、結果に切り替え、ハイスコアを超えていたら、保存します。


保存した値は、setup の中で、getItem で、読み出します。まだ、何も保存されていないときは、null が返るので、そのときは、0 のままに、します。

進める関数と、描く関数

sketch.js
} else if (scene === 'play') {
  updateGame();
  drawGame();
} else if (scene === 'result') {
  drawGame();
  drawResult();
}

プレイ中は、進めて、描く。結果の場面では、描くだけ。終わった瞬間の画面が、止まったまま、表示され、その上に、結果の文字が、重なります。

完成したプログラムの、全体

冒頭のプログラムが、完成形です。全体の形を、まとめます。

部分 内容
一番上の変数 素材、場面、5種類のもの、スコア、残り、時間
setup 素材を読み込み、ハイスコアを読み出す
draw 星を描き、場面に応じて、関数を呼ぶ
updateGame 撃つ、敵を出す、すべてを動かす、当たりを調べる、消えたものを取り除く
spawnEnemy、hitPlayer、explode、finish よく起きる出来事を、1つずつ、関数にしたもの
drawGame、drawTitle、drawResult、drawStars 描く
keyPressed 場面を切り替える
クラス Player、Bullet、Enemy、ZigZag、Tank、Boss、Particle

updateGame の中の、順番

順番 すること
1 時間を進める。待ち時間を減らす
2 自機を動かす
3 弾を撃つ
4 敵を出す
5 自分の弾を動かす
6 敵の弾を動かし、自機との当たりを調べる
7 敵を動かし、弾との当たり、自機との当たりを調べる
8 爆発の粒を動かす

400 行近い、長いプログラムです。しかし、どの部分も、これまでに作ったことのある形です。配列を、後ろから回して、動かし、消えたものを取り除く。距離で、当たりを調べる。場面を、変数で切り替える。待ち時間を、数えて減らす。


大きな作品は、小さな、知っている形の、組み合わせです。

流れる星

背景の星は、配列も、乱数も、使っていません。番号から、位置を計算しています。

sketch.js
let x = (i * 97) % 400;
let y = (i * 53 + frameCount * (1 + i % 3)) % 500;

i * 97 を 400 で割った余りは、i ごとに、ばらばらな値に、なります。規則的な計算ですが、見た目は、でたらめに、散らばります。y には、frameCount を足しているので、時間とともに、下へ流れ、500 を超えると、上へ戻ります。


1 + i % 3 は、1、2、3 の、どれかです。星ごとに、流れる速さが違い、遠くの星と、近くの星が、あるように、見えます。

大きな作品を、作るときの進め方

この作品を、作りながら、使ってきた進め方を、まとめます。

進め方 理由
先に、登場するものと、当たり判定の組み合わせを、書き出す 作り始めてから、迷わない
遊びの中心から作り、動かしながら、足していく 早い段階で、面白いかどうかが、わかる
同じ役割のメソッドには、同じ名前を付ける 配列を回す部分が、どのクラスでも、同じ形になる
個性は、プロパティにする 種類を増やすとき、値を変えるだけで、済む
よく起きる出来事は、関数にする 同じ処理を、あちこちに、書かずに済む
絵や音は、あとから足す まず、四角形と円で、動きを完成させる

最後の点は、大事です。この作品も、スプライトを、円や四角形に置き換えれば、絵のファイルなしで、同じように、動きます。遊びとして成り立つことを、先に、確かめてから、見た目と音を、整えます。

やってみよう

次の3つを作ってください。

  1. 4種類目の敵として、速くて、小さい敵を足す。Enemy を継承し、速さを 5、当たり判定の半径を 16 にする。赤い敵の絵を、小さく描く
  2. 弾を、2発、並べて撃てるようにする
  3. ボスの体力が、半分より減ったら、動きが速くなり、弾を撃つ間隔が、短くなるようにする
▶ 1. 速くて、小さい敵を足す

Dart というクラスを、Enemy を継承して、作ります。値を上書きし、show() を、小さく描くように、書き直します。出す確率も、決めます。

sketch.js
let ships;
let bossImage;
let shootSound;
let boomSound;
let bgm;
let bgmPlaying = false;

let scene = 'title';
let message = '';

let player;
let bullets = [];
let enemyBullets = [];
let enemies = [];
let particles = [];

let score = 0;
let highScore = 0;
let lives = 3;
let timer = 0;
let bossAppeared = false;
let shootWait = 0;
let boomWait = 0;

async function setup() {
  createCanvas(400, 500);
  ships = await loadImage('ships.png');
  bossImage = await loadImage('boss.png');
  shootSound = await loadSound('shoot.wav');
  boomSound = await loadSound('boom.wav');
  bgm = await loadSound('bgm.wav');
  bgm.loop();
  bgm.amp(0.25);
  shootSound.amp(0.4);

  let saved = getItem('shooter_highScore');
  if (saved !== null) {
    highScore = saved;
  }
  player = new Player();
}

function draw() {
  background(10, 10, 30);
  drawStars();

  if (scene === 'title') {
    drawTitle();
  } else if (scene === 'play') {
    updateGame();
    drawGame();
  } else if (scene === 'result') {
    drawGame();
    drawResult();
  }
}

// 流れる星。位置は、番号から計算する
function drawStars() {
  noStroke();
  fill(255, 255, 255, 150);
  for (let i = 0; i < 40; i++) {
    let x = (i * 97) % 400;
    let y = (i * 53 + frameCount * (1 + i % 3)) % 500;
    circle(x, y, 1 + i % 3);
  }
}

function startGame() {
  player = new Player();
  bullets = [];
  enemyBullets = [];
  enemies = [];
  particles = [];
  score = 0;
  lives = 3;
  timer = 0;
  bossAppeared = false;
  shootWait = 0;
}

function updateGame() {
  timer += 1;
  if (shootWait > 0) {
    shootWait -= 1;
  }
  if (boomWait > 0) {
    boomWait -= 1;
  }

  player.update();

  // 弾を撃つ
  if (keyIsDown(' ') && shootWait === 0) {
    bullets.push(new Bullet(player.x, player.y - 24, -9));
    shootSound.play();
    shootWait = 10;
  }

  // 敵を出す。1500フレームたったら、ボスを出す
  if (bossAppeared === false) {
    let interval = max(20, 50 - floor(timer / 300) * 6);
    if (timer % interval === 0) {
      spawnEnemy();
    }
    if (timer > 1500) {
      enemies.push(new Boss());
      bossAppeared = true;
    }
  }

  // 自分の弾
  for (let i = bullets.length - 1; i >= 0; i--) {
    bullets[i].update();
    if (bullets[i].isGone()) {
      bullets.splice(i, 1);
    }
  }

  // 敵の弾。自機に当たったら、消す
  for (let i = enemyBullets.length - 1; i >= 0; i--) {
    enemyBullets[i].update();
    if (dist(enemyBullets[i].x, enemyBullets[i].y, player.x, player.y) < 18) {
      hitPlayer();
      enemyBullets.splice(i, 1);
    } else if (enemyBullets[i].isGone()) {
      enemyBullets.splice(i, 1);
    }
  }

  // 敵
  for (let i = enemies.length - 1; i >= 0; i--) {
    let enemy = enemies[i];
    enemy.update();

    // 自分の弾との当たり
    for (let j = bullets.length - 1; j >= 0; j--) {
      if (enemy.hp > 0 && dist(bullets[j].x, bullets[j].y, enemy.x, enemy.y) < enemy.r) {
        enemy.hp -= 1;
        bullets.splice(j, 1);
        explode(enemy.x, enemy.y + enemy.r * 0.5, 3);
      }
    }

    // 自機との当たり
    if (dist(player.x, player.y, enemy.x, enemy.y) < enemy.r + 14) {
      hitPlayer();
    }

    if (enemy.hp <= 0) {
      score += enemy.points;
      explode(enemy.x, enemy.y, enemy.r);
      if (enemy.isBoss) {
        finish('クリア!');
      }
      enemies.splice(i, 1);
    } else if (enemy.isGone()) {
      enemies.splice(i, 1);
    }
  }

  // 爆発の粒
  for (let i = particles.length - 1; i >= 0; i--) {
    particles[i].update();
    if (particles[i].isDead()) {
      particles.splice(i, 1);
    }
  }
}

function spawnEnemy() {
  let x = random(40, 360);
  let pick = random(1);
  if (pick < 0.55) {
    enemies.push(new Enemy(x));
  } else if (pick < 0.75) {
    enemies.push(new ZigZag(x));
  } else if (pick < 0.88) {
    enemies.push(new Dart(x));
  } else {
    enemies.push(new Tank(x));
  }
}

// 自機が、敵や、敵の弾に当たった
function hitPlayer() {
  if (player.safeTime === 0) {
    lives -= 1;
    player.safeTime = 90;
    explode(player.x, player.y, 20);
    if (lives <= 0) {
      finish('ゲームオーバー');
    }
  }
}

// 爆発。粒をまき、音を鳴らす
function explode(x, y, count) {
  for (let i = 0; i < count; i++) {
    particles.push(new Particle(x, y));
  }
  if (count >= 10 && boomWait === 0) {
    boomSound.play();
    boomWait = 6;
  }
}

// ゲームを終わらせ、ハイスコアを保存する
function finish(text) {
  message = text;
  scene = 'result';
  if (score > highScore) {
    highScore = score;
    storeItem('shooter_highScore', highScore);
  }
}

function drawGame() {
  for (let i = 0; i < bullets.length; i++) {
    bullets[i].show();
  }
  for (let i = 0; i < enemyBullets.length; i++) {
    enemyBullets[i].show();
  }
  for (let i = 0; i < enemies.length; i++) {
    enemies[i].show();
  }
  for (let i = 0; i < particles.length; i++) {
    particles[i].show();
  }
  if (lives > 0) {
    player.show();
  }

  noStroke();
  fill(255);
  textAlign(LEFT, BASELINE);
  textSize(16);
  text(`スコア: ${score}`, 12, 24);
  text(`ハイスコア: ${highScore}`, 150, 24);
  text(`残り: ${lives}`, 330, 24);
}

function drawTitle() {
  player.show();
  noStroke();
  fill(255);
  textAlign(CENTER, CENTER);
  textSize(32);
  text('シューティング', 200, 160);
  textSize(16);
  text('← → ↑ ↓: 動く   スペース: 撃つ', 200, 230);
  text('エンターキーで、スタート', 200, 290);
  text(`ハイスコア: ${highScore}`, 200, 340);
}

function drawResult() {
  noStroke();
  fill(0, 0, 0, 150);
  rect(0, 0, 400, 500);
  fill(255);
  textAlign(CENTER, CENTER);
  textSize(32);
  text(message, 200, 190);
  textSize(22);
  text(`スコア: ${score}`, 200, 245);
  textSize(16);
  text('エンターキーで、タイトルへ', 200, 310);
}

function keyPressed() {
  if (key === 'Enter') {
    if (scene === 'title') {
      // 最初の操作で、音を出す準備をして、音楽を流す
      userStartAudio();
      if (bgmPlaying === false) {
        bgm.play();
        bgmPlaying = true;
      }
      startGame();
      scene = 'play';
    } else if (scene === 'result') {
      scene = 'title';
    }
  }
}

class Player {
  constructor() {
    this.x = 200;
    this.y = 440;
    this.safeTime = 0;
  }

  update() {
    if (keyIsDown(LEFT_ARROW)) {
      this.x -= 5;
    }
    if (keyIsDown(RIGHT_ARROW)) {
      this.x += 5;
    }
    if (keyIsDown(UP_ARROW)) {
      this.y -= 4;
    }
    if (keyIsDown(DOWN_ARROW)) {
      this.y += 4;
    }
    this.x = max(24, min(376, this.x));
    this.y = max(60, min(470, this.y));

    if (this.safeTime > 0) {
      this.safeTime -= 1;
    }
  }

  show() {
    // 当たった直後は、点滅させる
    if (this.safeTime === 0 || frameCount % 6 < 3) {
      let frame = floor(frameCount / 4) % 2;
      image(ships, this.x - 32, this.y - 32, 64, 64, frame * 64, 0, 64, 64);
    }
  }
}

class Bullet {
  constructor(x, y, speedY) {
    this.x = x;
    this.y = y;
    this.speedY = speedY;
  }

  update() {
    this.y += this.speedY;
  }

  isGone() {
    return this.y < -20 || this.y > 520;
  }

  show() {
    noStroke();
    if (this.speedY < 0) {
      fill(255, 240, 150);
      rect(this.x - 2, this.y - 8, 4, 16, 2);
    } else {
      fill(255, 110, 140);
      circle(this.x, this.y, 10);
    }
  }
}

// 敵の、親クラス。まっすぐ、下へ進む
class Enemy {
  constructor(x) {
    this.x = x;
    this.y = -30;
    this.speed = 2;
    this.hp = 1;
    this.r = 22;
    this.points = 10;
    this.row = 1;
    this.isBoss = false;
  }

  update() {
    this.y += this.speed;
  }

  isGone() {
    return this.y > 540;
  }

  show() {
    let frame = floor(frameCount / 10) % 2;
    image(ships, this.x - 32, this.y - 32, 64, 64, frame * 64, this.row * 64, 64, 64);
  }
}

// 左右に、行ったり来たりしながら、進む敵
class ZigZag extends Enemy {
  constructor(x) {
    super(x);
    this.row = 2;
    this.points = 20;
    this.dir = 3;
  }

  update() {
    super.update();
    this.x += this.dir;
    if (this.x < 30 || this.x > 370) {
      this.dir = -this.dir;
    }
  }
}

// 遅いが、何発も当てないと、倒せない敵
class Tank extends Enemy {
  constructor(x) {
    super(x);
    this.row = 3;
    this.speed = 1;
    this.hp = 4;
    this.r = 24;
    this.points = 50;
  }
}

// 速くて、小さい敵
class Dart extends Enemy {
  constructor(x) {
    super(x);
    this.speed = 5;
    this.r = 16;
    this.points = 30;
  }

  show() {
    let frame = floor(frameCount / 10) % 2;
    image(ships, this.x - 20, this.y - 20, 40, 40, frame * 64, 64, 64, 64);
  }
}

// ボス。上のほうで、左右に動きながら、弾を撃つ
class Boss extends Enemy {
  constructor() {
    super(200);
    this.y = -60;
    this.hp = 40;
    this.r = 48;
    this.points = 500;
    this.dir = 2;
    this.isBoss = true;
  }

  update() {
    if (this.y < 100) {
      this.y += 1;
    } else {
      this.x += this.dir;
      if (this.x < 70 || this.x > 330) {
        this.dir = -this.dir;
      }
      if (frameCount % 45 === 0) {
        enemyBullets.push(new Bullet(this.x - 40, this.y + 30, 4));
        enemyBullets.push(new Bullet(this.x, this.y + 40, 5));
        enemyBullets.push(new Bullet(this.x + 40, this.y + 30, 4));
      }
    }
  }

  show() {
    let frame = floor(frameCount / 15) % 2;
    image(bossImage, this.x - 64, this.y - 48, 128, 96, frame * 128, 0, 128, 96);

    // 残りの体力
    noStroke();
    fill(80, 80, 100);
    rect(100, 40, 200, 8);
    fill(255, 90, 120);
    rect(100, 40, this.hp * 5, 8);
  }
}

class Particle {
  constructor(x, y) {
    this.x = x;
    this.y = y;
    this.speedX = random(-4, 4);
    this.speedY = random(-4, 4);
    this.life = 30;
  }

  update() {
    this.x += this.speedX;
    this.y += this.speedY;
    this.speedX *= 0.92;
    this.speedY *= 0.92;
    this.life -= 1;
  }

  isDead() {
    return this.life <= 0;
  }

  show() {
    noStroke();
    fill(255, 150 + this.life * 3, 60, this.life * 8);
    circle(this.x, this.y, this.life / 4);
  }
}

足したのは、クラス1つと、spawnEnemy の中の、条件1つだけです。当たり判定も、爆発も、スコアも、何も、足していません。Dart は、Enemy の子クラスなので、enemies の配列に入れれば、ほかの敵と同じ扱いを、受けます。

▶ 2. 2発、並べて撃つ

弾を作る行を、2つにして、x を、左右に 10 ずつ、ずらします。

sketch.js
let ships;
let bossImage;
let shootSound;
let boomSound;
let bgm;
let bgmPlaying = false;

let scene = 'title';
let message = '';

let player;
let bullets = [];
let enemyBullets = [];
let enemies = [];
let particles = [];

let score = 0;
let highScore = 0;
let lives = 3;
let timer = 0;
let bossAppeared = false;
let shootWait = 0;
let boomWait = 0;

async function setup() {
  createCanvas(400, 500);
  ships = await loadImage('ships.png');
  bossImage = await loadImage('boss.png');
  shootSound = await loadSound('shoot.wav');
  boomSound = await loadSound('boom.wav');
  bgm = await loadSound('bgm.wav');
  bgm.loop();
  bgm.amp(0.25);
  shootSound.amp(0.4);

  let saved = getItem('shooter_highScore');
  if (saved !== null) {
    highScore = saved;
  }
  player = new Player();
}

function draw() {
  background(10, 10, 30);
  drawStars();

  if (scene === 'title') {
    drawTitle();
  } else if (scene === 'play') {
    updateGame();
    drawGame();
  } else if (scene === 'result') {
    drawGame();
    drawResult();
  }
}

// 流れる星。位置は、番号から計算する
function drawStars() {
  noStroke();
  fill(255, 255, 255, 150);
  for (let i = 0; i < 40; i++) {
    let x = (i * 97) % 400;
    let y = (i * 53 + frameCount * (1 + i % 3)) % 500;
    circle(x, y, 1 + i % 3);
  }
}

function startGame() {
  player = new Player();
  bullets = [];
  enemyBullets = [];
  enemies = [];
  particles = [];
  score = 0;
  lives = 3;
  timer = 0;
  bossAppeared = false;
  shootWait = 0;
}

function updateGame() {
  timer += 1;
  if (shootWait > 0) {
    shootWait -= 1;
  }
  if (boomWait > 0) {
    boomWait -= 1;
  }

  player.update();

  // 弾を撃つ
  if (keyIsDown(' ') && shootWait === 0) {
    bullets.push(new Bullet(player.x - 10, player.y - 20, -9));
    bullets.push(new Bullet(player.x + 10, player.y - 20, -9));
    shootSound.play();
    shootWait = 10;
  }

  // 敵を出す。1500フレームたったら、ボスを出す
  if (bossAppeared === false) {
    let interval = max(20, 50 - floor(timer / 300) * 6);
    if (timer % interval === 0) {
      spawnEnemy();
    }
    if (timer > 1500) {
      enemies.push(new Boss());
      bossAppeared = true;
    }
  }

  // 自分の弾
  for (let i = bullets.length - 1; i >= 0; i--) {
    bullets[i].update();
    if (bullets[i].isGone()) {
      bullets.splice(i, 1);
    }
  }

  // 敵の弾。自機に当たったら、消す
  for (let i = enemyBullets.length - 1; i >= 0; i--) {
    enemyBullets[i].update();
    if (dist(enemyBullets[i].x, enemyBullets[i].y, player.x, player.y) < 18) {
      hitPlayer();
      enemyBullets.splice(i, 1);
    } else if (enemyBullets[i].isGone()) {
      enemyBullets.splice(i, 1);
    }
  }

  // 敵
  for (let i = enemies.length - 1; i >= 0; i--) {
    let enemy = enemies[i];
    enemy.update();

    // 自分の弾との当たり
    for (let j = bullets.length - 1; j >= 0; j--) {
      if (enemy.hp > 0 && dist(bullets[j].x, bullets[j].y, enemy.x, enemy.y) < enemy.r) {
        enemy.hp -= 1;
        bullets.splice(j, 1);
        explode(enemy.x, enemy.y + enemy.r * 0.5, 3);
      }
    }

    // 自機との当たり
    if (dist(player.x, player.y, enemy.x, enemy.y) < enemy.r + 14) {
      hitPlayer();
    }

    if (enemy.hp <= 0) {
      score += enemy.points;
      explode(enemy.x, enemy.y, enemy.r);
      if (enemy.isBoss) {
        finish('クリア!');
      }
      enemies.splice(i, 1);
    } else if (enemy.isGone()) {
      enemies.splice(i, 1);
    }
  }

  // 爆発の粒
  for (let i = particles.length - 1; i >= 0; i--) {
    particles[i].update();
    if (particles[i].isDead()) {
      particles.splice(i, 1);
    }
  }
}

function spawnEnemy() {
  let x = random(40, 360);
  let pick = random(1);
  if (pick < 0.55) {
    enemies.push(new Enemy(x));
  } else if (pick < 0.85) {
    enemies.push(new ZigZag(x));
  } else {
    enemies.push(new Tank(x));
  }
}

// 自機が、敵や、敵の弾に当たった
function hitPlayer() {
  if (player.safeTime === 0) {
    lives -= 1;
    player.safeTime = 90;
    explode(player.x, player.y, 20);
    if (lives <= 0) {
      finish('ゲームオーバー');
    }
  }
}

// 爆発。粒をまき、音を鳴らす
function explode(x, y, count) {
  for (let i = 0; i < count; i++) {
    particles.push(new Particle(x, y));
  }
  if (count >= 10 && boomWait === 0) {
    boomSound.play();
    boomWait = 6;
  }
}

// ゲームを終わらせ、ハイスコアを保存する
function finish(text) {
  message = text;
  scene = 'result';
  if (score > highScore) {
    highScore = score;
    storeItem('shooter_highScore', highScore);
  }
}

function drawGame() {
  for (let i = 0; i < bullets.length; i++) {
    bullets[i].show();
  }
  for (let i = 0; i < enemyBullets.length; i++) {
    enemyBullets[i].show();
  }
  for (let i = 0; i < enemies.length; i++) {
    enemies[i].show();
  }
  for (let i = 0; i < particles.length; i++) {
    particles[i].show();
  }
  if (lives > 0) {
    player.show();
  }

  noStroke();
  fill(255);
  textAlign(LEFT, BASELINE);
  textSize(16);
  text(`スコア: ${score}`, 12, 24);
  text(`ハイスコア: ${highScore}`, 150, 24);
  text(`残り: ${lives}`, 330, 24);
}

function drawTitle() {
  player.show();
  noStroke();
  fill(255);
  textAlign(CENTER, CENTER);
  textSize(32);
  text('シューティング', 200, 160);
  textSize(16);
  text('← → ↑ ↓: 動く   スペース: 撃つ', 200, 230);
  text('エンターキーで、スタート', 200, 290);
  text(`ハイスコア: ${highScore}`, 200, 340);
}

function drawResult() {
  noStroke();
  fill(0, 0, 0, 150);
  rect(0, 0, 400, 500);
  fill(255);
  textAlign(CENTER, CENTER);
  textSize(32);
  text(message, 200, 190);
  textSize(22);
  text(`スコア: ${score}`, 200, 245);
  textSize(16);
  text('エンターキーで、タイトルへ', 200, 310);
}

function keyPressed() {
  if (key === 'Enter') {
    if (scene === 'title') {
      // 最初の操作で、音を出す準備をして、音楽を流す
      userStartAudio();
      if (bgmPlaying === false) {
        bgm.play();
        bgmPlaying = true;
      }
      startGame();
      scene = 'play';
    } else if (scene === 'result') {
      scene = 'title';
    }
  }
}

class Player {
  constructor() {
    this.x = 200;
    this.y = 440;
    this.safeTime = 0;
  }

  update() {
    if (keyIsDown(LEFT_ARROW)) {
      this.x -= 5;
    }
    if (keyIsDown(RIGHT_ARROW)) {
      this.x += 5;
    }
    if (keyIsDown(UP_ARROW)) {
      this.y -= 4;
    }
    if (keyIsDown(DOWN_ARROW)) {
      this.y += 4;
    }
    this.x = max(24, min(376, this.x));
    this.y = max(60, min(470, this.y));

    if (this.safeTime > 0) {
      this.safeTime -= 1;
    }
  }

  show() {
    // 当たった直後は、点滅させる
    if (this.safeTime === 0 || frameCount % 6 < 3) {
      let frame = floor(frameCount / 4) % 2;
      image(ships, this.x - 32, this.y - 32, 64, 64, frame * 64, 0, 64, 64);
    }
  }
}

class Bullet {
  constructor(x, y, speedY) {
    this.x = x;
    this.y = y;
    this.speedY = speedY;
  }

  update() {
    this.y += this.speedY;
  }

  isGone() {
    return this.y < -20 || this.y > 520;
  }

  show() {
    noStroke();
    if (this.speedY < 0) {
      fill(255, 240, 150);
      rect(this.x - 2, this.y - 8, 4, 16, 2);
    } else {
      fill(255, 110, 140);
      circle(this.x, this.y, 10);
    }
  }
}

// 敵の、親クラス。まっすぐ、下へ進む
class Enemy {
  constructor(x) {
    this.x = x;
    this.y = -30;
    this.speed = 2;
    this.hp = 1;
    this.r = 22;
    this.points = 10;
    this.row = 1;
    this.isBoss = false;
  }

  update() {
    this.y += this.speed;
  }

  isGone() {
    return this.y > 540;
  }

  show() {
    let frame = floor(frameCount / 10) % 2;
    image(ships, this.x - 32, this.y - 32, 64, 64, frame * 64, this.row * 64, 64, 64);
  }
}

// 左右に、行ったり来たりしながら、進む敵
class ZigZag extends Enemy {
  constructor(x) {
    super(x);
    this.row = 2;
    this.points = 20;
    this.dir = 3;
  }

  update() {
    super.update();
    this.x += this.dir;
    if (this.x < 30 || this.x > 370) {
      this.dir = -this.dir;
    }
  }
}

// 遅いが、何発も当てないと、倒せない敵
class Tank extends Enemy {
  constructor(x) {
    super(x);
    this.row = 3;
    this.speed = 1;
    this.hp = 4;
    this.r = 24;
    this.points = 50;
  }
}

// ボス。上のほうで、左右に動きながら、弾を撃つ
class Boss extends Enemy {
  constructor() {
    super(200);
    this.y = -60;
    this.hp = 40;
    this.r = 48;
    this.points = 500;
    this.dir = 2;
    this.isBoss = true;
  }

  update() {
    if (this.y < 100) {
      this.y += 1;
    } else {
      this.x += this.dir;
      if (this.x < 70 || this.x > 330) {
        this.dir = -this.dir;
      }
      if (frameCount % 45 === 0) {
        enemyBullets.push(new Bullet(this.x - 40, this.y + 30, 4));
        enemyBullets.push(new Bullet(this.x, this.y + 40, 5));
        enemyBullets.push(new Bullet(this.x + 40, this.y + 30, 4));
      }
    }
  }

  show() {
    let frame = floor(frameCount / 15) % 2;
    image(bossImage, this.x - 64, this.y - 48, 128, 96, frame * 128, 0, 128, 96);

    // 残りの体力
    noStroke();
    fill(80, 80, 100);
    rect(100, 40, 200, 8);
    fill(255, 90, 120);
    rect(100, 40, this.hp * 5, 8);
  }
}

class Particle {
  constructor(x, y) {
    this.x = x;
    this.y = y;
    this.speedX = random(-4, 4);
    this.speedY = random(-4, 4);
    this.life = 30;
  }

  update() {
    this.x += this.speedX;
    this.y += this.speedY;
    this.speedX *= 0.92;
    this.speedY *= 0.92;
    this.life -= 1;
  }

  isDead() {
    return this.life <= 0;
  }

  show() {
    noStroke();
    fill(255, 150 + this.life * 3, 60, this.life * 8);
    circle(this.x, this.y, this.life / 4);
  }
}

弾が、2列になり、当てやすく、なります。撃つ音は、1回だけ、鳴らしています。2発分、2回鳴らすと、同じ瞬間に、同じ音を、2回鳴らすことになり、エラーに、なります。

▶ 3. ボスを、途中から強くする

ボスの update() の中で、体力を見て、撃つ間隔と、動く速さを、変えます。

sketch.js
let ships;
let bossImage;
let shootSound;
let boomSound;
let bgm;
let bgmPlaying = false;

let scene = 'title';
let message = '';

let player;
let bullets = [];
let enemyBullets = [];
let enemies = [];
let particles = [];

let score = 0;
let highScore = 0;
let lives = 3;
let timer = 0;
let bossAppeared = false;
let shootWait = 0;
let boomWait = 0;

async function setup() {
  createCanvas(400, 500);
  ships = await loadImage('ships.png');
  bossImage = await loadImage('boss.png');
  shootSound = await loadSound('shoot.wav');
  boomSound = await loadSound('boom.wav');
  bgm = await loadSound('bgm.wav');
  bgm.loop();
  bgm.amp(0.25);
  shootSound.amp(0.4);

  let saved = getItem('shooter_highScore');
  if (saved !== null) {
    highScore = saved;
  }
  player = new Player();
}

function draw() {
  background(10, 10, 30);
  drawStars();

  if (scene === 'title') {
    drawTitle();
  } else if (scene === 'play') {
    updateGame();
    drawGame();
  } else if (scene === 'result') {
    drawGame();
    drawResult();
  }
}

// 流れる星。位置は、番号から計算する
function drawStars() {
  noStroke();
  fill(255, 255, 255, 150);
  for (let i = 0; i < 40; i++) {
    let x = (i * 97) % 400;
    let y = (i * 53 + frameCount * (1 + i % 3)) % 500;
    circle(x, y, 1 + i % 3);
  }
}

function startGame() {
  player = new Player();
  bullets = [];
  enemyBullets = [];
  enemies = [];
  particles = [];
  score = 0;
  lives = 3;
  timer = 0;
  bossAppeared = false;
  shootWait = 0;
}

function updateGame() {
  timer += 1;
  if (shootWait > 0) {
    shootWait -= 1;
  }
  if (boomWait > 0) {
    boomWait -= 1;
  }

  player.update();

  // 弾を撃つ
  if (keyIsDown(' ') && shootWait === 0) {
    bullets.push(new Bullet(player.x, player.y - 24, -9));
    shootSound.play();
    shootWait = 10;
  }

  // 敵を出す。1500フレームたったら、ボスを出す
  if (bossAppeared === false) {
    let interval = max(20, 50 - floor(timer / 300) * 6);
    if (timer % interval === 0) {
      spawnEnemy();
    }
    if (timer > 1500) {
      enemies.push(new Boss());
      bossAppeared = true;
    }
  }

  // 自分の弾
  for (let i = bullets.length - 1; i >= 0; i--) {
    bullets[i].update();
    if (bullets[i].isGone()) {
      bullets.splice(i, 1);
    }
  }

  // 敵の弾。自機に当たったら、消す
  for (let i = enemyBullets.length - 1; i >= 0; i--) {
    enemyBullets[i].update();
    if (dist(enemyBullets[i].x, enemyBullets[i].y, player.x, player.y) < 18) {
      hitPlayer();
      enemyBullets.splice(i, 1);
    } else if (enemyBullets[i].isGone()) {
      enemyBullets.splice(i, 1);
    }
  }

  // 敵
  for (let i = enemies.length - 1; i >= 0; i--) {
    let enemy = enemies[i];
    enemy.update();

    // 自分の弾との当たり
    for (let j = bullets.length - 1; j >= 0; j--) {
      if (enemy.hp > 0 && dist(bullets[j].x, bullets[j].y, enemy.x, enemy.y) < enemy.r) {
        enemy.hp -= 1;
        bullets.splice(j, 1);
        explode(enemy.x, enemy.y + enemy.r * 0.5, 3);
      }
    }

    // 自機との当たり
    if (dist(player.x, player.y, enemy.x, enemy.y) < enemy.r + 14) {
      hitPlayer();
    }

    if (enemy.hp <= 0) {
      score += enemy.points;
      explode(enemy.x, enemy.y, enemy.r);
      if (enemy.isBoss) {
        finish('クリア!');
      }
      enemies.splice(i, 1);
    } else if (enemy.isGone()) {
      enemies.splice(i, 1);
    }
  }

  // 爆発の粒
  for (let i = particles.length - 1; i >= 0; i--) {
    particles[i].update();
    if (particles[i].isDead()) {
      particles.splice(i, 1);
    }
  }
}

function spawnEnemy() {
  let x = random(40, 360);
  let pick = random(1);
  if (pick < 0.55) {
    enemies.push(new Enemy(x));
  } else if (pick < 0.85) {
    enemies.push(new ZigZag(x));
  } else {
    enemies.push(new Tank(x));
  }
}

// 自機が、敵や、敵の弾に当たった
function hitPlayer() {
  if (player.safeTime === 0) {
    lives -= 1;
    player.safeTime = 90;
    explode(player.x, player.y, 20);
    if (lives <= 0) {
      finish('ゲームオーバー');
    }
  }
}

// 爆発。粒をまき、音を鳴らす
function explode(x, y, count) {
  for (let i = 0; i < count; i++) {
    particles.push(new Particle(x, y));
  }
  if (count >= 10 && boomWait === 0) {
    boomSound.play();
    boomWait = 6;
  }
}

// ゲームを終わらせ、ハイスコアを保存する
function finish(text) {
  message = text;
  scene = 'result';
  if (score > highScore) {
    highScore = score;
    storeItem('shooter_highScore', highScore);
  }
}

function drawGame() {
  for (let i = 0; i < bullets.length; i++) {
    bullets[i].show();
  }
  for (let i = 0; i < enemyBullets.length; i++) {
    enemyBullets[i].show();
  }
  for (let i = 0; i < enemies.length; i++) {
    enemies[i].show();
  }
  for (let i = 0; i < particles.length; i++) {
    particles[i].show();
  }
  if (lives > 0) {
    player.show();
  }

  noStroke();
  fill(255);
  textAlign(LEFT, BASELINE);
  textSize(16);
  text(`スコア: ${score}`, 12, 24);
  text(`ハイスコア: ${highScore}`, 150, 24);
  text(`残り: ${lives}`, 330, 24);
}

function drawTitle() {
  player.show();
  noStroke();
  fill(255);
  textAlign(CENTER, CENTER);
  textSize(32);
  text('シューティング', 200, 160);
  textSize(16);
  text('← → ↑ ↓: 動く   スペース: 撃つ', 200, 230);
  text('エンターキーで、スタート', 200, 290);
  text(`ハイスコア: ${highScore}`, 200, 340);
}

function drawResult() {
  noStroke();
  fill(0, 0, 0, 150);
  rect(0, 0, 400, 500);
  fill(255);
  textAlign(CENTER, CENTER);
  textSize(32);
  text(message, 200, 190);
  textSize(22);
  text(`スコア: ${score}`, 200, 245);
  textSize(16);
  text('エンターキーで、タイトルへ', 200, 310);
}

function keyPressed() {
  if (key === 'Enter') {
    if (scene === 'title') {
      // 最初の操作で、音を出す準備をして、音楽を流す
      userStartAudio();
      if (bgmPlaying === false) {
        bgm.play();
        bgmPlaying = true;
      }
      startGame();
      scene = 'play';
    } else if (scene === 'result') {
      scene = 'title';
    }
  }
}

class Player {
  constructor() {
    this.x = 200;
    this.y = 440;
    this.safeTime = 0;
  }

  update() {
    if (keyIsDown(LEFT_ARROW)) {
      this.x -= 5;
    }
    if (keyIsDown(RIGHT_ARROW)) {
      this.x += 5;
    }
    if (keyIsDown(UP_ARROW)) {
      this.y -= 4;
    }
    if (keyIsDown(DOWN_ARROW)) {
      this.y += 4;
    }
    this.x = max(24, min(376, this.x));
    this.y = max(60, min(470, this.y));

    if (this.safeTime > 0) {
      this.safeTime -= 1;
    }
  }

  show() {
    // 当たった直後は、点滅させる
    if (this.safeTime === 0 || frameCount % 6 < 3) {
      let frame = floor(frameCount / 4) % 2;
      image(ships, this.x - 32, this.y - 32, 64, 64, frame * 64, 0, 64, 64);
    }
  }
}

class Bullet {
  constructor(x, y, speedY) {
    this.x = x;
    this.y = y;
    this.speedY = speedY;
  }

  update() {
    this.y += this.speedY;
  }

  isGone() {
    return this.y < -20 || this.y > 520;
  }

  show() {
    noStroke();
    if (this.speedY < 0) {
      fill(255, 240, 150);
      rect(this.x - 2, this.y - 8, 4, 16, 2);
    } else {
      fill(255, 110, 140);
      circle(this.x, this.y, 10);
    }
  }
}

// 敵の、親クラス。まっすぐ、下へ進む
class Enemy {
  constructor(x) {
    this.x = x;
    this.y = -30;
    this.speed = 2;
    this.hp = 1;
    this.r = 22;
    this.points = 10;
    this.row = 1;
    this.isBoss = false;
  }

  update() {
    this.y += this.speed;
  }

  isGone() {
    return this.y > 540;
  }

  show() {
    let frame = floor(frameCount / 10) % 2;
    image(ships, this.x - 32, this.y - 32, 64, 64, frame * 64, this.row * 64, 64, 64);
  }
}

// 左右に、行ったり来たりしながら、進む敵
class ZigZag extends Enemy {
  constructor(x) {
    super(x);
    this.row = 2;
    this.points = 20;
    this.dir = 3;
  }

  update() {
    super.update();
    this.x += this.dir;
    if (this.x < 30 || this.x > 370) {
      this.dir = -this.dir;
    }
  }
}

// 遅いが、何発も当てないと、倒せない敵
class Tank extends Enemy {
  constructor(x) {
    super(x);
    this.row = 3;
    this.speed = 1;
    this.hp = 4;
    this.r = 24;
    this.points = 50;
  }
}

// ボス。上のほうで、左右に動きながら、弾を撃つ
class Boss extends Enemy {
  constructor() {
    super(200);
    this.y = -60;
    this.hp = 40;
    this.r = 48;
    this.points = 500;
    this.dir = 2;
    this.isBoss = true;
  }

  update() {
    if (this.y < 100) {
      this.y += 1;
    } else {
      this.x += this.dir;
      if (this.x < 70 || this.x > 330) {
        this.dir = -this.dir;
      }
      // 体力が半分より減ったら、速く動き、短い間隔で撃つ
      let wait = 45;
      if (this.hp < 20) {
        wait = 25;
        this.x += this.dir;
      }
      if (frameCount % wait === 0) {
        enemyBullets.push(new Bullet(this.x - 40, this.y + 30, 4));
        enemyBullets.push(new Bullet(this.x, this.y + 40, 5));
        enemyBullets.push(new Bullet(this.x + 40, this.y + 30, 4));
      }
    }
  }

  show() {
    let frame = floor(frameCount / 15) % 2;
    image(bossImage, this.x - 64, this.y - 48, 128, 96, frame * 128, 0, 128, 96);

    // 残りの体力
    noStroke();
    fill(80, 80, 100);
    rect(100, 40, 200, 8);
    fill(255, 90, 120);
    rect(100, 40, this.hp * 5, 8);
  }
}

class Particle {
  constructor(x, y) {
    this.x = x;
    this.y = y;
    this.speedX = random(-4, 4);
    this.speedY = random(-4, 4);
    this.life = 30;
  }

  update() {
    this.x += this.speedX;
    this.y += this.speedY;
    this.speedX *= 0.92;
    this.speedY *= 0.92;
    this.life -= 1;
  }

  isDead() {
    return this.life <= 0;
  }

  show() {
    noStroke();
    fill(255, 150 + this.life * 3, 60, this.life * 8);
    circle(this.x, this.y, this.life / 4);
  }
}

体力が 20 を切ると、間隔が、45 フレームから 25 フレームに、縮まります。横の動きも、もう1回分、足されて、2倍の速さに、なります。


変えたのは、Boss クラスの中だけです。ボスのことは、ボスのクラスの中に、まとまっています。追い詰められると、激しくなる。それだけで、戦いに、山場が、生まれます。

まとめ

  • 大きな作品は、先に、登場するもの、場面、当たり判定の組み合わせを、書き出してから、作る
  • たくさんあるものは、クラスにして、配列で管理する。update、show、消えるべきかを返すメソッドを、どのクラスにも持たせる
  • 2つの配列の間の当たり判定は、二重ループで、すべての組み合わせを調べる。途中で取り除くので、後ろから回す
  • 当たった瞬間には、体力を減らすだけにし、取り除くのは、ループのあとにする
  • 敵の種類は、継承で増やす。違う値だけを上書きし、違う動きだけを書き直す。super で、親の処理も使う
  • 種類が違っても、同じ配列に入れ、同じメソッドを呼ぶ。配列を回す部分は、種類が増えても、変えなくてよい
  • 当たる相手が違うものは、別の配列にする
  • 「撃つ間隔」「無敵の時間」「音を鳴らす間隔」は、どれも、残りのフレーム数を、数えて減らす仕組みで作れる
  • 遊びの中心から作り、絵や音は、あとから足す