用C語言寫一個簡單的三子棋,實現玩家與電腦的對戰
阿新 • • 發佈:2018-11-28
原始碼:
#define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <windows.h> #include <time.h> /* 用 C 寫一個三子棋 */ //邏輯: //1. 畫一個棋盤 --> 用二維陣列實現 //2. 規定使用者先下棋 x //3. 判斷遊戲是否結束 //4. 電腦再下棋 o //5. 判斷遊戲是否結束 //從 2 開始重複上述操作 //畫一個初始棋盤 //行列都為3 #define ROW 3 #define COL 3 char chess[ROW][COL]; //初始化二維陣列 void init() { for (int row = 0; row < ROW; row++) { for (int col = 0; col < COL; col++) { chess[row][col] = ' '; } } } void chessboard() { //繪畫邊界 for (int row = 0; row < ROW; row++) { printf(" %c | %c | %c \n", chess[row][0], chess[row][1], chess[row][2]); if (row != 2) { printf("---|---|---\n"); } } } //使用者先下棋 void playerFall() { //規定下棋的位置 int row = 0; int col = 0; printf("請使用者輸入你要落子的位置(row col)\n"); while (1) { scanf("%d %d", &row, &col); if (row < 0 || row >= ROW || col < 0 || col >= COL) { printf("你的輸入有誤請重新落子\n"); continue; } if (chess[row][col] != ' ') { printf("該位置已經有棋子,請重新落子\n"); continue; } chess[row][col] = 'X'; break; } system("cls"); chessboard(); } //電腦下棋 void computerFall() { //規定下棋的位置 int row = 0; int col = 0; while (1) { row = rand() % 3; col = rand() % 3; if (chess[row][col] != ' ') { continue; } chess[row][col] = 'O'; break; } system("cls"); chessboard(); } //判斷遊戲狀態 enum state { FAIL, WIN, KEEP, DRAW, }nowState; int gameState() { //判斷每行連成三子的情況 for (int row = 0; row < ROW; row++) { if (chess[row][0] == chess[row][1] && chess[row][0] == chess[row][2] && chess[row][0] != ' ') { if (chess[row][0] == 'X') { nowState = WIN; return nowState; } else { nowState = FAIL; return nowState; } } } //判斷每列連成三子的情況 for (int col = 0; col < COL; col++) { if (chess[0][col] == chess[1][col] && chess[0][col] == chess[2][col] && chess[0][col] != ' ') { if (chess[0][col] == 'X') { nowState = WIN; return nowState; } else { nowState = FAIL; return nowState; } } } //判斷對角線連成三子的情況 if ((chess[0][0] == chess[1][1] && chess[0][0] == chess[2][2] && chess[0][0] != ' ') || (chess[2][0] == chess[1][1] && chess[2][0] == chess[0][2] && chess[2][0] != ' ')) { if (chess[2][0] == 'X') { nowState = WIN; return nowState; } else { nowState = FAIL; return nowState; } } //判斷遊戲是否繼續 for (int row = 0; row < ROW; row++) { for (int col = 0; col < COL; col++) { if (chess[row][col] == ' ') { nowState = KEEP; return nowState; } } } //判斷是否下滿棋盤依然未分出勝負的情況 nowState = DRAW; return nowState; } int main() { init(); srand((unsigned int)time(NULL)); chessboard(); while (1) { playerFall(); if (gameState() != KEEP) { printf("遊戲結束\n"); break; } computerFall(); if (gameState() != KEEP) { printf("遊戲結束\n"); break; } } if (gameState() == FAIL) { printf("玩家失敗!!!\n"); } else if (gameState() == WIN) { printf("玩家勝利!!!\n"); } else { printf("和棋!!!\n"); } system("pause"); return 0; }