/* TicTacToe.c */ #include "TicTacToe.h" #include /* function to allow a player to make a move * * parameters: * * board - The board for playing the game * * player - variable to keep track of whose * * turn it is. */ void playerTurn(int board[][B_SIZE], int player) { int mark; /* This while loop runs until a player has input a valid position in which to place his or her X or O */ do { printf("It is player %d's turn.\n", player); printf("Please enter the space where you would like to put your mark: "); scanf("%d", &mark); }while(mark < 1 || mark > 9 || board[(mark-1)/3][(mark-1)%3] == 10 || board[(mark-1)/3][(mark-1)%3] == 11); /* Notice that the condition for the loop requires that the mark be between 1 and 9 and it checks to see if the position contains a 10 or an 11 (i.e. an X or an O).*/ /* place the mark on the board */ board[(mark-1)/3][(mark-1)%3] = player + 9; } /* function to check if a player has won * * parameters: * * board - The board for playing the game* * win - acts as a boolean to determine * * if a win or a tie has occured * * winner - variable to hold the winner * * i.e. player 1 or 2 or no one * * in the case of a tie * * player - holds the current player */ void checkWin(int board[][B_SIZE], int* win, int*winner, int player) { int p; if(player == 1) p = 10; else p = 11; /* check all possible winning combinations for the current player */ if( (board[0][0] == p && board[0][1] == p && board[0][2] == p) || (board[1][0] == p && board[1][1] == p && board[1][2] == p) || (board[2][0] == p && board[2][1] == p && board[2][2] == p) || (board[0][0] == p && board[1][0] == p && board[2][0] == p) || (board[0][1] == p && board[1][1] == p && board[2][1] == p) || (board[0][2] == p && board[1][2] == p && board[2][2] == p) || (board[0][0] == p && board[1][1] == p && board[2][2] == p) || (board[0][2] == p && board[1][1] == p && board[2][0] == p) ) { *win = 1; *winner = p - 9; } else if(isTie(board)) { *win = 1; *winner = 0; } } /* function to print out the board * * parameters - * * board - the tic tac toe board */ void printBoard(int board[][B_SIZE]) { int i = 0, j = 0; /* look through the board and print out X's, O's, or * numbers (indicating empty spaces) as appropriate */ for(i = 0; i < B_SIZE; i++) { for(j = 0; j < B_SIZE; j++) { if(board[i][j] >= 1 && board[i][j] <= B_SIZE*B_SIZE) printf(" %d ", board[i][j]); else if(board[i][j] == 10) printf(" %c ", 'X'); else if(board[i][j] == 11) printf(" %c ", 'O'); if(j < B_SIZE-1) printf("|"); } if(i < B_SIZE-1) printf("\n------------\n"); else printf("\n"); } } /* function to check if a tie has occured * * parameters - * * board - the tic tac toe board */ int isTie(int board[][B_SIZE]) { int i = 0, j = 0, count = 0; /* check if all the spaces are full */ for(i = 0; i < B_SIZE; i++) { for(j = 0; j < B_SIZE; j++) { if(board[i][j] == 11 || board[i][j] == 10) count++; } } if( count == B_SIZE*B_SIZE ) return 1; else return 0; }