Created
August 19, 2015 09:08
-
-
Save jrialland/3af403a4424dd299bf8e to your computer and use it in GitHub Desktop.
algorithm for scanning cells in an array in diagonal, may be used for ordering drawing of sprites in an isometric 3d game.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def dscan(w, h): | |
""" scans a 2-dimensions array of width 'w', height 'h', in diagonal, starting at the upper-left corner. | |
example for w=3,h=3 : | |
+---+---+---+ | |
|000|002|003| | |
|001|004|007| | |
|005|006|008| | |
+---+---+---+ | |
>>> list(dscan(3,3)) | |
[(0, 2), (0, 1), (1, 2), (2, 2), (1, 1), (0, 0), (1, 0), (2, 1), (2, 0)] | |
>>> list(dscan(2,5)) | |
[(0, 4), (0, 3), (1, 4), (1, 3), (0, 2), (0, 1), (1, 2), (1, 1), (0, 0), (1, 0)] | |
>>> list(dscan(5,2)) | |
[(0, 1), (0, 0), (1, 1), (2, 1), (1, 0), (2, 0), (3, 1), (4, 1), (3, 0), (4, 0)] | |
""" | |
i, j = 0, h - 1 | |
di, dj = -1, -1 | |
for _ in xrange(w * h): | |
yield i, j | |
i += di | |
j += dj | |
if i == -1: | |
di, dj = 1, 1 | |
i = 0 | |
if j == -1: | |
j = 0 | |
i = 1 | |
continue | |
if j == h: | |
di, dj = -1, -1 | |
j = h - 1 | |
if i == w: | |
j = h - 2 | |
i = w - 1 | |
continue | |
if j == -1: | |
di, dj = 1, 1 | |
j = 0 | |
i += 2 | |
continue | |
if i == w: | |
di, dj = -1, -1 | |
i = w - 1 | |
j -= 2 | |
continue | |
if __name__ == '__main__': | |
import doctest | |
doctest.testmod() |
Author
jrialland
commented
Aug 19, 2015
r=''
mx = 1+max([x for (x,y) in g])
my = 1+max([y for (x,y) in g])
size = max([len(str(v)) for k,v in g.iteritems()])
head = '┌'+('┬'.join(['─'*size for _ in range(mx)]))+'┐\n'
sep = '├'+('┼'.join(['─'*size for _ in range(mx)]))+'┤\n'
foot = '└'+('┴'.join(['─'*size for _ in range(mx)]))+'┘\n'
r = head
for y in range(my):
l=[]
for x in range(mx):
if (x,y) in g:
l.append(str(g[x,y]).center(size))
else:
l.append(' '*size)
r += '│'+('│'.join(l))+'│\n'
if y <> my-1: r+=sep
return r+foot
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment