#define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <stdlib.h> /*函數聲明*/ void Init_Arr(int arr[ ][3]); //數組初始化 void Print_Checkerboard(int arr[ ][3]); //打印棋盤函數 int Player(int arr[ ][3], int line, int list); //玩家下棋 void Robot(int *arr); //電腦下棋 int Judge(int arr[ ][3]); //判斷輸贏 int main() { int Arr[3][3]; int x=0, y=0; int result = 0; int Result = 0; printf("Welcome to play the Checkboard Game!\n"); Init_Arr(Arr); Print_Checkerboard(Arr); while (1) { printf("Enter X,Y coordinates for your move:"); scanf("%d", &x); scanf("%d", &y); Result= Player(Arr, x, y); if (Result) { Robot(&Arr[0][0]); Print_Checkerboard(Arr); result = Judge(Arr); if (result == 1) { printf("The player win!\n\n"); break; } if (result == 2) { printf("The robot win!\n\n"); break; } if (result == 3) { printf("Peace!\n\n"); break; } } else printf("Can not next chess here!\n"); } system("pause"); return 0; } void Print_Checkerboard(int arr[ ][3]) //打印棋盤函數 { int size = 3; for (int i = 0; i < size; i++) { printf("\t\t %c | %c | %c \n",arr[i][0],arr[i][1],arr[i][2]); if(i<size-1) printf("\t\t---|---|---\n"); } } void Init_Arr(int arr[ ][3]) //數組初始化 { int row = 3; int list = 3; for (int i = 0; i < row; i++) { for (int j = 0; j < list; j++) { arr[i][j] = ' '; } } } int Player(int arr[ ][3],int line,int list) //玩家下棋 { if (line < 4 && list < 4) { if (arr[line - 1][list - 1] != ' ') { return 0; //下棋的位置不正確 } else { arr[line - 1][list - 1] = 'X'; return 1; //下棋位置正確 } } else { return 0; //下棋的位置不正確 } } void Robot(int *arr) //電腦下棋 { int size = 9; for (int i = 0; i < size; i++) { if (arr[i] ==' ') { arr[i] = '0'; break; } } } int Judge(int arr[ ][3]) //判斷輸贏 { int size = 3; int flag = 0; for (int i = 0; i < 3; i++) { if (((arr[i][0] == arr[i][1]) && (arr[i][1] == arr[i][2]) && (arr[i][0] == 'X')) || ((arr[0][i] == arr[1][i]) && (arr[1][i] == arr[2][i]) && (arr[0][i] == 'X'))) return 1; //玩家勝利 } if (((arr[0][0] == arr[1][1]) && (arr[0][0] == arr[2][2]) && (arr[0][0] == 'X')) || ((arr[0][2] == arr[1][1]) && (arr[1][1] == arr[2][0]) && (arr[0][2] == 'X'))) { return 1; //玩家勝利 } for (int i = 0; i < 3; i++) { if (((arr[i][0] == arr[i][1]) && (arr[i][1] == arr[i][2]) && (arr[i][0] == '0')) || ((arr[0][i] == arr[1][i]) && (arr[1][i] == arr[2][i]) && (arr[0][i] == '0'))) return 2; //電腦勝利 } if (((arr[0][0] == arr[1][1]) && (arr[0][0] == arr[2][2]) && (arr[0][0] == '0')) || ((arr[0][2] == arr[1][1]) && (arr[1][1] == arr[2][0]) && (arr[0][2] == '0'))) { return 2; //電腦勝利 } for (int i = 0; i < size; i++)//判斷棋盤是否已下滿 { for (int j = 0; j < size; j++) { if (arr[i][j] != ' ') flag++; } } if (flag == 9) { return 3;//平局 } return 0;//返回繼續判斷 }