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.
CodePudding user response:
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)
CodePudding user response:
It's not perfect yet. (too many cars created but it's what I was roughly aiming for)
from turtle import Turtle
import random
import time
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):
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)