ToroVerse

作品:タワーディフェンス

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

敵が、道に沿って、ぞろぞろと、進んできます。道のわきに、タワーを建てると、タワーが、自動で、敵を狙って、撃ちます。限られた資金で、どこに、どのタワーを建てるか。考えて、守る。タワーディフェンスという種類のゲームを、作ります。道をたどる敵、狙いを定めるタワー、追いかける弾。たくさんの「自分で動くもの」が、互いに、関わり合います。

sketch.js
const TILE = 40;
const SIZE = 10;

// 敵が通る道の、曲がり角(マスの番号)
const WAYPOINTS = [
  { col: 0, row: 1 },
  { col: 7, row: 1 },
  { col: 7, row: 4 },
  { col: 2, row: 4 },
  { col: 2, row: 7 },
  { col: 9, row: 7 }
];

// タワーの種類ごとの、値段、射程、色。0:ふつう 1:遅くする 2:大砲
const COSTS = [50, 70, 100];
const RANGES = [90, 80, 130];
const TOWER_COLORS = [[240, 220, 90], [120, 200, 255], [240, 110, 110]];

let scene = 'title';
let message = '';
let grid = [];
let enemies = [];
let towers = [];
let bullets = [];

let money = 0;
let lives = 0;
let wave = 0;
let toSpawn = 0;
let spawnWait = 0;
let selected = 0;

function setup() {
  createCanvas(400, 470);
  angleMode(DEGREES);
  makeGrid();
}

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

  if (scene === 'play') {
    updateGame();
  }
  drawField();
  drawPanel();

  if (scene === 'title') {
    drawOverlay('タワーディフェンス', 'クリックで、スタート');
  } else if (scene === 'result') {
    drawOverlay(message, 'クリックで、タイトルへ');
  }
}

// ---------- 盤面 ----------

// 盤面を作る。0:空き地 1:道 2:タワーがある
function makeGrid() {
  for (let row = 0; row < SIZE; row++) {
    grid[row] = [];
    for (let col = 0; col < SIZE; col++) {
      grid[row][col] = 0;
    }
  }

  // 曲がり角から、次の曲がり角までを、道にする
  for (let i = 0; i < WAYPOINTS.length - 1; i++) {
    let a = WAYPOINTS[i];
    let b = WAYPOINTS[i + 1];
    for (let col = min(a.col, b.col); col <= max(a.col, b.col); col++) {
      for (let row = min(a.row, b.row); row <= max(a.row, b.row); row++) {
        grid[row][col] = 1;
      }
    }
  }
}

// マスの番号から、その真ん中の座標(ベクトル)を作る
function centerOf(col, row) {
  return createVector(col * TILE + TILE / 2, row * TILE + TILE / 2);
}

// ---------- ゲームの進行 ----------

function startGame() {
  makeGrid();
  enemies = [];
  towers = [];
  bullets = [];
  money = 120;
  lives = 10;
  wave = 0;
  toSpawn = 0;
  selected = 0;
}

function startWave() {
  wave += 1;
  toSpawn = 4 + wave * 2;
  spawnWait = 0;
}

function updateGame() {
  // 敵を、一定の間隔で、1体ずつ出す
  if (toSpawn > 0) {
    spawnWait -= 1;
    if (spawnWait <= 0) {
      spawnEnemy();
      toSpawn -= 1;
      spawnWait = 40;
    }
  }

  enemies.forEach(enemy => enemy.update());
  towers.forEach(tower => tower.update());
  bullets.forEach(bullet => bullet.update());

  // 倒した敵の分だけ、資金が増える
  enemies.forEach(enemy => {
    if (enemy.hp <= 0) {
      money += enemy.reward;
    }
  });

  // 役目を終えたものを、取り除く
  enemies = enemies.filter(enemy => enemy.hp > 0 && enemy.reached === false);
  bullets = bullets.filter(bullet => bullet.done === false);

  if (lives <= 0) {
    message = 'ゲームオーバー';
    scene = 'result';
  } else if (wave >= 8 && toSpawn === 0 && enemies.length === 0) {
    message = 'クリア!';
    scene = 'result';
  }
}

// ウェーブと、何体目かに応じて、敵の種類を決める
function spawnEnemy() {
  let index = 4 + wave * 2 - toSpawn;
  if (wave >= 3 && index % 4 === 3) {
    enemies.push(new TankEnemy());
  } else if (wave >= 2 && index % 3 === 1) {
    enemies.push(new FastEnemy());
  } else {
    enemies.push(new Enemy());
  }
}

// ---------- 描画 ----------

function drawField() {
  noStroke();
  for (let row = 0; row < SIZE; row++) {
    for (let col = 0; col < SIZE; col++) {
      if (grid[row][col] === 1) {
        fill(190, 170, 130);
      } else {
        fill(70, 130, 80);
      }
      rect(col * TILE, row * TILE, TILE, TILE);
    }
  }

  // マウスが乗っているマスに、置けるかどうかと、射程を見せる
  if (scene === 'play' && mouseY < SIZE * TILE && mouseY >= 0 && mouseX >= 0 && mouseX < 400) {
    let col = floor(mouseX / TILE);
    let row = floor(mouseY / TILE);
    let center = centerOf(col, row);
    if (canBuild(col, row)) {
      fill(255, 255, 255, 60);
      stroke(255);
    } else {
      fill(255, 80, 80, 60);
      stroke(255, 80, 80);
    }
    strokeWeight(1);
    circle(center.x, center.y, rangeOf(selected) * 2);
    noStroke();
  }

  towers.forEach(tower => tower.show());
  enemies.forEach(enemy => enemy.show());
  bullets.forEach(bullet => bullet.show());
}

function drawPanel() {
  noStroke();
  fill(20, 20, 40);
  rect(0, 400, 400, 70);

  // タワーを選ぶ、3つのボタン
  textAlign(CENTER, CENTER);
  for (let i = 0; i < 3; i++) {
    let x = 8 + i * 68;
    if (i === selected) {
      fill(90, 100, 150);
    } else {
      fill(50, 55, 85);
    }
    rect(x, 408, 62, 54, 6);
    useTowerColor(i);
    noStroke();
    circle(x + 31, 426, 20);
    fill(255);
    textSize(12);
    text(costOf(i), x + 31, 450);
  }

  // 次のウェーブのボタン
  let waiting = toSpawn === 0 && enemies.length === 0 && wave < 8;
  if (waiting) {
    fill(230, 150, 60);
  } else {
    fill(70, 70, 90);
  }
  rect(218, 408, 80, 54, 6);
  fill(255);
  textSize(12);
  text('次の', 258, 427);
  text('ウェーブ', 258, 443);

  textAlign(LEFT, CENTER);
  textSize(13);
  text(`資金 ${money}`, 308, 420);
  text(`残り ${lives}`, 308, 437);
  text(`ウェーブ ${wave}/8`, 308, 454);
}

function drawOverlay(title, guide) {
  noStroke();
  fill(0, 0, 0, 160);
  rect(0, 0, 400, 470);
  fill(255);
  textAlign(CENTER, CENTER);
  textSize(30);
  text(title, 200, 190);
  textSize(16);
  text(guide, 200, 250);
}

// ---------- タワーの種類ごとの値 ----------

function costOf(kind) {
  return COSTS[kind];
}

function rangeOf(kind) {
  return RANGES[kind];
}

// その種類のタワーの色で、塗りと線を、設定する
function useTowerColor(kind) {
  let c = TOWER_COLORS[kind];
  fill(c[0], c[1], c[2]);
  stroke(c[0], c[1], c[2]);
}

function canBuild(col, row) {
  return grid[row][col] === 0 && money >= costOf(selected);
}

// ---------- 入力 ----------

function mousePressed() {
  if (scene === 'title') {
    startGame();
    scene = 'play';
  } else if (scene === 'result') {
    scene = 'title';
  } else if (mouseY >= 400) {
    // 下のパネル
    for (let i = 0; i < 3; i++) {
      if (mouseX > 8 + i * 68 && mouseX < 70 + i * 68) {
        selected = i;
      }
    }
    if (mouseX > 218 && mouseX < 298 && toSpawn === 0 && enemies.length === 0 && wave < 8) {
      startWave();
    }
  } else if (mouseX >= 0 && mouseX < 400 && mouseY >= 0) {
    // 盤面。置けるなら、タワーを置く
    let col = floor(mouseX / TILE);
    let row = floor(mouseY / TILE);
    if (canBuild(col, row)) {
      money -= costOf(selected);
      grid[row][col] = 2;
      if (selected === 0) {
        towers.push(new Tower(col, row));
      } else if (selected === 1) {
        towers.push(new SlowTower(col, row));
      } else {
        towers.push(new CannonTower(col, row));
      }
    }
  }
}

// ---------- 敵 ----------

// 道に沿って、曲がり角から曲がり角へ、進む
class Enemy {
  constructor() {
    this.pos = centerOf(WAYPOINTS[0].col, WAYPOINTS[0].row);
    this.pos.x -= TILE;
    this.next = 0;
    this.speed = 1;
    this.hp = 6 + wave * 3;
    this.maxHp = this.hp;
    this.reward = 8;
    this.r = 11;
    this.slow = 0;
    this.traveled = 0;
    this.reached = false;
  }

  update() {
    let target = centerOf(WAYPOINTS[this.next].col, WAYPOINTS[this.next].row);
    let toward = p5.Vector.sub(target, this.pos);

    // 遅くされている間は、半分の速さ
    let speed = this.speed;
    if (this.slow > 0) {
      speed = this.speed * 0.5;
      this.slow -= 1;
    }

    if (toward.mag() <= speed) {
      // 曲がり角に着いた。次の曲がり角を、目指す
      this.pos = target;
      this.next += 1;
      if (this.next >= WAYPOINTS.length) {
        this.reached = true;
        lives -= 1;
      }
    } else {
      toward.setMag(speed);
      this.pos.add(toward);
    }
    this.traveled += speed;
  }

  show() {
    noStroke();
    this.paint();
    circle(this.pos.x, this.pos.y, this.r * 2);

    // 体力の棒
    fill(60);
    rect(this.pos.x - 12, this.pos.y - this.r - 8, 24, 4);
    fill(120, 230, 120);
    rect(this.pos.x - 12, this.pos.y - this.r - 8, 24 * this.hp / this.maxHp, 4);
  }

  paint() {
    fill(230, 90, 90);
    if (this.slow > 0) {
      fill(150, 150, 230);
    }
  }
}

class FastEnemy extends Enemy {
  constructor() {
    super();
    this.speed = 2;
    this.hp = 4 + wave * 2;
    this.maxHp = this.hp;
    this.r = 8;
  }

  paint() {
    fill(250, 200, 80);
    if (this.slow > 0) {
      fill(150, 150, 230);
    }
  }
}

class TankEnemy extends Enemy {
  constructor() {
    super();
    this.speed = 0.6;
    this.hp = 25 + wave * 8;
    this.maxHp = this.hp;
    this.reward = 25;
    this.r = 15;
  }

  paint() {
    fill(150, 90, 170);
    if (this.slow > 0) {
      fill(150, 150, 230);
    }
  }
}

// ---------- タワー ----------

// 射程の中で、いちばん先へ進んでいる敵を狙って、弾を撃つ
class Tower {
  constructor(col, row) {
    this.pos = centerOf(col, row);
    this.kind = 0;
    this.range = rangeOf(0);
    this.cooldown = 30;
    this.damage = 3;
    this.wait = 0;
    this.angle = -90;
  }

  // 射程の中の敵のうち、いちばん先へ進んでいるものを返す
  findTarget() {
    let inRange = enemies.filter(enemy => this.pos.dist(enemy.pos) < this.range);
    inRange.sort((a, b) => b.traveled - a.traveled);
    return inRange[0];
  }

  update() {
    if (this.wait > 0) {
      this.wait -= 1;
    }
    let target = this.findTarget();
    if (target) {
      // 敵のほうへ、向きを変える
      this.angle = atan2(target.pos.y - this.pos.y, target.pos.x - this.pos.x);
      if (this.wait === 0) {
        this.fire(target);
        this.wait = this.cooldown;
      }
    }
  }

  fire(target) {
    bullets.push(new Bullet(this.pos.x, this.pos.y, target, this.damage, 0, 0));
  }

