屏幕上的字符不会移动(pygame)

时间:2013-04-21 15:54:25

标签: pygame sprite

由于某种原因,箭头键不会移动“guy.png”精灵。有没有人解释为什么?是的,精灵确实显示在屏幕上,是的,guy.png与项目位于同一文件夹下。

代码:

import pygame, sys
from pygame.locals import *
pygame.init()
screen = pygame.display.set_mode((500, 500), 0, 32)
guy_sprite = pygame.image.load("guy.png")
wall_sprite = pygame.image.load("wall.png")

class guy_class(pygame.sprite.Sprite):
    def __init__(self, surface):
        self.surface = surface
        self.x = 250
        self.y = 250
        self.vx = 0
        self.vy = 0
        self.sprite = guy_sprite

    def event(self, event):
        if event.type == pygame.K_UP:
            self.vy = -1
        elif event.type == pygame.K_DOWN:
            self.vy = 1
        elif event.type == pygame.K_LEFT:
            self.vx = -1
        elif event.type == pygame.K_RIGHT:
            self.vx = 1

    def move(self):
        self.x += self.vx
        self.y += self.vy

    def draw(self, surface):
        surface.blit(self.sprite, (int(self.x), int(self.y)))

    def position(self):
        return self.x, self.y

class wall_class(pygame.sprite.Sprite):
    def __init__(self, surface):
        self.x = 100
        self.y = 250
        self.vx = 0
        self.vy = 0
        self.sprite = wall_sprite

    def draw(self, surface):
        surface.blit(self.sprite, (self.x, self.y))

def end_game():
    pygame.quit()
    sys.exit()

clock = pygame.time.Clock()
guy = guy_class(screen)
wall = wall_class(screen)

while True:
    screen.fill((0, 0, 0))
    guy.move()
    guy.draw(screen)

    for event in pygame.event.get():
        if event.type == QUIT:
            end_game()
        elif event.type == pygame.KEYDOWN:
            guy.event(event)

    clock.tick(100)
    pygame.display.update()

1 个答案:

答案 0 :(得分:1)

你的精灵没有移动的原因是因为你正在检查你的家伙事件功能中的类型而不是键。

所以改成它:

def event(self, event):
    if event.key == pygame.K_UP:
        self.vy = -1
    elif event.key == pygame.K_DOWN:
        self.vy = 1
    elif event.key == pygame.K_LEFT:
        self.vx = -1
    elif event.key == pygame.K_RIGHT:
        self.vx = 1

你还应该检查KEY_UP事件,这样你的精灵就会在你释放钥匙时停止。