Basically this is a more efficient method of getting the grid coordinates from the mouse coordinates. For example, this could be used in a RPG or RTS type game. The code is probably general enough to be used for pygame and others as well.
The first function, rfind, takes any empty list, the size of the playing field (probably in pixels, i mean, thats the point of it), the location of the mouse cursor (if you’re not looking straight down you’re probably going to have to do some adjustments) and then a 0.
The map size for this should always be a power of 2. eg 2^x. This isn’t really a problem though, as you can simply block the player from moving into the ones you don’t want, so you’ll still be able to have fancy shaped maps.
There is a problem at the moment however. For some reason, it’s not returning properly. I can print the value correctly 1 instruction before returning it, but returning it screws up.
Anyway, here’s the file.
#recursive find.py import sys width = 1000 height = 1000 x = 48 y = 48 def rFind(l, width, height, posx, posy, count): halfx = width/2.0 halfy = height/2.0 if posx >= halfx: posx -= halfx if posy >= halfy: quadrant = 4 posy -= halfy else: quadrant = 1 else: if posy >= halfy: posy -= halfy quadrant = 3 else: quadrant = 2 l.append(quadrant) if count < 10: rFind(l, halfx, halfy, posx, posy, count + 1) else: print l return l def processData(l, width, height, x, y, i, locx, locy): """Takes the stuff from rFind and gives you the actual grid location """ #not sure if i need width and height if i + 1 < len(l): print "finding grid square" number = l[i] #weird part starts here if number == 1: locx += x/2 if number == 2: pass if number == 3: locy += y/2 if number == 4: locx += x/2 locy += y/2 processData(l, width, height, x/2, y/2, i+1, locx, locy) else: return (locx, locy) if __name__ == "__main__": width = 1000 height = 1000 ls = rFind(, width, height, 0, 300, 0) endPos = processData(ls, width, height, 48, 48, 0, 0, 0) print endPos