game - Platform ゲーム - [3] Game クラスの作成


Pygame Platform ゲームを作成 [3]

Gameクラスの作成

Tasks

  • main.pyにGameクラスを作成

プロジェクトストラクチャー

  • project/ -- 全てを入れるフォルダ(ディレクトリ)
    • main.py -- ゲームをスタートするファイル
    • settings.py -- constantを入れておくファイル
main.py

import pygame as pg
import random
from settings import *

# NEW!! 
class Game:
    def __init__(self):
        # ゲームを初期化
        self.running = True  # ゲームが走っているか否か
        pg.init()
        pg.mixer.init()
        self.screen = pg.display.set_mode((WIDTH, HEIGHT))
        pg.display.set_caption(TITLE)
        self.clock = pg.time.Clock()

    def new(self):
        # ゲームオーバー後のニューゲーム
        all_sprites = pg.sprite.Group()

    def run(self):
        # ゲームループ
        self.playing = True  # ゲームをプレイしているか
        while self.playing:
            self.clock.tick(FPS)
            self.events()
            self.update()
            self.draw()

    def update(self):
        # アップデート
        pass  # あとで実装するためpassにしておく

    def events(self):
        # イベント
        pass  # あとで実装するためpassにしておく

    def draw(self):
        # 描画
        pass  # あとで実装するためpassにしておく

    def show_start_screen(self):
        # ゲームスタート画面
        pass  # あとで実装するためpassにしておく

    def show_go_screen(self):
        # ゲームオーバー画面
        pass  # あとで実装するためpassにしておく


g = Game()  # Gameクラスをインスタンス化
g.show_start_screen()  # Gameインスタンスのshow_start_screenメソッド
while g.running:
    g.new()
    g.show_go_screen()

pg.quit()

settings.py

# game options/settings
TITLE = "My Game"
WIDTH = 360
HEIGHT = 480
FPS = 30

# define colors
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
DARKGREY = (27, 140, 141)
LIGHTGREY = (189, 195, 199)
GREEN = (60, 186, 84)
RED = (219, 50, 54)
YELLOW = (244, 194, 13)
BLUE = (72, 133, 237)

Links

Github platformer

Pygame - Platform ゲーム - [2]

Pygame - Platform ゲーム - [1]