  show() {
    noStroke();
    fill(60, 60, 80);
    rect(this.pos.x - 15, this.pos.y - 15, 30, 30, 6);
    useTowerColor(this.kind);
    noStroke();
    circle(this.pos.x, this.pos.y, 20);

    // 砲身。向いている角度へ、線を伸ばす
    useTowerColor(this.kind);
    strokeWeight(5);
    line(this.pos.x, this.pos.y, this.pos.x + cos(this.angle) * 17, this.pos.y + sin(this.angle) * 17);
    noStroke();
  }
}

// 当たった敵を、しばらく遅くする
class SlowTower extends Tower {
  constructor(col, row) {
    super(col, row);
    this.kind = 1;
    this.range = rangeOf(1);
    this.cooldown = 45;
    this.damage = 1;
  }

  fire(target) {
    bullets.push(new Bullet(this.pos.x, this.pos.y, target, this.damage, 120, 0));
  }
}

// 遠くまで届き、当たった場所のまわりの敵にも、ダメージを与える
class CannonTower extends Tower {
  constructor(col, row) {
    super(col, row);
    this.kind = 2;
    this.range = rangeOf(2);
    this.cooldown = 80;
    this.damage = 8;
  }

  fire(target) {
    bullets.push(new Bullet(this.pos.x, this.pos.y, target, this.damage, 0, 45));
  }
}

// ---------- 弾 ----------

// 狙った敵を、追いかけて飛ぶ
class Bullet {
  constructor(x, y, target, damage, slow, splash) {
    this.pos = createVector(x, y);
    this.target = target;
    this.damage = damage;
    this.slow = slow;
    this.splash = splash;
    this.done = false;
  }

  update() {
    let toward = p5.Vector.sub(this.target.pos, this.pos);
    if (toward.mag() < 8) {
      this.hit();
      this.done = true;
    } else {
      toward.setMag(6);
      this.pos.add(toward);
    }
  }

  hit() {
    if (this.splash > 0) {
      // まわりの敵にも、ダメージを与える
      enemies
        .filter(enemy => enemy.pos.dist(this.pos) < this.splash)
        .forEach(enemy => {
          enemy.hp -= this.damage;
        });
    } else {
      this.target.hp -= this.damage;
    }
    if (this.slow > 0) {
      this.target.slow = this.slow;
    }
  }

  show() {
    noStroke();
    if (this.splash > 0) {
      fill(255, 140, 80);
      circle(this.pos.x, this.pos.y, 10);
    } else if (this.slow > 0) {
      fill(170, 220, 255);
      circle(this.pos.x, this.pos.y, 7);
    } else {
      fill(255, 240, 150);
      circle(this.pos.x, this.pos.y, 6);
    }
  }
}

キャンバスをクリックすると、始まります。

操作 働き
下の、3つの丸いボタン 建てるタワーの種類を選ぶ。数字は、値段
緑の空き地を、クリック 選んだタワーを建てる。マウスを乗せると、射程が、円で見える
「次のウェーブ」 敵の、次の一団を、呼ぶ

タワーは、3種類です。

色 値段 特徴
黄 50 ふつう。ほどよい速さで撃つ
水色 70 当たった敵を、しばらく、遅くする。ダメージは、小さい
赤 100 遠くまで届き、当たった場所の、まわりの敵にも、ダメージを与える。撃つ間隔は、長い

敵が、道の終わりまで、たどり着くと、残りが、1 減ります。0 になると、ゲームオーバーです。8 つのウェーブを、すべて防ぐと、クリアです。


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

  • 曲がり角の並びから、道を作り、敵に、たどらせる
  • タワーが、射程の中の敵から、狙う相手を選ぶ仕組みを作る
  • 相手を追いかける弾を作る
  • 継承で、敵とタワーの種類を増やす
  • 配列のメソッドで、絞り込み、並べ替え、取り除きを、短く書く
  • 資金、配置、ウェーブという、ゲームの進み方を、組み立てる

全体を、設計する

登場するもの

もの クラス 自分ですること
敵 Enemy と、子クラス2つ 道に沿って、進む
タワー Tower と、子クラス2つ 射程の中の敵を探し、狙って、弾を撃つ
弾 Bullet 狙った敵を、追いかけ、当たったら、ダメージを与える

3つとも、遊ぶ人が、動かすものでは、ありません。それぞれが、決まりに従って、自分で、動きます。遊ぶ人がするのは、タワーを、どこに建てるかを、決めることだけです。

関わり合い

だれが だれに 何をする
タワー 敵 射程の中から、狙う相手を選ぶ
タワー 弾 弾を作り、狙う相手を、教える
弾 敵 追いかけて、体力を減らす。遅くする
敵 ゲーム 倒されると、資金が増える。たどり着くと、残りが減る

データ

データ 中身
WAYPOINTS 道の、曲がり角の並び
grid 盤面。マスごとに、空き地(0)、道(1)、タワーがある(2)
enemies、towers、bullets 3種類のものを入れる、配列
money、lives、wave 資金、残り、いまのウェーブ

作る順番

順番 作るもの
1 道を作り、描く
2 敵が、道を進む
3 タワーが、敵を狙って、弾を撃つ
4 種類を増やす
5 資金、配置、ウェーブ、画面

ステップ1:道を作る

盤面は、10 × 10 のマスです。マスの大きさは、40 です。

道を、曲がり角で表す

道を、マスを1つずつ指定して、作ることも、できます。しかし、道は、まっすぐな区間が、つながったものです。曲がり角だけを、決めれば、足ります。

sketch.js
const WAYPOINTS = [
  { col: 0, row: 1 },
  { col: 7, row: 1 },
  { col: 7, row: 4 },
  { col: 2, row: 4 },
  { col: 2, row: 7 },
  { col: 9, row: 7 }
];

オブジェクトの配列です。1つのオブジェクトが、1つの曲がり角で、列と行の番号を、持っています。最初の要素が、道の入口。最後の要素が、出口です。


この1つの配列を、2つの目的に、使います。

目的 使い方
盤面に、道を描く 隣り合う曲がり角の間のマスを、道にする
敵を、進ませる 敵が、曲がり角を、順に、目指す

道の形と、敵の進み方が、同じデータから、作られます。だから、2つが、食い違うことは、ありません。配列を書き換えれば、道の形も、敵の進み方も、いっしょに、変わります。

曲がり角の間を、道にする

sketch.js
for (let i = 0; i < WAYPOINTS.length - 1; i++) {
  let a = WAYPOINTS[i];
  let b = WAYPOINTS[i + 1];
  for (let col = min(a.col, b.col); col <= max(a.col, b.col); col++) {
    for (let row = min(a.row, b.row); row <= max(a.row, b.row); row++) {
      grid[row][col] = 1;
    }
  }
}

a と b は、隣り合う、2つの曲がり角です。その間の、すべてのマスを、1(道)に、します。


min と max を、使っています。道は、右へ進む区間も、左へ進む区間も、あります。a.col から b.col へ、と書くと、左へ進む区間では、a.col のほうが大きく、ループが、1回も、回りません。小さいほうから、大きいほうへ、回すことで、どちら向きの区間でも、同じように、扱えます。


区間は、横か、縦の、どちらかです。横の区間なら、行は、1つだけ(a.row と b.row が、同じ)。縦の区間なら、列が、1つだけです。二重ループに、していますが、片方は、1回しか、回りません。

マスの真ん中の座標

敵も、タワーも、マスの真ん中に、置きます。マスの番号から、その真ん中の座標を、ベクトルで返す関数を、用意します。

sketch.js
function centerOf(col, row) {
  return createVector(col * TILE + TILE / 2, row * TILE + TILE / 2);
}
sketch.js
const TILE = 40;
const SIZE = 10;

// 敵が通る道の、曲がり角(マスの番号)
const WAYPOINTS = [
  { col: 0, row: 1 },
  { col: 7, row: 1 },
  { col: 7, row: 4 },
  { col: 2, row: 4 },
  { col: 2, row: 7 },
  { col: 9, row: 7 }
];

let grid = [];

function setup() {
  createCanvas(400, 400);
  makeGrid();
}

function draw() {
  noStroke();
  for (let row = 0; row < SIZE; row++) {
    for (let col = 0; col < SIZE; col++) {
      if (grid[row][col] === 1) {
        fill(190, 170, 130);
      } else {
        fill(70, 130, 80);
      }
      rect(col * TILE, row * TILE, TILE, TILE);
    }
  }

  // 曲がり角に、印を付ける
  fill(255);
  WAYPOINTS.forEach(point => {
    let center = centerOf(point.col, point.row);
    circle(center.x, center.y, 10);
  });
}

// 盤面を作る。0:空き地 1:道 2:タワーがある
function makeGrid() {
  for (let row = 0; row < SIZE; row++) {
    grid[row] = [];
    for (let col = 0; col < SIZE; col++) {
      grid[row][col] = 0;
    }
  }

  // 曲がり角から、次の曲がり角までを、道にする
  for (let i = 0; i < WAYPOINTS.length - 1; i++) {
    let a = WAYPOINTS[i];
    let b = WAYPOINTS[i + 1];
    for (let col = min(a.col, b.col); col <= max(a.col, b.col); col++) {
      for (let row = min(a.row, b.row); row <= max(a.row, b.row); row++) {
        grid[row][col] = 1;
      }
    }
  }
}

// マスの番号から、その真ん中の座標(ベクトル)を作る
function centerOf(col, row) {
  return createVector(col * TILE + TILE / 2, row * TILE + TILE / 2);
}

緑の空き地の中に、ベージュの道が、折れ曲がって、通っています。白い点が、曲がり角です。左上から入り、右下から、出ていきます。

ステップ2:敵が、道を進む

敵は、次の曲がり角を目指して、まっすぐ、進みます。着いたら、その次の曲がり角を、目指します。

javascript
class Enemy {
  constructor() {
    this.pos = centerOf(WAYPOINTS[0].col, WAYPOINTS[0].row);
    this.pos.x -= TILE;
    this.next = 0;
    this.speed = 1;
    // ...
  }
}
プロパティ 意味
pos 位置(ベクトル)。入口より、1マス左の、画面の外から、始まる
next 次に目指す曲がり角の番号
speed 進む速さ

目指す場所へ、1歩、進む

javascript
let target = centerOf(WAYPOINTS[this.next].col, WAYPOINTS[this.next].row);
let toward = p5.Vector.sub(target, this.pos);

if (toward.mag() <= speed) {
  this.pos = target;
  this.next += 1;
} else {
  toward.setMag(speed);
  this.pos.add(toward);
}

target は、次の曲がり角の、座標です。toward は、自分から、そこへ向かう矢印です。

場合 すること
矢印の長さが、1歩の長さ以下 もう、着く。位置を、曲がり角に、ぴったり合わせ、next を、1 増やす
まだ、遠い 矢印の長さを、1歩の長さにして、位置に、足す

setMag(speed) は、矢印の向きを保ったまま、長さを、速さに、そろえます。曲がり角が、右にあれば、右へ。下にあれば、下へ。向きを、if で分ける必要は、ありません。ベクトルの引き算が、向きを、決めてくれます。

ぴったり、合わせる

曲がり角の、すぐ手前まで来たら、位置を、曲がり角に、合わせます。


1歩の長さは、速さによって、違います。合わせないと、曲がり角を、少し、行き過ぎたり、手前で止まったりします。そのずれが、曲がるたびに、積み重なり、敵が、道から、はみ出していきます。

出口に着いたら

sketch.js
if (this.next >= WAYPOINTS.length) {
  this.reached = true;
  lives -= 1;
}

next が、曲がり角の数を、超えたら、最後の曲がり角(出口)に、着いたということです。reached を true にして、残りを、1 減らします。

進んだ距離を、覚えておく

sketch.js
this.traveled += speed;

traveled は、これまでに、進んだ距離の合計です。あとで、タワーが、「いちばん先頭の敵」を選ぶときに、使います。

配列のメソッドで、まとめて処理する

sketch.js
enemies.forEach(enemy => enemy.update());
enemies = enemies.filter(enemy => enemy.reached === false);

1行目は、すべての敵の、update() を、呼び出します。


