For a school projet that wants us to use python turtle but no external libraries (that you have to install from command line), I firstly made a car that can move following a few tutorials. The car worked perfectly. I then tried to add multiple cars. Because I couldn't use multi threading libraries, I succesfully used the exec function to create autmatically a given number of turtles acting as cars. They work fine (although having to many of them is laggy, I don't need a lot of them)
My problem is when the cars are colliding, one frame it shows a car on top and the next frame it's the other car on top, and each frame it switches making them "flicker", while I want the bottom one (with the smallest Y value) to be the one shown when 2 or more cars are colliding (for perspective reasons).
Here is my code that I simplified the best I could :
from turtle import *
from random import *
from tkinter import *
#Setup of Turtles and Screen
root = Tk()
screen = Screen()
screen.setup(width=root.winfo_screenwidth(), height=root.winfo_screenheight())
screen.tracer(False)
root.destroy()
for loop in range(1, 3):
exec("car" + str(loop) + " = Turtle()")
for loop in range(1, 3):
exec("car" + str(loop) + ".hideturtle()")
exec("car" + str(loop) + ".speed(0)")
#Car itself (simplified to a rectangle)
def car_form(car_color: tuple, car):
size = 1.7
car.pendown()
colormode(255)
car.fillcolor(car_color)
car.begin_fill()
car.setx(car.xcor() + 75 * size)
car.sety(car.ycor() + 20 * size)
car.setx(car.xcor() - 75 * size)
car.sety(car.ycor() - 20 * size)
car.end_fill()
#Movement of the cars
def infinite_car(car, car_color, way):
screen.update()
car.clear()
car_form(car_color, car)
car.setheading(0)
if way == 1:
car.setx(car.xcor() + 0.2)
else:
car.setx(car.xcor() - 0.2)
#Main function that position the cars, give some values and start the movement loop
def main():
for loop in range(1, 3):
exec('car_color' + str(loop) +' = (randint(0, 255), randint(0, 255), randint(0, 255))')
if loop == 1:
exec('car' + str(loop) + '.setx(-100)')
else:
exec('car' + str(loop) + '.setx(100)')
while True:
for loop in range(1, 3):
if loop == 1:
exec('infinite_car(car' + str(loop) + ', car_color' + str(loop) + ', 1' + ')')
else:
exec('infinite_car(car' + str(loop) + ', car_color' + str(loop) + ', 2' + ')')
main()