井字棋
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <time.h>int Menu(){printf("+++++++++++++++++\n");printf("1.開始游戲\n");printf("0.結束游戲\n");printf("+++++++++++++++++\n");int choise = 0;scanf("%d", &choise);return choise;
}#define MAX_ROW 3
#define MAX_COL 3char chess_board[MAX_ROW][MAX_COL];void Init(){for (int row = 0; row < MAX_ROW; ++row) {for (int col = 0; col < MAX_COL; ++col){chess_board[row][col] = ' ';}}srand((unsigned int)time(0));
}void Print(){for (int row = 0; row < MAX_ROW; ++row) {printf("| %c | %c | %c |\n", chess_board[row][0], chess_board[row][1], chess_board[row][2]);if (row != MAX_ROW - 1){printf("|---|---|---|\n");}}//TODO//system("pause");
}void PlayerMove(){printf("玩家落子\n");while (1){printf("請輸入落子坐標(row col)\n");int row = 0, col = 0;scanf("%d %d", &row, &col);if (row < 0 || row >= MAX_ROW || col<0 || col>MAX_COL){printf("輸入坐標有誤,請從新輸入\n");continue;}if (chess_board[row][col] != ' '){printf("該位置已被占用!\n");continue;}chess_board[row][col] = 'x';break;}printf("玩家落子結束\n");
}void ComputerMove(){printf("電腦落子!\n");while (1){int row = rand() % 3;int col = rand() % 3;if (chess_board[row][col] != ' '){continue;}chess_board[row][col] = 'o';break;}printf("電腦落子完畢!\n");
}//如果滿了返回1 否則返回0
int IsFull(){for (int row = 0; row < MAX_ROW; ++row){for (int col = 0; col < MAX_COL; ++col){if (chess_board[row][col] == ' '){return 0;}}}return 1;
}// x為玩家獲勝
// o為電腦獲勝
// q表示和棋
// ' '勝負未分
char WinnerCheck(){//行成線for (int row = 0; row < MAX_ROW; ++row){if (chess_board[row][0] == chess_board[row][1] && chess_board[row][0] == chess_board[row][2]){return chess_board[row][0];}}//列成線for (int col = 0; col < MAX_COL; ++col){if (chess_board[0][col] == chess_board[1][col] && chess_board[0][col] == chess_board[2][col]){return chess_board[0][col];}}//對角成線if (chess_board[0][0] == chess_board[1][1] && chess_board[0][0] == chess_board[2][2]){return chess_board[0][0];}if (chess_board[0][2] == chess_board[1][1] && chess_board[0][2] == chess_board[2][0]){return chess_board[0][2];}if (IsFull()){return 'q';}return ' ';
}void Game(){//1. 初始化棋盤Init();char winner = ' ';while (1){//2. 打印棋盤Print();//3. 玩家落子PlayerMove();//4. 檢測勝負winner = WinnerCheck();if (winner != ' '){break;}//5. 電腦落子ComputerMove();//6. 檢測勝負winner = WinnerCheck();if (winner != ' '){break;}system("cls");}Print();if (winner == 'x'){printf("您贏了!\n");}else if (winner == 'o'){printf("您輸了!\n");}else if (winner == 'q'){printf("平局!\n");}else{printf("代碼BUG!\n");}}int main(){while (1){int choice = Menu();if (choice == 1){Game();}else if(choice == 0){printf("goodbye\n");break;}else {printf("您的輸入有誤!\n");}}system("pause");return 0;
}
總結
- 上一篇: c语言习题---(switch语句)
- 下一篇: 闹钟的设计原理与实现