2行目は、出口に着いていない敵だけを集めた、新しい配列を作り、enemies に、入れ直します。着いた敵は、新しい配列に、入らないので、取り除かれたことに、なります。


for ループを、後ろから回して、splice で取り除く方法と、結果は、同じです。filter を使うと、「残したいものの条件」を、1行で、書けます。

sketch.js
const TILE = 40;
const SIZE = 10;

// 敵が通る道の、曲がり角(マスの番号)
const WAYPOINTS = [
  { col: 0, row: 1 },
  { col: 7, row: 1 },
  { col: 7, row: 4 },
  { col: 2, row: 4 },
  { col: 2, row: 7 },
  { col: 9, row: 7 }
];

let grid = [];
let enemies = [];
let lives = 10;
let wave = 1;

function setup() {
  createCanvas(400, 400);
  makeGrid();
}

function draw() {
  // 60フレームごとに、敵を1体出す
  if (frameCount % 60 === 0) {
    enemies.push(new Enemy());
  }

  enemies.forEach(enemy => enemy.update());
  enemies = enemies.filter(enemy => enemy.reached === false);

  noStroke();
  for (let row = 0; row < SIZE; row++) {
    for (let col = 0; col < SIZE; col++) {
      if (grid[row][col] === 1) {
        fill(190, 170, 130);
      } else {
        fill(70, 130, 80);
      }
      rect(col * TILE, row * TILE, TILE, TILE);
    }
  }
  enemies.forEach(enemy => enemy.show());

  fill(255);
  textSize(16);
  text(`残り ${lives}`, 12, 390);
}

// 盤面を作る。0:空き地 1:道 2:タワーがある
function makeGrid() {
  for (let row = 0; row < SIZE; row++) {
    grid[row] = [];
    for (let col = 0; col < SIZE; col++) {
      grid[row][col] = 0;
    }
  }

  // 曲がり角から、次の曲がり角までを、道にする
  for (let i = 0; i < WAYPOINTS.length - 1; i++) {
    let a = WAYPOINTS[i];
    let b = WAYPOINTS[i + 1];
    for (let col = min(a.col, b.col); col <= max(a.col, b.col); col++) {
      for (let row = min(a.row, b.row); row <= max(a.row, b.row); row++) {
        grid[row][col] = 1;
      }
    }
  }
}

// マスの番号から、その真ん中の座標(ベクトル)を作る
function centerOf(col, row) {
  return createVector(col * TILE + TILE / 2, row * TILE + TILE / 2);
}

// 道に沿って、曲がり角から曲がり角へ、進む
class Enemy {
  constructor() {
    this.pos = centerOf(WAYPOINTS[0].col, WAYPOINTS[0].row);
    this.pos.x -= TILE;
    this.next = 0;
    this.speed = 1;
    this.hp = 6 + wave * 3;
    this.maxHp = this.hp;
    this.reward = 8;
    this.r = 11;
    this.slow = 0;
    this.traveled = 0;
    this.reached = false;
  }

  update() {
    let target = centerOf(WAYPOINTS[this.next].col, WAYPOINTS[this.next].row);
    let toward = p5.Vector.sub(target, this.pos);

    // 遅くされている間は、半分の速さ
    let speed = this.speed;
    if (this.slow > 0) {
      speed = this.speed * 0.5;
      this.slow -= 1;
    }

    if (toward.mag() <= speed) {
      // 曲がり角に着いた。次の曲がり角を、目指す
      this.pos = target;
      this.next += 1;
      if (this.next >= WAYPOINTS.length) {
        this.reached = true;
        lives -= 1;
      }
    } else {
      toward.setMag(speed);
      this.pos.add(toward);
    }
    this.traveled += speed;
  }

  show() {
    noStroke();
    this.paint();
    circle(this.pos.x, this.pos.y, this.r * 2);

    // 体力の棒
    fill(60);
    rect(this.pos.x - 12, this.pos.y - this.r - 8, 24, 4);
    fill(120, 230, 120);
    rect(this.pos.x - 12, this.pos.y - this.r - 8, 24 * this.hp / this.maxHp, 4);
  }

  paint() {
    fill(230, 90, 90);
    if (this.slow > 0) {
      fill(150, 150, 230);
    }
  }
}

赤い敵が、1秒に1体、左上から現れ、道に沿って、進みます。曲がり角で、向きを変え、右下から、出ていきます。出るたびに、左下の「残り」が、減ります。

クイズ

WAYPOINTS の3つ目の要素を、{ col: 7, row: 4 } から、{ col: 5, row: 4 } に、書き換えたとします。道と、敵の動きは、どうなるでしょう?

▶ 答えを確認する

道の描き方と、敵の進み方が、食い違います。


2つ目の曲がり角は (7, 1)、3つ目は (5, 4) に、なります。列も、行も、違うので、この区間は、斜めです。


道を作る二重ループは、列が 5 から 7、行が 1 から 4 の、四角形の範囲を、すべて、道にします。3 × 4 = 12 マスの、広場が、できます。


一方、敵は、(7, 1) から (5, 4) へ、まっすぐ、斜めに、進みます。


曲がり角は、隣どうしが、同じ行か、同じ列になるように、決める必要が、あります。データの形には、守るべき約束が、あります。

ステップ3:タワーが、狙って撃つ

タワーは、毎フレーム、次のことを、します。

順番 すること
1 射程の中に、敵がいるかを、調べる
2 いれば、その中から、狙う相手を、1体、選ぶ
3 相手のほうを、向く
4 撃てる状態なら、弾を撃つ

狙う相手を、選ぶ

sketch.js
findTarget() {
  let inRange = enemies.filter(enemy => this.pos.dist(enemy.pos) < this.range);
  inRange.sort((a, b) => b.traveled - a.traveled);
  return inRange[0];
}

3行で、相手を、選んでいます。

行 していること
1行目 すべての敵から、射程の中にいるものだけを、集める
2行目 それを、進んだ距離の大きい順に、並べ替える
3行目 先頭の要素、つまり、いちばん先へ進んでいる敵を、返す

this.pos.dist(enemy.pos) は、タワーと敵の、距離です。this.range(射程)より、小さければ、届きます。


sort に渡している (a, b) => b.traveled - a.traveled は、「どちらを、先に並べるか」を、決める関数です。b - a の形にすると、大きい順に、並びます。


射程の中に、敵が、1体もいなければ、inRange は、空の配列です。空の配列の [0] は、undefined(何もない)です。

なぜ、先頭の敵を狙うのか

いちばん近い敵を、狙う方法も、あります。しかし、タワーディフェンスで、困るのは、出口に、たどり着かれることです。出口に、いちばん近づいている敵を、先に倒すほうが、守りとして、理にかなっています。


filter で絞り込むときに使った sort は、inRange という、新しい配列を、並べ替えています。元の enemies の順番は、変わりません。

相手のほうを、向く

sketch.js
this.angle = atan2(target.pos.y - this.pos.y, target.pos.x - this.pos.x);

atan2(縦の差, 横の差) は、タワーから、相手を見た方角を、角度で、返します。この角度を、覚えておき、描くときに、砲身を、その向きへ、伸ばします。

sketch.js
line(this.pos.x, this.pos.y, this.pos.x + cos(this.angle) * 17, this.pos.y + sin(this.angle) * 17);

中心から、その角度の向きへ、17 だけ進んだ点まで、線を引いています。タワーが、敵を、目で追っているように、見えます。

撃つ間隔

sketch.js
if (this.wait === 0) {
  this.fire(target);
  this.wait = this.cooldown;
}

wait は、次に撃てるまでの、残りフレーム数です。撃ったら、cooldown(30)に、します。毎フレーム、1 ずつ減らし、0 のときだけ、撃てます。

弾は、相手を追いかける

javascript
class Bullet {
  constructor(x, y, target, damage, slow, splash) {
    this.pos = createVector(x, y);
    this.target = target;
    // ...
  }

  update() {
    let toward = p5.Vector.sub(this.target.pos, this.pos);
    if (toward.mag() < 8) {
      this.hit();
      this.done = true;
    } else {
      toward.setMag(6);
      this.pos.add(toward);
    }
  }
}

弾は、生まれるときに、狙う相手(target)を、受け取ります。相手の位置では、なく、相手のインスタンスそのものを、覚えておきます。


毎フレーム、相手の、いまの位置へ向かう矢印を、作り、その向きへ、6 だけ、進みます。相手が動いても、弾は、向きを変えて、追いかけます。必ず、当たります。


敵が道を進むのと、まったく同じ形です。目指す場所への矢印を作り、長さを速さにして、位置に足す。目指す場所が、止まっている曲がり角か、動いている敵か、の違いだけです。


相手に、十分、近づいたら(距離が 8 より小さくなったら)、hit() で、ダメージを与え、done を true に、します。

sketch.js
const TILE = 40;
const SIZE = 10;

// 敵が通る道の、曲がり角(マスの番号)
const WAYPOINTS = [
  { col: 0, row: 1 },
  { col: 7, row: 1 },
  { col: 7, row: 4 },
  { col: 2, row: 4 },
  { col: 2, row: 7 },
  { col: 9, row: 7 }
];

let grid = [];
let enemies = [];
let towers = [];
let bullets = [];
let lives = 10;
let wave = 1;

function setup() {
  createCanvas(400, 400);
  angleMode(DEGREES);
  makeGrid();
}

function draw() {
  if (frameCount % 60 === 0) {
    enemies.push(new Enemy());
  }

  enemies.forEach(enemy => enemy.update());
  towers.forEach(tower => tower.update());
  bullets.forEach(bullet => bullet.update());

  enemies = enemies.filter(enemy => enemy.hp > 0 && enemy.reached === false);
  bullets = bullets.filter(bullet => bullet.done === false);

  noStroke();
  for (let row = 0; row < SIZE; row++) {
    for (let col = 0; col < SIZE; col++) {
      if (grid[row][col] === 1) {
        fill(190, 170, 130);
      } else {
        fill(70, 130, 80);
      }
      rect(col * TILE, row * TILE, TILE, TILE);
    }
  }
  towers.forEach(tower => tower.show());
  enemies.forEach(enemy => enemy.show());
  bullets.forEach(bullet => bullet.show());

  fill(255);
  textSize(16);
  text(`残り ${lives}`, 12, 390);
}

// 空き地をクリックしたら、タワーを置く
function mousePressed() {
  let col = floor(mouseX / TILE);
  let row = floor(mouseY / TILE);
  if (col >= 0 && col < SIZE && row >= 0 && row < SIZE && grid[row][col] === 0) {
    grid[row][col] = 2;
    towers.push(new Tower(col, row));
  }
}

// 盤面を作る。0:空き地 1:道 2:タワーがある
function makeGrid() {
  for (let row = 0; row < SIZE; row++) {
    grid[row] = [];
    for (let col = 0; col < SIZE; col++) {
      grid[row][col] = 0;
    }
  }

  // 曲がり角から、次の曲がり角までを、道にする
  for (let i = 0; i < WAYPOINTS.length - 1; i++) {
    let a = WAYPOINTS[i];
    let b = WAYPOINTS[i + 1];
    for (let col = min(a.col, b.col); col <= max(a.col, b.col); col++) {
      for (let row = min(a.row, b.row); row <= max(a.row, b.row); row++) {
        grid[row][col] = 1;
      }
    }
  }
}

// マスの番号から、その真ん中の座標(ベクトル)を作る
function centerOf(col, row) {
  return createVector(col * TILE + TILE / 2, row * TILE + TILE / 2);
}

// 道に沿って、曲がり角から曲がり角へ、進む
class Enemy {
  constructor() {
    this.pos = centerOf(WAYPOINTS[0].col, WAYPOINTS[0].row);
    this.pos.x -= TILE;
    this.next = 0;
    this.speed = 1;
    this.hp = 6 + wave * 3;
    this.maxHp = this.hp;
    this.reward = 8;
    this.r = 11;
    this.slow = 0;
    this.traveled = 0;
    this.reached = false;
  }

