K
One line verification cycle (in method) checkand line group verification cycles (in the method checkAllprivate static class GotWinnerException extends Exception
{
private final char winnerType;
public GotWinnerException(char winnerType)
{
this.winnerType = winnerType;
}
}
private static final int
FIELD_SIZE = 4,
WIN_COUNT = 3;
private static final char EMPTY_CELL = ' ';
public static void main(String[] args)
{
char[][] desc = new char[FIELD_SIZE][FIELD_SIZE];
desc[0] = new char[] { '0', 'x', '0', EMPTY_CELL };
desc[1] = new char[] { EMPTY_CELL, 'x', '0', EMPTY_CELL };
desc[2] = new char[] { EMPTY_CELL, '0', 'x', EMPTY_CELL };
desc[3] = new char[] { EMPTY_CELL, '0', EMPTY_CELL, 'x' };
char result = checkAll(desc);
if (result != EMPTY_CELL)
{
System.out.println("Winner: " + checkAll(desc));
}
}
public static char checkAll(char[][] desc)
{
char winner = EMPTY_CELL;
try
{
for (int i = 0; i < FIELD_SIZE; i++)
{
check(desc, 1, 0, 0, i); //columns
}
for (int i = 0; i < FIELD_SIZE; i++)
{
check(desc, 0, i, 1, 0); //rows
}
check(desc, 1, 0, 1, 0); //first diagonal
check(desc, -1, FIELD_SIZE - 1, 1, 0); //second diagonal
}
catch (GotWinnerException e)
{
winner = e.winnerType;
}
return winner;
}
public static void check(char[][] desc, int xCoef, int xShift, int yCoef, int yShift)
throws GotWinnerException
{
char savedSymbol = EMPTY_CELL;
int savedSymbolCount = 0;
for (int i = 0; i < FIELD_SIZE; i++)
{
int x = i * xCoef + xShift;
int y = i * yCoef + yShift;
char symbol = desc[x][y];
if (symbol == savedSymbol)
{
savedSymbolCount++;
}
else
{
savedSymbol = symbol;
savedSymbolCount = 1;
}
if (symbol != EMPTY_CELL && savedSymbolCount == WIN_COUNT)
{
throw new GotWinnerException(symbol);
}
}
}
FIELD_SIZE Makes the size of the field, WIN_COUNT - the number of consecutive cells on one line to win.The field 4x4 and 3 winning symbols shall be used for the test. In this case x wins diagons.