Game specifications:
1. Assume n>=3.
2. If n is even and # of x and o are not equal, then the tic-tac-toe is INVALID.
3. If n is odd and the absolute difference between # of x and o is not 1, then the tic-tac-toe is INVALID.
4. WINNER: If # of x OR o == n.
5. If both x and o win, there is no TIE, rather the game is INVALID.
Here's what I have so far:
#include <stdio.h>
#include <string.h>
#define VALID 1
#define INVALID 0
int is_valid(char *str, int n);
int get_winner(char *str, int n);
void print2d(char *str, int n);
int main()
{
//gets size of matrix (n x n)
int n;
scanf("%d", &n);
//gets matrix values in string form
char str[n][n];
int i;
for (i=0; i<n; i++)
{
scanf("%s", &(str[i][0]));
}
printf("\n");
int validity = is_valid(*str, n);
if(is_valid == INVALID)
printf("INVALID GAME.");
//checks winner
int winner = get_winner(*str, n);
if(winner == 1)
printf("X WINS!");
if(winner == 0)
printf("O WINS!");
//if both x and o win, INVALID GAME
if(winner == -1)
printf("INVALID GAME.");
return(0);
}
/*LE FUNCTIONS*/
//CHECKS IF STRINGS ARE VALID
//If n is even and a and b are not equal,
//then the tictactoe is invalid.
//If n is odd and the absolute difference between a and b is not 1,
//then the tictactoe is invalid.
int is_valid(char *str, int n)
{
int freq_o=0, freq_x=0;
int i;
for(i=0; i<n; i++)
{
if(str[i] == 'x')
freq_x++;
if(str[i] == 'o')
freq_o++;
}
if(n%2 != 0 && freq_x - freq_o != 1 || freq_o - freq_x != 1)
return INVALID;
if(n%2 == 0 && freq_x == freq_o)
return INVALID;
else
return VALID;
}
//GETS THE WINNER
//Winner: if # of x OR o = n
//Invalid Game: if both x AND o = n
int get_winner(char *str, int n)
{
int i, winner, a, b;
for(i=0; i<n; i++)
{
if(str[i] == 'x')
{
winner = 1;
a++;
}
if(str[i] == 'o')
{
winner = 0;
b++;
}
}
return winner;
}
But I'm kinda stuck at how to determine the winner...

New Topic/Question
Reply



MultiQuote




|