diff --git a/Week 11 - TTTLib/GameWinnerService.cs b/Week 11 - TTTLib/GameWinnerService.cs index 9152003..1ffd197 100644 --- a/Week 11 - TTTLib/GameWinnerService.cs +++ b/Week 11 - TTTLib/GameWinnerService.cs @@ -8,15 +8,69 @@ namespace Week_11___TTTLib { public class GameWinnerService : IGameWinnerService { + private const char NO_WINNER = ' '; + public char Validate(char[,] board) { - var rowOne = board[0,0]; - var rowTwo = board[0,1]; - var rowThree = board[0,2]; - if (rowOne == rowTwo && rowTwo == rowThree) - return rowOne; + return CheckRow(board,2); + } - return ' '; + private static char CheckRow(char[,] board, int rowLimit=2) + { + char leftDiag = board[0, 0]; + char rightDiag = board[rowLimit, 0]; + + for (int row = 0; row < rowLimit; row++) + { + char rowResult = board[0,row]; + char colResult = board[row, 0]; + + + // loop through the row and check it; reset the value if not correct + for (int col = 1; col < rowLimit; col++) + { + if (board[col, row] != rowResult) + { + rowResult = NO_WINNER; + break; + } + } + + // loop through the col and check it; reset the value if not correct (transposed) + for (int col = 1; col < rowLimit; col++) + { + if (board[row, col] != colResult) + { + colResult = NO_WINNER; + break; + } + } + + // Verify the the results were won + if (rowResult != NO_WINNER) + return rowResult; + else if (colResult != NO_WINNER) + return colResult; + + + // Verify diagonals + if (board[row, row] != leftDiag) + { + leftDiag = NO_WINNER; + } + if (board[rowLimit - row, row] != rightDiag) + { + rightDiag = NO_WINNER; + } + } + + if (leftDiag != NO_WINNER) + return leftDiag; + if (rightDiag != NO_WINNER) + return rightDiag; + + // return no result otherwise + return NO_WINNER; } }