"Correct" Way to Wire a Tic-Tac-Toe AI

Posted by Sprawcketz@reddit | learnprogramming | View on Reddit | 18 comments

I'm working on a simple Tic-Tac-Toe game that includes a one-player mode against the computer.

I've got three levels of AI skill:

  1. Newbie - AI just selects a random available square
  2. Intermediate - Every time it moves, the AI will (in order):
  3. Try to play a winning move
  4. Or else, try to block an opponent's winning move
  5. Or else, play a move in any "open lane"
  6. Or else, play a random available move
  7. Masterful - ...and as you'd guess, this one is where I'm getting lost.

At first, my thought process what going something like:

"Phyiscally write out a bunch of potential move patterns and try to codify the optimal plays into the program using switching."

But that feels like the wrong way to do it. Also it could produce a BIG and UGLY set of nested switches. So then I thought:

"After each opponent move, give the AI player a "copy" of the board to play against itself and find the winning (or at least drawable) strategies and choose one (win > draw)."

But that feels like it'd wasting compute time (I know, probably trivial in human time), or like there should be a way that's more elegant than re-crunching everything after every move, every game. So then I thought:

"Ok, make the AI play itself a WHOLE LOT of times using some combination of random moves and mandatory opponent blocking and record the optimals / patterns that produce a forced-win."

But.... that sounds like programming a statistical neural network, which I'm not sure my limited and mathematically un-gifted experience is up to.

So my question is this: What is considered an "appropriate" strategy for building this kind of an AI player? Did I get it right with one of these thoughts, and I'm just to dumb to know it? Or is there a sweet-spot that I'm just missing?

(I've seen something about "Minimax" on Google, but.... I'm regrettably not trained professionally in any of this and don't have an algorithm education at all.)