如何测量海龟之间的距离?

问题描述 投票:0回答:3

我正在python中进行乌龟竞赛,我们应该在其中重新发明基本代码。我的想法是创建一个领奖台,并把3名首位获奖者。我设法将第一名获胜者放在了领奖台上,但现在我不知道如何测量海龟之间的距离并找出谁在第二和第三名。有任何想法吗?这是最终输出: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)
python function object distance python-turtle
3个回答
1
投票

这是您如何执行此操作的最小示例。我创建了一些随机位置的乌龟作为演示。请注意,我已经赋予了乌龟名称属性,否则,您的排名将只是对象本身的名称,这不是很容易阅读。重要的部分是如何按xcor属性在倒数第二行对海龟列表进行排序。

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)

输出:

['d', 'c', 'b', 'e', 'a']

希望这可以帮助您入门。


0
投票

尝试一下:

print(Turtle1.distance(Turtle2))

0
投票

我可能会使用字典而不是顶级变量来包含跑步者的领域:

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))

输出

% python3 test.py
[(75.0, 'Celeste'), (53.0, 'Toino'), (52.0, 'Maria'), (44.0, 'Tia'), (24.0, 'Jaquina')]
%

结果包括距离,因此您可以看到它正在工作。如果只需要名称,则可以按照@SimonR(+1)解决方案的方式简化代码:

def show_winners(field):
    return sorted(field, key=lambda name: field[name].distance(STARTING_POINT), reverse=True)

并扔掉importitemgetter(只有在平局的情况下才避免出现错误。)

% python3 test.py
['Toino', 'Jaquina', 'Tia', 'Maria', 'Celeste']
%
© www.soinside.com 2019 - 2024. All rights reserved.