Skip to content Skip to sidebar Skip to footer

Simple Tic-tac-toe AI

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 de

Solution 1:

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.


Solution 2:

Use the format of your choice to "encode" this image into a set of moves. The AI will always win or tie.

For example, you could encode it as follows:

var turns = {
  "mefirst":{
    "move":0,
    "next":[
      null,
      {
        "move":4,
        "next":[
          null,
          null,
          {"move":8}, // win
          {"move":8}, // win
          null,
          {"move":8}, // win
          {"move":8}, // win
          {"move":8}, // win
          {
            "move":6,
            "next":[
              null,
              null,
       /* AND SO ON... */
    ]
  }
};

Then you can start with:

if( ai_goes_first) {
    game = turns.mefirst;
    makeMove(game.move);
}
else game = turns.themfirst;
playerTurn();

Where playerTurn is something like:

function playerTurn() {
    when player clicks a valid squeare {
        game = game.next[chosenSquare];
        makeMove(game.move);
        if( game.next) playerTurn();
    }
}

Post a Comment for "Simple Tic-tac-toe AI"