Pygameの勉強 *キーイベントの処理の巻*
カーソルキーで蛇を動かしてみた
イベントハンドラを使う方法
#! /usr/bin/env python
# -*- coding: utf-8 -*-
import pygame
from pygame.locals import *
import sys
SCR_WIDTH,SCR_HEIGHT = 640,480
pygame.init()
screen = pygame.display.set_mode((SCR_WIDTH,SCR_HEIGHT))
pygame.display.set_caption("key event")
backImg = pygame.image.load('grass.jpg').convert() #背景画像
Img = pygame.image.load('pythonImg.png').convert_alpha() #蛇の画像
Img_rect = Img.get_rect()
Img_rect.center = (320,240)
vx = vy = 10 #キーを押したときの移動距離
while True:
screen.blit(backImg,(0,0))
screen.blit(Img,Img_rect)
pygame.display.update()
#イベント処理
for event in pygame.event.get():
if event.type == QUIT:
sys.exit()
if event.type == KEYDOWN:
if event.key == K_ESCAPE:
sys.exit()
if event.key == K_LEFT:
if Img_rect.left > 0:
Img_rect.move_ip(-vx,0)
if event.key == K_RIGHT:
if Img_rect.right < SCR_WIDTH:
Img_rect.move_ip(vx,0)
if event.key == K_UP:
if Img_rect.top > 0:
Img_rect.move_ip(0,-vy)
if event.key == K_DOWN:
if Img_rect.bottom < SCR_HEIGHT:
Img_rect.move_ip(0,vy)
これでは、キーを押した時一度しか蛇が動いてくれないので、キーを押している間、蛇を動かしたい。
こうすればいいのだ!!
#! /usr/bin/env python # -*- coding: utf-8 -*- import pygame from pygame.locals import * import sys SCR_WIDTH,SCR_HEIGHT = 640,480 pygame.init() screen = pygame.display.set_mode((SCR_WIDTH,SCR_HEIGHT)) pygame.display.set_caption("key event") backImg = pygame.image.load('grass.jpg').convert() #背景画像 Img = pygame.image.load('pythonImg.png').convert_alpha() #蛇の画像 Img_rect = Img.get_rect() Img_rect.center = (320,240) vx = vy = 5 #キーを押したときの移動距離 while True: #押されているキーをチェック pressed_keys = pygame.key.get_pressed() #押されているキーに応じて蛇ちゃんを移動 if pressed_keys[K_LEFT]: if Img_rect.left > 0: Img_rect.move_ip(-vx,0) if pressed_keys[K_RIGHT]: if Img_rect.right < SCR_WIDTH: Img_rect.move_ip(vx,0) if pressed_keys[K_UP]: if Img_rect.top > 0: Img_rect.move_ip(0,-vy) if pressed_keys[K_DOWN]: if Img_rect.bottom < SCR_HEIGHT: Img_rect.move_ip(0,vy) #画像処理 screen.blit(backImg,(0,0)) screen.blit(Img,Img_rect) pygame.display.update() #イベント処理 for event in pygame.event.get(): if event.type == QUIT: sys.exit() if event.type == KEYDOWN and event.key == K_ESCAPE: sys.exit()