I am making a tic tac toe game for n number of players on a nxn board, but the winning condition is aways 3 on a row. My so far solution to the problem is: when a move is made the program will check the following square for 3 on a row.
(x-1,y+1) (x,y+1) (x+1,y+1)
(x-1,y) (x,y) (x+1,y)
(x-1,y-1) (x,y-1) (x+1,y-1)
where (x,y) is the move that has being made. We have 4 cases here which is check: a row win, a column win, a diagonal win and a anti diagonal win. Then the program will check will check this next square for 3 on a row.
(x-2,y+2) 0 (x,y+1) 0 (x+2,y+2)
0 (x-1,y+1) (x,y+1) (x+1,y+1) 0
(x-2,y) (x-1,y) (x,y) (x+1,y) (x+2,y)
0 (x-1,y-1) (x,y-1) (x+1,y-1) 0
(x-2,y-2) 0 (x,y-2) 0 (x+2,y-2)
Again (x,y) is the move that has being made. We have here 8 cases because WE CHECK! the move coordinate as an end point of the 3 in a row. The 0 above represents just the ones that are not checked.
The piece of code to check this would be long and a lot of text. An example of the code:
public int checkWinning(Coordinate c) {
if (board[c.getX()][c.getY()] == board[c.getX()+1][c.getY()] && board[c.getX()][c.getY()] == board[c.getX()-1][c.getY()]){
return board[c.getX()][c.getY()];
}else if(board[c.getX()][c.getY()] == board[c.getX()][c.getY()+1] && board[c.getX()][c.getY()] == board[c.getX()][c.getY()-1]){
return board[c.getX()][c.getY()];
}else if(board[c.getX()][c.getY()] == board[c.getX()-1][c.getY()+1] && board[c.getX()][c.getY()] == board[c.getX()+1][c.getY()-1]){
return board[c.getX()][c.getY()];
}
}
Here are Coordinate c the "move" that has being made(X and Y comes from another class thats why I use getters) and note also :
Board[x][y] -> 2-dimensional array representing the board, The coordinates are counted from top-left (0,0) to bottom-right (size-1, size-1), board[x][y] == 0 signifies free at position (x,y), board[x][y] == i for i > 0 signifies that Player i made a move on (x,y)
Is there a smarter way to do this?
I saw a major flaw in this:
1. The first problem here is that these arrays will be out of bounds, so by using the "first method" looking at a 3x3 array and then loop for all the element that are inside size+1 and size-1 that will eliminate the out of bounds but:
I am missing the most top, most bottom most left and right sides to check. i.e. i need to check
(x-1,y+1),(x,y+1),(x+1,y+1) , (x-1,y-1) (x,y-1) (x+1,y-1) , (x-1,y+1) (x-1,y) (x-1,y-1) , (x+1,y+1) (x+1,y) (x+1,y-1) for winners...