mardi 9 février 2021

How to limit what numbers a rand function could generate. (Segmentation Fault)

I'm trying to create a tic-tac-toe game in C++

So far, I have it set up where the player and the program take turns. The program's move is determined by rand()%10. It generates a number 1-9, one number for each box in tic tac toe.

But this becomes a problem because eventually it will select a box that has already been filled. This seems to always cause a Segmentation Fault.

Is there any way to limit the rand() to boxes that are empty? I have tried if but they seem to be ignored. And then I would have to get rand() to keep trying until it generates a random number that corresponds to an empty box.

Any tips?

void program_move(){
    std::cout<<"My turn!\n";
    srand (time(NULL));
    move = rand()%10;
            if (boxes[move-1]!="x"&&boxes[move-1]!="o") {
    boxes[move-1]="o";
                
            }

    else{while(boxes[move-1]=="x"||boxes[move-1]=="o")
    {
        srand (time(NULL));
        move = rand()%10;
    
    boxes[move-1]="o";
        
    }
        
    }



Aucun commentaire:

Enregistrer un commentaire