你如何上下移动精灵?

时间:2018-04-17 13:53:37

标签: python python-3.x pygame

我已经有一段时间了,我似乎无法弄清楚为什么我的精灵在程序运行时没有向上或向下移动。

玩家精灵类

def __init__(self,name,x,y):
    pygame.sprite.Sprite.__init__(self)
    self.name = str(name)
    self.speed = 5
    self.image = pygame.image.load(name+'.png').convert_alpha()
    self.rect = self.image.get_rect()
    self.rect.x = x
    self.rect.y = y
def move_up(self):
    self.rect.y -= self.speed
def move_down(self):
    self.rect.y += self.speed
def move_left(self):
    self.rect.x -= self.speed
def move_right(self):
    self.rect.x += self.speed

def update(self):
    self.screen.blit(self.image,(self.rect))

主文件/循环

class Console:
    def __init__(self,width,height):
        pygame.init()
        self.w = width
        self.h = height
        self.clock = pygame.time.Clock()
        self.screen = pygame.display.set_mode((self.w,self.h))
        self.screenName = pygame.display.set_caption("Star's Labyrinth")

class Background(pygame.sprite.Sprite):
    def __init__(self,image_file,x,y):
        pygame.sprite.Sprite.__init__(self)
        self.image = pygame.image.load(image_file)
        self.rect = self.image.get_rect()
        self.rect.x = x
        self.rect.y = y

def main():
    gameExit = False
    game_display = Console(1024,576)
    game_display.screen
    starboy = Player("starboy",200,200)
    background = Background("background.png",0,0)
    while not gameExit:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                gameExit = True
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_a:
                    starboy.move_left()
                elif event.key == pygame.K_d:
                    starboy.move_right()
                elif event.type == pygame.K_w:
                    starboy.move_up()
                elif event.type == pygame.K_s:
                    starboy.move_down()
    print(pygame.event.get())
    game_display.screen.blit(background.image,background.rect)
    starboy.update
    game_display.screen.blit(starboy.image,(starboy.rect.x,starboy.rect.y))
    pygame.display.update()
    game_display.clock.tick(30)

我尝试过不同类型的命令,试图弄清楚它是变量还是函数问题。还有一种方法可以让它移动而不必点击键。

1 个答案:

答案 0 :(得分:1)

在事件循环中,您要检查event.typepygame.K_w还是pygame.K_s,但是您必须检查event.key是否等于这些常量。变化

elif event.type == pygame.K_w:
    starboy.move_up()
elif event.type == pygame.K_s:
    starboy.move_down()

到:

elif event.key == pygame.K_w:
    starboy.move_up()
elif event.key == pygame.K_s:
    starboy.move_down()

您也忘记了starboy.update背后的括号。