Featured image of post 【第5回】戦闘フェーズを管理したい - PerlとMooでテキストRPG戦闘エンジンを作ろう

【第5回】戦闘フェーズを管理したい - PerlとMooでテキストRPG戦闘エンジンを作ろう

RPG戦闘エンジン第5回。Stateパターンを導入し、戦闘フェーズ(開始・プレイヤーターン・敵ターン・終了)を状態オブジェクトとして管理します。状態遷移を明確にし、複雑な制御フローを整理しましょう。

前回、Commandパターンで行動をオブジェクト化しました。これでさまざまな行動を柔軟に追加できるようになりました。

しかし、戦闘にはもう1つ重要な要素があります。それは「フェーズ」です。

  • 戦闘開始: 敵が出現し、戦闘が始まる
  • プレイヤーターン: プレイヤーが行動を選ぶ
  • 敵ターン: 敵が行動する
  • 戦闘終了: どちらかが倒れて戦闘が終わる

これらのフェーズを管理するために、Stateパターンを導入しましょう。

前回までに導入したmax_hpなどの属性は維持したまま、状態遷移の仕組みだけを追加する方針です。

Stateパターンの状態遷移

Stateパターンとは

Stateパターンは、オブジェクトの内部状態に応じて振る舞いを変えるデザインパターンです。状態をオブジェクトとして表現し、状態の切り替えによって動作が変わります。

自動販売機を例に考えてみましょう。

  • 待機中: お金を入れられる
  • 商品選択中: ボタンを押すと商品が出る
  • 販売中: 商品を出している最中

状態によって「ボタンを押したときの動作」が変わります。戦闘システムも同様に、フェーズによって可能な操作が変わるのです。

BattleStateロールを定義する

すべての戦闘状態が実装すべきインターフェースを定義します。

1
2
3
4
5
6
7
package BattleState;
use v5.36;
use Moo::Role;

requires 'enter';    # この状態に入ったときの処理
requires 'execute';  # この状態での処理を実行
requires 'exit';     # この状態から出るときの処理

enterは状態に入ったときの初期化処理、executeはその状態でのメイン処理、exitは状態を出るときの後処理です。

BattleContext: 状態を管理するクラス

状態を保持し、状態遷移を管理するコンテキストクラスを作ります。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
package BattleContext;
use v5.36;
use Moo;

has player => (
    is       => 'ro',
    required => 1,
);

has enemy => (
    is       => 'ro',
    required => 1,
);

has current_state => (
    is      => 'rw',
    default => sub { undef },
);

has is_finished => (
    is      => 'rw',
    default => 0,
);

sub change_state($self, $new_state) {
    $self->current_state->exit($self) if $self->current_state;
    $self->current_state($new_state);
    $new_state->enter($self);
}

sub update($self) {
    return if $self->is_finished;
    $self->current_state->execute($self) if $self->current_state;
}

change_stateで状態を切り替え、updateで現在の状態の処理を実行します。

各状態を実装する

BattleStartState: 戦闘開始

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
package BattleStartState;
use v5.36;
use Moo;

with 'BattleState';

sub enter($self, $context) {
    say "=== 戦闘開始! ===";
    say $context->enemy->name . "が現れた!";
}

sub execute($self, $context) {
    say "";
    say $context->player->name . " HP: " . $context->player->hp;
    say $context->enemy->name . " HP: " . $context->enemy->hp;
    say "";
    
    # プレイヤーターンへ遷移
    $context->change_state(PlayerTurnState->new());
}

sub exit($self, $context) {
    # 特に処理なし
}

PlayerTurnState: プレイヤーターン

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
package PlayerTurnState;
use v5.36;
use Moo;

with 'BattleState';

sub enter($self, $context) {
    say "--- " . $context->player->name . "のターン ---";
}

