python - Finding all legal moves in a simple board game -
i have 8x8 board represented numpy.ndarray:
array([[0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0]]) # 0 = free space # 1 = player1's figure
a figure can either move forward , left, forward , right or forward (forward means down board in case).
right using nested loops in order through board indexes. when find figure append board states can achieved making moves figure list , keep searching figures.
for example output of function looks this:
[array([[[0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0]], [[0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0]], [[0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 1, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0]]])]
is there faster way in can find possible moves given board state?
wouldn't easier memory performance sake, rather keeping complete board
in memory , keep player figure's position in memory. lets take example, player figure's location -
player1 = (1, 4)
let's assume , players position denoted (x,y)
. can compute moves player @ runtime (no need keep in memory) , possible moves -
- (x+1,y)
- (x+1,y+1)
- (x+1,y-1)
if player figure can circle in board, if @ bottom position in board, , next moves top row , if case, moves determined taking modulo
against number of rows , columns (assuming nr - number of rows
, nc - number of columns
) . example , (x,y)
next moves -
- ((x+1) % nr,y % nc)
- ((x+1) % nr,(y+1) % nc)
- ((x+1) % nr,(y-1) % nc)
Comments
Post a Comment