DEV Community

Mike Kameta
Mike Kameta

Posted on

100 Days of Code: The Complete Python Pro Bootcamp for 2022 - Day 19 (Turtle Race Game)

  • 19.1 Make an etch a sketch app
import turtle
from turtle import Turtle, Screen


tim = Turtle()
screen = Screen()
turtle.listen()


def move_forward():
    tim.forward(10)


def move_backwards():
    tim.back(10)


def counter_clockwise():
    tim.left(15)


def clockwise():
    tim.right(15)


def reset_screen():
    tim.screen.reset()


screen.onkey(move_forward, "w")
screen.onkey(move_backwards, "s")
screen.onkey(counter_clockwise, "a")
screen.onkey(clockwise, "d")
screen.onkey(reset_screen, "c")
screen.exitonclick()
Enter fullscreen mode Exit fullscreen mode
  • Turtle Race Game
"""Import Statements"""
from turtle import Turtle, Screen
import random

"""Variables"""
colors = ["purple", "blue", "green", "yellow", "orange", "red"]
y_position = [-140, -80, -20, 40, 100, 150, ]
is_race_on = True
all_turtles = []

"""Screen setup"""
screen = Screen()
screen.setup(width=500, height=400)
user_bet = screen.textinput(title="Make your bet", prompt="Which turtle will win the race? Pick a color (purple, blue,"
                                                          "green, yellow, orange, red)")

"""Objects"""
for turtle_index in range(0, 6):
    new_turtle = Turtle(shape="turtle")
    new_turtle.color(colors[turtle_index])
    new_turtle.penup()
    new_turtle.goto(x=-225, y=y_position[turtle_index])
    all_turtles.append(new_turtle)

if user_bet:
    is_race_on = True

while is_race_on:

    for turtle in all_turtles:
        if turtle.xcor() > 217:
            is_race_on = False
            winning_color = turtle.pencolor()
            if winning_color == user_bet:
                print(f"Congratulations, your turtle {winning_color} has won")
            else:
                print(f"The winning turtle is {winning_color}, better luck next time")
        rand_distance = random.randint(0, 10)
        turtle.forward(rand_distance)

"""Keep screen open until clicked"""
screen.exitonclick()
Enter fullscreen mode Exit fullscreen mode

Top comments (0)