Today, I did more on turtle graphics and also leart about event listeners and multiple instances.
Basically, an event listener is a function that 'listens' for when you press a certain key and it then preformes an action when you do press that key and multiple instances means having multiple objects from the same class, in my case this would mean having multiple turtles at once.
First Project - Drawing
from turtle import Turtle, Screen
turtle = Turtle()
screen = Screen()
turtle.shape("turtle")
turtle.pensize(2)
screen.bgcolor("#FDFBD4")
screen.setup(width=700, height=500)
screen.title("Etch-a-Sketch")
def forwards():
turtle.forward(10)
def backwards():
turtle.backward(10)
def clockwise():
turtle.left(10)
def anti_clockwise():
turtle.right(10)
def clearscreen():
turtle.penup()
turtle.home()
turtle.pendown()
turtle.clear()
screen.onkey(forwards, "w")
screen.onkey(backwards, "s")
screen.onkey(anti_clockwise, "a")
screen.onkey(clockwise, "d")
screen.onkey(clearscreen, "c")
screen.listen()
screen.exitonclick()
Second Project - Turtle Race
from turtle import Turtle, Screen
import random as r
is_race_on = False
colors = ["red", "orange", "yellow", "green", "blue", "purple"]
positions_y = [-70, -40, -10, 20, 50, 80]
all_turtles = []
screen = Screen()
screen.setup(width=500, height=400)
screen.title("~~~~~~~~~~~~~~~~Turtle Race~~~~~~~~~~~~~~~~")
user_bet = screen.textinput("Place your bet", "Please bet on a colour: \n(red/orange/yellow/green/blue/purple)")
for index in range(0,6):
turtle = Turtle("turtle")
turtle.pensize(2)
turtle.color(colors[index])
turtle.penup()
turtle.goto(-230,positions_y[index])
all_turtles.append(turtle)
turtle.pendown()
if user_bet:
is_race_on = True
while is_race_on:
for turtle in all_turtles:
if turtle.xcor() > 230:
is_race_on = False
winner = turtle.pencolor()
if winner == user_bet:
print(f"You win! The winner was the {winner} turtle")
else:
print(f"You lose! The winner was the {winner} turtle")
for turtle in all_turtles:
distance = r.randint(0,15)
turtle.forward(distance)
screen.exitonclick()
Top comments (0)