gpt4 book ai didi

python - 加速python pygame中的AI障碍检测

转载 作者:行者123 更新时间:2023-12-04 12:02:47 24 4
gpt4 key购买 nike

我正在尝试训练一个 NEAT 算法来玩一个名为“curvefever”的简单游戏。
我能够创建 pygame 版本的 curvefever,现在我想训练 AI 来玩它。
因此,AI 必须学会避开障碍物:围绕游戏的边界并跟踪每个玩家留下的痕迹,就像在 Snake 中一样。

目前我正在通过以下方式执行此操作:

  • 每个玩家都有一组向前伸出的“传感器”,用于检测障碍物是否以及距离有多远。
  • 每个“传感器”都是由几个 pygame 矩形组成的直线。
  • 对于每个传感器,它将检测是否与障碍物矩形之一发生碰撞,并计算碰撞到玩家的距离。
  • 哪个传感器检测到碰撞以及碰撞的距离是进入神经网络的信息。

  • 问题是这很慢!运行 'python -m cProfile -s cumtime ai.py' 我认为是检测障碍物导致脚本变慢,占总运行时间的 50% 左右。

    请参阅下面我如何创建视线的一些代码:

    posx = 玩家的 x 位置

    posy = 玩家的 y 位置

    dir = 玩家前进的方向

    dangle = 是视线之间的度数间距

    角度 = 视线的总范围(以度为单位)

    sketch illustrating the sensors
    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

    并保存在一个 Sprite 组中。

    我试过的

    我尝试添加一个 map 命令来摆脱 for 循环,但这并没有加快速度。

    我尝试添加函数名称以删除函数查找,我读到这使它更快,但事实并非如此。

    我尝试使用“Bresenham's Line Algorithm”检测障碍物并检查障碍物 (x,y) 位置是否与视线重叠。虽然这是一个更快的它没有工作,因为它经常错过障碍。发生这种情况是因为视线与障碍物中心 (rectx,recty) 不完全匹配,尽管它确实与矩形本身重叠。

    其他人用什么来检测障碍物(可能在 pygame 中)?非常欢迎任何有关如何使其更快或更有效的提示。

    非常感谢您的帮助!

    最佳答案

    我一直在做一个类似的项目。
    最后我用了 pygame.Rect.clipline()pygame.Vector2.distance_to() pygame的方法:

    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
    selfother都是一个类,继承自 pygame.Rect类(class)。 self.aself.b是两个 pygame.Vector2对象。哪里 self.a是在播放器的起源和 self.b洛斯。
    与纯 python 函数相比,这导致了 100 倍的加速。

    关于python - 加速python pygame中的AI障碍检测,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61202251/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com