repl.it
@Charanpreet/

Lab 4.01 Example - Turtle Race

Python (with Turtle)

No description

fork
loading
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
import random
import turtle

# Hide the default turtle so that the
# triangle isn't visible while the turtle
# is drawing the start and finish lines.
turtle.hideturtle()

# Draw the starting line
turtle.pensize(5)
turtle.color('yellow')
turtle.penup()
turtle.goto(-100, -75)
turtle.setheading(90)
turtle.pendown()
turtle.forward(150)
turtle.penup()

# Draw the finish line
turtle.pensize(5)
turtle.color('black')
turtle.penup()
turtle.goto(100, -75)
turtle.setheading(90)
turtle.pendown()
turtle.forward(150)
turtle.penup()

# Create a turtle to participate in the race.
franklin = turtle.Turtle()
franklin.color('green')
franklin.shape('turtle')
franklin.penup()

flamingo = turtle.Turtle()
flamingo.color('pink')
flamingo.shape('turtle')
flamingo.penup()
# Create another turtle to participate in the race.
donatello = turtle.Turtle()
donatello.color('purple')
donatello.shape('turtle')
donatello.penup()

# Take positions for the race.
franklin.setheading(0)
franklin.goto(-120, -50)
donatello.setheading(0)
donatello.goto(-120, 50)
flamingo.setheading(0)
flamingo.goto(-120, 0)

# Make the turtles move slowly so it seems more realistic.
franklin.speed(1)
donatello.speed(1)
flamingo.speed(1)
# Randomly move one of the turtles by choosing a random
# number from 1 to 100. If the chosen number is 50 or less,
# move one turtle. Otherwise, move the other turtle.
# This is repeated over and over as long as the x-coordinate
# of both turtles is less than 80. Once one turtle
# has an x-coordinate that is larger than 80,
# this loop will stop repeating and the script will finish.
while franklin.xcor() < 80 and donatello.xcor() < 80 and flamingo.xcor() < 80:
  random_number = random.randint(1, 150)
  if random_number <= 50:
    franklin.forward(2)
  elif 50 <= random_number <= 100:
    flamingo.forward(2)
  else :
    donatello.forward(2)
  
result
console