- // program 5.8 tic-tac-toe
- #include <stdio.h>
- int main(void)
- {
- int player = 0; //current player number - 1 or 2
- int winner = 0; //the winning player number
- int choice = 0; //chosen square
- unsigned int row = 0; //row index for a square
- unsigned int column = 0; //column index for a square
- char board[3][3] = { //the board
- {'1','2','3'}, //initial values are characters '1' to'9'
- {'4','5','6'}, //used to select a vacant square
- {'7','8','9'} //for a player's turn
- };
- unsigned int i,line;
- //the main game loop.the game continues for up to 9 turns
- //as long as there is no winner
- for(i = 0; i < 9 && winner == 0; ++i)
- {
- //display the board
- printf("\n");
- printf(" %c | %c| %c\n", board[0][0], board[0][1],board[0][2]);
- printf("---+---+---\n");
- printf(" %c | %c | %c\n",board[1][0],board[1][1],board[1][2]);
- printf("---+---+---\n");
- printf(" %c | %c | %c\n",board[2][0],board[2][1],board[2][2]);
- player = i%2 + 1; // select selection
- do
- {
- printf("player %d, please enter a valid square number "
- "for where you want to place your %c: ",
- player,(player == 1) ? 'x' : 'o');
- scanf("%d", &choice);
- row = --choice/3; //get row index of square
- column = choice % 3; //get column index of square
- }while(choice < 0 ||choice > 8 || board[row][column] > '9');
- // insert player symbol
- board[row][column] = (player == 1) ? 'x' : 'o';
- //check for a winning line - diagonals first
- if((board[0][0]==board[1][1] && board[0][0]==board[2][2]||
- board[0][2]==board[1][1] && board[0][2]==board[2][0]))
- winner = player;
- else
- {
- //check rows and columns for a winning line
- for( line = 0; line<=2;++line)
- {
- if((board[line][0] ==board[line][1] && board[line][0] ==board[line][2] ||
- board[0][line]==board[1][line] &&board[0][line] ==board[2][line]))
- winner = player;
- }
- }
- }
- // game is over so display the final board
- printf("\n");
- printf(" %c | %c| %c\n", board[0][0], board[0][1],board[0][2]);
- printf("---+---+---\n");
- printf(" %c | %c | %c\n",board[1][0],board[1][1],board[1][2]);
- printf("---+---+---\n");
- printf(" %c | %c | %c\n",board[2][0],board[2][1],board[2][2]);
- //display result message
- if(winner)
- printf("\ncongratulations, player %d, you are the winner!|n", winner);
- else
- printf("\nhow boring, it is a draw\n");
- return 0;
- }
复制代码 |