1

I'm trying to make space invaders in Pygame. I am trying to make the player move I saw few tutorials and that suppose to work but nothing happening when I am pressing the button.

this is the code:

import pygame

pygame.init()

WIN = pygame.display.set_mode((800, 600))
WIDTH, HEIGHT = 800, 600
VEL = 3
FPS = 60
WHITE_COLOR = (255, 255, 255)
pygame.display.set_caption("Space Invaders")
ufo_icon = pygame.image.load('ufo.png')
player = pygame.image.load('space-invaders.png')
player = pygame.transform.scale(player, (60, 60))
playerX = 400 - player.get_width()/2
playerY = 300
pygame.display.set_icon(ufo_icon)




def player_movement(playerX , keys):
    if keys[pygame.K_LEFT]:
        playerX += VEL

def draw_window(player, playerX, playerY):
    WIN.fill((WHITE_COLOR))
    WIN.blit(player, (playerX, playerY + 100))
    pygame.display.update()



def main():
    run = True
    while run:
        for event in pygame.event.get():

            if event.type == pygame.QUIT:
                run = False



            keys = pygame.key.get_pressed()
        player_movement(playerX, keys)
        draw_window(player, playerX, playerY)



main()

1 Answers1

1

Python has no concept of in-out parameters. You need to return the new value from the function:

def player_movement(playerX , keys):
    if keys[pygame.K_LEFT]:
        playerX -= VEL
    if keys[pygame.K_RIGHT]:
        playerX += VEL
    return playerX
def main():
    playerX = 400 - player.get_width()/2
    playerY = 300
    run = True
    while run:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False

        keys = pygame.key.get_pressed()
        playerX = player_movement(playerX, keys)
        draw_window(player, playerX, playerY)
Rabbid76
  • 202,892
  • 27
  • 131
  • 174
  • 1
    yes I just fixed it, this is my first program in Pygame and I am a pretty beginner in programming. this is why i had a lot of problems – Noam Aharoni Aug 08 '21 at 08:48