I'm currently working on a school project, but I'm stuck trying to get my sprite to move. My error message is saying that I'm missing 1 required positional argument: 'self' in Mario.handle_keys().
Here's my main code:
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()
And my sprite:
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))
Thanks in advance.
I appreciate any advice!
Mario
is a class. The method handle_keys(self)
is an instance method -- meaning it can only be called against an Mario
instance. (It is possible to have a classmethod
, but that's not what you want here since you need to modify self
.)
At the top you made a b = Mario([0, 800])
-- I'd change b
to mario
everywhere and c
to ladder
.
mario = Mario([0, 800])
Then instead of Mario.handle_keys()
you would use mario.handle_keys()
.
More background:
When you call mario.handle_keys()
what is actually happening underneath is more or less handle_keys(mario)
. The object mario
ends up being the argument self
. Since you are attempting to call handle_keys
on the class Mario
instead, Python is complaining that nothing is being passed to handle_keys
for the self
parameter.
More off into the weeds:
If you define a class method, you would do it like this:
class Foo():
@classmethod
def my_class_method(cls):
...
You would call it Foo.my_class_method()
, which would pass Foo
to my_class_method
as the cls
parameter.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.