I'm trying to code a tic tac toe game in java and I need help figuring out how to efficiently and without freezing the program check if someone won the game.

I'm only in the design stages now, I haven't started programming anything but I'm wondering how would I know at all times the state of the game and exactly when someone wins?

Response to MarkR: (note: had to place comment here, it was too long for comment section)

It's not a homework problem, I'm trying to get more practice programming GUI's which I've only done once as a freshman in my second introductory programming course. I understand I'll have a 2D array. I plan to have a 2D integer array where x would equal 1 and o would equal 0. However, won't it take too much time if I check after every move if someone won the game? Is there a way or a data structure or algorithm I can use so that the program will know the state (when I say state I mean not just knowing every position on the board, the int array will take care of that, I mean knowing that user 1 will win if he places x on this block) of the game at all times and thus can know automatically when someone won?

4 Answers
4

The brute force approach as recommended by others is how you should proceed. Modern CPU's, even mobile ones, can check the whole board several thousand times per second, so you should not worry about game freezing.

However in your question you ask can this be speeded up, a question that will become very important if your game becomes more complex. And the answer is 'yes', it can and it should be speeded up, and indeed you should practice this on tic-tac-toe. The idea is not to brute force check the whole grid, but to check if the last move created a winning combinatin. So you start from the newly placed move, and then check in all directions if any makes a winning move.

For tic-tac-toe, this more complex algorithm will probabaly be slower then brute force one, because 3x3 grid is very small. But the algorithm scales very nicely, where brute force approach does not.

I don't think you really need to worry about "freezing the program". A function to check who has won in tic-tac-toe would be able to execute very quickly.

This sounds like a homework question - I don't want to write your answer for you. But I expect you would have some kind of two-dimensional array containing the state of each square on the board. This would have to be maintained throughout the program's running