Click here to Skip to main content
15,887,328 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
i am a new coder using python and i am reading a book called hello world 3rd edition and i am try to run listing 16.14 but all i get is a black screen, what the program is suppose to do is make a imported image of a beach ball move across the screen horizontally and when reaching the edge bounce back forever intill the window is closed

What I have tried:

Python
import pygame, sys
pygame.init()
screen = pygame.display.set_mode([640, 480])
screen.fill([255,255,255])
my_ball=pygame.image.load("beach_ball.png")
x = 50
y = 50
x_speed = 10
running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
            pygame.time.delay(20)
            pygame.draw.rect(screen,[255,255,255],[x,y,90,90],0)
            x = x + x_speed
if x > screen.get_width()-90 or x <0:
      x_speed = -x_speed
      screen.blit(my_ball,[x, y])
      pygame.display.flip()
pygame.quit()
Posted
Updated 10-Jul-23 18:27pm
v2

1 solution

In Python, indentation controls what code is part of what block: all the contiguous code at a particular indentation level is part of a block, and any lesser indentation ends that.
As a result, your if statement
Python
if x > screen.get_width()-90 or x <0:
terminates the while loop above it meaning that the loop consists only of this code:
Python
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
            pygame.time.delay(20)
            pygame.draw.rect(screen,[255,255,255],[x,y,90,90],0)
            x = x + x_speed
Since running does not change inside the loop unless the user exits, and the loop does nothing else at all until that does happen, the screen remains blank.
 
Share this answer
 
Comments
Kao Enyeartdecarlo 11-Jul-23 18:50pm    
am i suppose to indent if x > screen.get_width()-90 or x <0: as much as the pervious line of code?
OriginalGriff 12-Jul-23 0:21am    
At a guess, indent it to the same level as the for line. That puts them both inside the while loop.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900