  update() {
    let target = centerOf(WAYPOINTS[this.next].col, WAYPOINTS[this.next].row);
    let toward = p5.Vector.sub(target, this.pos);

    // 遅くされている間は、半分の速さ
    let speed = this.speed;
    if (this.slow > 0) {
      speed = this.speed * 0.5;
      this.slow -= 1;
    }

    if (toward.mag() <= speed) {
      // 曲がり角に着いた。次の曲がり角を、目指す
      this.pos = target;
      this.next += 1;
      if (this.next >= WAYPOINTS.length) {
        this.reached = true;
        lives -= 1;
      }
    } else {
      toward.setMag(speed);
      this.pos.add(toward);
    }
    this.traveled += speed;
  }

  show() {
    noStroke();
    this.paint();
    circle(this.pos.x, this.pos.y, this.r * 2);

    // 体力の棒
    fill(60);
    rect(this.pos.x - 12, this.pos.y - this.r - 8, 24, 4);
    fill(120, 230, 120);
    rect(this.pos.x - 12, this.pos.y - this.r - 8, 24 * this.hp / this.maxHp, 4);
  }

  paint() {
    fill(230, 90, 90);
    if (this.slow > 0) {
      fill(150, 150, 230);
    }
  }
}

// 射程の中で、いちばん先へ進んでいる敵を狙って、弾を撃つ
class Tower {
  constructor(col, row) {
    this.pos = centerOf(col, row);
    this.kind = 0;
    this.range = 90;
    this.cooldown = 30;
    this.damage = 3;
    this.wait = 0;
    this.angle = -90;
  }

  // 射程の中の敵のうち、いちばん先へ進んでいるものを返す
  findTarget() {
    let inRange = enemies.filter(enemy => this.pos.dist(enemy.pos) < this.range);
    inRange.sort((a, b) => b.traveled - a.traveled);
    return inRange[0];
  }

  update() {
    if (this.wait > 0) {
      this.wait -= 1;
    }
    let target = this.findTarget();
    if (target) {
      // 敵のほうへ、向きを変える
      this.angle = atan2(target.pos.y - this.pos.y, target.pos.x - this.pos.x);
      if (this.wait === 0) {
        this.fire(target);
        this.wait = this.cooldown;
      }
    }
  }

  fire(target) {
    bullets.push(new Bullet(this.pos.x, this.pos.y, target, this.damage, 0, 0));
  }

  show() {
    noStroke();
    fill(60, 60, 80);
    rect(this.pos.x - 15, this.pos.y - 15, 30, 30, 6);
    fill(240, 220, 90);
    circle(this.pos.x, this.pos.y, 20);

    // 砲身。向いている角度へ、線を伸ばす
    stroke(240, 220, 90);
    strokeWeight(5);
    line(this.pos.x, this.pos.y, this.pos.x + cos(this.angle) * 17, this.pos.y + sin(this.angle) * 17);
    noStroke();
  }
}

// 狙った敵を、追いかけて飛ぶ
class Bullet {
  constructor(x, y, target, damage, slow, splash) {
    this.pos = createVector(x, y);
    this.target = target;
    this.damage = damage;
    this.slow = slow;
    this.splash = splash;
    this.done = false;
  }

  update() {
    let toward = p5.Vector.sub(this.target.pos, this.pos);
    if (toward.mag() < 8) {
      this.hit();
      this.done = true;
    } else {
      toward.setMag(6);
      this.pos.add(toward);
    }
  }

  hit() {
    if (this.splash > 0) {
      // まわりの敵にも、ダメージを与える
      enemies
        .filter(enemy => enemy.pos.dist(this.pos) < this.splash)
        .forEach(enemy => {
          enemy.hp -= this.damage;
        });
    } else {
      this.target.hp -= this.damage;
    }
    if (this.slow > 0) {
      this.target.slow = this.slow;
    }
  }

  show() {
    noStroke();
    if (this.splash > 0) {
      fill(255, 140, 80);
      circle(this.pos.x, this.pos.y, 10);
    } else if (this.slow > 0) {
      fill(170, 220, 255);
      circle(this.pos.x, this.pos.y, 7);
    } else {
      fill(255, 240, 150);
      circle(this.pos.x, this.pos.y, 6);
    }
  }
}

緑の空き地を、クリックすると、タワーが、建ちます。タワーは、近づいた敵に、砲身を向け、弾を撃ちます。体力の棒が、減っていき、0 になると、敵が、消えます。道の上には、建てられません。


道の曲がり角の、内側に建てると、敵が、長い間、射程の中に、とどまります。同じタワーでも、置く場所で、働きが、大きく変わります。それが、このゲームの、考えどころです。

ステップ4:種類を増やす

敵の種類

速い敵と、固い敵を、足します。Enemy を継承し、値だけを、変えます。

クラス 速さ 体力 倒したときの資金 色
Enemy 1 ふつう 8 赤
FastEnemy 2 少ない 8 黄
TankEnemy 0.6 とても多い 25 紫

道を進む update() は、どの敵も、親クラスのものを、そのまま、使います。


色だけは、種類ごとに、違います。show() の全体を、書き直すのは、大げさです。そこで、親クラスの show() の中で、色を決める部分だけを、paint() という、別のメソッドに、しておきます。

javascript
show() {
  noStroke();
  this.paint();
  circle(this.pos.x, this.pos.y, this.r * 2);
  // 体力の棒を描く
}

paint() {
  fill(230, 90, 90);
}

子クラスは、paint() だけを、書き直せば、色が、変わります。円を描く処理も、体力の棒も、親クラスのものが、使われます。変えたい部分だけを、小さなメソッドに、切り出しておくと、子クラスが、書き直す量を、減らせます。

タワーの種類

タワーの違いは、「どんな弾を撃つか」です。そこで、弾を撃つ部分を、fire() というメソッドに、分けてあります。

sketch.js
fire(target) {
  bullets.push(new Bullet(this.pos.x, this.pos.y, target, this.damage, 0, 0));
}

Bullet に渡す、最後の2つの数が、弾の、特別な働きです。

引数 意味 0 のとき
slow 当たった敵を、何フレーム、遅くするか 遅くしない
splash 当たった場所から、どの範囲の敵に、ダメージを与えるか 狙った1体だけ

子クラスは、値を上書きし、fire() を、書き直します。

クラス 射程 撃つ間隔 ダメージ 弾の働き
Tower 90 30 3 なし
SlowTower 80 45 1 120 フレーム、遅くする
CannonTower 130 80 8 半径 45 の範囲に、ダメージ

相手を探す findTarget()、砲身を向けて撃つ update()、描く show()。どれも、親クラスのものを、そのまま、使います。

範囲へのダメージ

sketch.js
enemies
  .filter(enemy => enemy.pos.dist(this.pos) < this.splash)
  .forEach(enemy => {
    enemy.hp -= this.damage;
  });

「弾の位置から、splash 以内にいる敵」を、filter で集め、その全員の体力を、forEach で、減らしています。メソッドを、ドットで、つなげて、書いています。左から順に、実行されます。


敵が、かたまって進んでくると、1発で、まとめて、ダメージを、与えられます。

遅くする

弾が当たると、敵の slow に、120 が、入ります。敵は、slow が 0 より大きい間、半分の速さで、進み、毎フレーム、slow を、1 減らします。2 秒たつと、元の速さに、戻ります。


遅くなった敵は、ほかのタワーの射程に、長く、とどまります。水色のタワー自体は、ほとんど、ダメージを与えません。ほかのタワーと、組み合わせて、はじめて、力を、発揮します。

ステップ5:資金、配置、ウェーブ

タワーごとの値を、配列にまとめる

タワーの種類ごとの、値段、射程、色を、配列に、まとめます。番号が、種類です。

sketch.js
const COSTS = [50, 70, 100];
const RANGES = [90, 80, 130];
const TOWER_COLORS = [[240, 220, 90], [120, 200, 255], [240, 110, 110]];

ボタンを描くとき。置けるかを調べるとき。射程の円を描くとき。どこでも、種類の番号から、値を、取り出せます。値段を変えたくなったら、この配列を、書き換えるだけです。

置けるかどうか

sketch.js
function canBuild(col, row) {
  return grid[row][col] === 0 && money >= costOf(selected);
}

そのマスが、空き地で、資金が足りているとき、置けます。道(1)や、すでにタワーがあるマス(2)には、置けません。


この関数は、2か所で、使います。

場所 使いみち
描くとき マウスが乗っているマスに、置けるなら、白い円。置けないなら、赤い円を出す
クリックされたとき 置けるなら、実際に、置く

表示と、実際の動きが、同じ関数を、通ります。「白い円が出たのに、置けない」ということが、起きません。

置く前に、射程を見せる

マウスを乗せたマスを中心に、選んでいるタワーの射程を、円で、表示します。建てる前に、「ここに建てたら、道の、どこまで、届くか」が、わかります。


遊ぶ人が、考えるための情報を、見せることが、大事です。射程が見えなければ、置いてみるまで、わからず、資金を、無駄にしてしまいます。

ウェーブ

敵は、ウェーブと呼ばれる、ひとまとまりで、やってきます。ボタンを押すと、次のウェーブが、始まります。

sketch.js
function startWave() {
  wave += 1;
  toSpawn = 4 + wave * 2;
  spawnWait = 0;
}

toSpawn は、これから出す、敵の数です。ウェーブが進むほど、増えます。

ウェーブ 敵の数
1 6
4 12
8 20

敵を、いっぺんに出すと、重なってしまいます。40 フレームに1体ずつ、出します。

sketch.js
if (toSpawn > 0) {
  spawnWait -= 1;
  if (spawnWait <= 0) {
    spawnEnemy();
    toSpawn -= 1;
    spawnWait = 40;
  }
}

敵の種類を、決まった順番で出す

sketch.js
let index = 4 + wave * 2 - toSpawn;
if (wave >= 3 && index % 4 === 3) {
  enemies.push(new TankEnemy());
} else if (wave >= 2 && index % 3 === 1) {
  enemies.push(new FastEnemy());
} else {
  enemies.push(new Enemy());
}

index は、そのウェーブの中で、何体目かです。0 から、数えます。

条件 出る敵
ウェーブ 3 以降で、4体ごとに1体 固い敵
ウェーブ 2 以降で、3体ごとに1体 速い敵
それ以外 ふつうの敵

乱数を、使っていません。同じウェーブは、いつも、同じ並びで、敵が、出てきます。何度も遊ぶうちに、「ウェーブ 3 で、固い敵が来るから、その前に、赤いタワーを」と、作戦を、立てられます。考えるゲームでは、でたらめより、決まった並びのほうが、向いています。


敵の体力も、ウェーブが進むほど、増えます。Enemy のコンストラクタの中で、6 + wave * 3 と、ウェーブの数から、決めています。

資金の出入り

出来事 資金
ゲームの最初 120
タワーを建てる 値段の分、減る
敵を倒す 敵の reward の分、増える
sketch.js
enemies.forEach(enemy => {
  if (enemy.hp <= 0) {
    money += enemy.reward;
  }
});

// 役目を終えたものを、取り除く
enemies = enemies.filter(enemy => enemy.hp > 0 && enemy.reached === false);

倒した敵を、取り除く前に、資金を、足しています。取り除いたあとでは、もう、配列に、いないので、数えられません。


そのあと、filter で、体力が残っていて、出口に着いていない敵だけを、残します。

終わりの条件

条件 結果
残りが、0 以下 ゲームオーバー
ウェーブ 8 が終わり、敵が、1体も残っていない クリア

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

冒頭のプログラムが、完成形です。

まとまり 内容
データ WAYPOINTS、COSTS、RANGES、TOWER_COLORS
盤面 makeGrid、centerOf
進行 startGame、startWave、updateGame、spawnEnemy
描画 drawField、drawPanel、drawOverlay
タワーの値 costOf、rangeOf、useTowerColor、canBuild
入力 mousePressed
クラス Enemy、FastEnemy、TankEnemy、Tower、SlowTower、CannonTower、Bullet

継承の、使い方

親クラス 子クラスが、書き直すもの 親から、そのまま使うもの
Enemy 値、paint()(色) 道を進む update()、show()
Tower 値、fire()(どんな弾を撃つか) findTarget()、update()、show()

どちらも、子クラスに書くのは、ほんの数行です。親クラスの中で、「種類によって、変わる部分」を、小さなメソッドに、切り出しておいたからです。色を決める paint()。弾を撃つ fire()。そこだけを、書き直せば、新しい種類が、作れます。

