private unsafe int ScoreForGrid(GridStack stack, int depth) { int permutations = GridFunctions.CountEmptySquares(stack.current); if (permutations == 0) { return(0); } int startIndex = 0; int score = int.MaxValue; for (int i = 0; i < permutations; i++) { stack.pushCurrent(); GridFunctions.TryAddPermutation(stack.current, ref startIndex); //if(!success) //{ // //GridFunctions.printGrid(grid); // //GridFunctions.printGrid((grids + i * 16)); // //GridFunctions.TryAddPermutation((grids + i * 16), startIndex, out startIndex); // throw new Exception(); //} startIndex++; int subScore = -1; foreach (Direction subDirection in Enum.GetValues(typeof(Direction))) { stack.pushCurrent(); GridFunctions.CollapseGridInPlace(stack.current, subDirection); if (depth == 1) { subScore = Math.Max(subScore, FinalScoreForGrid(stack.current)); } else { subScore = Math.Max(subScore, ScoreForGrid(stack, depth - 1)); } stack.pop(); } stack.pop(); score = Math.Min(score, subScore); } return(score); }