开始菜单
void menu()//打印菜单 { printf("******************\n"); printf("******1.play******\n"); printf("******0.exit******\n"); printf("******************\n"); }
打印棋盘
//存放下棋数据 char board[ROW][COL] = { 0 }; //初始化棋盘为全空格 InitBoard(board, ROW, COL); //初始化棋盘为空格 void InitBoard(char board[ROW][COL], int row, int col) { int i = 0; for (i = 0; i < row; i++) { int j = 0; for (j = 0; j < col; j++) { board[i][j] = ' '; } } } //打印棋盘 void DisplayBoard(char board[ROW][COL], int row, int col)//打印棋盘 { //打印数据 int i = 0; for (i = 0; i < row; i++) { int j = 0; for (j = 0; j < col; j++) { printf(" %c ",board[i][j]);//别忘记board[i][j] if (j < col - 1) { printf("|"); } } printf("\n"); //打印分割行 if (i < row-1)//记住 row-1 { for (j = 0; j < col; j++) { printf("---"); if (j < col - 1) { printf("|"); } } printf("\n"); } } }
玩家下棋
//玩家下棋 void player_move(char board[ROW][COL], int row, int col) { int x = 0; int y = 0; printf("玩家下棋\n"); while (1) { printf("请输入坐标:"); scanf("%d %d", &x, &y); if (x >= 1 && x <= row && y >= 1 && y <= col) { if (board[x - 1][y - 1] == ' ') { board[x - 1][y - 1] = '*'; break; } else { printf("该坐标被占用,请重新输入\n"); } } else { printf("非法坐标,请重新输入\n"); } }
电脑下棋
void computer_move(char board[ROW][COL], int row, int col) { int x = 0; int y = 0; printf("电脑下棋:>\n"); while (1) { x = rand() % 3;//范围(a,b)用rand表示就是rand()%(b-a+1) y = rand() % 3; if (board[x][y] == ' ')//判断是否为空格,因为只有这一个条件,所以满足这个条件就可以下 { board[x][y] = '#'; break; } } }
判断输赢
while (1)//玩家和电脑轮流下棋,直到一方胜利 { //玩家下棋 player_move(board, ROW, COL); //打印棋盘 DisplayBoard(board, ROW, COL); ret = is_win(board, ROW, COL); if (ret != 'C') { break; } //电脑下棋 computer_move(board, ROW, COL); //打印棋盘 DisplayBoard(board, ROW, COL); ret = is_win(board, ROW, COL); if (ret != 'C') { break; } } if (ret == '*') { printf("玩家获胜\n"); } else if (ret == '#') { printf("电脑获胜\n"); } else // (ret == 'Q') { printf("平局\n"); } DisplayBoard(board, ROW, COL); } //判断输赢 char is_win(char board[ROW][COL], int row, int col) { //判断每一行是否都相等 int i = 0; for (i = 0; i < col; i++) { if (board[i][0] == board[i][1] && board[i][1] == board[i][2] && board[i][1] != ' ') { return board[i][1]; } } //判断每一列是否都相等 for (i = 0; i < col; i++) { if (board[0][i] == board[1][i] && board[1][i] == board[2][i] && board[1][i] != ' ') { return board[i][1]; } } //判断对角线是否都相等 if (board[0][0] == board[1][1] && board[1][1] == board[2][2] && board[1][1] != ' ') { return board[1][1]; } if (board[0][2] == board[1][1] && board[1][1] == board[2][0] && board[1][1] != ' ') { return board[1][1]; } //判断平局 if (is_full(board, row, col) == 1) { return 'Q'; } //继续 return 'C'; }