sub execute($self, $context) {
    # プレイヤーの行動を実行(簡易版: 常に攻撃)
    my $command = AttackCommand->new(
        actor  => $context->player,
        target => $context->enemy,
    );
    $command->execute();
    
    # 敵が倒れたか確認
    unless ($context->enemy->is_alive) {
        $context->change_state(BattleEndState->new(winner => 'player'));
        return;
    }
    
    # 敵ターンへ遷移
    $context->change_state(EnemyTurnState->new());
}

sub exit($self, $context) {
    # 特に処理なし
}

EnemyTurnState: 敵ターン

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
package EnemyTurnState;
use v5.36;
use Moo;

with 'BattleState';

sub enter($self, $context) {
    say "";
    say "--- " . $context->enemy->name . "のターン ---";
}

sub execute($self, $context) {
    # 敵の行動を実行(簡易版: 常に攻撃)
    my $command = AttackCommand->new(
        actor  => $context->enemy,
        target => $context->player,
    );
    $command->execute();
    
    # プレイヤーが倒れたか確認
    unless ($context->player->is_alive) {
        $context->change_state(BattleEndState->new(winner => 'enemy'));
        return;
    }
    
    # プレイヤーターンへ遷移
    $context->change_state(PlayerTurnState->new());
}

sub exit($self, $context) {
    # 特に処理なし
}

BattleEndState: 戦闘終了

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
package BattleEndState;
use v5.36;
use Moo;

with 'BattleState';

has winner => (
    is       => 'ro',
    required => 1,
);

sub enter($self, $context) {
    say "";
    say "=== 戦闘終了! ===";
}

sub execute($self, $context) {
    if ($self->winner eq 'player') {
        say $context->enemy->name . "を倒した!";
    } else {
        say $context->player->name . "は倒れた...";
    }
    $context->is_finished(1);
}

sub exit($self, $context) {
    # 特に処理なし
}

状態遷移図

	stateDiagram-v2
    [*] --> BattleStart
    BattleStart --> PlayerTurn
    PlayerTurn --> EnemyTurn: 敵が生存
    PlayerTurn --> BattleEnd: 敵を撃破
    EnemyTurn --> PlayerTurn: プレイヤーが生存
    EnemyTurn --> BattleEnd: プレイヤー撃破
    BattleEnd --> [*]

完成コード

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
#!/usr/bin/env perl
use v5.36;

package Command {
    use Moo::Role;
    requires 'execute';
    
    has actor => (
        is       => 'ro',
        required => 1,
    );
    
    has target => (
        is       => 'ro',
        required => 0,
    );
}

package Character {
    use Moo;
    
    has name => (
        is       => 'ro',
        required => 1,
    );
    
    has hp => (
        is      => 'rw',
        default => 100,
    );

    has max_hp => (
        is      => 'ro',
        default => 100,
    );
    
    has attack_power => (
        is      => 'ro',
        default => 10,
    );
    
    has is_defending => (
        is      => 'rw',
        default => 0,
    );
    
    sub is_alive($self) {
        return $self->hp > 0;
    }
    
    sub take_damage($self, $damage) {
        my $actual_damage = $self->is_defending ? int($damage / 2) : $damage;
        my $new_hp = $self->hp - $actual_damage;
        $self->hp($new_hp < 0 ? 0 : $new_hp);
        $self->is_defending(0);
        return $actual_damage;
    }
}

package AttackCommand {
    use Moo;
    with 'Command';
    
    sub execute($self) {
        my $actor = $self->actor;
        my $target = $self->target;
        my $damage = $actor->attack_power;
        my $actual = $target->take_damage($damage);

        my $msg = $actor->name . "の攻撃! " . $target->name . "に " . $actual . " のダメージ!";
        $msg .= "(防御で軽減)" if $actual < $damage;
        say $msg;
    }
}

package BattleState {
    use Moo::Role;
    requires 'enter';
    requires 'execute';
    requires 'exit';
}

