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?
The only thing I would do is to change the
ifs to loops. Consider that at some point you might want to change the winning condition from 3 to 5. In the case ofifs you will have to rewrite a lot of code, with loops it will remain the same.I would not recommend you to look for any solution "smarter" than this one, because your code should be easy to understand and support. Also I doubt that any smart solution will be faster than you current one.