概要
本記事は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()
補足
- 今回はメソッドの説明のため、クラス化はしていない。
- scrollメソッドを使えば、無限スクロールを作れるが、今回は。横スクロールは用いないので、スキップする。