三子棋游戏

xiaoxiao2021-02-28  8

game.h #ifndef _GAME_H_ #define _GAME_H_ #include<stdio.h> #include<stdlib.h> #include<time.h> #include<Windows.h> #pragma warning(disable:4996) #define ROW 3 #define COL 3 void game(); #endif main.c #include"game.h" void menu() { printf("***********************************\n"); printf("***********1 play 0 exit**********\n"); printf("***********************************\n"); } int main() { system("color F4"); int m; do { menu(); printf("Please select the number '1' or '0'\n"); scanf("%d", &m); switch (m) { case 1:game(); break; case 0:exit(0); break; default: printf("Please enter the number<1 or 0>\n"); break; } } while (1); system("pause"); return 0; }game.c #include"game.h" void display_board(char board[][COL], int row) { int i = 0; for (; i < row; i++) { printf(" %c | %c | %c \n", board[i][0], board[i][1], board[i][2]); if (i < row - 1) { printf("---|---|---\n"); } } } void player_move(char board[][COL], int row) { int x, y; do{//输入正确才能进行下一步，所以有必要用循环 printf("请输入你要下棋的位置："); scanf("%d%d", &x, &y); if (x >= 1 && x <= 3 && y >= 1 && y <= 3) { if (board[x - 1][y - 1] == ' ') { board[x - 1][y - 1] = 'x'; break;//注意，下完棋 跳出循环 } else { printf("你输入的位置被占用请重新输入：\n"); } } else { printf("请输入正确的位置\n"); } } while (1); } void computer_move(char board[][COL], int row) { int x, y; do { srand((unsigned long)time(NULL)); x = rand() % row;//生成随机数 y = rand() % COL; if (board[x][y] == ' ') { board[x][y] = 'o'; break;//跳出 } } while (1); } int full(char board[][COL], int row) { int i = 0; for (; i < row;i++) { int j = 0; for (; j < COL;j++) { if (board[i][j] == ' ') { return 0; } } } return 1; } char judge_win(char board[][COL], int row)//3 种情况 两方有一方赢或平局或没满也没赢（平局要判断‘满’） { int i = 0; for (; i < row; i++)//横行 { if (board[i][0] == board[i][1] && board[i][1] == board[i][2] && board[i][0] != ' ') { return board[i][0]; } } for (i=0; i <COL; i++)//竖行 注意i 要清零！！！！！ { if (board[0][i] == board[1][i] && board[1][i] == board[2][i] && board[0][i] != ' ') { return board[0][i]; } } if (board[0][0] == board[1][1] && board[1][1] == board[2][2] && board[0][0] != ' ')//对角线 { return board[0][0]; } if (board[0][2] == board[1][1] && board[1][1] == board[2][0] && board[0][2] != ' ')//对角线 { return board[0][2]; } int flag = full(board, ROW); if (flag) { return 'q'; } return ' ';//注意， 第三种返回值，没满也没赢 } void game() { char board[ROW][COL]; memset(board, ' ', ROW*COL); char ret ; do{ system("CLS"); display_board(board, ROW); player_move(board, ROW); ret = judge_win(board, ROW);//每走一步都得判断 if (ret != ' ')//判断满了没 { break; } computer_move(board, ROW); ret = judge_win(board, ROW);//判断赢了没 }while(ret == ' '); system("CLS"); display_board(board, ROW); if (ret == 'x') { printf("恭喜！你赢了！\n"); } else if (ret == 'o') { printf("你输了\n"); } else if (ret == 'q') { printf("平局\n"); } else { printf("debug\n"); } }