Tic Tac Toe 棋盘游戏

Posted on 2020-12-03 17:07  金色的省略号  阅读(193)  评论(0编辑  收藏  举报

  代码来源于 C The Complete Reference 一书,3*3 二维数组模拟棋盘,二维数组用空格字符初始化;输入函数用到了递归,scanf 用到了%*c;主要是游戏思想,判赢的 check 函数遍历数组,每行、每列、正反对角线的字符是否一致,返回 'X' 下棋者赢,返回 ( 'O' ) 计算机赢,返回空格,游戏继续;计算机找空格,遍历数组,i*j==9 即没有空格,平局 ( a draw game ), 游戏结束!

/* A simple Tic Tac Toe game. */
#include <stdio.h>
#include <stdlib.h>
char matrix[3][3]; /* the tic tac toe matrix */
char check(void);
void init_matrix(void);
void get_player_move(void);
void get_computer_move(void);
void disp_matrix(void);
int main(void)
{
  char done;
  printf("This is the game of Tic Tac Toe.\n");
  printf("You will be playing against the computer.\n");
  done = ' ';
  init_matrix();
  do {         //数组元素没有空格循环结束
    disp_matrix();
    get_player_move();
    done = check(); /* see if winner */
    if(done!= ' ') break; /* winner!*/
    get_computer_move ();
    done = check(); /* see if winner */
  } while(done== ' ');    
  if(done=='X') printf("You won!\n");
  else printf("I won!!!!\n");
  disp_matrix(); /* show final positions */
  return 0;
}
/* Initialize the matrix. */
void init_matrix(void)
{
  int i, j;
  for(i=0; i<3; i++)
    for(j=0; j<3; j++) matrix[i][j] = ' ';
}
/* Get a player's move. */
void get_player_move (void)
{
  int x, y;
  printf("Enter X,Y coordinates for your move: ");
  scanf("%d%*c%d", &x, &y);
  x--; y--;
  if(matrix[x][y]!= ' '){  //只有空格才可以下棋子
    printf("Invalid move, try again.\n");
    get_player_move();    //递归调用
  }
  else matrix[x][y] = 'X';
}
/* Get a move from the computer. */
void get_computer_move(void)
{
  int i, j;
  for(i=0; i<3; i++){
    for(j=0; j<3; j++)
      if(matrix[i][j]==' ') break;
    if(matrix[i][j]==' ') break;
  }
  if(i*j==9) {        // 没有找到空格 i*j==9
    printf("draw\n"); //打印平局( a draw game ) 游戏结束
    exit(0);
  }
  else
    matrix[i][j] = 'O';
}
/* Display the matrix on the screen. */
void disp_matrix(void)
{
  int t;
  for(t=0; t<3; t++) {
    printf(" %c | %c | %c ",matrix[t][0],
            matrix[t][1], matrix [t][2]);
    if(t!=2) printf("\n---|---|---\n");
  }
  printf ( "\n");
}
/* See if there is a winner. */
char check(void) 
{
  int i;
  for(i=0; i<3; i++) /* check rows */   //每一行
    if(matrix[i][0]==matrix[i][1] &&
       matrix[i][0]==matrix[i][2]) 
        return matrix[i][0];
  for(i=0; i<3; i++) /* check columns */ //每一列
    if(matrix[0][i]==matrix[1][i] &&
       matrix[0][i]==matrix[2][i]) 
        return matrix[0] [i];
  /* test diagonals */
  if(matrix[0] [0]==matrix[1][1] &&   //正对角线
     matrix[1][1]==matrix[2][2])
       return matrix[0][0];
  if(matrix[0] [2]==matrix[1][1] &&   //反对角线
     matrix[1] [1]==matrix[2][0])
       return matrix[0][2];
  return ' ';                      //还有空格
}
View Code