繁体   English   中英

如何检测多个海龟对象的碰撞?

[英]How can I detect the collision of multiple turtle objects?

我在屏幕上有一堆乌龟对象。 他们还没有做任何事情,但我正在尝试以最简单的方式检测海龟对象的碰撞。 我知道我应该将所有海龟元素turtle.pos与所有其他元素的turtle.pos进行比较,但我不确定该怎么做。

此外,我担心不将任何一项与其自身的 position 进行比较。

from turtle import *
import random

screen = Screen()

screen.bgcolor("grey")
screen.setup(width=800, height=600)

my_turtles = []


for i in range(10):

    turtle = Turtle()
    turtle.penup()
    turtle.setx(random.randrange(-50, 50))
    turtle.sety(random.randrange(-50, 50))
    my_turtles.append(turtle)

#for t in turtles:
#    if t.pos == anyother t.pos_except_itself
#    do something


screen.listen()
screen.exitonclick()

不想做的就是直接比较一个turtle.position()和另一个turtle.position() 原因是海龟在一个浮点平面上游荡,直接比较坐标值很少能按你想要的方式工作。 相反,您需要决定将被视为碰撞的两只海龟(的中心)之间的最小距离。 一旦你知道那个距离,然后是一个循环:

for a in turtles:
    if any(a != b and a.distance(b) < SAFE_MARGIN for b in turtles):
        # collision, do something here 

这是您的代码的返工,它会导致任何过度侵入彼此个人空间的海龟眨眼:

from turtle import Screen, Turtle
from random import randrange

RADIUS = 10

def blink_turtles():
    for a in turtles:
        if any(a != b and a.distance(b) < RADIUS for b in turtles):
            a.color(*reversed(a.color()))

    screen.ontimer(blink_turtles, 1000)

screen = Screen()
screen.setup(width=800, height=600)

turtles = []

for _ in range(15):
    turtle = Turtle()
    turtle.hideturtle()
    turtle.shape('turtle')
    turtle.color('red', 'green')
    turtle.penup()
    turtle.goto(randrange(-50, 50), randrange(-50, 50))
    turtle.showturtle()

    turtles.append(turtle)

blink_turtles()

screen.exitonclick()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM