コンテンツにスキップ

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

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

main.js が長くなってきました。この節では挙動を一切変えず、コードをシーンごとの ファイルに分けて整理します(いわゆるリファクタリングの回です)。この先の実装章は、 この分割された形を土台に進めます。

今回さわる game/: main.js を書き換え / scenes/start-scene.js・scenes/game-scene.js・scenes/gameover-scene.js を追加 / index.html を書き換え

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

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

シーンのクラスを 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 は使いません。各ファイルはクラスを定義するだけで、全部が同じ場所で つながります。)

index.html の <script> に、分けたファイルを順番に足します。main.js は StartScene などの クラスを使うので、シーンを先に、main.js を最後に読み込みます。

index.html
3
3
<head>
4
4
<meta charset="utf-8" />
5
5
<meta name="viewport" content="width=device-width, initial-scale=1" />
6
<title>10 線を超えるとゲームオーバー</title>
6
<title>11 シーンごとにファイルを分ける</title>
7
7
<style>
8
8
body {
9
9
margin: 0;
index.html
17
17
}
18
18
</style>
19
19
<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>
20
23
<script src="main.js" defer></script>
21
24
</head>
22
25
<body></body>

defer を付けたスクリプトは書いた順に実行されます。もし main.js を先に読み込むと、 まだ StartScene が定義されておらずエラーになります。

中身は前の節(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
1
// スタート画面
2
3
class StartScene extends Phaser.Scene {
4
constructor() {
5
super('Start');
6
}
7
8
create() {
9
this.add
10
.text(200, 220, 'スイカゲーム風', {
11
fontSize: '32px',
12
color: '#8b5a2b',
13
fontStyle: 'bold',
14
})
15
.setOrigin(0.5);
16
17
const startText = this.add
18
.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
1
// ゲーム本編
2
3
class 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: 12
15
};
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.radius
59
},
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
1
// ゲームオーバー画面
2
3
class GameOverScene extends Phaser.Scene {
4
constructor() {
5
super('GameOver');
6
}
7
8
create() {
9
this.add
10
.text(200, 240, 'ゲームオーバー', {
11
fontSize: '32px',
12
color: '#c0392b',
13
fontStyle: 'bold',
14
})
15
.setOrigin(0.5);
16
17
this.add
18
.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
1
class StartScene extends Phaser.Scene {
2
constructor() {
3
super('Start');
4
}
1
// 10 と挙動は同じ。コードをファイルごとに分けて整理する。
5
2
6
create() {
7
this.add
8
.text(200, 220, 'スイカゲーム風', {
9
fontSize: '32px',
10
color: '#8b5a2b',
11
fontStyle: 'bold',
12
})
13
.setOrigin(0.5);
14
15
const startText = this.add
16
.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
29
class 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: 12
41
};
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.radius
85
},
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
115
class GameOverScene extends Phaser.Scene {
116
constructor() {
117
super('GameOver');
118
}
119
120
create() {
121
this.add
122
.text(200, 240, 'ゲームオーバー', {
123
fontSize: '32px',
124
color: '#c0392b',
125
fontStyle: 'bold',
126
})
127
.setOrigin(0.5);
128
129
this.add
130
.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
140
3
new Phaser.Game({
141
4
type: Phaser.AUTO,
142
5
width: 400,

見た目も操作も 10 とまったく同じです。動きが変わっていないのに、ファイルが役割ごとに分かれて 読みやすくなりました。これで基本編は完了です。

ここで一度、03. 解説1 — ゲームの仕組み を読むと、ここまで書いてきた 物理・Canvas・シーンの理解が固まります。

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

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

Section titled “この節を終えたときのディレクトリ”
game
// ゲーム本編
class GameScene extends Phaser.Scene {
constructor() {
super('Game');
}
create() {
const box = {
left: 60,
right: 340,
top: 150,
bottom: 540,
wall: 12
};
this.radius = 25;
this.lineY = 190;
this.balls = [];
this.isOver = false;
const g = this.add.graphics();
g.fillStyle(0xe74c3c, 1);
g.fillRect(box.left - box.wall, box.top, box.wall, box.bottom - box.top);
g.fillStyle(0x2ecc71, 1);
g.fillRect(box.right, box.top, box.wall, box.bottom - box.top);
g.fillStyle(0x3498db, 1);
g.fillRect(box.left - box.wall, box.bottom, box.right - box.left + box.wall * 2, box.wall);
g.lineStyle(2, 0xc0392b, 0.8);
g.beginPath();
g.moveTo(box.left, this.lineY);
g.lineTo(box.right, this.lineY);
g.strokePath();
const wallH = box.bottom - box.top;
const wallCY = (box.top + box.bottom) / 2;
this.matter.add.rectangle(box.left - box.wall / 2, wallCY, box.wall, wallH, { isStatic: true });
this.matter.add.rectangle(box.right + box.wall / 2, wallCY, box.wall, wallH, { isStatic: true });
const floorW = box.right - box.left + box.wall * 2;
this.matter.add.rectangle((box.left + box.right) / 2, box.bottom + box.wall / 2, floorW, box.wall, { isStatic: true });
this.input.on('pointerdown', (pointer) => {
if (this.isOver) return;
const dropY = 100;
// 箱の内側からはみ出さないよう X を制限する
const x = Phaser.Math.Clamp(pointer.x, box.left + this.radius, box.right - this.radius);
const ball = this.add.circle(x, dropY, this.radius, 0x333333);
this.matter.add.gameObject(ball, {
shape: {
type: 'circle',
radius: this.radius
},
restitution: 0.2, // 跳ね返りの強さ(0=跳ねない 〜 1=よく跳ねる)
});
this.balls.push(ball);
});
}
update(time, delta) {
if (this.isOver) return;
// 落下中は速いので、止まって線を超え続けたときだけゲームオーバー(誤検出を防ぐ)
for (const ball of this.balls) {
if (!ball.body) continue;
const isSlow = ball.body.speed < 1;
const top = ball.y - this.radius;
if (!isSlow || top >= this.lineY) {
ball.overLineTime = 0;
continue;
}
ball.overLineTime = (ball.overLineTime ?? 0) + delta;
if (ball.overLineTime > 1000) {
this.isOver = true;
this.scene.start('GameOver');
return;
}
}
}
}
// ゲームオーバー画面
class GameOverScene extends Phaser.Scene {
constructor() {
super('GameOver');
}
create() {
this.add
.text(200, 240, 'ゲームオーバー', {
fontSize: '32px',
color: '#c0392b',
fontStyle: 'bold',
})
.setOrigin(0.5);
this.add
.text(200, 320, 'クリックでスタートに戻る', {
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(200, 220, 'スイカゲーム風', {
fontSize: '32px',
color: '#8b5a2b',
fontStyle: 'bold',
})
.setOrigin(0.5);
const startText = this.add
.text(200, 340, '▶ スタート', {
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;
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>
// 10 と挙動は同じ。コードをファイルごとに分けて整理する。
new Phaser.Game({
type: Phaser.AUTO,
width: 400,
height: 600,
backgroundColor: '#fdf6e3',
physics: {
default: 'matter',
matter: { gravity: { y: 1 } },
},
scene: [StartScene, GameScene, GameOverScene],
});
この節を終えたときのファイル