Minimax algorithm: tic tac toe

closed account (1vf9z8AR)
I am trying to write an unbeatable ai for tic tac toe game. Everything else is fine but the ai is not playing perfectly.

Here is my implementation of minimax
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
  int aivsai(char temp[1000][1000],int n,char curai,pair<int,int>&bestmove,int deep)
{
    vector<pair<int,int>>emptypos;
    findempty(temp,n,emptypos);
    int bestscore,score;
    if(curai==human)
    {
        bestscore=1000000000;
        score=0;
    }
    else
    {
        bestscore=-1000000000;
        score=0;
    }
    if(emptypos.size()==0)
        return 0;
    for(auto x:emptypos)
    {
        temp[x.first][x.second]=curai;
        if(checkvictory(temp,n,x)==true)
        {
            if(curai==human)
                return -1;
            else
                return 1;
        }
        if(curai==human)
        {
            score+=aivsai(temp,n,ai,bestmove,deep+1);
            if(score<bestscore)
                bestscore=score;
        }
        else
        {
            score+=aivsai(temp,n,human,bestmove,deep+1);
            if(score>bestscore)
            {
                bestscore=score;
                if(deep==0)
                    bestmove=x;
            }
        }
        temp[x.first][x.second]='-';
    }
    return bestscore;
}

temp->copy of actual board
n size of board
curai minplayer(human) or maxplayer(ai)
bestmove to get the best coord
deep to calculate if we are in original game or not
emptypos stores all empty coord
You are not calculating the score correctly. You are finding the sum of the scores of each move when you want to find the score of the best move (and at the root you need the actual move itself)

I’m distracted and haven’t analyzed the whole code so there may be more issues.
Last edited on
closed account (1vf9z8AR)
Ya i got the issues. the whole code was wrong.
converting single player tic tac toe to ai version messed up everything.
Topic archived. No new replies allowed.