0

出于某种原因,箭头键不会移动“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()

4

1 回答 1

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 事件,因此当您释放键时,您的精灵将停止。

于 2013-04-21T16:23:39.670 回答