0
1

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を作る(2. Surface)

Last updated at Posted at 2024-12-30

概要

本記事はSurfaceについて解説する
Surfaceとは、日本語で表面という意味で、GameWindowが舞台だとしたら、舞台の幕のようなものだと思います。

使い方の例

公式には、このようなものしかない。
Surface((width, height), flags=0, depth=0, masks=None) -> Surface
Surface((width, height), flags=0, Surface) -> Surface

やはりちょっとわからない
ともかく、サイズ(横、縦)を指定し、定義する

SURFACE_SIZE = (100, 100)
# Surface((width, height), flags=0, depth=0, masks=None) -> Surface
self.test_surface = pg.surface.Surface(SURFACE_SIZE)

次に、
Surfaceを表示させる(blitメソッド)(ビルドの略称?)

# blits(((source, dest, area), ...)) -> [Rect, ...]
# self.display_surfaceはメインWindowのSurface
self.display_surface.blit(self.test_surface,(100, 100))

これで真っ黒なSurfaceが表示される

もう一つ、fillメソッドを使うとSurfaceに色で塗ることができる

self.test_surface.fill(RED)

今回の完成例
(Surface表示するだけだと面白くないので、ピンポンみたいに左右並行移動を繰り返す)

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

        # surface
        self.test_surface = pg.surface.Surface(SURFACE_POS)
        self.test_surface.fill(RED)

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

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

            # draw
            self.display_surface.fill(BLUE)

            dx = dx + direction*1 
            if dx >= WIDTH:
                direction = -1
            elif dx <= 0:
                direction = 1
            self.display_surface.blit(self.test_surface,(dx, 100))

            pg.display.update()

        pg.quit()

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

uploading...0

補足

  1. 今回はメソッドの説明のため、クラス化はしていない。
  2. scrollメソッドを使えば、無限スクロールを作れるが、今回は。横スクロールは用いないので、スキップする。
0
1
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
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?