コンテンツにスキップ

シーンごとにファイルを分ける

シーンごとにファイルを分ける

前の 10 弾切れでゲームオーバー で、main.js に3つのシーンが 入って長くなりました。この節では動きは変えずに、シーンごとにファイルを分けて整理します。 こういう「動きを変えずに整理する作業」をリファクタリングと呼びます。

今回さわる game/: ファイル構成を変える(scenes/ を作る)

前の節を終えていない人は、ここから始められます。

この節を始めるときのファイル

1つの Game の中に、シーンが3つ入っている

Section titled “1つの Game の中に、シーンが3つ入っている”

ファイルを分ける前に、いまのゲームの形をおさらいします。08〜10 で作った StartScene・ GameScene・GameOverScene は、それぞれ別々のゲームではありません。1つの Phaser.Game の中に、3つのシーンが入っているという関係になっています。

1つの Phaser.Game の中に StartScene・GameScene・GameOverScene の3つのシーンが入っている

図: Game(ゲーム全体)とシーン(画面)の関係。3つとも Game の中にいて、映るのは常に1つ

  • Phaser.Game … ゲーム全体。ページに1つだけ作ります。画面の大きさや物理エンジンの 設定は、こちらが持っています。
  • シーン … Game の中に入る「画面」。いくつでも入れられますが、実際に動いて画面に 映るのは常に1つだけです。残りは出番を待っています。
  • scene: [StartScene, GameScene, GameOverScene] … Game に「この3つを使う」と 登録する名簿です。ここに書いたシーンだけを Game は知っています。
  • this.scene.start('Game') … 動かすシーンを切り替える命令。super('Game') で付けた 名前を呼ぶと、Game が名簿から探して切り替えてくれます。

この「Game が3つのシーンを抱えている」という形は、これから何をしても変わりません。この節で やるのは、中身の置き場所だけを「1シーン = 1ファイル」に整理することです。

scenes/ フォルダを作り、シーンを1つずつ別ファイルに移します。

game/ の下に scenes/ フォルダを作り、StartScene・GameScene・GameOverScene を1ファイルずつに分ける

図: scenes/ を作り、シーンのクラスを 1 つずつ別ファイルに移す。main.js には起動の設定だけが残る。

  • scenes/start-scene.js … StartScene クラスだけを入れます。
  • scenes/game-scene.js … GameScene クラスだけを入れます。
  • scenes/gameover-scene.js … GameOverScene クラスだけを入れます。

中身のコードはそのまま移すだけです。クラスはファイルをまたいで共有されるので、書き換えは要りません。

main.js に残すのは、ゲームを起動する設定だけです。

ファイル全体(起動の設定だけを残す)

main.js
1
new Phaser.Game({
2
type: Phaser.AUTO,
3
width: 720,
4
height: 480,
5
backgroundColor: '#fdf6e3',
6
physics: {
7
default: 'matter',
8
matter: { gravity: { y: 1 } },
9
},
10
scene: [StartScene, GameScene, GameOverScene],
11
});

index.html で、分けたファイルを読み込みます。シーンを先に、main.js を最後に読み込むのが大切です。 main.js が起動するとき、3つのシーンのクラスがすでに用意されている必要があるからです。

<head> の中(<script> の並びを書き換え)

index.html
20
<script src="https://cdnjs.cloudflare.com/ajax/libs/phaser/3.90.0/phaser.min.js"></script>
21
<script src="scenes/start-scene.js" defer></script>
22
<script src="scenes/game-scene.js" defer></script>
23
<script src="scenes/gameover-scene.js" defer></script>
24
<script src="main.js" defer></script>
  • 上から順に、Phaser 本体 → 各シーン → main.js の順で読み込みます。
  • defer を付けているので、読み込みの順番どおりに実行されます。

見た目も動きも 10 とまったく同じです。でも、コードがシーンごとに整理されて、これから機能を 足すときに読みやすくなりました。ここまでで「基本」は完成です。次の章から、標的(ブタ)や スコアなど、ゲームのルールを作っていきます。

↗ 新しいタブで開く
このステップの完成イメージ(実際に触って動かせます)

この節を終えたときのディレクトリ

