我试着训练一个简洁的算法来玩一个简单的游戏,叫做“曲线”。我能够创造一个曲线搭桥的游戏版本,现在我想训练人工智能来玩它。因此,AI必须学会避免障碍:游戏的边界和每个玩家留下的轨迹,就像蛇一样。
目前,我这样做的方式如下:
问题是这太慢了!运行'python -m cProfile -s + the ai.py‘时,我认为是对障碍的检测减慢了脚本的速度,约占运行时总数的50%。
--请看下面的代码--如何创建视线:
posx =x-球员的位置
posy =y-球员的位置
玩家正在前进的方向
悬空=是视线之间的度间距。
角度=视线的总范围(以度为单位)
def create_lines_of_sight(posx, posy, dir, dangle, angle, length):
dirs = [xdir for xdir in np.ceil(np.arange(dir-angle,dir+angle,dangle))]
d_posx = np.cos(np.deg2rad(dir))
d_posy = np.sin(np.deg2rad(dir))
return list(map(functools.partial(f_lrects,posx,posy,length), dirs))
def create_rects(posx, posy, d_posx, d_posy, i):
return f_rect(posx+i*d_posx,posy+i*d_posy,1,1,0,curvefever.WHITE)
f_create_rect = create_rects
def create_line_of_rects(posx, posy, length,dir):
l = pygame.sprite.Group()
ladd = l.add
d_posx = np.cos(np.deg2rad(dir))
d_posy = np.sin(np.deg2rad(dir))
i = [i for i in range(2,length,8)]
ladd(map(functools.partial(f_create_rect,posx,posy,d_posx,d_posy),i))
return l
f_lrects = create_line_of_rects
所有障碍都是矩形,定义为:
class Rect(pygame.sprite.Sprite):
def __init__(self,x,y,width,height,dir,color):
super().__init__()
self.image = pygame.Surface([width, height])
self.image.fill(color)
self.rect = self.image.get_rect()
self.rect.centerx = x
self.rect.centery = y
并被保存在一个精灵组中。
我试过什么
我尝试添加一个map命令以摆脱for循环,这并没有加快它的速度。
我试着添加函数名以删除函数查找,我阅读它可以使它更快,但它没有。
我试着用“Bresenham‘s Line算法”检测障碍物,并检查障碍物(x,y)的位置是否与视线重叠。虽然这是一个更快,但没有工作,因为它经常错过障碍。之所以发生这种情况,是因为视线与障碍物中心(矩形、矩形)并不完全匹配,尽管它确实与矩形本身重叠。
其他人用什么来探测障碍(也许是在游戏中)?任何关于我如何使这更快或更有效率的建议都是非常受欢迎的。
非常感谢您的帮助!
发布于 2021-08-25 18:57:57
我一直在做一个类似的项目。最后,我使用了吡咯的pygame.Rect.clipline()
和pygame.Vector2.distance_to()
方法:
def intersect_rect(self,other) -> tuple[float,float]:
cl=other.clipline(self.a.x,self.a.y,self.b.x,self.b.y)
if cl:
return cl[0] if self.a.distance_to(cl[0]) <self.a.distance_to(cl[1]) else cl[1]
else:
return
self
和other
都是一个类,继承自pygame.Rect
类。self.a
和self.b
是两个pygame.Vector2
对象。其中,self.a
位于播放机的原点,self.b
位于LoS。与纯python函数相比,这导致了100倍的加速。
https://stackoverflow.com/questions/61202251
复制相似问题