这个Python / Pygame代码中的错误是什么?

时间:2016-08-26 07:07:01

标签: python-2.7 pygame

这是我的代码。我正试图让精灵四处走动。有课程,因为这只是项目的开始。

import pygame, sys
pygame.init()
surf = pygame.display.set_mode((1280, 720))
blackorwhiteorsomething = (0, 0, 0)
surf.fill(blackorwhiteorsomething)
fps_clock = pygame.time.Clock()
pygame.display.flip()

class Player(pygame.sprite.Sprite):
    def __init__(self, name):
        self.name = name
        self.image = pygame.Surface((22, 22))
        self.image.fill((130, 100, 200))
        self.rect = self.image.get_rect(x = 100, y = 300)
        self.x_vel = 0
        self.y_vel = 0
    def speed(self, speed):
        self.speed = speed
    def update(self, keys):
            if keys[pygame.K_DOWN]:
                self.y_vel = 1
            elif keys[pygame.K_UP]:
                self.y_vel = -1
            else:
                self.y_vel = 0   
            if keys[pygame.K_LEFT]:
                self.x_vel = -1
            elif keys[pygame.K_RIGHT]:
                self.x_vel = 1
            else:
                self.x_vel = 0
    def update1(self, keys):
            if keys[pygame.K_s]:
                self.y_vel = 1
            elif keys[pygame.K_w]:
                self.y_vel = -1
            else:
                self.y_vel = 0

            if keys[pygame.K_a]:
                self.x_vel = -1
            elif keys[pygame.K_s]:
                self.x_vel = 1
            else:
                self.x_vel = 0
    def draw(self, surface):
            surface.blit(self.image, self.rect)

player = Player('Tank')
def main():
    while True:    
        keys = pygame.key.get_pressed()
        player.draw(surf)
        player.update(keys)
        player.update1(keys)
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
        pygame.display.update()

        fps_clock.tick(60)

main()

不会引发错误,但精灵不会移动。救命! (P.S,我有点像新手,所以如果它是愚蠢的话,不要太苛刻。)

1 个答案:

答案 0 :(得分:0)

您必须根据 x_vely_velspeed 更新玩家的位置:

class Player(pygame.sprite.Sprite):
    # [...]

    def update(self, keys):
        self.x_vel = keys[pygame.K_RIGHT] - keys[pygame.K_LEFT]
        self.y_vel = keys[pygame.K_DOWN] - keys[pygame.K_UP]
        self.rect.x += self.x_vel * self.speed
        self.rect.y += self.y_vel * self.speed