Ask coding questions

← Back to all posts
Can anyone help me improve my code?
EDHENATION (1)

I am worried as the game goes the ram usage will increase, which will slow down the performance, so I tried to delete car objects. But my code only removes them from the list total, but not actually deletes them.

Comments
hotnewtop
DynamicSquid (4933)

The main problem I see is that you have 3 for loops that iterates over the cars. You have one in cars.move(), cars.remove_cars(), and on line 46. What you can do instead is to just use one for loop for your cars:

for car in cars.total:
    # move car
    car.forward(car.move_speed)

    # remove car
    if car.xcor() <= -270:
        car.hideturtle()
        cars.total.remove(car)
    # check is player hit
    elif car.distance(player) <= 20:
        scoreboard.game_over()
        game_is_on = False
        break

Your class design pattern is also a little weird. You should have a class for a car, not a class for all the cars, but, that's something else

Hope this helps :)