Thursday, 15 May 2014

function - How to get valid neighbors from a board? -



function - How to get valid neighbors from a board? -

i started programming, , i'm trying create function called "verifyneighbor" uses list function called "getneighborlabels", returns list of neighbors around number "me" on board of boardwidth*boardheight (excluding negatives , duplicates). however, returns neighbour list may contain invalid neighbors (eg., on board of 5 5, me=0, neighbor=4 in list, not neighbor). that's "verifyneighbors" function comes in- homecoming either true or false each neighbour around "me". ideas on how logically approach/ start this?

well, code not formatted , can't create much sense of it. here's piece of code should want:

# gives x , y coordinates on board def coords(point, boardwidth): x = point % boardwidth; y = point // boardwidth homecoming (x,y) #inverse transform above def point(x, y, boardwidth): homecoming x + y * boardwidth def verifyneighbor(boardwidth, boardheight, neighbor, me): mx,my = coords(me, boardwidth) nx,ny = coords(neighbor, boardwidth) # if generated neightbor has coords # off grid, invalid # since x calculated modulo boardwidth never # less 0 or greater boardwidth # need check y if ny < 0 or ny >= boardheight: homecoming false dx = abs(mx-nx) dy = abs(my-ny) # neighbors points coordinates relative me are: # (-1,-1) top left # (-1, 0) left # (-1, 1) bottom left # (0, -1) top # (0, 1) bottom # (1, -1) top right # (1, 0) right # (1, 1) bottom right # hence absolute values 1 of 3 options # below otherwise it's not neighbour homecoming (dx,dy) in [(0,1),(1,0), (1,1)] def getneighborlabels(boardwidth, boardheight, me): mx,my = coords(me, boardwidth) result = [] in range(-1,2): j in range(-1,2): if == j == 0: go on p = point(mx+i, mx+j, boardwidth) if verifyneighbor(boardwidth, boardheight, p, me): result.append(point(mx+i,mx+j, boardwidth)) homecoming result

edit: been programming in c way much lately. used // comments >_<

edit2: added wgetneighborlabelsfunction passes things throughverifyneighborbefore adding list.getneighborlabels` should work now.

function

No comments:

Post a Comment