配列のメソッド

メソッド 使っている場所
forEach すべての敵、タワー、弾の、update() と show() を呼ぶ
filter 射程の中の敵を集める。役目を終えたものを取り除く。範囲の中の敵を集める
sort 射程の中の敵を、進んだ順に並べる

遊びの、釣り合い

タワーディフェンスは、数字の釣り合いで、面白さが、決まります。

数字 大きすぎると 小さすぎると
最初の資金 最初から、たくさん建てられて、簡単 最初のウェーブが、防げない
敵を倒したときの資金 すぐに、盤面が、タワーで埋まる タワーを、増やせない
敵の体力の増え方 後半が、どうやっても、防げない 最後まで、楽に進む
タワーの値段の差 高いタワーを、だれも、建てない 安いタワーが、いらなくなる

ちょうどよい数字は、何度も遊んで、探します。何もしないと、途中で負ける。よく考えて建てれば、ぎりぎりで、守り切れる。そのくらいが、目標です。


3種類のタワーに、それぞれの、出番があることも、大事です。黄色は、安くて、数を、そろえやすい。水色は、ほかのタワーを、助ける。赤は、かたまった敵と、遠くの敵に、強い。どれか1種類だけを建てれば勝てる、という作りに、ならないように、数字を、調整します。

やってみよう

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

  1. すでに建てたタワーを、クリックすると、売れるようにする。売ると、30 の資金が、戻る
  2. タワーが狙う相手を、「いちばん先へ進んでいる敵」から、「いちばん体力の多い敵」に、変える。遊んで、違いを確かめる
  3. 4種類目の敵として、体力が半分より減ると、速くなる敵を、足す
▶ 1. タワーを売る

クリックしたマスの値が、2(タワーがある)なら、そのマスの真ん中にあるタワーを、filter で、取り除きます。マスを、0 に戻し、資金を、足します。

sketch.js
const TILE = 40;
const SIZE = 10;

// 敵が通る道の、曲がり角(マスの番号)
const WAYPOINTS = [
  { col: 0, row: 1 },
  { col: 7, row: 1 },
  { col: 7, row: 4 },
  { col: 2, row: 4 },
  { col: 2, row: 7 },
  { col: 9, row: 7 }
];

// タワーの種類ごとの、値段、射程、色。0:ふつう 1:遅くする 2:大砲
const COSTS = [50, 70, 100];
const RANGES = [90, 80, 130];
const REFUND = 30;
const TOWER_COLORS = [[240, 220, 90], [120, 200, 255], [240, 110, 110]];

let scene = 'title';
let message = '';
let grid = [];
let enemies = [];
let towers = [];
let bullets = [];

let money = 0;
let lives = 0;
let wave = 0;
let toSpawn = 0;
let spawnWait = 0;
let selected = 0;

function setup() {
  createCanvas(400, 470);
  angleMode(DEGREES);
  makeGrid();
}

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

  if (scene === 'play') {
    updateGame();
  }
  drawField();
  drawPanel();

  if (scene === 'title') {
    drawOverlay('タワーディフェンス', 'クリックで、スタート');
  } else if (scene === 'result') {
    drawOverlay(message, 'クリックで、タイトルへ');
  }
}

// ---------- 盤面 ----------

// 盤面を作る。0:空き地 1:道 2:タワーがある
function makeGrid() {
  for (let row = 0; row < SIZE; row++) {
    grid[row] = [];
    for (let col = 0; col < SIZE; col++) {
      grid[row][col] = 0;
    }
  }

  // 曲がり角から、次の曲がり角までを、道にする
  for (let i = 0; i < WAYPOINTS.length - 1; i++) {
    let a = WAYPOINTS[i];
    let b = WAYPOINTS[i + 1];
    for (let col = min(a.col, b.col); col <= max(a.col, b.col); col++) {
      for (let row = min(a.row, b.row); row <= max(a.row, b.row); row++) {
        grid[row][col] = 1;
      }
    }
  }
}

// マスの番号から、その真ん中の座標(ベクトル)を作る
function centerOf(col, row) {
  return createVector(col * TILE + TILE / 2, row * TILE + TILE / 2);
}

// ---------- ゲームの進行 ----------

function startGame() {
  makeGrid();
  enemies = [];
  towers = [];
  bullets = [];
  money = 120;
  lives = 10;
  wave = 0;
  toSpawn = 0;
  selected = 0;
}

function startWave() {
  wave += 1;
  toSpawn = 4 + wave * 2;
  spawnWait = 0;
}

function updateGame() {
  // 敵を、一定の間隔で、1体ずつ出す
  if (toSpawn > 0) {
    spawnWait -= 1;
    if (spawnWait <= 0) {
      spawnEnemy();
      toSpawn -= 1;
      spawnWait = 40;
    }
  }

  enemies.forEach(enemy => enemy.update());
  towers.forEach(tower => tower.update());
  bullets.forEach(bullet => bullet.update());

  // 倒した敵の分だけ、資金が増える
  enemies.forEach(enemy => {
    if (enemy.hp <= 0) {
      money += enemy.reward;
    }
  });

  // 役目を終えたものを、取り除く
  enemies = enemies.filter(enemy => enemy.hp > 0 && enemy.reached === false);
  bullets = bullets.filter(bullet => bullet.done === false);

  if (lives <= 0) {
    message = 'ゲームオーバー';
    scene = 'result';
  } else if (wave >= 8 && toSpawn === 0 && enemies.length === 0) {
    message = 'クリア!';
    scene = 'result';
  }
}

// ウェーブと、何体目かに応じて、敵の種類を決める
function spawnEnemy() {
  let index = 4 + wave * 2 - toSpawn;
  if (wave >= 3 && index % 4 === 3) {
    enemies.push(new TankEnemy());
  } else if (wave >= 2 && index % 3 === 1) {
    enemies.push(new FastEnemy());
  } else {
    enemies.push(new Enemy());
  }
}

// ---------- 描画 ----------

function drawField() {
  noStroke();
  for (let row = 0; row < SIZE; row++) {
    for (let col = 0; col < SIZE; col++) {
      if (grid[row][col] === 1) {
        fill(190, 170, 130);
      } else {
        fill(70, 130, 80);
      }
      rect(col * TILE, row * TILE, TILE, TILE);
    }
  }

  // マウスが乗っているマスに、置けるかどうかと、射程を見せる
  if (scene === 'play' && mouseY < SIZE * TILE && mouseY >= 0 && mouseX >= 0 && mouseX < 400) {
    let col = floor(mouseX / TILE);
    let row = floor(mouseY / TILE);
    let center = centerOf(col, row);
    if (canBuild(col, row)) {
      fill(255, 255, 255, 60);
      stroke(255);
    } else {
      fill(255, 80, 80, 60);
      stroke(255, 80, 80);
    }
    strokeWeight(1);
    circle(center.x, center.y, rangeOf(selected) * 2);
    noStroke();
  }

  towers.forEach(tower => tower.show());
  enemies.forEach(enemy => enemy.show());
  bullets.forEach(bullet => bullet.show());
}

function drawPanel() {
  noStroke();
  fill(20, 20, 40);
  rect(0, 400, 400, 70);

  // タワーを選ぶ、3つのボタン
  textAlign(CENTER, CENTER);
  for (let i = 0; i < 3; i++) {
    let x = 8 + i * 68;
    if (i === selected) {
      fill(90, 100, 150);
    } else {
      fill(50, 55, 85);
    }
    rect(x, 408, 62, 54, 6);
    useTowerColor(i);
    noStroke();
    circle(x + 31, 426, 20);
    fill(255);
    textSize(12);
    text(costOf(i), x + 31, 450);
  }

  // 次のウェーブのボタン
  let waiting = toSpawn === 0 && enemies.length === 0 && wave < 8;
  if (waiting) {
    fill(230, 150, 60);
  } else {
    fill(70, 70, 90);
  }
  rect(218, 408, 80, 54, 6);
  fill(255);
  textSize(12);
  text('次の', 258, 427);
  text('ウェーブ', 258, 443);

  textAlign(LEFT, CENTER);
  textSize(13);
  text(`資金 ${money}`, 308, 420);
  text(`残り ${lives}`, 308, 437);
  text(`ウェーブ ${wave}/8`, 308, 454);
}

function drawOverlay(title, guide) {
  noStroke();
  fill(0, 0, 0, 160);
  rect(0, 0, 400, 470);
  fill(255);
  textAlign(CENTER, CENTER);
  textSize(30);
  text(title, 200, 190);
  textSize(16);
  text(guide, 200, 250);
}

// ---------- タワーの種類ごとの値 ----------

function costOf(kind) {
  return COSTS[kind];
}

function rangeOf(kind) {
  return RANGES[kind];
}

// その種類のタワーの色で、塗りと線を、設定する
function useTowerColor(kind) {
  let c = TOWER_COLORS[kind];
  fill(c[0], c[1], c[2]);
  stroke(c[0], c[1], c[2]);
}

function canBuild(col, row) {
  return grid[row][col] === 0 && money >= costOf(selected);
}

// ---------- 入力 ----------

function mousePressed() {
  if (scene === 'title') {
    startGame();
    scene = 'play';
  } else if (scene === 'result') {
    scene = 'title';
  } else if (mouseY >= 400) {
    // 下のパネル
    for (let i = 0; i < 3; i++) {
      if (mouseX > 8 + i * 68 && mouseX < 70 + i * 68) {
        selected = i;
      }
    }
    if (mouseX > 218 && mouseX < 298 && toSpawn === 0 && enemies.length === 0 && wave < 8) {
      startWave();
    }
  } else if (mouseX >= 0 && mouseX < 400 && mouseY >= 0) {
    // 盤面。置けるなら、タワーを置く
    let col = floor(mouseX / TILE);
    let row = floor(mouseY / TILE);
    if (grid[row][col] === 2) {
      // すでにあるタワーをクリックしたら、売る
      let spot = centerOf(col, row);
      towers = towers.filter(tower => tower.pos.dist(spot) > 1);
      grid[row][col] = 0;
      money += REFUND;
    } else if (canBuild(col, row)) {
      money -= costOf(selected);
      grid[row][col] = 2;
      if (selected === 0) {
        towers.push(new Tower(col, row));
      } else if (selected === 1) {
        towers.push(new SlowTower(col, row));
      } else {
        towers.push(new CannonTower(col, row));
      }
    }
  }
}

// ---------- 敵 ----------

// 道に沿って、曲がり角から曲がり角へ、進む
class Enemy {
  constructor() {
    this.pos = centerOf(WAYPOINTS[0].col, WAYPOINTS[0].row);
    this.pos.x -= TILE;
    this.next = 0;
    this.speed = 1;
    this.hp = 6 + wave * 3;
    this.maxHp = this.hp;
    this.reward = 8;
    this.r = 11;
    this.slow = 0;
    this.traveled = 0;
    this.reached = false;
  }

  update() {
    let target = centerOf(WAYPOINTS[this.next].col, WAYPOINTS[this.next].row);
    let toward = p5.Vector.sub(target, this.pos);

    // 遅くされている間は、半分の速さ
    let speed = this.speed;
    if (this.slow > 0) {
      speed = this.speed * 0.5;
      this.slow -= 1;
    }

    if (toward.mag() <= speed) {
      // 曲がり角に着いた。次の曲がり角を、目指す
      this.pos = target;
      this.next += 1;
      if (this.next >= WAYPOINTS.length) {
        this.reached = true;
        lives -= 1;
      }
    } else {
      toward.setMag(speed);
      this.pos.add(toward);
    }
    this.traveled += speed;
  }

  show() {
    noStroke();
    this.paint();
    circle(this.pos.x, this.pos.y, this.r * 2);

    // 体力の棒
    fill(60);
    rect(this.pos.x - 12, this.pos.y - this.r - 8, 24, 4);
    fill(120, 230, 120);
    rect(this.pos.x - 12, this.pos.y - this.r - 8, 24 * this.hp / this.maxHp, 4);
  }

  paint() {
    fill(230, 90, 90);
    if (this.slow > 0) {
      fill(150, 150, 230);
    }
  }
}

