markop
markop

Reputation: 75

Pygame shortest route from A to B

I wanted to create a program where there is a pixel which selects a random point in the surface and then walks to it by straight line. When he is finished, then he selects another random point. And it's like that forever. The problem is, how do i convert that to x += 1 or y += 1 or x -= 1 or y-= 1 sort of instructions?

So far what i've got:

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

Upvotes: 0

Views: 391

Answers (2)

sciroccorics
sciroccorics

Reputation: 2427

This is a very classical problem in Computer Graphics (each low-level graphics API has to draw straight lines on a grid of pixels). An optimal solution for this question has been developped by Bresenham in 1962 (much older than me).

Basically the idea is to find the octant of the trigonometric circle covered by the line segment to draw, then loop either over x or y. All details could be found on the corresponding Wikipedia page:

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

and a implementation based on Pygame here:

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

Upvotes: 1

mnistic
mnistic

Reputation: 11020

Bresenham's line algorithm yields the coordinates of all the points in a straight line, which seems to be what you're looking for. Here is an implementation of it in Python:

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

Upvotes: 1

Related Questions