简体   繁体   English

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

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

I have a bunch of turtle objects on the screen.我在屏幕上有一堆乌龟对象。 They don't do anything yet but I am trying to detect collision of turtle objects the simplest way.他们还没有做任何事情,但我正在尝试以最简单的方式检测海龟对象的碰撞。 I know I am supposed to compare all turtle elements turtle.pos with the turtle.pos of all the other elements, but I am not sure how to do it.我知道我应该将所有海龟元素turtle.pos与所有其他元素的turtle.pos进行比较,但我不确定该怎么做。

Also, I am concerned with not comparing any one item with its own position.此外,我担心不将任何一项与其自身的 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()

The last thing you want to do is directly compare one turtle.position() with another turtle.position() .不想做的就是直接比较一个turtle.position()和另一个turtle.position() The reason is that turtles wander a floating point plane, and directly comparing coordinate values rarely works the way you want.原因是海龟在一个浮点平面上游荡,直接比较坐标值很少能按你想要的方式工作。 Instead, you need to decide on the minimal distance between (the centers of) two turtles that will be considered a collision .相反,您需要决定将被视为碰撞的两只海龟(的中心)之间的最小距离。 Once you know that distance, then a loop like:一旦你知道那个距离,然后是一个循环:

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

Here's a rework of your code that does this, causing any turtles that have overly invaded each other's personal space to blink:这是您的代码的返工,它会导致任何过度侵入彼此个人空间的海龟眨眼:

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