#include <stdio.h>
void chessboard(int arr[][3], int len){ //棋盘初始化
int i = 0;
int j = 0;
for (i = 0; i < len; i++){
for (j = 0; j < len; j++){
arr[i][j] = ‘ ‘;
}
}
}
void print(int arr[][3], int len){ //显示函数
int i = 0;
for (i = 0; i < 3; i++){
printf(" %c | %c | %c ", arr[i][0], arr[i][1], arr[i][2]);
printf("\n");
if (i != 2){
printf("___|___|___");
printf("\n");
}
}
}
void computer(int arr[][3], int len){ //电脑下棋函数
int i = 0;
int j = 0;
int flag = 0;
for (i = 0; i < len; i++){
for (j = 0; j < len; j++){
if (arr[i][j] == ‘ ‘){
arr[i][j] = ‘0‘; //找到一个符合的位置就下棋
flag = 1;
break;
}
}
if (flag == 1)
break;
else if (flag == 0)
continue;
}
print(arr,len );
Is_win(arr, len);
}
void player(int arr[][3] ,int len){ //玩家下棋函数
int x = 0;
int y = 0;
flag: printf("请输入棋子坐标:\n");
scanf_s("%d %d", &x, &y); //输入棋子坐标
if (arr[x - 1][y - 1] == ‘ ‘){
arr[x - 1][y - 1] = ‘X‘;
computer(arr ,len );
player(arr, len);
}
else if ((arr[x - 1][y - 1] == ‘0‘) || (arr[x - 1][y - 1] == ‘X‘)){
printf("这里不能落子!\n");
goto flag;
}
}
int Is_win(int arr[][3], int len){
int i = 0;
int ret = 0;
for (i = 0; i < 3; i++){
if (arr[i][0] == arr[i][1] && arr[i][0] == arr[i][2]){ //行判断
ret = arr[i][0];
}
}
for (i = 0; i < 3; i++){
if (arr[0][i] == arr[1][i] && arr[0][i] == arr[2][i]){ //列判断
ret = arr[0][i ];
}
}
if (( arr[0][0]) == arr[1][1] && arr[0][0] == arr[2][2]){ //\方向判断
ret = arr[0][0];
}
if (arr[0][2] == arr[1][1] && arr[0][2]== arr[2][0] ){ // /方向判断
ret = arr[0][2];
}
if (ret == ‘X‘){
printf("你赢了!\n");
exit(0);
}
else if (ret == ‘0‘){
printf("电脑赢了!\n");
exit(0);
}
return 0;
}
int main(){ //主函数
int len = 0; //数组长度
int chess[3][3]; //定义数组
len = sizeof(chess ) / sizeof(chess[0]);
chessboard(chess,len );
print(chess, len);
player(chess, len);
return 0;
}
本文出自 “moLova” 博客,请务必保留此出处http://molova.blog.51cto.com/10594266/1684925
原文地址:http://molova.blog.51cto.com/10594266/1684925