Fernaldy Aristo
Fernaldy Aristo

Reputation: 51

How can I make my "AI" do an action until certain criteria are met?

This is a player vs AI tic-tac-toe game in C. If the AI rolls into an occupied spot, how do I make it so that it rolls again until it reaches an unoccupied spot?

char boardchar[3][3] = { {'1', '2', '3'}, {'4', '5', '6'}, {'7', '8', '9'} }; 


void Turn()
{
    /*Player's Turn*/

    AIrandomizer();
    AI = AI_roll();


        if (AI == 1 && boardchar[0][0] == '1')
        {
            boardchar[0][0] = symbAI;
        }

        else if (AI == 2 && boardchar[0][1] == '2')
        {
            boardchar[0][1] = symbAI;                   
        }


        else if (AI == 3 && boardchar[0][2] == '3')
        {
            boardchar[0][2] = symbAI;               
        }


        else if (AI == 4 && boardchar[1][0] == '4')
        {
            boardchar[1][0] = symbAI;       
        }

        else if (AI == 5 && boardchar[1][1] == '5')
        {
            boardchar[1][1] = symbAI;               
        }


        else if (AI == 6 && boardchar[1][2] == '6')
        {
            boardchar[1][2] = symbAI;               
        }

        else if (AI == 7 && boardchar[2][0] == '7')
        {
            boardchar[2][0] = symbAI;               
        }

        else if (AI == 8 && boardchar[2][1] == '8')
        {
            boardchar[2][1] = symbAI;               
        }

        else if (AI == 9 && boardchar[2][2] == '9')
        {
            boardchar[2][2] = symbAI;           
        }

}

I've tried switch(case) and multiple ifs and else ifs but I still can't manage to figure out a way to fix this issue.

Upvotes: 5

Views: 288

Answers (1)

Michel Keijzers
Michel Keijzers

Reputation: 15357

You can use a while or do-while statement.

Also make a 3x3 twodimensional array that keeps track of the spots: 0 = unfilled, 1 = Human, 2 = AI (better is to use an enum).

In pseudo code:

Global variable:

int spots[3][3]; // 3x3 array

Code:

Setup(); // Setup of board, sets 0's to spots.

while (!endOfGame())
{
    Player(); // Handle player, assuming it plays first, sets a 1 in one spot

    if (!endOfGame())
    {
         AI();
    }
}


void AI() 
{
    do
    {
       square = AIChoice();
    } while (spots[square] == 0);

    // Now we know spots[square] == 0, thus unfilled
    spots[square] = 2; // AI
}

Upvotes: 2

Related Questions