Math help

BlitzMax Forums/BlitzMax Programming/Math help

Eikon(Posted 2006) [#1]
I need some help shrinking a function that contains a lot of if/endif statements. I have a 12x12 grid containing colored pieces, when the user clicks on a piece, I want the function to search all surrounding pieces and remove ones which are the same color as the clicked piece. Example:
[ ][ ][ ][ ][ ][ ][ ][ ][ ][ ][ ][ ]
[ ][ ][ ][ ][ ][ ][ ][ ][ ][ ][ ][ ]
[ ][ ][ ][ ][ ][ ][ ][ ][ ][2][ ][ ]
[ ][ ][ ][ ][ ][ ][ ][ ][2][2][ ][ ]
[ ][2][2][ ][ ][2][ ][ ][2][ ][ ][ ]
[ ][ ][2][ ][ ][2][ ][ ][2][ ][ ][ ]
[ ][ ][2][2][2][X][2][2][2][2][ ][ ]
[ ][ ][2][ ][ ][ ][ ][ ][ ][2][ ][ ]
[ ][ ][2][ ][ ][ ][ ][ ][ ][2][ ][ ]
[ ][ ][2][2][2][ ][ ][ ][ ][2][ ][ ]
[ ][ ][ ][ ][2][ ][ ][ ][ ][2][ ][ ]
[ ][ ][ ][ ][ ][ ][ ][ ][ ][ ][ ][2]
If the user were to click the X (which is a 2), all connected two pieces would be removed, but the 2 in the bottom right corner would remain since it isn't connected. Anyone got an algorithm that can handle this kind of thing? The values are kept in an array, gridArr[12, 12]. It would also be helpful if the function could return how many pieces were removed.


Yan(Posted 2006) [#2]
Here's a recursive routine taken from a colour match game I did ages ago in B3D, if it helps any...
Global g_balls_selected
Dim board.orb(13, 11)

; x and y = array position
; id = balls id
Function pick_all(x, y, id, root=True)
	
	If root = True
		g_balls_selected = 0
		root = False
	EndIf
	
	If x > 0	
		If board(x - 1, y)\id = id
			If board(x, y)\selected = False
				board(x, y)\selected = True
				g_balls_selected = g_balls_selected + 1
			EndIf
			
			If board(x - 1, y)\selected = False Then pick_all(x - 1, y, id, root)
		EndIf
	EndIf
	
	If x < (C_BOARD_MAX_X - 1)
		If board(x + 1, y)\id = id
			If board(x, y)\selected = False
				board(x, y)\selected = True
				g_balls_selected = g_balls_selected + 1
			EndIf
			
			If board(x + 1, y)\selected = False Then pick_all(x + 1, y, id, root)
		EndIf
	EndIf
	
	If y > 0
		If board(x, y - 1)\id = id
			If board(x, y)\selected = False
				board(x, y)\selected = True
				g_balls_selected = g_balls_selected + 1
			EndIf
			
			If board(x, y - 1)\selected = False Then pick_all(x, y - 1, id, root)
		EndIf
	EndIf
	
	If y < (C_BOARD_MAX_Y - 1)
		If board(x, y + 1)\id = id
			If board(x, y)\selected = False
				board(x, y)\selected = True
				g_balls_selected = g_balls_selected + 1
			EndIf
			
			If board(x, y + 1)\selected = False Then pick_all(x, y + 1, id, root)
		EndIf
	EndIf
	
	Return board(x, y)\selected
End Function



Eikon(Posted 2006) [#3]
Thank you Melvin, it's working great now. I had the basics in place, I just didn't think about recalling the function for each piece successively.