キーイベント1
マウスイベント同様にキーイベントについても説明します.
import pygame from pygame.locals import * import sys SCREEN_SIZE = (1000,700) pygame.init() screen = pygame.display.set_mode(SCREEN_SIZE) pygame.display.set_caption("キーイベント") backImg = pygame.image.load("hakusuiko.jpg").convert() pythonImg2 = pygame.image.load("kappa3.png").convert() colorkey = pythonImg2.get_at((0,0)) # 左上の色を透明色に pythonImg2.set_colorkey(colorkey, RLEACCEL) pythonImg2_rect = pythonImg2.get_rect() pythonImg2_rect.center = (500,350) vx = vy = 10 # キーを押したときの移動距離 while True: screen.blit(backImg, (0,0)) screen.blit(pythonImg2, pythonImg2_rect) pygame.display.update() for event in pygame.event.get(): if event.type == QUIT: sys.exit() if event.type == KEYDOWN: # キーを押したとき # ESCキーならスクリプトを終了 if event.key == K_ESCAPE: sys.exit() # 矢印キーなら画像を移動 if event.key == K_LEFT: pythonImg2_rect.move_ip(-vx, 0) if event.key == K_RIGHT: pythonImg2_rect.move_ip(vx, 0) if event.key == K_UP: pythonImg2_rect.move_ip(0, -vy) if event.key == K_DOWN: pythonImg2_rect.move_ip(0, vy)
while文からキーイベントの操作なので, そこから説明します.
for event in pygame.event.get(): if event.type == QUIT: sys.exit() if event.type == KEYDOWN: # キーを押したとき # ESCキーならスクリプトを終了 if event.key == K_ESCAPE: sys.exit() # 矢印キーなら画像を移動 if event.key == K_LEFT: pythonImg2_rect.move_ip(-vx, 0) if event.key == K_RIGHT: pythonImg2_rect.move_ip(vx, 0) if event.key == K_UP: pythonImg2_rect.move_ip(0, -vy) if event.key == K_DOWN: pythonImg2_rect.move_ip(0, vy)
最初は終了のイベントとして, QUITとESCAPEキーが押されたとき終了する設定です.
次にrect.move_ip()によって上下左右それぞれのキーが押された場合, 前に指定したピクセル分だけ動きます.