So I'm making a boardgame that's 19 by 19. It is basically connect 5, called Gomoku.
I want to make an efficient algorithm to find if there are 'n' pieces in a row. The data is stored as a 2D array of 19x19. But for question's sake, let's say it's 6x6.
0 0 0 1 0 0 0 0 0 0 0 0
0 0 0 1 0 0 0 1 0 0 0 0
0 0 0 1 0 0 0 0 1 0 0 0
0 0 0 1 0 0 0 0 0 1 0 0
0 0 0 1 0 0 0 0 0 0 1 0
0 0 0 0 0 0 0 0 0 0 0 1
These are two examples of '5' of 1's in a row. How can i test for HORIZONTAL, VERTICAL, and both DIAGONALS?
Here's my inefficient code:
private boolean firstDiagonalCheck(int x, int y, int num) {
int count = 1;
int check = 0;
boolean rflag = true;
boolean lflag = true;
int pos = 1;
check = turnHuman + 1;
while (rflag) {
if (x + pos >= 19 || y + pos >= 19) {
rflag = false;
break;
}
if (gb.getBoard()[x + pos][y + pos] == check) {
count++;
pos++;
} else {
rflag = false;
}
}
pos = 1;
while (lflag) {
if (x - pos < 0 || y - pos < 0) {
lflag = false;
break;
}
if (gb.getBoard()[x - pos][y - pos] == check) {
count++;
pos++;
} else {
lflag = false;
}
}
if (count == num) {
return true;
}
return false;
}
This is only one method for the first Diagonal. There are 3 more.
How can I make it more efficient and check all 4 directions?
EDIT ##################
What my code does is: - Get's the position of the piece (x,y) - Check both sides (up and down if vertical) and count how many in a row there are - If the number of count matches desired, ("num"), then return true, otherwise return false.
WOULD it be more efficient if I checked the WHOLE board every time to see if there are pieces in a row?