Pygame从A到B的最短路线

问题描述 投票:0回答:2

我想创建一个程序,其中有一个像素,它选择表面中的随机点,然后通过直线走到它。当他完成后,他会选择另一个随机点。它永远就是这样。问题是,我如何将其转换为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
python pygame
2个回答
1
投票

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

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

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

以及基于Pygame的实现:

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


1
投票

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

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

© www.soinside.com 2019 - 2024. All rights reserved.