【问题标题】:Finding distance to one of either the x or y coordinate查找到 x 或 y 坐标之一的距离
【发布时间】:2014-11-10 21:17:49
【问题描述】:
使用turtle.distance(),我们可以找到从当前位置(turtle.position)到指定x,y坐标的距离。但是,我们似乎不能将任一选项留空。有没有一种简单的方法可以找到从乌龟当前位置到仅 x 或仅 y 坐标的距离?
任务是画一条线,当它碰到一个 400x400 的边界框时会转身,我能想到的最好方法是找出它是否在框的 x 或 y 值范围内。
【问题讨论】:
标签:
python
drawing
coordinates
distance
turtle-graphics
【解决方案1】:
def check_bounds(pos,a_rect):
rect_left = a_rect[0][0]
rect_top = a_rect[0][1]
rect_right = a_rect[1][0]
rect_top = a_rect[1][1]
hit_x = rect_left <= pos[0] <= rect_right
hit_y = rect_top <= pos[1] <= rect_bottom
return hit_x and hit_y #the player has hit the box
box = [(50,50),(100,100)] #TL,BR
turtle_pos = (40,40)
check_bounds(turtle_pos,box)
当然你可以简化它....只是希望它漂亮而详细,以便 OP 可以理解发生了什么。