DEV Community

Discussion on: I wrote an unbeatable Tic-Tac-Toe AI in Java

Collapse
nestedsoftware profile image
Nested Software • Edited on

The basic idea seems to be correct (though I have not run the code).

I'm not very fond of initializing the values to +100/-100. Instead, I'd recommend extracting the logic to a function that returns the correct value.

I'd also suggest removing the boolean parameter that determines whether you are doing min or max: You can derive this from whose turn it is, which is known from the board position alone.

The logic that computes the value of a move depending on whether we are doing min or max can be combined together (note how it's almost the same in each case): You can extract this logic into a min or max strategy that will return either the minimum or the maximum, and that way you can combine all the rest of the code together.

Beyond that, for testing, I think it would be good to run this code both as X and as O against itself and against an opponent that plays random legal moves. Then you can calculate the statistics of the results for each of the cases.

Also, I think it would be interesting to time this code to see how long it takes it to play a game. It looks as though it is currently doing a recursive computation for each move, so there will be a lot of the same positions being re-evaluated over and over again. I'm not sure how slow that would make this code in Java, but it would be interesting to find out.

Note: Make sure to be aware of the code of conduct. You can post a full article here about your project, and also provide a link to the same article on your personal blog. However, you shouldn't post an article that's basically just a straight up link without meaningful content of its own.