After reviewing the below code for the past hour, I cannot seem to figure out this problem.
This is a basic WIP for a tic-tac-toe game (I'm new to C and thought this would be a decent little challenge). I've got most of everything done, however - after you enter in Player #1's name and Player #2's name, the program will ALWAYS give the turn to whoever was assigned as Player #1 (who is assigned as player #1 is supposed to be random).
So, to summarize:
>enter in player #1's name [josh]
>enter in player #2's name [justin]
>program randomly assigns josh as player #1
>[turn #1] josh, make your move
>enter in coordinates
>[turn #2] josh, make your move
It never gives a turn to player two. Any ideas why this is? Thanks.
Code:
#include <stdio.h>
#include <string.h>
#include "player.h"
int board[3][3];
int maxInput = 3; /* this represents the maximum int they can specify when choosing a position to play */
int a = 0; //represent the turn currently being played
int done = 0;
struct players player[2];
//prototypes
int isEven(int x);
void markPosition(int x, int y, char type);
void checkForWinner();
int main()
{
int first; //the player the goes first
int x;
int y;
printf("Player one, enter your name: ");
fgets(player[0].name, 256, stdin);
printf("Player two, enter your name: ");
fgets(player[1].name, 256, stdin);
//remove \n at the end of each name
player[0].name[strlen(player[0].name)-1] = '\0';
player[1].name[strlen(player[1].name)-1] = '\0';
//generate who will go first randomly
first = (isEven(rand())) ? 1 : 0;
//set who is x, who is y
if(first == 1){
player[0].type = 'O';
player[1].type = 'X';
}else{
player[0].type = 'X';
player[1].type = 'O';
}
printf("Player %s, you are X.\n", player[first].name);
printf("=========================\n");
while(done == 0){
a++;
printf("\n\n[TURN %d] %s, make your move.", a, (isEven(a) && first == 1) ? player[1].name : player[0].name);
printf("\nInput X-Coord: ");
scanf("%d", &x);
printf("\nInput Y-Coord: ");
scanf("%d", &y);
markPosition(x,y, (isEven(a) && first == 1) ? player[1].type : player[0].type);
checkForWinner();
}
FILE *file;
file = fopen("C:\\Users\\Justin\\Desktop\\tictactoe_results.txt", "w+");
//print results of the board/game into a text file
int o = 0;
int z = 0;
int b;
for(b = 0; b < 9; b++){
//if the position isn't played, set it to the char -, else write who played that pos
fputc((board[o][z] == NULL) ? '-' : board[o][z], file);
if(o == 2) fputc('\n', file);
if(o >= 2){
o = 0;
z++;
}else{
o++;
}
}
fclose(file);
getchar();
}
int isEven(int x){
return !(x%2);
}
void checkForWinner(){
if(a == 9){
done = 1;
}
}
void markPosition(int x, int y, char type){
if(board[x][y] != NULL){
printf("[ERROR] You cant select position already played.\n");
if(a > 0) a--;
}else if(x > maxInput || y > maxInput){
printf("[ERROR] Your coordinates are off the board! \n");
if(a > 0) a--;
}else{
board[x][y] = type;
}
}