class FastEnemy extends Enemy {
  constructor() {
    super();
    this.speed = 2;
    this.hp = 4 + wave * 2;
    this.maxHp = this.hp;
    this.r = 8;
  }

  paint() {
    fill(250, 200, 80);
    if (this.slow > 0) {
      fill(150, 150, 230);
    }
  }
}

class TankEnemy extends Enemy {
  constructor() {
    super();
    this.speed = 0.6;
    this.hp = 25 + wave * 8;
    this.maxHp = this.hp;
    this.reward = 25;
    this.r = 15;
  }

  paint() {
    fill(150, 90, 170);
    if (this.slow > 0) {
      fill(150, 150, 230);
    }
  }
}

// ---------- タワー ----------

// 射程の中で、いちばん先へ進んでいる敵を狙って、弾を撃つ
class Tower {
  constructor(col, row) {
    this.pos = centerOf(col, row);
    this.kind = 0;
    this.range = rangeOf(0);
    this.cooldown = 30;
    this.damage = 3;
    this.wait = 0;
    this.angle = -90;
  }

  // 射程の中の敵のうち、いちばん先へ進んでいるものを返す
  findTarget() {
    let inRange = enemies.filter(enemy => this.pos.dist(enemy.pos) < this.range);
    inRange.sort((a, b) => b.traveled - a.traveled);
    return inRange[0];
  }

  update() {
    if (this.wait > 0) {
      this.wait -= 1;
    }
    let target = this.findTarget();
    if (target) {
      // 敵のほうへ、向きを変える
      this.angle = atan2(target.pos.y - this.pos.y, target.pos.x - this.pos.x);
      if (this.wait === 0) {
        this.fire(target);
        this.wait = this.cooldown;
      }
    }
  }

  fire(target) {
    bullets.push(new Bullet(this.pos.x, this.pos.y, target, this.damage, 0, 0));
  }

  show() {
    noStroke();
    fill(60, 60, 80);
    rect(this.pos.x - 15, this.pos.y - 15, 30, 30, 6);
    useTowerColor(this.kind);
    noStroke();
    circle(this.pos.x, this.pos.y, 20);

    // 砲身。向いている角度へ、線を伸ばす
    useTowerColor(this.kind);
    strokeWeight(5);
    line(this.pos.x, this.pos.y, this.pos.x + cos(this.angle) * 17, this.pos.y + sin(this.angle) * 17);
    noStroke();
  }
}

// 当たった敵を、しばらく遅くする
class SlowTower extends Tower {
  constructor(col, row) {
    super(col, row);
    this.kind = 1;
    this.range = rangeOf(1);
    this.cooldown = 45;
    this.damage = 1;
  }

  fire(target) {
    bullets.push(new Bullet(this.pos.x, this.pos.y, target, this.damage, 120, 0));
  }
}

// 遠くまで届き、当たった場所のまわりの敵にも、ダメージを与える
class CannonTower extends Tower {
  constructor(col, row) {
    super(col, row);
    this.kind = 2;
    this.range = rangeOf(2);
    this.cooldown = 80;
    this.damage = 8;
  }

  fire(target) {
    bullets.push(new Bullet(this.pos.x, this.pos.y, target, this.damage, 0, 45));
  }
}

// ---------- 弾 ----------

// 狙った敵を、追いかけて飛ぶ
class Bullet {
  constructor(x, y, target, damage, slow, splash) {
    this.pos = createVector(x, y);
    this.target = target;
    this.damage = damage;
    this.slow = slow;
    this.splash = splash;
    this.done = false;
  }

  update() {
    let toward = p5.Vector.sub(this.target.pos, this.pos);
    if (toward.mag() < 8) {
      this.hit();
      this.done = true;
    } else {
      toward.setMag(6);
      this.pos.add(toward);
    }
  }

  hit() {
    if (this.splash > 0) {
      // まわりの敵にも、ダメージを与える
      enemies
        .filter(enemy => enemy.pos.dist(this.pos) < this.splash)
        .forEach(enemy => {
          enemy.hp -= this.damage;
        });
    } else {
      this.target.hp -= this.damage;
    }
    if (this.slow > 0) {
      this.target.slow = this.slow;
    }
  }

  show() {
    noStroke();
    if (this.splash > 0) {
      fill(255, 140, 80);
      circle(this.pos.x, this.pos.y, 10);
    } else if (this.slow > 0) {
      fill(170, 220, 255);
      circle(this.pos.x, this.pos.y, 7);
    } else {
      fill(255, 240, 150);
      circle(this.pos.x, this.pos.y, 6);
    }
  }
}

towers.filter(tower => tower.pos.dist(spot) > 1) は、「クリックしたマスの真ん中から、1 より離れているタワーだけを、残す」という意味です。そのマスにあるタワーは、距離が 0 なので、残らず、取り除かれます。


建て直しが、できるようになると、ウェーブの合間に、配置を、変えるという、新しい作戦が、生まれます。

▶ 2. 体力の多い敵を、狙う

sort に渡す、比べ方を、変えるだけです。

sketch.js
const TILE = 40;
const SIZE = 10;

// 敵が通る道の、曲がり角(マスの番号)
const WAYPOINTS = [
  { col: 0, row: 1 },
  { col: 7, row: 1 },
  { col: 7, row: 4 },
  { col: 2, row: 4 },
  { col: 2, row: 7 },
  { col: 9, row: 7 }
];

// タワーの種類ごとの、値段、射程、色。0:ふつう 1:遅くする 2:大砲
const COSTS = [50, 70, 100];
const RANGES = [90, 80, 130];
const TOWER_COLORS = [[240, 220, 90], [120, 200, 255], [240, 110, 110]];

let scene = 'title';
let message = '';
let grid = [];
let enemies = [];
let towers = [];
let bullets = [];

let money = 0;
let lives = 0;
let wave = 0;
let toSpawn = 0;
let spawnWait = 0;
let selected = 0;

function setup() {
  createCanvas(400, 470);
  angleMode(DEGREES);
  makeGrid();
}

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

  if (scene === 'play') {
    updateGame();
  }
  drawField();
  drawPanel();

  if (scene === 'title') {
    drawOverlay('タワーディフェンス', 'クリックで、スタート');
  } else if (scene === 'result') {
    drawOverlay(message, 'クリックで、タイトルへ');
  }
}

// ---------- 盤面 ----------

// 盤面を作る。0:空き地 1:道 2:タワーがある
function makeGrid() {
  for (let row = 0; row < SIZE; row++) {
    grid[row] = [];
    for (let col = 0; col < SIZE; col++) {
      grid[row][col] = 0;
    }
  }

  // 曲がり角から、次の曲がり角までを、道にする
  for (let i = 0; i < WAYPOINTS.length - 1; i++) {
    let a = WAYPOINTS[i];
    let b = WAYPOINTS[i + 1];
    for (let col = min(a.col, b.col); col <= max(a.col, b.col); col++) {
      for (let row = min(a.row, b.row); row <= max(a.row, b.row); row++) {
        grid[row][col] = 1;
      }
    }
  }
}

// マスの番号から、その真ん中の座標(ベクトル)を作る
function centerOf(col, row) {
  return createVector(col * TILE + TILE / 2, row * TILE + TILE / 2);
}

// ---------- ゲームの進行 ----------

function startGame() {
  makeGrid();
  enemies = [];
  towers = [];
  bullets = [];
  money = 120;
  lives = 10;
  wave = 0;
  toSpawn = 0;
  selected = 0;
}

function startWave() {
  wave += 1;
  toSpawn = 4 + wave * 2;
  spawnWait = 0;
}

function updateGame() {
  // 敵を、一定の間隔で、1体ずつ出す
  if (toSpawn > 0) {
    spawnWait -= 1;
    if (spawnWait <= 0) {
      spawnEnemy();
      toSpawn -= 1;
      spawnWait = 40;
    }
  }

  enemies.forEach(enemy => enemy.update());
  towers.forEach(tower => tower.update());
  bullets.forEach(bullet => bullet.update());

  // 倒した敵の分だけ、資金が増える
  enemies.forEach(enemy => {
    if (enemy.hp <= 0) {
      money += enemy.reward;
    }
  });

  // 役目を終えたものを、取り除く
  enemies = enemies.filter(enemy => enemy.hp > 0 && enemy.reached === false);
  bullets = bullets.filter(bullet => bullet.done === false);

  if (lives <= 0) {
    message = 'ゲームオーバー';
    scene = 'result';
  } else if (wave >= 8 && toSpawn === 0 && enemies.length === 0) {
    message = 'クリア!';
    scene = 'result';
  }
}

// ウェーブと、何体目かに応じて、敵の種類を決める
function spawnEnemy() {
  let index = 4 + wave * 2 - toSpawn;
  if (wave >= 3 && index % 4 === 3) {
    enemies.push(new TankEnemy());
  } else if (wave >= 2 && index % 3 === 1) {
    enemies.push(new FastEnemy());
  } else {
    enemies.push(new Enemy());
  }
}

// ---------- 描画 ----------

function drawField() {
  noStroke();
  for (let row = 0; row < SIZE; row++) {
    for (let col = 0; col < SIZE; col++) {
      if (grid[row][col] === 1) {
        fill(190, 170, 130);
      } else {
        fill(70, 130, 80);
      }
      rect(col * TILE, row * TILE, TILE, TILE);
    }
  }

  // マウスが乗っているマスに、置けるかどうかと、射程を見せる
  if (scene === 'play' && mouseY < SIZE * TILE && mouseY >= 0 && mouseX >= 0 && mouseX < 400) {
    let col = floor(mouseX / TILE);
    let row = floor(mouseY / TILE);
    let center = centerOf(col, row);
    if (canBuild(col, row)) {
      fill(255, 255, 255, 60);
      stroke(255);
    } else {
      fill(255, 80, 80, 60);
      stroke(255, 80, 80);
    }
    strokeWeight(1);
    circle(center.x, center.y, rangeOf(selected) * 2);
    noStroke();
  }

  towers.forEach(tower => tower.show());
  enemies.forEach(enemy => enemy.show());
  bullets.forEach(bullet => bullet.show());
}

function drawPanel() {
  noStroke();
  fill(20, 20, 40);
  rect(0, 400, 400, 70);

  // タワーを選ぶ、3つのボタン
  textAlign(CENTER, CENTER);
  for (let i = 0; i < 3; i++) {
    let x = 8 + i * 68;
    if (i === selected) {
      fill(90, 100, 150);
    } else {
      fill(50, 55, 85);
    }
    rect(x, 408, 62, 54, 6);
    useTowerColor(i);
    noStroke();
    circle(x + 31, 426, 20);
    fill(255);
    textSize(12);
    text(costOf(i), x + 31, 450);
  }

  // 次のウェーブのボタン
  let waiting = toSpawn === 0 && enemies.length === 0 && wave < 8;
  if (waiting) {
    fill(230, 150, 60);
  } else {
    fill(70, 70, 90);
  }
  rect(218, 408, 80, 54, 6);
  fill(255);
  textSize(12);
  text('次の', 258, 427);
  text('ウェーブ', 258, 443);

  textAlign(LEFT, CENTER);
  textSize(13);
  text(`資金 ${money}`, 308, 420);
  text(`残り ${lives}`, 308, 437);
  text(`ウェーブ ${wave}/8`, 308, 454);
}

function drawOverlay(title, guide) {
  noStroke();
  fill(0, 0, 0, 160);
  rect(0, 0, 400, 470);
  fill(255);
  textAlign(CENTER, CENTER);
  textSize(30);
  text(title, 200, 190);
  textSize(16);
  text(guide, 200, 250);
}

// ---------- タワーの種類ごとの値 ----------

function costOf(kind) {
  return COSTS[kind];
}

function rangeOf(kind) {
  return RANGES[kind];
}

// その種類のタワーの色で、塗りと線を、設定する
function useTowerColor(kind) {
  let c = TOWER_COLORS[kind];
  fill(c[0], c[1], c[2]);
  stroke(c[0], c[1], c[2]);
}

function canBuild(col, row) {
  return grid[row][col] === 0 && money >= costOf(selected);
}

// ---------- 入力 ----------

