LoginSignup
1
0

pygameのイベントハンドラをデコレータを使って(比較的)綺麗に書く方法

Posted at

はじめに

デコレータを使ったpygameのイベントハンドラを実装する方法を紹介します。

この記事の対象者

  • ある程度Pythonの知識があり、pygameのイベントハンドラをデコレータで実装したい。

前提知識

  • 基本的なPythonの記法と仕様を理解している
  • pygameの基本的な使い方を知っている

実装

実際のコード

main.py
import sys

import pygame
from pygame.locals import * # QUITやKEYDOWNなどのイベントを一括インポート


# 初期設定

SCREEN_SIZE = (320, 140)
clock = pygame.time.Clock()
fullscreen_flag = False
event_handlers = {}
 
pygame.init()
screen = pygame.display.set_mode(SCREEN_SIZE)
pygame.display.set_caption(u"hoge")


# デコレータの実装

def event(event_type):
    def decorator(func):
        event_handlers[event_type] = func
        return func
    return decorator


# - 使用例 - #

@event(QUIT)
def on_quit(event):
    pygame.quit()
    sys.exit()

@event(KEYDOWN)
def on_keydown(event):
    global screen
    if event.key == K_ESCAPE:
        pygame.quit()
        sys.exit()
    if event.key == K_F2:
        fullscreen_flag = not fullscreen_flag
        if fullscreen_flag:
            screen = pygame.display.set_mode(SCREEN_SIZE, FULLSCREEN)
        else:
            screen = pygame.display.set_mode(SCREEN_SIZE, 0)

@event(MOUSEMOTION)
def on_mouse_motion(event):
    x, y = event.pos
    pygame.draw.line(screen, (255,255,255), (SCREEN_SIZE[0]/2,SCREEN_SIZE[1]/2), (x,y), 1)


while True:
    screen.fill((0,0,0))
    clock.tick(120)
    for event in pygame.event.get():
        if event.type in event_handlers:
            event_handlers[event.type](event)
    pygame.display.update()

解説

event()デコレータ

このデコレータはevent_handlersに格納されたイベントとその処理を管理します。これによってそれぞれのイベントに応じた処理が実行されます。

終わりに

最後まで読んで頂きありがとうございます。不備があれば是非コメントで指摘して下さい。

1
0
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
1
0