2 views

First off, I am a noob. I am also a Janitor that has never made a dime writing code. This is just something that I love doing. It is for fun:) That being said, I wrote this console based tic-tak-toe game that has enough ai to not lose every game. (I guess ai is what it should be called.) It has something like 70 if/else if statements for the computers turn. I used 3 int arrays like so:

int L, M, R;

0 = blank; 1 = X; 2 = O;

The board then 'Looks' like

L | M | R

L | M | R

L | M | R

So I basically wrote out every possible scenario I could think something like:

if(M==1 & M==1 & M==0){M = 2;}//here the computer prevents a win else if(L ==2&M==2&R==0){R=2;}//here the computer wins //and so on....68 more times!

I guess my question(s) is(are):

Is there a better way?

Is there a way to achieve the same result with fewer lines of code?

Is this considered Artificial Intelligence?

by (108k points)

It is the standard algorithm for this is called Minimax. It basically builds a tree, where the beginning of the game is the root, and then the children represent every possible move X can make on the first turn, then the children of each of those nodes are all the moves O can make in response, etc. Once the entire tree is filled (which is possible for Tic-Tac-Toe, but for games like Chess computers still don't have enough memory), you work your way back up, assuming both players are smart enough to make the best move and arrive at the optimal move. Here is an explanation of Minimax specifically using Tic Tac Toe as an example.

Yes, there are better ways.

It can be considered that how different mirror views of the board would simplify the number of cases. Also, consider pre-storing "interesting" patterns in arrays and then comparing the game state against the data. For example, one series of patterns would be all the ways a player can win in the next move. Note that with the declaration in L, there are only two entries in array L, namely L and  L. The references you have to L, M, etc. are errors that should have been caught by the compiler. Consider turning up the warning level. How this is done depends on the compiler. For gcc, it is -Wall.

This counts as a form of artificial intelligence.