A Nice Little Recursive Algorithm for Go
As you may have noticed, I recently built my first multiplayer game, go. If you'd like to play, feel free to shoot me an email.
The game is still in an early alpha stage but I had a lot of fun writing the little recursive algorithm at its heart, which I'm going to share today.
I'm using the Django framework, so this is Python, which made writing the algorithm about as simple as could be. It also makes reading the code fairly straightforward. That's a plus, because of course I didn't comment it at all.
And here it is:
def check_for_life(board,list):
remove_list = list
new_removes = []
for pair in remove_list:
x = pair[0]
y = pair[1]
player = board[x][y]
size = len(board)
if x >0:
if not [x-1,y] in remove_list:
piece = board[x-1][y]
if piece == player:
new_removes.append([x-1,y])
elif piece == 0 or piece == "k":
return []
if x < size - 1:
if not [x+1,y] in remove_list:
piece = board[x+1][y]
if piece == player:
new_removes.append([x+1,y])
elif piece == 0 or piece == "k":
return []
if y >0:
if not [x,y-1] in remove_list:
piece = board[x][y-1]
if piece == player:
new_removes.append([x,y-1])
elif piece == 0 or piece == "k":
return []
if y < size - 1:
if not [x,y+1] in remove_list:
piece = board[x][y+1]
if piece == player:
new_removes.append([x,y+1])
elif piece == 0 or piece == "k":
return []
if len(new_removes) == 0:
return remove_list
else:
remove_list += new_removes
remove_list = check_for_life(board,remove_list)
return remove_list
The code looks at all of the stones around the one that was just played, checking to see if they are part of a larger group and then checking if that group is surrounded and should thus be removed. It returns the full list of stones to be removed.
I should probably be doing some things a little better, following the DRY principle and all that. I'm sure I could cut out a few lines. But it works and at this point, that's pretty exciting stuff.