シーンごとにファイルを分ける
main.js が長くなってきました。この節では挙動を一切変えず、コードをシーンごとの
ファイルに分けて整理します(いわゆるリファクタリングの回です)。この先の実装章は、
この分割された形を土台に進めます。
今回さわる
game/:main.jsを書き換え /scenes/start-scene.js・scenes/game-scene.js・scenes/gameover-scene.jsを追加 /index.htmlを書き換え
前の節を終えていない人は、ここから始められます。
どう分けるか
Section titled “どう分けるか”シーンのクラスを 3 つのファイルに切り出し、main.js にはゲームの起動だけを残します。
これまで育ててきた game/ は、この節から scenes/ フォルダが加わってこうなります。
game/├─ index.html├─ main.js 起動のみ(new Phaser.Game)└─ scenes/ ├─ start-scene.js StartScene ├─ game-scene.js GameScene └─ gameover-scene.js GameOverSceneビルドツールは使いません。複数の <script> を順番に読み込むだけの素直なやり方にします。
(import / export は使いません。各ファイルはクラスを定義するだけで、全部が同じ場所で
つながります。)
読み込む順番が大事
Section titled “読み込む順番が大事”index.html の <script> に、分けたファイルを順番に足します。main.js は StartScene などの
クラスを使うので、シーンを先に、main.js を最後に読み込みます。
index.html を変更する
Section titled “index.html を変更する”33<head>44 <meta charset="utf-8" />55 <meta name="viewport" content="width=device-width, initial-scale=1" />6 <title>10 線を超えるとゲームオーバー</title>6 <title>11 シーンごとにファイルを分ける</title>77 <style>88 body {99 margin: 0;1717 }1818 </style>1919 <script src="https://cdnjs.cloudflare.com/ajax/libs/phaser/3.90.0/phaser.min.js"></script>20 <script src="scenes/start-scene.js" defer></script>21 <script src="scenes/game-scene.js" defer></script>22 <script src="scenes/gameover-scene.js" defer></script>2023 <script src="main.js" defer></script>2124</head>2225<body></body>defer を付けたスクリプトは書いた順に実行されます。もし main.js を先に読み込むと、
まだ StartScene が定義されておらずエラーになります。
各ファイルの中身
Section titled “各ファイルの中身”中身は前の節(10)と同じコードを、そのまま該当ファイルへ移すだけです。
scenes/start-scene.js…class StartScene extends Phaser.Scene { ... }scenes/game-scene.js…class GameScene extends Phaser.Scene { ... }(createとupdate)scenes/gameover-scene.js…class GameOverScene extends Phaser.Scene { ... }
scenes/start-scene.js を作成する
Section titled “scenes/start-scene.js を作成する”1// スタート画面2
3class StartScene extends Phaser.Scene {4 constructor() {5 super('Start');6 }7
8 create() {9 this.add10 .text(200, 220, 'スイカゲーム風', {11 fontSize: '32px',12 color: '#8b5a2b',13 fontStyle: 'bold',14 })15 .setOrigin(0.5);16
17 const startText = this.add18 .text(200, 340, '▶ スタート', {19 fontSize: '28px',20 color: '#ffffff',21 backgroundColor: '#e08e3c',22 padding: { x: 24, y: 12 },23 })24 .setOrigin(0.5)25 .setInteractive({ useHandCursor: true });26
27 startText.on('pointerdown', () => this.scene.start('Game'));28 }29}scenes/game-scene.js を作成する
Section titled “scenes/game-scene.js を作成する”1// ゲーム本編2
3class GameScene extends Phaser.Scene {4 constructor() {5 super('Game');6 }7
8 create() {9 const box = {10 left: 60,11 right: 340,12 top: 150,13 bottom: 540,14 wall: 1215 };16
17 this.radius = 25;18 this.lineY = 190;19 this.balls = [];20 this.isOver = false;21
22 const g = this.add.graphics();23 g.fillStyle(0xe74c3c, 1);24 g.fillRect(box.left - box.wall, box.top, box.wall, box.bottom - box.top);25
26 g.fillStyle(0x2ecc71, 1);27 g.fillRect(box.right, box.top, box.wall, box.bottom - box.top);28
29 g.fillStyle(0x3498db, 1);30 g.fillRect(box.left - box.wall, box.bottom, box.right - box.left + box.wall * 2, box.wall);31
32 g.lineStyle(2, 0xc0392b, 0.8);33 g.beginPath();34 g.moveTo(box.left, this.lineY);35 g.lineTo(box.right, this.lineY);36 g.strokePath();37
38 const wallH = box.bottom - box.top;39 const wallCY = (box.top + box.bottom) / 2;40 this.matter.add.rectangle(box.left - box.wall / 2, wallCY, box.wall, wallH, { isStatic: true });41 this.matter.add.rectangle(box.right + box.wall / 2, wallCY, box.wall, wallH, { isStatic: true });42 const floorW = box.right - box.left + box.wall * 2;43 this.matter.add.rectangle((box.left + box.right) / 2, box.bottom + box.wall / 2, floorW, box.wall, { isStatic: true });44
45 this.input.on('pointerdown', (pointer) => {46 if (this.isOver) return;47
48 const dropY = 100;49
50 // 箱の内側からはみ出さないよう X を制限する51 const x = Phaser.Math.Clamp(pointer.x, box.left + this.radius, box.right - this.radius);52
53 const ball = this.add.circle(x, dropY, this.radius, 0x333333);54
55 this.matter.add.gameObject(ball, {56 shape: {57 type: 'circle',58 radius: this.radius59 },60 restitution: 0.2, // 跳ね返りの強さ(0=跳ねない 〜 1=よく跳ねる)61 });62
63 this.balls.push(ball);64 });65 }66
67 update(time, delta) {68 if (this.isOver) return;69
70 // 落下中は速いので、止まって線を超え続けたときだけゲームオーバー(誤検出を防ぐ)71 for (const ball of this.balls) {72 if (!ball.body) continue;73 const isSlow = ball.body.speed < 1;74 const top = ball.y - this.radius;75 if (!isSlow || top >= this.lineY) {76 ball.overLineTime = 0;77 continue;78 }79 ball.overLineTime = (ball.overLineTime ?? 0) + delta;80 if (ball.overLineTime > 1000) {81 this.isOver = true;82 this.scene.start('GameOver');83 return;84 }85 }86 }87}scenes/gameover-scene.js を作成する
Section titled “scenes/gameover-scene.js を作成する”1// ゲームオーバー画面2
3class GameOverScene extends Phaser.Scene {4 constructor() {5 super('GameOver');6 }7
8 create() {9 this.add10 .text(200, 240, 'ゲームオーバー', {11 fontSize: '32px',12 color: '#c0392b',13 fontStyle: 'bold',14 })15 .setOrigin(0.5);16
17 this.add18 .text(200, 320, 'クリックでスタートに戻る', {19 fontSize: '18px',20 color: '#555555',21 })22 .setOrigin(0.5);23
24 this.input.once('pointerdown', () => this.scene.start('Start'));25 }26}main.js は起動だけになります。
main.js を変更する
Section titled “main.js を変更する”1class StartScene extends Phaser.Scene {2 constructor() {3 super('Start');4 }1// 10 と挙動は同じ。コードをファイルごとに分けて整理する。52
6 create() {7 this.add8 .text(200, 220, 'スイカゲーム風', {9 fontSize: '32px',10 color: '#8b5a2b',11 fontStyle: 'bold',12 })13 .setOrigin(0.5);14
15 const startText = this.add16 .text(200, 340, '▶ スタート', {17 fontSize: '28px',18 color: '#ffffff',19 backgroundColor: '#e08e3c',20 padding: { x: 24, y: 12 },21 })22 .setOrigin(0.5)23 .setInteractive({ useHandCursor: true });24
25 startText.on('pointerdown', () => this.scene.start('Game'));26 }27}28
29class GameScene extends Phaser.Scene {30 constructor() {31 super('Game');32 }33
34 create() {35 const box = {36 left: 60,37 right: 340,38 top: 150,39 bottom: 540,40 wall: 1241 };42
43 this.radius = 25;44 this.lineY = 190;45 this.balls = [];46 this.isOver = false;47
48 const g = this.add.graphics();49 g.fillStyle(0xe74c3c, 1);50 g.fillRect(box.left - box.wall, box.top, box.wall, box.bottom - box.top);51
52 g.fillStyle(0x2ecc71, 1);53 g.fillRect(box.right, box.top, box.wall, box.bottom - box.top);54
55 g.fillStyle(0x3498db, 1);56 g.fillRect(box.left - box.wall, box.bottom, box.right - box.left + box.wall * 2, box.wall);57
58 g.lineStyle(2, 0xc0392b, 0.8);59 g.beginPath();60 g.moveTo(box.left, this.lineY);61 g.lineTo(box.right, this.lineY);62 g.strokePath();63
64 const wallH = box.bottom - box.top;65 const wallCY = (box.top + box.bottom) / 2;66 this.matter.add.rectangle(box.left - box.wall / 2, wallCY, box.wall, wallH, { isStatic: true });67 this.matter.add.rectangle(box.right + box.wall / 2, wallCY, box.wall, wallH, { isStatic: true });68 const floorW = box.right - box.left + box.wall * 2;69 this.matter.add.rectangle((box.left + box.right) / 2, box.bottom + box.wall / 2, floorW, box.wall, { isStatic: true });70
71 this.input.on('pointerdown', (pointer) => {72 if (this.isOver) return;73
74 const dropY = 100;75
76 // 箱の内側からはみ出さないよう X を制限する77 const x = Phaser.Math.Clamp(pointer.x, box.left + this.radius, box.right - this.radius);78
79 const ball = this.add.circle(x, dropY, this.radius, 0x333333);80
81 this.matter.add.gameObject(ball, {82 shape: {83 type: 'circle',84 radius: this.radius85 },86 restitution: 0.2, // 跳ね返りの強さ(0=跳ねない 〜 1=よく跳ねる)87 });88
89 this.balls.push(ball);90 });91 }92
93 update(time, delta) {94 if (this.isOver) return;95
96 // 落下中は速いので、止まって線を超え続けたときだけゲームオーバー(誤検出を防ぐ)97 for (const ball of this.balls) {98 if (!ball.body) continue;99 const isSlow = ball.body.speed < 1;100 const top = ball.y - this.radius;101 if (!isSlow || top >= this.lineY) {102 ball.overLineTime = 0;103 continue;104 }105 ball.overLineTime = (ball.overLineTime ?? 0) + delta;106 if (ball.overLineTime > 1000) {107 this.isOver = true;108 this.scene.start('GameOver');109 return;110 }111 }112 }113}114
115class GameOverScene extends Phaser.Scene {116 constructor() {117 super('GameOver');118 }119
120 create() {121 this.add122 .text(200, 240, 'ゲームオーバー', {123 fontSize: '32px',124 color: '#c0392b',125 fontStyle: 'bold',126 })127 .setOrigin(0.5);128
129 this.add130 .text(200, 320, 'クリックでスタートに戻る', {131 fontSize: '18px',132 color: '#555555',133 })134 .setOrigin(0.5);135
136 this.input.once('pointerdown', () => this.scene.start('Start'));137 }138}139
1403new Phaser.Game({1414 type: Phaser.AUTO,1425 width: 400,見た目も操作も 10 とまったく同じです。動きが変わっていないのに、ファイルが役割ごとに分かれて 読みやすくなりました。これで基本編は完了です。
ここで一度、03. 解説1 — ゲームの仕組み を読むと、ここまで書いてきた 物理・Canvas・シーンの理解が固まります。