vendredi 9 novembre 2018

Tic tac toe game in C stuck in a loop when finding a random number for the opponent

I started C and I am trying to write a tic tac toe with an opponent which searches a random number between 1 to 9 and then fill the slot with “O”. However, when the random number detects an occupied slot, it will continue to fill other empty slots without giving the player the turn. How do I resolve this?

I made two arrays, one for the game screen, one for the memory of the slots.

I’m sorry I couldn’t chuck out the code since I thought it’s all important and is there any better way to do this? Sorry for my writing style if it is a bit confusing, and I think there are unimportant variables.

Here is my code:

#include <stdio.h>
#include <stdlib.h> 
#include <time.h>

char values[3][4] = {  // screen board
{46, 46, 46,'\n'},
{46, 46, 46,'\n'},
{46, 46, 46,'\n'}
};

double memory[3][4] = { // memory board to put values
{0, 0, 0,'\n'},
{0, 0, 0,'\n'},
{0, 0, 0,'\n'}
};

int player(int i, char values[3][4]) {
int input;
printf("enter position: ");
scanf("%i", &input);
int x = (((input) / 3.3) - 3) * -1; //  important math to convert to num
int y = (input + 2) % 3;            //  important math to convert to num

if (memory[x][y] == 0) {
    values[x][y] = 'X';
    memory[x][y] = 1;
    printf("%s", values);
    getchar();
    return 0;
    getchar();
}
else {
    printf("Wrong!, choose another line\n");
    printf("%s", values);
    getchar();
    player(i, values);

}
}


int opponent(char values[3][4]) {  //function opponent
int count = 0;
srand(time(NULL));

int random = (rand() % 9) + 1;   // create random number

for (count = 0; count < 9; count++) {

    int x = (((random) / 3.3) - 3) * -1;
    int y = (random + 2) % 3;

    if (memory[x][y] == 0) {  // if memory is empty, do the following, loop 
stucks here

        values[x][y] = 'O';
        memory[x][y] = 2;
        printf("Opponent Move\n");
        printf("%s", values);
        count++;
        return 0;
    }

    else {          // if memory is not 0, do this. Error starts here
        getchar();
        printf("Move is %i", random);
        opponent(values);       // it calls itself to do a loop, 
    }
}
}

int main() {
int input;
int i = 2;;

   for (i = 2; i < 9; i++) {    
        player(i, values);  //Player goes first
        getchar();
        opponent(values);   
   }
}

Aucun commentaire:

Enregistrer un commentaire