package BattleContext {
    use Moo;
    
    has player => (
        is       => 'ro',
        required => 1,
    );
    
    has enemy => (
        is       => 'ro',
        required => 1,
    );
    
    has current_state => (
        is      => 'rw',
        default => sub { undef },
    );
    
    has is_finished => (
        is      => 'rw',
        default => 0,
    );
    
    sub change_state($self, $new_state) {
        $self->current_state->exit($self) if $self->current_state;
        $self->current_state($new_state);
        $new_state->enter($self);
    }
    
    sub update($self) {
        return if $self->is_finished;
        $self->current_state->execute($self) if $self->current_state;
    }
}

package BattleStartState {
    use Moo;
    with 'BattleState';
    
    sub enter($self, $context) {
        say "=== 戦闘開始! ===";
        say $context->enemy->name . "が現れた!";
    }
    
    sub execute($self, $context) {
        say "";
        say $context->player->name . " HP: " . $context->player->hp;
        say $context->enemy->name . " HP: " . $context->enemy->hp;
        say "";
        $context->change_state(PlayerTurnState->new());
    }
    
    sub exit($self, $context) {}
}

package PlayerTurnState {
    use Moo;
    with 'BattleState';
    
    sub enter($self, $context) {
        say "--- " . $context->player->name . "のターン ---";
    }
    
    sub execute($self, $context) {
        my $command = AttackCommand->new(
            actor  => $context->player,
            target => $context->enemy,
        );
        $command->execute();
        
        unless ($context->enemy->is_alive) {
            $context->change_state(BattleEndState->new(winner => 'player'));
            return;
        }
        
        $context->change_state(EnemyTurnState->new());
    }
    
    sub exit($self, $context) {}
}

package EnemyTurnState {
    use Moo;
    with 'BattleState';
    
    sub enter($self, $context) {
        say "";
        say "--- " . $context->enemy->name . "のターン ---";
    }
    
    sub execute($self, $context) {
        my $command = AttackCommand->new(
            actor  => $context->enemy,
            target => $context->player,
        );
        $command->execute();
        
        unless ($context->player->is_alive) {
            $context->change_state(BattleEndState->new(winner => 'enemy'));
            return;
        }
        
        $context->change_state(PlayerTurnState->new());
    }
    
    sub exit($self, $context) {}
}

package BattleEndState {
    use Moo;
    with 'BattleState';
    
    has winner => (
        is       => 'ro',
        required => 1,
    );
    
    sub enter($self, $context) {
        say "";
        say "=== 戦闘終了! ===";
    }
    
    sub execute($self, $context) {
        if ($self->winner eq 'player') {
            say $context->enemy->name . "を倒した!";
        } else {
            say $context->player->name . "は倒れた...";
        }
        $context->is_finished(1);
    }
    
    sub exit($self, $context) {}
}

# メイン処理
my $hero = Character->new(
    name         => '勇者',
    hp           => 100,
    attack_power => 15,
);

my $slime = Character->new(
    name         => 'スライム',
    hp           => 30,
    attack_power => 5,
);

my $battle = BattleContext->new(
    player => $hero,
    enemy  => $slime,
);

$battle->change_state(BattleStartState->new());

while (!$battle->is_finished) {
    $battle->update();
}

実行結果

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
=== 戦闘開始! ===
スライムが現れた!

勇者 HP: 100
スライム HP: 30

--- 勇者のターン ---
勇者の攻撃! スライムに 15 のダメージ!

--- スライムのターン ---
スライムの攻撃! 勇者に 5 のダメージ!
--- 勇者のターン ---
勇者の攻撃! スライムに 15 のダメージ!

=== 戦闘終了! ===
スライムを倒した!

今回のポイント

  • Stateパターンは状態をオブジェクトとして表現する
  • 状態ごとにenterexecuteexitを実装する
  • BattleContextが現在の状態を保持し、遷移を管理する
  • 状態遷移が明確になり、複雑な制御フローが整理される

現在、敵は常に攻撃しかしません。次回は、敵のAIを切り替えられるようにするためにStrategyパターンを導入します。


前回:

次回:

comments powered by Disqus
Hugo で構築されています。
テーマ StackJimmy によって設計されています。