Section titled “この節を終えたときのディレクトリ”
game
class GameScene extends Phaser.Scene {
constructor() {
super('Game');
}
create() {
const groundX = 360;
const groundY = 440;
const groundWidth = 720;
const groundHeight = 80;
const groundTop = groundY - groundHeight / 2; // 地面の上面。物はこの高さに乗る
const ground = this.add.rectangle(
groundX,
groundY,
groundWidth,
groundHeight,
0x888888,
);
this.matter.add.gameObject(ground, { isStatic: true });
const boxSize = 40;
const towerX = 560;
for (let i = 0; i < 3; i++) {
const boxY = groundTop - boxSize / 2 - i * boxSize;
const box = this.add.rectangle(towerX, boxY, boxSize, boxSize, 0xdddddd);
box.setStrokeStyle(3, 0x333333);
this.matter.add.gameObject(box, { restitution: 0.1 });
}
const anchor = { x: 140, y: 300 };
const power = 0.22; // 引っ張った長さを速さに変える倍率
const birdRadius = 18;
this.add.circle(anchor.x, anchor.y, 6, 0xbbbbbb);
const aim = this.add.graphics();
let birdsLeft = 5;
const reserve = this.add.graphics();
const drawReserve = () => {
reserve.clear();
for (let i = 0; i < birdsLeft; i++) {
const x = 30 + i * 26;
reserve.fillStyle(0xffffff, 1);
reserve.fillCircle(x, 40, 9);
reserve.lineStyle(2, 0x333333, 1);
reserve.strokeCircle(x, 40, 9);
}
};
// いま操作できる鳥。発射中やリロード待ちのときは null。
let bird = null;
let dragging = false;
const spawnBird = () => {
if (birdsLeft <= 0) return;
bird = this.add.circle(anchor.x, anchor.y, birdRadius, 0xffffff);
bird.setStrokeStyle(3, 0x333333);
this.matter.add.gameObject(bird, {
shape: { type: 'circle', radius: birdRadius },
restitution: 0.2,
});
// 待機中は動かないように静的にしておく。
bird.setStatic(true);
};
drawReserve();
spawnBird();
this.input.on('pointerdown', () => {
if (!bird || dragging) return;
dragging = true;
});
this.input.on('pointermove', (pointer) => {
if (!dragging || !bird) return;
bird.setPosition(pointer.x, pointer.y);
const forwardX = anchor.x + (anchor.x - bird.x) * 1.5;
const forwardY = anchor.y + (anchor.y - bird.y) * 1.5;
aim.clear();
aim.lineStyle(2, 0x333333, 0.5);
aim.lineBetween(bird.x, bird.y, forwardX, forwardY);
});
this.input.on('pointerup', () => {
if (!dragging || !bird) return;
dragging = false;
aim.clear();
const vx = (anchor.x - bird.x) * power;
const vy = (anchor.y - bird.y) * power;
bird.setStatic(false);
bird.setVelocity(vx, vy);
bird = null;
birdsLeft -= 1;
drawReserve();
this.time.delayedCall(1200, () => {
if (birdsLeft > 0) {
spawnBird();
} else {
this.scene.start('GameOver');
}
});
});
}
}
class GameOverScene extends Phaser.Scene {
constructor() {
super('GameOver');
}
create() {
this.add
.text(360, 200, 'ゲームオーバー', {
fontSize: '36px',
color: '#c0392b',
fontStyle: 'bold',
})
.setOrigin(0.5);
this.add
.text(360, 280, 'クリックでスタートに戻る', {
fontSize: '18px',
color: '#555555',
})
.setOrigin(0.5);
this.input.once('pointerdown', () => this.scene.start('Start'));
}
}
class StartScene extends Phaser.Scene {
constructor() {
super('Start');
}
create() {
this.add
.text(360, 180, 'パチンコ物理ゲーム', {
fontSize: '36px',
color: '#5d4037',
fontStyle: 'bold',
})
.setOrigin(0.5);
const startText = this.add
.text(360, 300, '▶ スタート', {
fontSize: '28px',
color: '#ffffff',
backgroundColor: '#e08e3c',
padding: { x: 24, y: 12 },
})
.setOrigin(0.5)
.setInteractive({ useHandCursor: true });
startText.on('pointerdown', () => this.scene.start('Game'));
}
}
<!doctype html>
<html lang="ja">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>11 シーンごとにファイルを分ける</title>
<style>
body {
margin: 0;
overflow: hidden;
display: grid;
place-items: center;
min-height: 100vh;
background: #222;
}
canvas {
display: block;
}
</style>
<script src="https://cdnjs.cloudflare.com/ajax/libs/phaser/3.90.0/phaser.min.js"></script>
<script src="scenes/start-scene.js" defer></script>
<script src="scenes/game-scene.js" defer></script>
<script src="scenes/gameover-scene.js" defer></script>
<script src="main.js" defer></script>
</head>
<body></body>
</html>
new Phaser.Game({
type: Phaser.AUTO,
width: 720,
height: 480,
backgroundColor: '#fdf6e3',
physics: {
default: 'matter',
matter: { gravity: { y: 1 } },
},
scene: [StartScene, GameScene, GameOverScene],
});
この節を終えたときのファイル