import turtle
tt = turtle.Turtle()
ts = turtle.Screen()
'''约省略100行代码'''
def MonsterAim(d=20):
a = tt.position()
b = mons.position()
x = (a-b)[0]
y = (a-b)[1]
# print(x,y)
# print(a,b)
if x > 0:
RorL = MoveMonsterR
elif x < 0:
RorL = MoveMonsterL
else:
RorL = None
if y > 0:
UorD = MoveMonsterU
elif y < 0:
UorD = MoveMonsterD
else:
UorD = None
dis1 = ComputeNorm(x, abs(y)-20) # !!!!! abs(y)
dis2 = ComputeNorm(abs(x)-20, y) # !!!!! abs(x), since the distance is definitely decreasing!
# print(dis1,dis2)
if dis1 < dis2: # moving along y is better
return UorD
elif dis1 > dis2: # moving along x is better
return RorL
elif dis1 == dis2:
# print("dis1==dis2")
return random.sample([RorL,UorD],1)
红色的是target,可以人为控制;黑色的是monster,电脑空值。二者只能沿正交方向移动。
![在这里插入图片描述](https://img-blog.csdnimg.cn/20200417021309709.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L2hjMDExMg==,size_16,color_FFFFFF,t_70)Sample of Game Over
本算法实现了每秒钟刷新两点间坐标,并预判monster移动后二者之间的距离,从而采取最优的移动方式(即移动后距离尽可能小)。