Pygame从A到B的最短路线

时间:2018-03-17 17:43:38

标签: python pygame

我想创建一个程序,其中有一个像素选择表面中的随机点,然后通过直线走到它。当他完成后,他会选择另一个随机点。它永远就是这样。问题是,我该怎么做 将其转换为x += 1y += 1x -= 1y-= 1种指示?

到目前为止我得到了什么:

class pixel:
def __init__(self, x, y):
    self.x = x
    self.y = y
    self.walking = False
def update(self):
    if self.walking == False:
        self.walking = True
        self.destx = random.randint(0, width)
        self.desty = random.randint(0, height)
     #Some form of script to walk to that position
     if self.x == self.destx and self.y == self.desty:
         self.walking = False

2 个答案:

答案 0 :(得分:1)

Bresenham's line algorithm产生直线上所有点的坐标,这似乎是您正在寻找的。以下是Python中的实现:

https://github.com/encukou/bresenham/blob/master/bresenham.py

答案 1 :(得分:1)

这是计算机图形学中的一个非常经典的问题(每个低级图形API必须在像素网格上绘制直线)。 Bresenham于1962年开发了这个问题的最佳解决方案(比我年龄大得多)。

基本上,我们的想法是找到线段所覆盖的三角圆的八分圆,然后在 x y 上循环。所有细节都可以在相应的维基百科页面上找到:

https://en.wikipedia.org/wiki/Bresenham%27s_line_algorithm

以及基于Pygame的实现:

https://gist.github.com/0xKD/4714810