How can I create multiple turtles all in different positions?

Question:

I am trying to build a crossy road sort of game through the use of the turtle package but I’m stuck on how I can create multiple different turtles (cars) that will go across my screen all at different y values.
This is literally all I have so far:

from turtle import Turtle
import random
from random import randint

COLORS = ["red", "orange", "yellow", "green", "blue", "purple"]
STARTING_MOVE_DISTANCE = 5
MOVE_INCREMENT = 10


class CarManager(Turtle):

    def __init__(self):
        super().__init__()
        self.color(random.choice(COLORS))
        self.setheading(180)

    def moveCars(self):
        self.fd(MOVE_INCREMENT)

Any ideas on how to get this result?

I’m expecting to have many different turtle objects that can all cross the screen separately (at differemt speeds) and will all have separate y values.

Asked By: TheJoeCa

||

Answers:

If you want multiple Turtles you can simply create multiple Turtle instances:

import turtle
screen = turtle.Screen()
turtle1 = turtle.Turtle()
turtle2 = turtle.Turtle()

# Move turtle1
turtle1.forward(100)
# Move turtle2 somewhere else
turtle2.left(90)
turtle2.forward(100)
Answered By: lstuma

This works as I originally intended

from turtle import Turtle
import random

COLORS = ["red", "orange", "yellow", "green", "blue", "purple"]
STARTING_MOVE_DISTANCE = 5
MOVE_INCREMENT = 10


class CarManager:

    def __init__(self):
        self.all_cars = []

    def create_car(self):
        random_chance = random.randint(1,6)
        if random_chance == 1:
            new_car = Turtle("square")
            new_car.shapesize(stretch_wid=1, stretch_len=2)
            new_car.penup()
            new_car.color(random.choice(COLORS))
            random_y = random.randint(-260, 260)
            new_car.goto(300, random_y)
            self.all_cars.append(new_car)

    def move_cars(self):
        for car in self.all_cars:
            car.bk(STARTING_MOVE_DISTANCE)

Hope this can be of use to someone at some point!

Just for reference the "random_chance" was used as a time delay only ruins the functionality of the game whereas this only reduces the number of cars.

Please look at turtle graphics page for further information about the use of the turtle module.

Answered By: TheJoeCa
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.