/* Build a list of pieces to process, either all white pieces or all black pieces. Start with the top one on the list. Add it to the 'chain', remove it from unprocessed. The build chain algorithm is recursive, it looks at the four adjacent squares; if the square is an enemy piece, it does nothing. if the square is empty, the chain is marked as alive (it is initially assumed dead). if the square is a friendly piece, then that square is added to the chain and the build chain algorithm is called on that piece. When the algorithm is finished recursing, the pieces are removed only if they are still marked as dead. */ $piecesRemoved = true; $player = "white"; for($i=0; $i<2; $i++) { // do this twice, once for player about to take turn, and then for player who just took turn $unproc = array_keys(array($player), $pieces) // get all the keys for players pieces foreach($unproc as $square){ chain = array(); chain[] = square; $unproc = $array_diff($unproc, array($square)); $chain_alive = false; checkIfAlive($square); if ($chain_alive == false) $pieces = array_diff_key($pieces, array_fill_keys($chain,$player)); } if (player=="black) player = "white"; else player="black"; } function checkIfAlive($square){ $dirs = array( array(0,1), array(0,-1), array(1,0), array(-1, 0)); foreach($dirs as $dir){ $checkSquare = addSquare($square, $dir); if (isEmpty($checkSquare) == true){ $chain_alive = true; } else if ($pieces[$checkSquare] == "white"){ if (in_array($checkSquare, $unproc)){ $chain[] = $checkSquare; $unproc = $array_diff($unproc, array(checkSquare)); checkIfAlive($checkSquare); } } } } function addSquare(square,dir){ pos=explode("_", square); pos[0]=dir[0] + int(pos[0]); pos[1]=dir[1] + int(pos[1]); return pos[0] + "_"+pos[1] } function isEmpty(checkSquare){ pos=explode("_", square); pos[0]=int(pos[0]); pos[1]=int(pos[1]); if (pos[0] < 0 || pos[1] < 0 || pos[0] >= size || pos[1] >= size) return false; if (pieces[checkSquare] == null) return true; return false; }