I am beginning to code a space invaders game and trying to just get the ship down and let it move back and forth across the screen. I'm very beginner status so it is a big challenge for me. Whenever I try to run it it tells me that I'm requiring another positional argument in my update function but I don't understand what I'm supposed to do.
I've tried moving around the variable initialization for keys but it hasn't changed anything. If anyone wants to take a look at my code and tell me what I could do it would be amazing.
import pygame, sys
from pygame import *
pygame.init()
screen = pygame.display.set_mode((800,600))
pygame.display.set_caption("Space Invaders")
pygame.mouse.set_visible(0)
WIDTH = 800
vel = 5
width = 64
keys = pygame.key.get_pressed()
BLACK = (0, 0, 0)
all_sprites = pygame.sprite.Group()
class Player(pygame.sprite.Sprite):
def _init_(self):
pygame.sprite.Sprite._init_(self)
self.image = pygame.image.load("images\ship.png")
self.rect = self.image.get_rect()
self.rect.center = (WIDTH/2, 40)
def update(self, keys, *args):
if keys[pygame.K_LEFT] and self.rect.x > vel:
self.rect.x -= vel
if keys[pygame.K_RIGHT] and self.rect.x < 800 - width - vel:
self.rect.x += vel
screen.blit(self.image, self.rect)
player = Player()
all_sprites.add(player)
run = True
while run:
pygame.time.delay(100)
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
all_sprites.update()
screen.fill(BLACK)
all_sprites.draw(screen)
pygame.display
pygame.quit()
I know this is just the beginning but I can't figure out what I'm missing here.
You've to pass the current states of the keyboard buttons to .update()
.
Note, the arguments which are passed to all_sprites.update()
are delegated to player.update()
. all_sprites
is pygame.sprite.Group
object. The .update()
method calls .update()
on each contained sprite and pass the parameters through.
Get the states of the keyboard buttons by pygame.key.get_pressed()
and pass it to .update
:
keys = pygame.key.get_pressed()
all_sprites.update(keys)
The name of the constructor has to be __init__
rather than _init_
. See Class:
class Player(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
# [...]