Monday, April 21, 2025

Python Turtle - Turtle Race - Automatic Winner Detection

This is Turtle Race Game with Automatic Winner Detection.

Run this code and than we will explain how to automatically detect winning turtle:

from turtle import *
import random

t1 = Turtle()
t1.shape("turtle")
t1.speed(0)
t1.penup()
t1.left(90)
t1.color("red")

t2 = t1.clone()
t2.color("yellow")

t1.goto(-300, -300)
t2.goto(300,  -300)
#-----------------------------

finish_1 = Turtle()
finish_1.penup()
finish_1.goto(-300, 300)
finish_1.pendown()
finish_1.circle(20)
finish_1.hideturtle()

finish_2 = Turtle()
finish_2.penup()
finish_2.goto(300, 300)
finish_2.pendown()
finish_2.circle(20)
finish_2.hideturtle()
#-----------------------------

def main():
    for x in range(600):
        t1.fd(random.randrange(10))
        #t1.shapesize(15, 15, 15)
        t2.fd(random.randrange(10))
        #t2.shapesize(15, 15, 15)

        if (t1.position()[1]) >= 300:
            print("Turtle 1 WINS")
            break
        elif (t2.position()[1]) >= 300:
            print("Turtle 2 WINS")
            break        

main()

There's no need to change source for turtle creation and starting points. We will just change custom functions that deals with random movements:

def main():
    for x in range(600):
        t1.fd(random.randrange(10))
        #t1.shapesize(15, 15, 15)
        t2.fd(random.randrange(10))
        #t2.shapesize(15, 15, 15)

        if (t1.position()[1]) >= 300:
            print("Turtle 1 WINS")
            break
        elif (t2.position()[1]) >= 300:
            print("Turtle 2 WINS")
            break        

To speed things up, we are using value 10 as argument for randrange() function.

Then we are introducing if / elif check to detect when any of turtles t1 and t2 reaches position 300 verticaly. How is that done ?

When we say t1.position()[1] >= 300 that means we are checking if t1 is reaching 300 value or more on y (vertical) axis. If that is correct, t1 is winner and there is no need to check more, that's why we need to break.

If t2 reaches 300 or more vertically, same story, t2 is winner and there's break again.

Results will be printed in Python Shell.

This is end of this tutorial, and corresponding YouTube playlist.

No comments:

Post a Comment

Tkinter Introduction - Top Widget, Method, Button

First, let's make shure that our tkinter module is working ok with simple  for loop that will spawn 5 instances of blank Tk window .  ...