So, basically this code is for a Tic Tac Toe game, I'm trying to make a Singleplayer mode where Player 1 inserts a spot number to put his X, and Player 2 uses a random number generating function and assigns his O in a random spot. Everything works fine except, Player 2's random number does not get assigned on the board.
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <time.h>
char choice, choice2, modsel;
int player = 1, winner, end = 0, counter = 0, ran_num;
char arr[3][3] = {
{'1','2','3'},{'4','5','6'},{'7','8','9'}
};
void numgen(int rannum) {
srand(time(NULL));
rannum = 1 + rand() % 9;
ran_num = rannum;
}
void printarray() {
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
printf("|%c|", arr[i][j]);
}
printf("\n");
}
}
void playingSP() {
char letter;
if (player == 1) {
scanf("%c", &choice2);
letter = 'x';
}
else if (player == 2) {
numgen(ran_num);
choice2 = ran_num;
letter = 'o';
}
else {
printf("wrong entry");
}
switch (choice2) {
case '1': arr[0][0] = letter; break;
case '2': arr[0][1] = letter; break;
case '3': arr[0][2] = letter; break;
case '4': arr[1][0] = letter; break;
case '5': arr[1][1] = letter; break;
case '6': arr[1][2] = letter; break;
case '7': arr[2][0] = letter; break;
case '8': arr[2][1] = letter; break;
case '9': arr[2][2] = letter; break;
}
counter++;
}
void endgame() {
for (int i = 0; i < 3; i++)
if ((arr[i][0] == arr[i][1]) && (arr[i][1] == arr[i][2])) {
if (arr[i][0] == 'x')
winner = 1;
else
winner = 2;
end = 1;
return;
}
for (int j = 0; j < 3; j++)
if ((arr[0][j] == arr[1][j]) && (arr[1][j] == arr[2][j])) {
if (arr[0][j] == 'x')
winner = 1;
else
winner = 2;
end = 1;
return;
}
if ((arr[0][0] == arr[1][1]) && (arr[1][1]) == arr[2][2]) {
if (arr[0][0] == 'x')
winner = 1;
else
winner = 2;
end = 1;
return;
}
if ((arr[0][2] == arr[1][1]) && (arr[1][1]) == arr[2][0]) {
if (arr[0][2] == 'x')
winner = 1;
else
winner = 2;
end = 1;
return;
}
if (counter == 8) {
winner = 0;
end = 1;
}
}
int main()
{
printarray();
while (end != 1)
{
printf("player %d enter your number:", player);
playingSP();
printarray();
endgame();
if (player == 1)
player = 2;
else
player = 1;
playingSP();
}
if (winner == 0)
printf("no winner\n");
else
printf("player %d won the game\n", winner);
return 0;
}