在PyGame中移动Sprite

时间:2016-06-07 23:57:07

标签: python pygame sprite

我目前正在开展一个学校项目,但我一直试图让我的精灵继续前进。我的错误信息是说我错过了1个必要的位置参数:' self'在Mario.handle_keys()。

这是我的主要代码:

import pygame
import sys
from pygame.locals import*
from Mario import Mario
from Ladder import Ladder

pygame.init()
b = Mario([0, 800])
c = Ladder([600, 800])
game_over = False
dispwidth = 600
dispheight = 800
cellsize = 10
white = (255, 255, 255)
black = (0, 0, 0)
bg = white


def main():
    FPS = 30
    while not game_over:
        for event in pygame.event.get():
            if event.type == QUIT:
                pygame.quit()
                sys.exit()

        Mario.handle_keys()

        Mario.draw(screen)
        screen.fill(bg)
        screen.blit(b.image, b.rect)
        screen.blit(c.image, c.rect)
        pygame.display.update()
        fpstime.tick(FPS)

while True:
    global fpstime
    global screen

    fpstime = pygame.time.Clock()
    screen = pygame.display.set_mode((dispwidth, dispheight))
    pygame.display.set_caption('Donkey Kong')
    main()

我的精灵:

import pygame
from pygame.locals import*


class Mario(pygame.sprite.Sprite):
    image = None

    def __init__(self, location):
        pygame.sprite.Sprite.__init__(self)

        if Mario.image is None:

            Mario.image = pygame.image.load('mario3.png')
        self.image = Mario.image

        self.rect = self.image.get_rect()
        self.rect.bottomleft = location

        self.x = 0
        self.y = 0

    def handle_keys(self):

        keys_pressed = pygame.key.get_pressed()

        if keys_pressed[K_LEFT]:
            self.x -= 5

        if keys_pressed[K_RIGHT]:
            self.y += 5

    def draw(self, surface):

        surface.blit(self.image, (self.x, self.y))

提前致谢。

我感谢任何建议!

1 个答案:

答案 0 :(得分:0)

Mario是一个班级。方法handle_keys(self)是一个实例方法 - 意味着它只能针对Mario实例进行调用。 (可以有一个classmethod,但这不是你想要的,因为你需要修改self。)

在顶部,您创建了b = Mario([0, 800]) - 我将b更改为mario,并c更改为ladder

 mario = Mario([0, 800])

然后使用Mario.handle_keys()代替mario.handle_keys()

更多背景资料:

当您致电mario.handle_keys()时,实际发生的事情或多或少handle_keys(mario)。对象mario最终成为参数self。由于您尝试在类handle_keys上调用Mario,因此Python抱怨没有任何内容传递给handle_keys self参数。

更多的杂草:

如果你定义一个类方法,你可以这样做:

class Foo():
    @classmethod
    def my_class_method(cls):
        ...

您可以将其称为Foo.my_class_method(),将Foo传递给my_class_method作为cls参数。

相关问题