Home > Back-end >  How do I remove a car when it reaches the edge of screen?
How do I remove a car when it reaches the edge of screen?

Time:05-17

I am a beginner in Python and trying to learn by building a Frogger Clone. I have created images of cars using a class, and looping them to create 6 cars. I have a problem in that how do i remove them when they reach the boundary of screen.

import random

import pygame

pygame.init()
screen = pygame.display.set_mode((600, 600))
# Dictionary of Car Images
cars = {
    1: pygame.image.load('images/police.png'),
    2: pygame.image.load('images/motorcycle.png'),
    3: pygame.image.load('images/sports1.png')
}
current_cars = []


class Car():
    def __init__(self, a,x, y):
        self.a = a
        self.x = x
        self.y = y



    def move(self):
        self.x  = 5
        screen.blit(cars.get(self.a), (self.x, self.y))

# Creates 6 cars
for i in range(6):
    a = random.randint(1,3)
    current_cars.append(Car(a,0, 100   (100*i)))

start = pygame.time.get_ticks()
clock = pygame.time.Clock()
running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    screen.fill((0, 0, 0))
    now = pygame.time.get_ticks()
    # Creates new enemy after every 6 seconds.
    if now - start > 6000:
        start = now
        a = random.randint(1,3)
        b = random.randrange(1,501,100)
        object = Car(a, 0, 100   b)
        current_cars.append(object)
       
        # moves all the cars in list
    for i in range(len(current_cars)):
        current_cars[i].move()

    clock.tick(11)
    pygame.display.update()

How do i create an if condition to check when x position of a car reaches the boundary and remove it from the list of current cars.

CodePudding user response:

You have to remove the care from the list when the car goes out of bounds. Use pygame.Rect.colliderect to test if there is still a part of the car on the screen.

Load the car image in the constructor of the Car class instead of in each frame

class Car():
    def __init__(self, a, x, y):
        self.image = cars.get(a)
        self.x = x
        self.y = y

    def move(self):
        self.x  = 5
        screen.blit(self.image, (self.x, self.y))

See How to remove items from a list while iterating?. Iterate through a shallow copy of the car list and remove the cars from the original car list if they are not on screen:

while running:
    # [...]

    for car in current_cars:     # iterate list of cars
        car.move()

    screen_rect = screen.get_rect()
    for car in current_cars[:]:  # iterate shallow copy of car list
        car_rect = car.image.get_rect(topleft = (car.x, car.y))
        if not screen_rect.collidrect(car_rect):
            current_cars.remove(car)
  • Related