#include<stdio.h> #include<stdlib.h> void init(char arr[3][3],int i,int j ) { for (i = 0; i < 3; i++) { for (j = 0; j < 3; j++) { arr[i][j] = ' '; } } } int prit(char arr[3][3], int i, int j) { for (i = 0; i < 3; i++) { printf(" %c | %c | %c ", arr[i][0],arr[i][1],arr[i][2]); if (i != 2) printf("\n---|---|---\n"); } return 0; } void play(char arr[3][3], int x, int y) { int i=0; int j = 0; arr[x][y] = 'X'; for (i = 0; i < 3; i++) { printf(" %c | %c | %c ", arr[i][0], arr[i][1], arr[i][2]); if (i != 2) printf("\n---|---|---\n"); } } void computer(char arr[3][3]) { int i = 0; int j = 0; int flag = 0; for (i = 0; i < 3; i++) { if (flag == 1) break; for (j = 0; j < 3; j++) { if ((arr[i][j] != 'X') && (arr[i][j] != 'O')) { arr[i][j] = 'O'; flag = 1; break; } } } for (i = 0; i < 3; i++) { printf(" %c | %c | %c ", arr[i][0], arr[i][1], arr[i][2]); if (i != 2) printf("\n---|---|---\n"); } } int check(char arr[3][3], int i, int j) { int k = 0;//判斷對角線X int n = 0;//判斷對角線O int a = 0;//判斷每一行 int b = 0;// for (i = 0; i < 3; i++) { if (arr[i][i] == 'X') k++; else if (arr[i][i] == 'O') n++; } if (k == 3) { return 1; } if (n == 3) { return 0; } for (i = 0; i < 3; i++) { if (((arr[i][0] == 'X') && (arr[i][1] == 'X') && (arr[i][2] == 'X'))|| ((arr[0][i] == 'X') && (arr[1][i] == 'X') && (arr[2][i] == 'X')) || ((arr[0][2] == 'X') && (arr[1][1] == 'X') && (arr[2][0] == 'X'))) { return 1; break; } if (((arr[i][0] == 'O') && (arr[i][1] == 'O') && (arr[i][2] == 'O')) || ((arr[0][i] == 'O') && (arr[1][i] == 'O') && (arr[2][i] == 'O'))|| ((arr[0][2] == 'O') && (arr[1][1] == 'O') && (arr[2][0] == 'O'))) { return 0; break; } } } void manu() { printf("****************************************\n"); printf("**************歡迎進入游戲**************\n"); printf("*************1.開始游戲*****************\n"); printf("*************0.退出游戲*****************\n"); printf("****************************************\n"); } void order() { printf("**********請選擇下棋先後次序************\n"); printf("*************1.玩家先下*****************\n"); printf("*************0.本機先下*****************\n"); } int main() { char arr[3][3]; int i = 0; int j = 0; int x = 0; int y = 0; int input = 1; int ret = 0; int c = 0; while (input) { manu(); printf("請選擇>"); scanf("%d", &input); switch (input) { case 1: {printf("開始游戲\n"); order(); printf("請選擇>"); scanf("%d", &c); switch (c) { case 1: {init(&arr[0], i, j); prit(&arr[0], i, j); while (1) { printf("\n請輸入要下棋的位置坐標:\n"); scanf("%d%d", &x, &y); printf("玩家下棋為:\n"); play(&arr[0], x, y); ret = check(&arr[0], i, j); if (ret == 1) { printf("\n恭喜你贏了!\n"); break; } lop: printf("\n本機下棋為:\n"); computer(&arr[0]); ret = check(&arr[0], i, j); if (ret == 0) { printf("\n很遺憾你輸了!\n"); break; } } break; } case 0: {init(&arr[0], i, j); prit(&arr[0], i, j); goto lop; break; } } default: { printf("退出游戲\n"); system("pause"); exit(0); break; } } } system("pause"); return 0; } }