2016-06-07 76 views
0

我目前正在研究一個學校項目,但我被困在試圖讓我的精靈移動。我的錯誤信息是說我缺少1個需要的位置參數:Mario.handle_keys()中的'self'。在PyGame中移動一個雪碧

這是我的主要代碼:

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)) 

在此先感謝。

我欣賞任何建議!

回答

0

Mario是一類。方法handle_keys(self)是一種實例方法 - 意味着它只能針對Mario實例調用。 (這是可能有一個classmethod,但是這不是你想要的這裏,因爲你需要修改self

在頂部,你做了一個b = Mario([0, 800]) - 我會改變bmario到處cladder

mario = Mario([0, 800]) 

然後,而不是Mario.handle_keys()你會使用mario.handle_keys()

更多的背景:

當你調用mario.handle_keys()什麼是實際發生的情況下或多或少handle_keys(mario)。對象mario最終成爲參數self。由於您試圖在類Mario上調用handle_keys,Python卻抱怨說參數沒有任何內容傳遞給handle_keys

更多,誤入歧途:

如果你定義一個類的方法,你會做這樣的:

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

你叫它Foo.my_class_method(),這將通過Foomy_class_methodcls參數。

+0

這有幫助,但我已經到了一個新的錯誤。現在它告訴我我缺少1個需要的位置參數:__init __()中的'location'。有什麼建議? –

+0

取決於它的__init __()。可能你應該用'mario = Mario([0,800])'替換'b = Mario([0,800])',或者調用'b.handle_keys()' – rrauenza

+0

謝謝。這真的有幫助。 –