perpetuum
perpetuum

Reputation: 129

Sprite won't move in pygame

Sprite of a "planet" from this code won't go left and right e.t., won't animate. Where is the error? Actually, the listing is from google play's app "Programming Hero" where the author of an app step by step directs students through video - game making process with python...

import pygame

screen_size = [360,640]
screen =     pygame.display.set_mode(screen_size)
background = pygame.image.load('background.png')
planet =     pygame.image.load('one.png')
spaceship =  pygame.image.load('spaceship.png')
bullet =     pygame.image.load('bullet.png')


keep_alive = True
planet_x = 140           # I've edited this
move_direction = 'right' # out of the loop, too

# according to the same logic "I've saved the planet" to go infinitely right
# thanx 

while keep_alive:
    pygame.event.get()
    keys = pygame.key.get_pressed()
    if keys[pygame.K_SPACE] == True:
        print('Space key pressed')

    screen.blit(background, [0,0])
    screen.blit(bullet,[180,500])
    screen.blit(spaceship,[160,500])

    # I put this out off loop:           planet_x = 140
    # wrong, must go out of a loop, too: move_direction = 'right'

    if move_direction == 'right':
        planet_x = planet_x + 5
        if planet_x == 270:
            move_direction = 'left'
    else:
        planet_x = planet_x - 5
        if planet_x == 0:
            move_direction = 'right'

    screen.blit(planet, [planet_x, 50])
    pygame.display.update()

Upvotes: 1

Views: 63

Answers (1)

Rabbid76
Rabbid76

Reputation: 210878

The position of the planet (planet_x) is reinitialized in every frame:

while keep_alive:
   # [...]

   planet_x = 140

   if move_direction == 'right':
       planet_x = planet_x + 5

   # [...]

   screen.blit(planet, [planet_x, 50])

Move the initialization of planet_x, before the main application loop:

planet_x = 140
while keep_alive:

    # [...]

    if move_direction == 'right':
        planet_x = planet_x + 5

    # [...]

    screen.blit(planet, [planet_x, 50])

Upvotes: 1

Related Questions