用C语言实现“智障”的棋盘游戏
程序员文章站
2024-01-31 14:12:10
#define _CRT_SECURE_NO_WARNINGS
#include
#include ...
#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;//返回继续判断 }