Simple tic-tac-toe AI

user1136342 picture user1136342 · Apr 2, 2013 · Viewed 19.1k times · Source

I know this has been asked a lot and I've searched other code but most of what I've seen doesn't seem flawless (never loses) and simple, elegant and efficient. And I'm unable to decide which type of solution would fit that description.

The solutions I've seen are:

(1) Using minimax with alpha-beta pruning. This seems complicated to me and possibly unnecessary for such a simple game? Is it probably too complicated? If not, would I need to do a lot of hard coding or am I misunderstanding the algorithm?

(2) Write your code using the pseudocode strategy from Wikipedia... I'm not exactly sure how to implement this. For example, it just says "check for forks". Would most of these checks be done by having an array of winningLines and checking if they'd be filled in or something like that? If not, can someone give me hints on what data structures or any basic tips on how to implement the checks posed in the pseudocode here: http://en.wikipedia.org/wiki/Tic-tac-toe#Strategy . I've also seen algorithms that give a numerical value to an 'X' square and an 'O' square and then use the sum to decide the winner but I don't see why this is particularly useful.

Any other reasonable solutions?

Answer

AnxGotta picture AnxGotta · Apr 2, 2013

To be honest, when dealing with AI and heuristics, the most simple tasks can become complicated very quickly. The minimax approach is going to give you the best results and it shouldn't be too difficult considering the fact that you are implementing AI. It is an established standard with 2 player turn based gaming logic.

Check out this website... it gives some good insight into tic-tac-toe AI and the minimax implementation.

http://www.ntu.edu.sg/home/ehchua/programming/java/JavaGame_TicTacToe_AI.html

Edit:

Noticing that someone wrote "Brute Force"... this is going to end up being an inefficient way of the implementation of the heuristics involved in minimax. Iteration through every possible move based on the other players last move is just another way to implement a heuristic.. except it seems to be, in my opinion, more work. Minimax implementation will be simple and effective.

Edit2:

"Simpler implementation" is somewhat relative. Minimax is the standard and as I said in the comment you can manipulate the heuristic to suit the cases you are looking for...

I wish I could tell you the simplest way but there are so many variables dependent on the implantation of your game in code.

Take the suggestions, look at you game implementation, and then see what suits you best!

What is simple to one person might be complicated to another. I'm just trying to give you options and minimax is pretty solid. Maybe try adjusting it to fit your needs.

Edit3:

Let me know if you need more direction. I'm happy to help.