Question: Need help with keeping the squares from leaving the screen. Its supposed to switch direction once it hits a side. import pygame import sys pygame.init

Need help with keeping the squares from leaving the screen. Its supposed to switch direction once it hits a side.
import pygame
import sys
pygame.init()
screen_width =1000
screen_height =500
rect_size =100
green =(0,255,0)
blue =(0,0,255)
move_speed =5
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption('Lab7C: Moving Rects with Surfaces')
clock = pygame.time.Clock()
surface_green = pygame.Surface((rect_size, rect_size))
surface_green.fill(green)
surface_blue = pygame.Surface((rect_size, rect_size))
surface_blue.fill(blue)
rect1= pygame.Rect(0,0, rect_size, rect_size)
rect2= pygame.Rect(0, screen_height - rect_size, rect_size, rect_size)
move_right1= True
move_right2= True
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
running = False
if move_right1:
rect1.x += move_speed
if rect1.x > screen_width:
rect1.x =-rect_size
else:
rect1.x -= move_speed
if rect1.x -rect_size:
rect1.x = screen_width
if move_right2:
rect2.x += move_speed
if rect2.x > screen_width:
rect2.x =-rect_size
else:
rect2.x -= move_speed
if rect2.x -rect_size:
rect2.x = screen_width
screen.fill((0,0,0))
screen.blit(surface_green, rect1)
screen.blit(surface_blue, rect2)
pygame.display.flip()
clock.tick(60)
pygame.quit()
sys.exit()
 Need help with keeping the squares from leaving the screen. Its

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!