function mousePressed() {
  if (scene === 'title') {
    startGame();
    scene = 'play';
  } else if (scene === 'result') {
    scene = 'title';
  } else if (mouseY >= 400) {
    // 下のパネル
    for (let i = 0; i < 3; i++) {
      if (mouseX > 8 + i * 68 && mouseX < 70 + i * 68) {
        selected = i;
      }
    }
    if (mouseX > 218 && mouseX < 298 && toSpawn === 0 && enemies.length === 0 && wave < 8) {
      startWave();
    }
  } else if (mouseX >= 0 && mouseX < 400 && mouseY >= 0) {
    // 盤面。置けるなら、タワーを置く
    let col = floor(mouseX / TILE);
    let row = floor(mouseY / TILE);
    if (canBuild(col, row)) {
      money -= costOf(selected);
      grid[row][col] = 2;
      if (selected === 0) {
        towers.push(new Tower(col, row));
      } else if (selected === 1) {
        towers.push(new SlowTower(col, row));
      } else {
        towers.push(new CannonTower(col, row));
      }
    }
  }
}

// ---------- 敵 ----------

// 道に沿って、曲がり角から曲がり角へ、進む
class Enemy {
  constructor() {
    this.pos = centerOf(WAYPOINTS[0].col, WAYPOINTS[0].row);
    this.pos.x -= TILE;
    this.next = 0;
    this.speed = 1;
    this.hp = 6 + wave * 3;
    this.maxHp = this.hp;
    this.reward = 8;
    this.r = 11;
    this.slow = 0;
    this.traveled = 0;
    this.reached = false;
  }

  update() {
    let target = centerOf(WAYPOINTS[this.next].col, WAYPOINTS[this.next].row);
    let toward = p5.Vector.sub(target, this.pos);

    // 遅くされている間は、半分の速さ
    let speed = this.speed;
    if (this.slow > 0) {
      speed = this.speed * 0.5;
      this.slow -= 1;
    }

    if (toward.mag() <= speed) {
      // 曲がり角に着いた。次の曲がり角を、目指す
      this.pos = target;
      this.next += 1;
      if (this.next >= WAYPOINTS.length) {
        this.reached = true;
        lives -= 1;
      }
    } else {
      toward.setMag(speed);
      this.pos.add(toward);
    }
    this.traveled += speed;
  }

  show() {
    noStroke();
    this.paint();
    circle(this.pos.x, this.pos.y, this.r * 2);

    // 体力の棒
    fill(60);
    rect(this.pos.x - 12, this.pos.y - this.r - 8, 24, 4);
    fill(120, 230, 120);
    rect(this.pos.x - 12, this.pos.y - this.r - 8, 24 * this.hp / this.maxHp, 4);
  }

  paint() {
    fill(230, 90, 90);
    if (this.slow > 0) {
      fill(150, 150, 230);
    }
  }
}

class FastEnemy extends Enemy {
  constructor() {
    super();
    this.speed = 2;
    this.hp = 4 + wave * 2;
    this.maxHp = this.hp;
    this.r = 8;
  }

  paint() {
    fill(250, 200, 80);
    if (this.slow > 0) {
      fill(150, 150, 230);
    }
  }
}

class TankEnemy extends Enemy {
  constructor() {
    super();
    this.speed = 0.6;
    this.hp = 25 + wave * 8;
    this.maxHp = this.hp;
    this.reward = 25;
    this.r = 15;
  }

  paint() {
    fill(150, 90, 170);
    if (this.slow > 0) {
      fill(150, 150, 230);
    }
  }
}

// ---------- タワー ----------

// 射程の中で、いちばん先へ進んでいる敵を狙って、弾を撃つ
class Tower {
  constructor(col, row) {
    this.pos = centerOf(col, row);
    this.kind = 0;
    this.range = rangeOf(0);
    this.cooldown = 30;
    this.damage = 3;
    this.wait = 0;
    this.angle = -90;
  }

  // 射程の中の敵のうち、いちばん先へ進んでいるものを返す
  findTarget() {
    let inRange = enemies.filter(enemy => this.pos.dist(enemy.pos) < this.range);
    inRange.sort((a, b) => b.hp - a.hp);
    return inRange[0];
  }

  update() {
    if (this.wait > 0) {
      this.wait -= 1;
    }
    let target = this.findTarget();
    if (target) {
      // 敵のほうへ、向きを変える
      this.angle = atan2(target.pos.y - this.pos.y, target.pos.x - this.pos.x);
      if (this.wait === 0) {
        this.fire(target);
        this.wait = this.cooldown;
      }
    }
  }

  fire(target) {
    bullets.push(new Bullet(this.pos.x, this.pos.y, target, this.damage, 0, 0));
  }

  show() {
    noStroke();
    fill(60, 60, 80);
    rect(this.pos.x - 15, this.pos.y - 15, 30, 30, 6);
    useTowerColor(this.kind);
    noStroke();
    circle(this.pos.x, this.pos.y, 20);

    // 砲身。向いている角度へ、線を伸ばす
    useTowerColor(this.kind);
    strokeWeight(5);
    line(this.pos.x, this.pos.y, this.pos.x + cos(this.angle) * 17, this.pos.y + sin(this.angle) * 17);
    noStroke();
  }
}

// 当たった敵を、しばらく遅くする
class SlowTower extends Tower {
  constructor(col, row) {
    super(col, row);
    this.kind = 1;
    this.range = rangeOf(1);
    this.cooldown = 45;
    this.damage = 1;
  }

  fire(target) {
    bullets.push(new Bullet(this.pos.x, this.pos.y, target, this.damage, 120, 0));
  }
}

// 遠くまで届き、当たった場所のまわりの敵にも、ダメージを与える
class CannonTower extends Tower {
  constructor(col, row) {
    super(col, row);
    this.kind = 2;
    this.range = rangeOf(2);
    this.cooldown = 80;
    this.damage = 8;
  }

  fire(target) {
    bullets.push(new Bullet(this.pos.x, this.pos.y, target, this.damage, 0, 45));
  }
}

// ---------- 弾 ----------

// 狙った敵を、追いかけて飛ぶ
class Bullet {
  constructor(x, y, target, damage, slow, splash) {
    this.pos = createVector(x, y);
    this.target = target;
    this.damage = damage;
    this.slow = slow;
    this.splash = splash;
    this.done = false;
  }

  update() {
    let toward = p5.Vector.sub(this.target.pos, this.pos);
    if (toward.mag() < 8) {
      this.hit();
      this.done = true;
    } else {
      toward.setMag(6);
      this.pos.add(toward);
    }
  }

  hit() {
    if (this.splash > 0) {
      // まわりの敵にも、ダメージを与える
      enemies
        .filter(enemy => enemy.pos.dist(this.pos) < this.splash)
        .forEach(enemy => {
          enemy.hp -= this.damage;
        });
    } else {
      this.target.hp -= this.damage;
    }
    if (this.slow > 0) {
      this.target.slow = this.slow;
    }
  }

  show() {
    noStroke();
    if (this.splash > 0) {
      fill(255, 140, 80);
      circle(this.pos.x, this.pos.y, 10);
    } else if (this.slow > 0) {
      fill(170, 220, 255);
      circle(this.pos.x, this.pos.y, 7);
    } else {
      fill(255, 240, 150);
      circle(this.pos.x, this.pos.y, 6);
    }
  }
}

タワーは、固い敵に、弾を、集中するように、なります。そのかわり、体力の少ない敵が、すり抜けやすくなります。先頭の敵が、出口の近くにいても、後ろに、体力の多い敵がいれば、そちらを、狙ってしまうからです。


1行の違いで、タワーの「考え方」が、変わります。狙う相手の選び方は、絞り込み(filter)と、並べ替え(sort)の、組み合わせで、いくらでも、作れます。

▶ 3. 途中から、速くなる敵

Enemy を継承して、update() と paint() を、書き直します。update() の中で、体力を調べ、半分より少なければ、速さを、上げます。そのあと、super.update() で、道を進む処理を、呼びます。

sketch.js
const TILE = 40;
const SIZE = 10;

// 敵が通る道の、曲がり角(マスの番号)
const WAYPOINTS = [
  { col: 0, row: 1 },
  { col: 7, row: 1 },
  { col: 7, row: 4 },
  { col: 2, row: 4 },
  { col: 2, row: 7 },
  { col: 9, row: 7 }
];

// タワーの種類ごとの、値段、射程、色。0:ふつう 1:遅くする 2:大砲
const COSTS = [50, 70, 100];
const RANGES = [90, 80, 130];
const TOWER_COLORS = [[240, 220, 90], [120, 200, 255], [240, 110, 110]];

let scene = 'title';
let message = '';
let grid = [];
let enemies = [];
let towers = [];
let bullets = [];

let money = 0;
let lives = 0;
let wave = 0;
let toSpawn = 0;
let spawnWait = 0;
let selected = 0;

function setup() {
  createCanvas(400, 470);
  angleMode(DEGREES);
  makeGrid();
}

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

  if (scene === 'play') {
    updateGame();
  }
  drawField();
  drawPanel();

  if (scene === 'title') {
    drawOverlay('タワーディフェンス', 'クリックで、スタート');
  } else if (scene === 'result') {
    drawOverlay(message, 'クリックで、タイトルへ');
  }
}

// ---------- 盤面 ----------

// 盤面を作る。0:空き地 1:道 2:タワーがある
function makeGrid() {
  for (let row = 0; row < SIZE; row++) {
    grid[row] = [];
    for (let col = 0; col < SIZE; col++) {
      grid[row][col] = 0;
    }
  }

  // 曲がり角から、次の曲がり角までを、道にする
  for (let i = 0; i < WAYPOINTS.length - 1; i++) {
    let a = WAYPOINTS[i];
    let b = WAYPOINTS[i + 1];
    for (let col = min(a.col, b.col); col <= max(a.col, b.col); col++) {
      for (let row = min(a.row, b.row); row <= max(a.row, b.row); row++) {
        grid[row][col] = 1;
      }
    }
  }
}

// マスの番号から、その真ん中の座標(ベクトル)を作る
function centerOf(col, row) {
  return createVector(col * TILE + TILE / 2, row * TILE + TILE / 2);
}

// ---------- ゲームの進行 ----------

function startGame() {
  makeGrid();
  enemies = [];
  towers = [];
  bullets = [];
  money = 120;
  lives = 10;
  wave = 0;
  toSpawn = 0;
  selected = 0;
}

function startWave() {
  wave += 1;
  toSpawn = 4 + wave * 2;
  spawnWait = 0;
}

function updateGame() {
  // 敵を、一定の間隔で、1体ずつ出す
  if (toSpawn > 0) {
    spawnWait -= 1;
    if (spawnWait <= 0) {
      spawnEnemy();
      toSpawn -= 1;
      spawnWait = 40;
    }
  }

  enemies.forEach(enemy => enemy.update());
  towers.forEach(tower => tower.update());
  bullets.forEach(bullet => bullet.update());

  // 倒した敵の分だけ、資金が増える
  enemies.forEach(enemy => {
    if (enemy.hp <= 0) {
      money += enemy.reward;
    }
  });

  // 役目を終えたものを、取り除く
  enemies = enemies.filter(enemy => enemy.hp > 0 && enemy.reached === false);
  bullets = bullets.filter(bullet => bullet.done === false);

  if (lives <= 0) {
    message = 'ゲームオーバー';
    scene = 'result';
  } else if (wave >= 8 && toSpawn === 0 && enemies.length === 0) {
    message = 'クリア!';
    scene = 'result';
  }
}

// ウェーブと、何体目かに応じて、敵の種類を決める
function spawnEnemy() {
  let index = 4 + wave * 2 - toSpawn;
  if (wave >= 3 && index % 4 === 3) {
    enemies.push(new TankEnemy());
  } else if (wave >= 4 && index % 5 === 0) {
    enemies.push(new AngryEnemy());
  } else if (wave >= 2 && index % 3 === 1) {
    enemies.push(new FastEnemy());
  } else {
    enemies.push(new Enemy());
  }
}

// ---------- 描画 ----------

