I have a method, that checks win conditions on a "Torus" board, which is a board without any borders. This means that if you place 4 diagonal stones on the top left, and 2 diagonal stones in the bottom right, if they are in the same diagonal and would connect if you ignored the border, which then would lead to a win. Basically it's a Connect 6 Game.
size()
returns the size of the board which either is 18 or 20.
currentPlayer
is a String like : "P1" or "P2".
r
and c
are the row and column where a move has just been made.
public boolean checkTorusWinner(int r, int c){
int count = 0;
boolean hasWinner = false;
String currentPlayer = board[r][c];
int hSize = size();
int vSize = size();
/*
Checks Horizontally for a Win.
*/
for (int i = c; i < hSize; i++) {
if (board[r][i] == currentPlayer) {
count++;
} else {
count = 0;
}
if (i == size() - 1) {
hSize = size() - 2;
for (int j = 0; j < hSize; j++) {
if (board[r][j] == currentPlayer) {
count++;
} else {
count = 0;
}
if (count == 6) {
boardType = "none";
hasWinner = true;
break;
}
}
}
if (count == 6) {
boardType = "none";
hasWinner = true;
break;
}
}
/*
Checks Vertically for a Win
*/
for (int i = r; i < vSize; i++) {
if (board[i][c] == currentPlayer) {
count++;
} else {
count = 0;
}
if (i == size() - 1) {
i = -1;
vSize = size() - 2;
}
if (count == 6) {
boardType = "none";
hasWinner = true;
break;
}
}
/*
Checks Diagonally from Top left to Bottom right
*/
if (c - r >= 0) {
int startingC;
startingC = c - r;
int size = size();
for (int i = r, j = c; j < size; i++, j++) {
if (board[i][j] == currentPlayer) {
count++;
} else {
count = 0;
}
if (j == size() - 1) {
j = startingC - 1;
i = -1;
size = size() - 2;
}
if (count == 6) {
boardType = "none";
hasWinner = true;
break;
}
}
} else {
int size = size();
int startingR;
startingR = r - c;
for (int i = r, j = c; i < size; i++, j++) {
if (board[i][j] == currentPlayer) {
count++;
} else {
count = 0;
}
if (i == size() - 1) {
j = -1;
i = startingR - 1;
size = size() - 2;
}
if (count == 6) {
boardType = "none";
hasWinner = true;
break;
}
}
}
/*
Checks Diagonally from bottom left to top right;
*/
if (r + c <= 17) {
int loop = 0;
int startingR;
startingR = r + c;
for (int i = r, j = c; i >= 0; i--, j++) {
if (board[i][j] == currentPlayer) {
count++;
} else {
count = 0;
}
if (i == 0 && loop == 0) {
i = startingR + 1;
j = -1;
loop++;
}
if (count == 6) {
boardType = "none";
hasWinner = true;
break;
}
}
} else if (r + c > 17) {
int loop = 0;
int startingC;
startingC = (r + c) - (size() - 1);
for (int i = r, j = c; i >= startingC; i--, j++) {
if (board[i][j] == currentPlayer) {
count++;
} else {
count = 0;
}
if (i == startingC && loop == 0) {
i = size();
j = startingC - 1;
loop++;
}
if (count == 6) {
boardType = "none";
hasWinner = true;
break;
}
}
}
return hasWinner;
}
Unfortunately this method's length doesn't meet the requirement for my university: it has to be a maximum of 80 lines. I don't know how I'm supposed to shorten this code so that it still works.