Besides from Andrzej's suggestion of using vars to see whether a field is used.. you should add some checks..
- Checking if the user might have a potential win, then the comp should play that to prevent the win.... something like this...
//checking horizontal..
if A0==true && A1==true &A2==false -> play on A2
if B0==true && B1==true &B2==false -> play on B2
etc.
etc.
//checking vertical
if A0==true && B0==true &C0==false -> play on C0
if A0==true && B0==false&C0==true -> play on B0
if A0==false&& B0==true&C0==true-> play on A0
etc.etc.
//checking diagonal
if A0==true && B1==true &C2==false -> play on C2
if A2==true && B1==true&C0==false-> play on C0
etc.etc.
So if all these ( and there are quite some more ;-) conditions are false, the comp should check the empty spots and try and find a spot connected hor, vert or diagonal to his sets.
Lets say we have this:
0XY
Y00
000
0= empty spot
X=computer placed
Y= player placed
So now the comp has checked that the user cannot place a winning spot the next step..
so the AI is free to place it anywhere on a 0...
Offcourse a human immediately sees the best spot in this situation. Thats B1, the center spot.
The comp would calculate that A0 and B1 are possibilities... if it takes into account that choosing a spot next to one already set by him/her (X) are best.. Actually it might think that B2 is good too...
So first we need a condition check that gets the 'possible connected' spots...
we create a variable for each spot..called something like... A0_rank, A1_rank
Then we loop all spots to see whether they are connected to a spot of the comp and empty. If so we add +1 to the rank for that spot.. if occupied either by the player or the computer we put it at 0..
//getting all connected spots
if A0 == false -> A0_rank += 1
if B2 == false && ...
etc. etc.
So checking what positions are filled or not...
If empty the rank of that spot will be raised +1
So ranking would be like this then
1XY
Y11
111
Another check then is needed to see what spots are connected to X
if A0 == false && A0_rank > 0 && A1=X or B0 == X -> Ao_rank +=1
So when connected add +1 to the rank of that spot...
So ranking would be like this then
2XY
Y22
111
Then we need a final check to see whether there is a free spot next to one of the higher ranked spots...
if A0 == false && A0_rank > 1 && A2=0 or C0 == 0 -> Ao_rank +=1
if B1 == false && B1_rank > 1 && A1=0 or C1 == 0 -> B1_rank +=1
So ranking would be like this then
2XY
Y32
111
And then check all spots and put the comps step on the highest ranking.
Realising now that especially using rankings of spots there is a way easier method...