I've written a game of tic-tac-toe in Java, and my current method of determining the end of the game accounts for the following possible scenarios for the game being over:
- The board is full, and no winner has yet been declared: Game is a draw.
- Cross has won.
- Circle has won.
Unfortunately, to do so, it reads through a predefined set of these scenarios from a table. This isn't necessarily bad considering that there are only 9 spaces on a board, and thus the table is somewhat small, but is there a better algorithmic way of determining if the game is over? The determination of whether someone has won or not is the meat of the problem, since checking if 9 spaces are full is trivial.
The table method might be the solution, but if not, what is? Also, what if the board were not size n=9
? What if it were a much larger board, say n=16
, n=25
, and so on, causing the number of consecutively placed items to win to be x=4
, x=5
, etc? A general algorithm to use for all n = { 9, 16, 25, 36 ... }
?
This is a really simple way to check.
}
you can use a magic square http://mathworld.wolfram.com/MagicSquare.html if any row, column, or diag adds up to 15 then a player has won.
Constant time O(8), on average 4 short AND's. Player = short number. Needs additional checks for making sure move is valid.