1

Something like this:

enter image description here

I am not sure how to code for this as I have only coded non-game apps. For instance how do you determine the best move after the player has made his move? I don't need the perfect moves, just challenging enough.

I don't know if I have to scan all the possible moves, etc. In a game like shown in the pic, the number of possible moves are very limited, right? So I could calculate them all. But I am not sure which one would be a better move, etc.

Joan Venge
  • 315,713
  • 212
  • 479
  • 689

1 Answers1

6

In a small, simple game like tic-tac-toe, you can build a tree, where:

  • each node is a board position
  • each leaf node is a finished game with a score of +1 is X wins, -1 if O wins, 0 for a draw
  • each child node is the result of a legal move from its parent

Then X is searching for a move which will maximize the minimum result, knowing that O will search (on his subsequent turn) for a move which will minimize the maximum result, knowing that X will search (on his subsequent turn to that) for a move which will...

This is the minimax algorithm.

In Tic-Tac-Toe, the tree can only get 9 layers deep, and if you want to be slick, you can take advantage of some board symmetries and keep the computations and data structures manageable.

Note that for more complex games this will fail for one reason or another (chess is deterministic, but too large to handle this way; backgammon needs probabilistic techniques, etc) but many approaches are variations on this theme.

Novak
  • 4,687
  • 2
  • 26
  • 64
  • 1
    +1. Check out http://en.wikipedia.org/wiki/Alpha-beta_search for more info. @Joan Venge, note that in simple games it is easy to make computer player to win, but much harder and more interesting to make it lose in spectacular ways so player does have a fighting chance. – Alexei Levenkov Feb 22 '12 at 03:18