python - Python turtle 中的碰撞触发比预期的要早
问题描述
我试图让乌龟在与乌龟碰撞r
时将颜色变为红色。b
出于某种原因,它会在视觉碰撞之前改变颜色。我不知道该怎么办,请帮忙。
我在trinket.io
. 你将不得不导入 turtle 和 import math 来运行它。
blue = {'turtle':turtle.Turtle(),'radius': 20,'x':100,'y': 5,'speed': 5}
ran = {'turtle':turtle.Turtle(),'radius': 20,'x': 100,'y':0}
game = {"status": "new", "mode": "play"}
b = blue['turtle']
b.penup()
b.shape('circle')
r = ran['turtle']
r.penup()
r.setx(ran['x'])
r.sety(ran['y'])
r.shape('circle')
screen = b.getscreen()
def up():
current_y = b.ycor()
new_y = current_y + blue['speed']
b.sety(new_y)
def down():
current_y = b.ycor()
new_y = current_y - blue['speed']
b.sety(new_y)
def left():
current_y = b.xcor()
new_y = current_y - blue['speed']
b.setx(new_y)
def right():
current_y = b.xcor()
new_y = current_y + blue['speed']
b.setx(new_y)
def coll(obj_1,obj_2):
turt_1 = obj_1['turtle']
turt_2 = obj_2['turtle']
dx = turt_1.xcor() - turt_2.xcor()
dy = turt_1.ycor() - turt_2.ycor()
distance = math.sqrt(dx**2 + dy**2)
if distance <= obj_1['radius'] + obj_2['radius']:
turt_2.color('red')
else:
turt_2.color('black')
screen.onkey(up,'Up')
screen.onkey(down,'down')
screen.onkey(left,'left')
screen.onkey(right,'right')
screen.listen()
# continue until game is over
while game["status"] != "over":
# if not paused
if (game["mode"] != "paused"):
coll(blue,ran)
解决方案
由于某种原因,它海龟 r 在视觉碰撞之前会改变颜色。
这似乎是由于当相关对象的直径为 20 且半径为 10 时,您使用了 20 的半径。下面是我对您的代码进行的修改和其他调整:
import turtle
import math
blue = {'turtle': turtle.Turtle(), 'radius': 10, 'x': 0, 'y': 0, 'speed': 5}
ran = {'turtle': turtle.Turtle(), 'radius': 10, 'x': 100, 'y': 0}
def up():
b.sety(b.ycor() + blue['speed'])
coll(blue, ran)
def down():
b.sety(b.ycor() - blue['speed'])
coll(blue, ran)
def left():
b.setx(b.xcor() - blue['speed'])
coll(blue, ran)
def right():
b.setx(b.xcor() + blue['speed'])
coll(blue, ran)
def coll(obj_1, obj_2):
turt_1 = obj_1['turtle']
turt_2 = obj_2['turtle']
dx = turt_1.xcor() - turt_2.xcor()
dy = turt_1.ycor() - turt_2.ycor()
distance = math.sqrt(dx**2 + dy**2)
if distance <= obj_1['radius'] + obj_2['radius']:
turt_2.color('red')
else:
turt_2.color('black')
b = blue['turtle']
b.shape('circle')
b.penup()
b.color('blue')
b.setposition(blue['x'], blue['y'])
r = ran['turtle']
r.shape('circle')
r.penup()
r.setposition(ran['x'], ran['y'])
screen = b.getscreen()
screen.onkey(up, 'Up')
screen.onkey(down, 'Down')
screen.onkey(left, 'Left')
screen.onkey(right, 'Right')
screen.listen()
screen.mainloop()
推荐阅读
- c# - 从另一个视图搜索时被重定向
- javascript - 如何在页面项目中获取多个选中的复选框值并在下一页提交
- ssis - 审计表的 SSIS 负载问题
- java - LWJGL OpenGL 投影矩阵问题
- java - 有没有一种简单的方法可以将有序列表转换为查找表?
- reactjs - 'this.props.history.push()' 适用于普通页面但不适用于嵌套组件?
- django - 如何确保 Django REST API 中的幂等性?
- outlook-redemption - 创建兑换对象失败
- reactjs - 是的,使用 url() 验证网站非常严格
- r - 计算一个单词是否同时匹配两列