Pythonによるグローバル変数を使ったゲーム状態管理のプロトタイプ構築

ゲーム開発の初期段階では、コアメカニクスの検証が最も重要です。このような局面では、設計よりも迅速な実装が求められます。Pythonのグローバルスコープを活用することで、わずか数十行のコードで動作可能なゲームフレームワークのプロトタイプを数分で構築できます。

基本的な状態データの定義

まず、ゲーム全体で共有される状態をグローバル変数として定義します。以下の3つのカテゴリに分けて整理するのが効果的です。

# プレイヤーのステータス
player_health = 100
player_score = 0
player_x, player_y = 0, 0

# ゲーム設定
game_difficulty = "normal"
bgm_volume = 0.7
sfx_enabled = True

# シーン管理
current_scene = "menu"
next_scene = None
is_paused = False

状態操作用のユーティリティ関数

直接変数にアクセスできるものの、初期化・保存・復元などの処理は関数にまとめておくことで保守性が向上します。

def init_game():
    global player_health, player_score, current_scene, is_paused
    player_health = 100
    player_score = 0
    player_x, player_y = 0, 0
    current_scene = "menu"
    is_paused = False

def save_current_state():
    return {
        'health': player_health,
        'score': player_score,
        'position': (player_x, player_y),
        'difficulty': game_difficulty,
        'volume': bgm_volume,
        'scene': current_scene,
        'paused': is_paused
    }

def load_state(state_data):
    global player_health, player_score, player_x, player_y
    global game_difficulty, bgm_volume, current_scene, is_paused
    
    player_health = state_data.get('health', 100)
    player_score = state_data.get('score', 0)
    player_x, player_y = state_data.get('position', (0, 0))
    game_difficulty = state_data.get('difficulty', 'normal')
    bgm_volume = state_data.get('volume', 0.7)
    current_scene = state_data.get('scene', 'menu')
    is_paused = state_data.get('paused', False)

def reset_game():
    init_game()

ゲーム内イベントでの利用例

敵との接触やアイテム取得といったイベント処理は、非常に直感的に記述できます。

def on_player_hit(damage=20):
    global player_health
    player_health -= damage
    if player_health <= 0:
        trigger_game_over()

def collect_coin():
    global player_score
    player_score += 10

def switch_to_next_stage():
    global current_scene, next_scene
    current_scene = next_scene or "stage_2"
    next_scene = None

プロトタイプから本番アーキテクチャへ

アイデアの検証が済んだら、以下のように段階的に改善していくのが望ましいです。

  • 関連する変数をPlayerGameConfigといったクラスに集約
  • グローバル参照を単一インスタンス(シングルトン)パターンに置き換え
  • JSONやファイルストレージへの永続化機能を追加
  • 状態変更時にイベントを発行するObserverパターンの導入

このアプローチにより、初期開発の速度と、将来的な拡張性の両立が可能になります。

タグ: Python ゲーム開発 グローバル変数 プロトタイプ 状態管理

6月18日 16:22 投稿