#define row 3
#define col 3
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
//目录
void menu() {
printf("###############################\n");
printf("########1.play 0.end#########\n");
printf("###############################\n");
}
//初始化数组
void Init_arr(char arr[row][col], int x, int y) {
int i = 0;
int j = 0;
for (i = 0; i < x; i++) {
for (j = 0; j < y; j++) {
arr[i][j] = ' ';
}
}
}
//打印数组
void print(char arr[row][col],int x,int y) {
int i = 0;
int j = 0;
int m = 0;
for (i = 0; i < row; i++) {
for (j = 0; j < col; j++) {
if (j == col - 1) {
printf(" %c ", arr[i][j]);
}
else {
printf(" %c |", arr[i][j]);
}
}
printf("\n");
if (i != row - 1) {
for (m = 0; m < col; m++) {
if (m == col - 1) {
printf("---");
}
else {
printf("---|");
}
}
}
printf("\n");
}
}
//判断是否棋盘已满
int Is_full(char arr[row][col]) {
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
if (arr[i][j] == ' ') {
return 0;
}
}
}
return 1;
}
//玩家下棋
void Playermove(char arr[row][col], int x, int y) {
printf("请输入想要下棋的坐标:");
int i = 0;
int j = 0;
while (1) {
scanf_s("%d %d", &i, &j);
if (i >= 1 && i <= row && j >= 1 && j <= col) {
if (arr[i-1][j-1] == ' ') {
arr[i-1][j-1] = '*';
print(arr, row, col);
break;
}
else {
printf("此处已经下子,不可再下棋,请重新下\n");
}
}
else {
printf("您输入的不符合棋盘规格,请重新输入下棋坐标\n");
}
}
}
//电脑下棋
void Computermove(char arr[row][col], int x, int y) {
while (1) {
int a = rand() % x;
int b = rand() % y;
if (arr[a][b] == ' ') {
arr[a][b] = '#';
print(arr, row, col);
break;
}
if (Is_full(arr) == 1) {
break;
}
}
}
//判断输赢
char Is_win(char arr[row][col]) {
for (int i = 0; i < row; i++) {
if (arr[i][0] == arr[i][1] && arr[i][0] == arr[i][2] && arr[i][0] != ' ') {
return arr[i][0];
}
}
for (int i = 0; i < col; i++) {
if (arr[0][i] == arr[1][i] && arr[1][i] == arr[2][i] && arr[0][i] != ' ') {
return arr[0][i];
}
}
if (arr[0][0] == arr[1][1] && arr[0][0] == arr[2][2]) {
return arr[0][0];
}
if (arr[2][0] == arr[1][1] && arr[0][0] == arr[0][2]) {
return arr[2][0];
}
if (Is_full(arr) == 1) {
return 'P';
}
return 'C';
}
//游戏本身
void fly() {
char rea = 'C';
//创建数组
char arr[row][col] = { 0 };
//初始化数组
Init_arr(arr, row, col);
//打印
print(arr,row,col);
//下棋步骤
while (rea=='C') {
//玩家下棋
Playermove(arr, row, col);
rea=Is_win(arr);
//电脑下棋
Computermove(arr, row, col);
rea=Is_win(arr);
}
//判断结果
if (rea == '*') {
printf("玩家获胜\n");
}
else if(rea=='#') {
printf("电脑获胜\n");
}
else {
printf("平局\n");
}
}
int main() {
int input = 0;
srand((unsigned int)time(NULL));
do {
menu();//目录
printf("请输入是否开始游戏:");
scanf_s("%d", &input);
switch (input) {
case 1:
fly();
break;
case 0:
printf("游戏终止");
break;
default:
printf("您的输入有误,请在1/0中重新输入\n");
break;
}
} while (input);
return 0;
}
不能在原有棋盘上来玩,每次电脑或者玩家走完棋子,必须重新打印棋盘,有能帮助解决的吗,谢谢
标签:arr,return,int,三子,求助,printf,col,row From: https://blog.51cto.com/u_13606048/6099072