As you can see on this Picture,
there is my rectangle (red) that I am controlling and green ones that I am not controlling. I want those green rectangles to constantly move from left to right (Every second one is moving in the opposite direction). I tried to do it, but I only managed them to go to one side and then they stop. I don't know how to make them go back to the other side and then do that constantly. Here is the picture how it looks after my
if
statement ends.
import pygame
pygame.init()
win = pygame.display.set_mode((1200, 600))
clock = pygame.time.Clock()
BLACK = (0, 0, 0)
WHITE = (255,255,255)
RED = (255, 0, 0)
GREEN = (13, 255, 0)
player = pygame.Rect(40, 45, 30, 30)
vel = 4
walls = [
pygame.Rect(0, 0, 1200, 20), pygame.Rect(0, 0, 20, 600),
pygame.Rect(0, 580, 1200, 20), pygame.Rect(1180, 0, 20, 600),
pygame.Rect(300, 0, 20, 530), pygame.Rect(20, 100, 230, 20),
pygame.Rect(70, 200, 230, 20), pygame.Rect(20, 300, 230, 20),
pygame.Rect(70, 400, 230, 20), pygame.Rect(600, 100, 20, 500),
]
movingobjectsleft = [
pygame.Rect(320, 120, 30, 30),
pygame.Rect(320, 240, 30, 30),
pygame.Rect(320, 360, 30, 30),
]
movingobjectsright = [
pygame.Rect(570, 180, 30, 30),
pygame.Rect(570, 300, 30, 30),
pygame.Rect(570, 420, 30, 30)
]
run = True
while run:
# Handle the events.
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
keys = pygame.key.get_pressed()
# Update the player coordinates.
if keys[pygame.K_LEFT] and player.x > 0:
player.x -= vel
if keys[pygame.K_RIGHT] and player.x < 1200 - player.width:
player.x += vel
if keys[pygame.K_UP] and player.y > 0:
player.y -= vel
if keys[pygame.K_DOWN] and player.y < 600 - player.height:
player.y += vel
# Game logic for walls and moving objects
for wall in walls:
# Check if the player rect collides with a wall rect.
if player.colliderect(wall):
print("Game over")
for object in movingobjectsleft:
if player.colliderect(object):
print("Game over")
if object.x < 570:
object.x += vel
for object in movingobjectsright:
if player.colliderect(object):
print("Game over")
if object.x > 320:
object.x -= vel
# Draw everything.
win.fill(WHITE)
pygame.draw.rect(win, RED, player)
# Drawing walls and moving objects
for wall in walls:
pygame.draw.rect(win, BLACK, wall)
for object in movingobjectsright:
pygame.draw.rect(win, GREEN, object)
for object in movingobjectsleft:
pygame.draw.rect(win, GREEN, object)
pygame.display.update()
clock.tick(60)
pygame.quit()
I think something needs to be done here
for object in movingobjectsleft:
if player.colliderect(object):
print("Game over")
if object.x < 570:
object.x += vel
for object in movingobjectsright:
if player.colliderect(object):
print("Game over")
if object.x > 320:
object.x -= vel