问题描述
我正在创建一个蛇游戏,如果我触摸屏幕上的另一只乌龟,我希望发生一个动作?
fruit = turtle.Turtle()
fruit.penup()
fruit.size = 45
fruit.color("Black")
fruit.shape("circle")
fruit.goto(randint(-180,0),randint(0,180))
解决方法
不幸的是,Turtle 包没有内置碰撞机制,因此您必须定义碰撞是什么,并自己反复检查碰撞。
您可以使用任何您想要的碰撞定义来定义“碰撞”检查函数。
例如,如果两个水果中心之间的距离小于海龟的组合半径,这意味着圆的边缘是重叠的。 (对于更复杂的形状,可以使用自定义框或形状来检测碰撞)
海龟的 shapesize 给出了默认海龟大小 20 的乘数,我们得到半径的一半:
def is_collided(a,b):
distance = b.distance(a.pos())
radius_a = a.shapesize()[0] * 10
radius_b = b.shapesize()[0] * 10
return radius_a + radius_b >= distance
然后您可以定义不同海龟的列表,并循环遍历它们以检查它们中是否有任何与您的水果发生碰撞,如果是,则打印:
other_turtles = [turtle1,turtle2,turtle3]
for t in other_turtles:
if is_collided(fruit,t):
# can define other actions here
print(f'collision between fruit and {t}')
如果您直接复制示例代码下方的这两个片段,并将 turtle1,turtle2
替换为其他海龟的名称,它应该可以工作。
您还可以看到不同水果here的作用。