function drawField() {
  noStroke();
  for (let row = 0; row < SIZE; row++) {
    for (let col = 0; col < SIZE; col++) {
      if (grid[row][col] === 1) {
        fill(190, 170, 130);
      } else {
        fill(70, 130, 80);
      }
      rect(col * TILE, row * TILE, TILE, TILE);
    }
  }

  // マウスが乗っているマスに、置けるかどうかと、射程を見せる
  if (scene === 'play' && mouseY < SIZE * TILE && mouseY >= 0 && mouseX >= 0 && mouseX < 400) {
    let col = floor(mouseX / TILE);
    let row = floor(mouseY / TILE);
    let center = centerOf(col, row);
    if (canBuild(col, row)) {
      fill(255, 255, 255, 60);
      stroke(255);
    } else {
      fill(255, 80, 80, 60);
      stroke(255, 80, 80);
    }
    strokeWeight(1);
    circle(center.x, center.y, rangeOf(selected) * 2);
    noStroke();
  }

  towers.forEach(tower => tower.show());
  enemies.forEach(enemy => enemy.show());
  bullets.forEach(bullet => bullet.show());
}

function drawPanel() {
  noStroke();
  fill(20, 20, 40);
  rect(0, 400, 400, 70);

  // タワーを選ぶ、3つのボタン
  textAlign(CENTER, CENTER);
  for (let i = 0; i < 3; i++) {
    let x = 8 + i * 68;
    if (i === selected) {
      fill(90, 100, 150);
    } else {
      fill(50, 55, 85);
    }
    rect(x, 408, 62, 54, 6);
    useTowerColor(i);
    noStroke();
    circle(x + 31, 426, 20);
    fill(255);
    textSize(12);
    text(costOf(i), x + 31, 450);
  }

  // 次のウェーブのボタン
  let waiting = toSpawn === 0 && enemies.length === 0 && wave < 8;
  if (waiting) {
    fill(230, 150, 60);
  } else {
    fill(70, 70, 90);
  }
  rect(218, 408, 80, 54, 6);
  fill(255);
  textSize(12);
  text('次の', 258, 427);
  text('ウェーブ', 258, 443);

  textAlign(LEFT, CENTER);
  textSize(13);
  text(`資金 ${money}`, 308, 420);
  text(`残り ${lives}`, 308, 437);
  text(`ウェーブ ${wave}/8`, 308, 454);
}

function drawOverlay(title, guide) {
  noStroke();
  fill(0, 0, 0, 160);
  rect(0, 0, 400, 470);
  fill(255);
  textAlign(CENTER, CENTER);
  textSize(30);
  text(title, 200, 190);
  textSize(16);
  text(guide, 200, 250);
}

// ---------- タワーの種類ごとの値 ----------

function costOf(kind) {
  return COSTS[kind];
}

function rangeOf(kind) {
  return RANGES[kind];
}

// その種類のタワーの色で、塗りと線を、設定する
function useTowerColor(kind) {
  let c = TOWER_COLORS[kind];
  fill(c[0], c[1], c[2]);
  stroke(c[0], c[1], c[2]);
}

function canBuild(col, row) {
  return grid[row][col] === 0 && money >= costOf(selected);
}

// ---------- 入力 ----------

function mousePressed() {
  if (scene === 'title') {
    startGame();
    scene = 'play';
  } else if (scene === 'result') {
    scene = 'title';
  } else if (mouseY >= 400) {
    // 下のパネル
    for (let i = 0; i < 3; i++) {
      if (mouseX > 8 + i * 68 && mouseX < 70 + i * 68) {
        selected = i;
      }
    }
    if (mouseX > 218 && mouseX < 298 && toSpawn === 0 && enemies.length === 0 && wave < 8) {
      startWave();
    }
  } else if (mouseX >= 0 && mouseX < 400 && mouseY >= 0) {
    // 盤面。置けるなら、タワーを置く
    let col = floor(mouseX / TILE);
    let row = floor(mouseY / TILE);
    if (canBuild(col, row)) {
      money -= costOf(selected);
      grid[row][col] = 2;
      if (selected === 0) {
        towers.push(new Tower(col, row));
      } else if (selected === 1) {
        towers.push(new SlowTower(col, row));
      } else {
        towers.push(new CannonTower(col, row));
      }
    }
  }
}

// ---------- 敵 ----------

// 道に沿って、曲がり角から曲がり角へ、進む
class Enemy {
  constructor() {
    this.pos = centerOf(WAYPOINTS[0].col, WAYPOINTS[0].row);
    this.pos.x -= TILE;
    this.next = 0;
    this.speed = 1;
    this.hp = 6 + wave * 3;
    this.maxHp = this.hp;
    this.reward = 8;
    this.r = 11;
    this.slow = 0;
    this.traveled = 0;
    this.reached = false;
  }

  update() {
    let target = centerOf(WAYPOINTS[this.next].col, WAYPOINTS[this.next].row);
    let toward = p5.Vector.sub(target, this.pos);

    // 遅くされている間は、半分の速さ
    let speed = this.speed;
    if (this.slow > 0) {
      speed = this.speed * 0.5;
      this.slow -= 1;
    }

    if (toward.mag() <= speed) {
      // 曲がり角に着いた。次の曲がり角を、目指す
      this.pos = target;
      this.next += 1;
      if (this.next >= WAYPOINTS.length) {
        this.reached = true;
        lives -= 1;
      }
    } else {
      toward.setMag(speed);
      this.pos.add(toward);
    }
    this.traveled += speed;
  }

  show() {
    noStroke();
    this.paint();
    circle(this.pos.x, this.pos.y, this.r * 2);

    // 体力の棒
    fill(60);
    rect(this.pos.x - 12, this.pos.y - this.r - 8, 24, 4);
    fill(120, 230, 120);
    rect(this.pos.x - 12, this.pos.y - this.r - 8, 24 * this.hp / this.maxHp, 4);
  }

  paint() {
    fill(230, 90, 90);
    if (this.slow > 0) {
      fill(150, 150, 230);
    }
  }
}

class FastEnemy extends Enemy {
  constructor() {
    super();
    this.speed = 2;
    this.hp = 4 + wave * 2;
    this.maxHp = this.hp;
    this.r = 8;
  }

  paint() {
    fill(250, 200, 80);
    if (this.slow > 0) {
      fill(150, 150, 230);
    }
  }
}

// 体力が減ると、速くなる敵
class AngryEnemy extends Enemy {
  constructor() {
    super();
    this.hp = 14 + wave * 4;
    this.maxHp = this.hp;
    this.reward = 15;
  }

  update() {
    if (this.hp < this.maxHp / 2) {
      this.speed = 2.2;
    }
    super.update();
  }

  paint() {
    fill(255, 130, 60);
    if (this.hp < this.maxHp / 2) {
      fill(255, 40, 40);
    }
  }
}

class TankEnemy extends Enemy {
  constructor() {
    super();
    this.speed = 0.6;
    this.hp = 25 + wave * 8;
    this.maxHp = this.hp;
    this.reward = 25;
    this.r = 15;
  }

  paint() {
    fill(150, 90, 170);
    if (this.slow > 0) {
      fill(150, 150, 230);
    }
  }
}

// ---------- タワー ----------

// 射程の中で、いちばん先へ進んでいる敵を狙って、弾を撃つ
class Tower {
  constructor(col, row) {
    this.pos = centerOf(col, row);
    this.kind = 0;
    this.range = rangeOf(0);
    this.cooldown = 30;
    this.damage = 3;
    this.wait = 0;
    this.angle = -90;
  }

  // 射程の中の敵のうち、いちばん先へ進んでいるものを返す
  findTarget() {
    let inRange = enemies.filter(enemy => this.pos.dist(enemy.pos) < this.range);
    inRange.sort((a, b) => b.traveled - a.traveled);
    return inRange[0];
  }

  update() {
    if (this.wait > 0) {
      this.wait -= 1;
    }
    let target = this.findTarget();
    if (target) {
      // 敵のほうへ、向きを変える
      this.angle = atan2(target.pos.y - this.pos.y, target.pos.x - this.pos.x);
      if (this.wait === 0) {
        this.fire(target);
        this.wait = this.cooldown;
      }
    }
  }

  fire(target) {
    bullets.push(new Bullet(this.pos.x, this.pos.y, target, this.damage, 0, 0));
  }

  show() {
    noStroke();
    fill(60, 60, 80);
    rect(this.pos.x - 15, this.pos.y - 15, 30, 30, 6);
    useTowerColor(this.kind);
    noStroke();
    circle(this.pos.x, this.pos.y, 20);

    // 砲身。向いている角度へ、線を伸ばす
    useTowerColor(this.kind);
    strokeWeight(5);
    line(this.pos.x, this.pos.y, this.pos.x + cos(this.angle) * 17, this.pos.y + sin(this.angle) * 17);
    noStroke();
  }
}

// 当たった敵を、しばらく遅くする
class SlowTower extends Tower {
  constructor(col, row) {
    super(col, row);
    this.kind = 1;
    this.range = rangeOf(1);
    this.cooldown = 45;
    this.damage = 1;
  }

  fire(target) {
    bullets.push(new Bullet(this.pos.x, this.pos.y, target, this.damage, 120, 0));
  }
}

// 遠くまで届き、当たった場所のまわりの敵にも、ダメージを与える
class CannonTower extends Tower {
  constructor(col, row) {
    super(col, row);
    this.kind = 2;
    this.range = rangeOf(2);
    this.cooldown = 80;
    this.damage = 8;
  }

  fire(target) {
    bullets.push(new Bullet(this.pos.x, this.pos.y, target, this.damage, 0, 45));
  }
}

// ---------- 弾 ----------

// 狙った敵を、追いかけて飛ぶ
class Bullet {
  constructor(x, y, target, damage, slow, splash) {
    this.pos = createVector(x, y);
    this.target = target;
    this.damage = damage;
    this.slow = slow;
    this.splash = splash;
    this.done = false;
  }

  update() {
    let toward = p5.Vector.sub(this.target.pos, this.pos);
    if (toward.mag() < 8) {
      this.hit();
      this.done = true;
    } else {
      toward.setMag(6);
      this.pos.add(toward);
    }
  }

  hit() {
    if (this.splash > 0) {
      // まわりの敵にも、ダメージを与える
      enemies
        .filter(enemy => enemy.pos.dist(this.pos) < this.splash)
        .forEach(enemy => {
          enemy.hp -= this.damage;
        });
    } else {
      this.target.hp -= this.damage;
    }
    if (this.slow > 0) {
      this.target.slow = this.slow;
    }
  }

  show() {
    noStroke();
    if (this.splash > 0) {
      fill(255, 140, 80);
      circle(this.pos.x, this.pos.y, 10);
    } else if (this.slow > 0) {
      fill(170, 220, 255);
      circle(this.pos.x, this.pos.y, 7);
    } else {
      fill(255, 240, 150);
      circle(this.pos.x, this.pos.y, 6);
    }
  }
}

この敵は、ダメージを受けると、赤くなって、走り出します。中途半端に、削ると、かえって、止めにくく、なります。一気に、倒し切る必要が、あります。ウェーブ 4 から、5体ごとに1体、出てきます。


道を進む仕組みは、親クラスに、任せています。子クラスが、しているのは、「速さを、書き換える」ことだけです。

まとめ

  • 道は、曲がり角の並びで表す。その1つの配列から、盤面の道も、敵の進み方も、作る
  • 目指す場所への矢印(引き算)を作り、長さを速さにして、位置に足す。道を進む敵も、相手を追う弾も、同じ形
  • 目指す場所の、すぐ手前まで来たら、位置を、ぴったり合わせる。ずれを、積み重ねない
  • タワーは、filter で射程の中の敵を集め、sort で並べ替えて、先頭を、狙う。比べ方を変えると、狙い方が変わる
  • 弾は、狙う相手のインスタンスを覚えておき、相手の、いまの位置を、追いかける
  • 親クラスの中で、種類によって変わる部分を、小さなメソッドに切り出しておくと、子クラスは、そこだけを書き直せば済む
  • 種類ごとの値は、配列にまとめ、番号で取り出す
  • 「置けるか」のような判断は、1つの関数にして、表示にも、実際の操作にも、使う
  • 役目を終えたものは、filter で、残すものの条件を書いて、取り除く。取り除く前に、必要な集計を済ませる
  • 遊ぶ人が、考えるための情報(射程、値段、資金)を、見せる。数字の釣り合いは、何度も遊んで、決める