Reputation: 1
I'm doing a turtle race in Python, where we should reinvent the base code. My idea was to create a podium and put the 3 first winners. I managed to put the first winner in the podium, but now I don't know how to measure the distance between the turtles and find out who's in second and third places. Any ideas? This is the final output: the end of the game
while True:
turtle_winner = choice([maria, jaquina, toino, celeste, tia])
turtle_winner.forward(randint(1, 5))
if turtle_winner.xcor() > 70:
break
turtle_winner.shapesize(3)
screen.ontimer(winner_podium, 250)
Upvotes: 0
Views: 2601
Reputation: 961
You just have to create a function for when each turtle finishes, in front of the break
, and only when all of them finish, the podium shows. You also need a list for the places.
places = []
def onFinish(turtleName):
places.append(turtleName)
You just need to put in the turtle name into the function, then it lists them all from 1st to last, which you can use for a podium.
Upvotes: 0
Reputation: 41872
I might go about this using a dictionary instead of top level variables to contain the field of runners:
from turtle import Turtle
from operator import itemgetter
from random import randint
STARTING_POINT = (0, 0)
RUNNERS = ["Maria", "Jaquina", "Toino", "Celeste", "Tia"]
def show_winners(field):
return sorted(((turtle.distance(STARTING_POINT), name) for name, turtle in field.items()), key=itemgetter(0), reverse=True)
field = {runner: Turtle() for runner in RUNNERS}
for turtle in field.values(): # simulate a race for example purposes
turtle.forward(randint(10, 100))
print(show_winners(field))
OUTPUT
% python3 test.py
[(75.0, 'Celeste'), (53.0, 'Toino'), (52.0, 'Maria'), (44.0, 'Tia'), (24.0, 'Jaquina')]
%
The results include the distances so that you can see it's working. If you only need the names, you can simplify the code along the lines of @SimonR's (+1) solution:
def show_winners(field):
return sorted(field, key=lambda name: field[name].distance(STARTING_POINT), reverse=True)
And tossing the import
of itemgetter
(which was only there to avoid a bug in the case of a tie.)
% python3 test.py
['Toino', 'Jaquina', 'Tia', 'Maria', 'Celeste']
%
Upvotes: 0
Reputation: 1824
Here's a minimal example of how you might do this. I created a some turtles with random positions as a demonstration. Notice that i've given the turtles name attributes, otherwise your standings will just be the names of the objects themselves, which isn't very readable. The important part is how to sort the list of turtles by their xcor
attribute, on the second-to-last line.
from random import random
class Turtle:
def __init__(self, name):
self.xcor = random()
self.name = name
a = Turtle('a')
b = Turtle('b')
c = Turtle('c')
d = Turtle('d')
e = Turtle('e')
turtles = [a,b,c,d,e]
final_standings = [t.name for t in sorted(turtles, key=lambda turtle: turtle.xcor)]
print(final_standings)
Output:
['d', 'c', 'b', 'e', 'a']
Hopefully that should get you started.
Upvotes: 1