samedi 15 juin 2019

Is there a way to imlement AI to the computer in TicTacToe?

I have this program that runs the game of Tictactoe, but i'd like to add AI to the computer function so it can be more difficult in order to play with

I tried by rand(); but it just make the computer put the decision in whatever slot is available.

void ia_turn(){
    while (true){
        int ia_tu = (rand() % 9) +1;
        int ia_op = ia_tu - 1;

        int row = ia_op / 3;
        int column = ia_op % 3;

    char matrix_pos = matrix[row][column];
            if (matrix_pos == 'X' || matrix_pos == 'O'){ 
                continue;
            }else{
                cout << "The AI selected the position: "<<ia_tu<<endl;
                matrix[row][column] = 'O';
                break;
            }
    }
}

I expect the movements of the ComputerAI to block my movements, but it can't be done with the rand() function.

This is the checking for wins function that i have

void checking_for_wins(){
    const char* wins_possibilities[8] = {"123","456","789","159","753","147","258","369"};

    for (int i =0;i<8;i++){
        bool win = true;
        char prev_op = '0';
        const char* win_possibility = wins_possibilities[i]; //funciona como puntero en caso de que se cumpla uno de las wins_possibilities[]

        for (int rcl = 0;rcl<dim_m;rcl++){
                char alphaChar = win_possibility[rcl];

                int intr_number = alphaChar - '0';
                int op_sp = intr_number - 1;

                int row = op_sp / dim_m;    //busca la posición de la fila
                int column = op_sp % dim_m; //busca la posición de la columna

                char current_op = matrix[row][column];

                    if (prev_op == '0'){
                        prev_op = current_op;
                    }else if (prev_op == current_op){
                        continue;
                    }else{
                        win = false;
                        break;
                    }
        }
                if (win){
                    cout << "Felicidades, ganaste!! \n";
                    cout << "El jugador "<<prev_op<<" gana, felicidades! \n";
                    exit(0);
                    break;
                }
    }
}




Aucun commentaire:

Enregistrer un commentaire