0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Pygameを使って RPGを作る(1. スケルトン)

Last updated at Posted at 2024-12-30

背景

今から約4年前にPygameを使って一時的に作成していた、色んな原因があって中断してしまっていた。今回は、Pythonの実装スキルを維持するため、(常になにかを作っておかないとスキルが廃れてしまう)再度Pygameを挑戦する。

準備

まずは仮想環境を作成、pygameをインストールしておく
https://www.pygame.org/news

pip install pygame 

プログラミングスタイル

  • メインプログラムを含めて、すべてクラス化をして作成するスタイルにする
  • Gameパラメータについては、利便性のため、setting.pyを暫定的に使用する
  • メインプログラムに最小限のコードのみ書いて、ゲームの本体を少しずつ拡張していくスタイルにする
  • クラスの継承をなるべく使わないスタイル

スケルトン

万事の始まりはスケルトンであり、ここがスタートとなる

main.py

import pygame as pg
from settings import *

class game:
    def __init__(self):
        pg.init()
        # screen
        self.display_surface = pg.display.set_mode((WIDTH, HEIGHT))
        # title
        pg.display.set_caption(TITLE)
        # clock
        self.clock = pg.time.Clock()
        self.running = True

    def run(self):
        """ゲームループ"""
        dt = self.clock.tick(FPS) / 1000

        while self.running:
            # イベント処理
            for event in pg.event.get():
                if event.type == pg.QUIT:
                    self.running = False
            # draw
            self.display_surface.fill(BLUE)

            pg.display.update()

        pg.quit()

if __name__ == "__main__":
    new_game = game()
    new_game.run()

setting.py

# game options/settings
TITLE = "RPG Game"
WIDTH = 1280
HEIGHT = 720
FPS = 60

BLUE = (72, 133, 237)

要素解説

無限ループ

pygameのメイン処理には、無限ループがあり、終了イベント受け取ったら終了するようにしている

 def run(self):
    """ゲームループ"""
    while self.running:

イベント処理

実は、メインプログラムでイベント処理の分岐を書く人が多い。

# イベント処理
for event in pg.event.get():
    if event.type == pg.QUIT:
        self.running = False

ゲーム速度

FPSについては、ゲームの画面の大きさ、描くレイヤーなど情報の多寡により、影響を受けてしまうため、最も扱うにくいパラメータ

dt = self.clock.tick(FPS) / 1000

目安としてFPSは24から1000まで

ゲーム画面の大きさとゲームのタイトル(タイトルバーの文字)

# screen
self.display_surface = pg.display.set_mode((WIDTH, HEIGHT))
 # title
pg.display.set_caption(TITLE)

実行結果

image.png

0
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?