-
Notifications
You must be signed in to change notification settings - Fork 0
/
turtle_racing.py
65 lines (53 loc) · 1.93 KB
/
turtle_racing.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
import turtle
import time
import random
WIDTH, HEIGHT = 500, 500 # constant values are all caps
COLORS = ['red', 'green', 'blue', 'orange', 'yellow', 'black', 'purple', 'pink', 'brown', 'cyan']
def get_number_of_racers():
racers = 0
while True:
racers = input('Enter the number of racers (2-10): ')
if racers.isdigit():
racers = int(racers) #can only convert an digit to a int so check first
else:
print('Input is not numeric.. Try again!')
continue # will go back to start of while loop rather than next if statement
if 2 <= racers <= 10:
return racers
else:
print('Number not in range 2-10. Try again!')
def race(colors):
turtles = create_turtles(colors)
while True:
for racer in turtles:
distance = random.randrange(1, 20)
racer.forward(distance)
x, y = racer.pos()
if y >= HEIGHT // 2 - 10:
return colors[turtles.index(racer)]
def create_turtles(colors):
turtles = []
spacingx = WIDTH // (len(colors) + 1)
for i, color in enumerate(colors): # enumerate gives us the index and the value
racer = turtle.Turtle()
racer.color(color)
racer.shape('turtle')
racer.left(90)
racer.penup()
racer.setpos(-WIDTH//2 + (i + 1) * spacingx, -HEIGHT//2 + 20)
racer.pendown()
turtles.append(racer)
return turtles
def init_turtle():
screen = turtle.Screen()
screen.setup(WIDTH, HEIGHT)
screen.title('Turtle Racing!')
racers = get_number_of_racers()
init_turtle()
random.shuffle(COLORS)
colors = COLORS[:racers] # : is called the slice operator.
# It takes that number of elements from the list.
#In this case, the number of turtles the user wants to race
winner = race(colors)
print('The', winner, 'turtle won the race!')
time.sleep(5)