python - How to draw a line of characters in a grid (nested lists) -
given w x h sized grid, produced in following way
self.grid = [ ['-'] * self.w ] * self.h
i wish "draw" "line" of characters between 2 points in said grid. following code i've come with
def line( self, char, (x1, y1), (x2, y2) ): self.point( char, (x1, y1) ) x = x1 + cmp( x2, x1 ) y = y1 + cmp( y2, y1 ) while x != x2 or y != y2: self.point( char, (x, y) ) x = x + cmp( x2, x ) y = y + cmp( y2, y ) self.point( char, (x2, y2) )
where point() function fills in single point in grid char.
this works charm straight lines , perfect diagonals. works "crooked" lines too, in sense doesn't throw errors, doesn't line between 2 points, more like... don't know, hockey stick.
for example, given 10x7 grid , call
line( 'x', (1,1), (5,9) )
i get
---------- -x-------- --x------- ---x------ ----x----- -----xxxxx ----------
what i'd more like
---------- -x-------- ---x------ -----x---- -------x-- ---------x ----------
how this, while not breaking straight lines , perfect diagonals in process? need 2 distinct pieces of code handle 2 cases, or can 1 algorithm both?
you should using bresenham's line algorithm, if insist on programming @ all. furthermore, careful initialising grid this:
grid = [ ['-'] * self.w ] * self.h
because of edning self.h
copies of same list:
grid = [ ['-'] * 3 ] * 3 grid[0][0] = 'x' print grid # [['x', '-', '-'], ['x', '-', '-'], ['x', '-', '-']]
use
grid = [['-'] * self.w ignored in xrange(self.h)]
or numpy arrays instead.
Comments
Post a Comment