import pygame
import random
black = (0,0,0)
white = (255,255,255)
green = (0,255,0)
red = (255,0,0)
screen = pygame.display.set_mode((1200, 600))
title = pygame.display.set_caption("Speeding cars")
clock = pygame.time.Clock()
clock.tick(60)
class Car:
def __init__(self, x, y, height, width):
self.x = x
self.y = y
self.height = height
self.width = width
def drive(self, change):
self.change = random.randint(1, 2)
self.x += self.change
pygame.draw.rect(screen, black, (self.x, self.y, self.height, self.width))
def again(self):
while True:
if self.x + 50 > 1200:
for car in cars:
car.drive(False)
cars = []
for i in range(1, 6):
cars.append(Car(0, i*100, 50, 25))
driving = True
while driving:
screen.fill(white)
for car in cars:
car.drive(False)
car.again()
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
pygame.display.flip()
Whenever i try to run this code, my pygame window stops responding. Something i have noticed is whenever i delete def again(self):
block of code, my winodw works fine, however i want the blocks to come back again after they go off the screen. Thank you.
You've implemented an endless loop in again
:
def again(self): while True: if self.x + 50 > 1200: for car in cars: car.drive(False)
Note, again
is called in the main application loop and it is called for each car:
while driving: # [...] for car in cars: # [...] car.again()
If you want to set all the cars at its initial position, when 1 car has reached the end of the track, then you've to verify if any car has reached the end of the track and to est the .x
coordinate of all cars 0:
finished = [car for car in cars if car.x + 50 > 1200]
if len(finished) > 0:
for car in cars:
car.x = 0
or a bit shorter
if any([car for car in cars if car.x + 50 > 1200]):
for car in cars:
car.x = 0
Do the evaluation in the main application loop:
driving = True
while driving:
screen.fill(white)
for car in cars:
car.drive(False)
if any([car for car in cars if car.x + 50 > 1200]):
for car in cars:
car.x = 0
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
pygame.display.flip()
If you want to keep the individual position of each car, then just set a single car at the start, when it reaches the end of the track (car.x -= 1200
):
class Car:
# [...]
def again(self):
if self.x + 50 > 1200:
self.x -= 1200
driving = True
while driving:
screen.fill(white)
for car in cars:
car.drive(False)
car.again()
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
pygame.display.flip()
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments