0

I created a program with pygame. The background and player are appearing but the player is not moving. The program is not giving any errors, can you help me? I am using python 3.8.6. Here is some of my code.

 # Game Loop
running = True
while running:

for event in pygame.event.get():

    player(playerX, playerY)
    pygame.display.update()

        # Movment
if event.type == pygame.KEYDOWN:
    if event.key == pygame.K_a:
        player_x_change -= 10
    if event.key == pygame.K_d:
        player_x_change += 10
    if event.key == pygame.K_w:
            player_y_change -= 10
    if event.key == pygame.K_s:
            player_y_change += 10

if event.type == pygame.KEYUP:
    if event.key == pygame.K_a:
        player_x_change = 0
    if event.key == pygame.K_d:
        player_x_change = 0
        
    # Close the game
    if event.type == pygame.QUIT:
        running = False

2 Answers2

2

You need to check for the event when a user pressed a button to move the character and then update the players position. For example, here's checking if the player pressed the right arrow:

while running:
    for event in pygame.event.get():

        player(playerX, playerY)

        pygame.display.update()

        # checking if right arrow is being pressed
        if events.type == pygame.KEYDOWN:
            if events.key == pygame.K_RIGHT
                # update players x position here to move right
                # for example, player.x += 2

        # Close the game
        if event.type == pygame.QUIT:
            running = False
BWallDev
  • 345
  • 3
  • 13
2

Your code is just displaying the player, not moving him.
To move the player, you have, in a first step, to define a speed variable. Then you have to get the rectangle of your player. That will allow you to modify player position by using the speed variable you defined.
Also, if you want to move your player, you have to draw the background before drawing the player. Otherwise, every player you draw will not disappear.
And don't forget to define the game speed.

Code

#!/usr/bin/python3

import pygame

# set the game speed
delay = 10

screen = pygame.display.set_mode((800, 600))

# loading player image and get pos
player = pygame.image.load('pixel_ship_yellow.png')
player_pos = player.get_rect()

# define speed variable
speed = [1, 1]

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            break

    # drawing background
    screen.fill((0,0,0))

    # apply speed (position is automatically updated)
    player_pos = player_pos.move(speed)

    # drawing player
    screen.blit(player, player_pos)
    
    pygame.display.flip()

    # set the game speed
    pygame.time.delay(delay)


Haunui
  • 68
  • 6