This code checks winning conditions in Tic-Tac-Toe by checking if there is any row, column or diagonal with the same symbols.
The board is a 2-dimensional array of char
s. The character ' '
means that a field is empty.
How can I refactor/simplify this code?
public static bool SomeoneWins(char[][] board)
{
// Check columns
for (var x = 0; x < board.Length; x++)
{
var firstField = board[x][0];
if (firstField == ' ') continue;
bool allFieldsTheSame = true;
for (var y = 1; y < board[x].Length; y++)
{
if (board[x][y] != firstField)
{
allFieldsTheSame = false;
break;
}
}
if (allFieldsTheSame) return true;
}
// Check rows
for (var y = 0; y < board.Length; y++)
{
var firstField = board[0][y];
if (firstField == ' ') continue;
var allFieldsTheSame = true;
for (var x = 1; y < board.Length; x++)
{
if (board[x][y] != firstField)
{
allFieldsTheSame = false;
break;
}
}
if (allFieldsTheSame) return true;
}
// first diagonal
if (board[0][0] != ' ')
{
var allFieldsTheSame = true;
for (var d = 0; d < board.Length; d++)
{
if (board[d][d] != board[0][0])
{
allFieldsTheSame = false;
break;
}
}
if (allFieldsTheSame) return true;
}
// second diagonal
if ( board[board.Length - 1][0] != ' ')
{
var allFieldsTheSame = true;
for (var d = 0; d < board.Length; d++)
{
if (board[d][board.Length-d-1] != board[board.Length - 1][0])
{
allFieldsTheSame = false;
break;
}
}
if (allFieldsTheSame) return true;
}
return false;
}
for (var x = 1; y < board.Length; x++)
\$\endgroup\$x
while checkingy < length
. \$\endgroup\$