#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<time.h>
#include<math.h>
enum OP
{
Exit,
Playgame
};
char arr[3][3] = { 0 };
int arr_size = 9;
void menu()
{
//菜单初始化
printf("**************************\n");
printf(" 0.Exit \n");
printf(" 1.Playgame \n");
printf("**************************\n");
}
void c_board()
{ //打印棋盘
printf(" | | \n");
for (int i = 0; i < 3; i++)
{
printf("_%c_|_%c_|_%c_\n", arr[i][0], arr[i][1], arr[i][2]);//棋子显示
if (i < 2)
{
printf(" | | \n");
}
}
}
void c_Pplay()
{
//人工下棋
int m = 0, n = 0;
printf("请输入棋子坐标:");
scanf("%d%d", &m, &n);
if (m<1 || m>3 || n<1 || n>3)
{
printf("不符合规则,请重新输入");
c_Pplay();
}
else
{
arr[m-1][n-1] = 'X';
arr_size--;
}
}
void c_Cplay()
{
//计算机
printf("计算机下棋:\n");
srand(time(NULL));
int m = rand() % 3;//随机数取0,1,2
int n = rand() % 3;
while (arr[m][n] != ' ')
{
m = rand() % 3;//随机数取0,1,2
n = rand() % 3;
}
arr[m][n] = '*';
arr_size--;
}
int c_win()
{ //玩家赢判断
for (int m = 0; m < 3; m++)
{
if ((arr[m][0] == 'X') && (arr[m][1] == 'X') && (arr[m][2] == 'X'))
{
return 1;
}
else if ((arr[0][m] == 'X') && (arr[1][m] == 'X') && (arr[2][m] == 'X'))
{
return 1;
}
}
if (((arr[0][0] == 'X') && (arr[1][1] == 'X') && (arr[2][2] == 'X')) || ((arr[0][2] == 'X') && (arr[1][1] == 'X') && (arr[2][0] == 'X')))
{
return 1;
}
//电脑赢结果判断
for (int m = 0; m < 3; m++)
{
if ((arr[m][0] == '*') && (arr[m][1] == '*') && (arr[m][2] == '*'))
{
return -1;
}
else if ((arr[0][m] == '*') && (arr[1][m] == '*') && (arr[2][m] == '*'))
{
return -1;
}
}
if (((arr[0][0] == '*') && (arr[1][1] == '*') && (arr[2][2] == '*')) || ((arr[0][2] == '*') && (arr[1][1] == '*') && (arr[2][0] == '*')))
{
return -1;
}
//平局
if (arr_size == 0)
return 2;
}
int main()
{
int num = 0;
menu();
printf("请选择 :");
scanf("%d", &num);
//棋盘初始化清空
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3;j++)
{
arr[i][j] = ' ';
}
}
switch (num)
{
case Exit:
exit(0);
case Playgame:
while (1)
{
c_board();
if (c_win() == -1 || c_win() == 1 || c_win() == 2)
{
break;
}
c_Pplay();
c_board();
if (c_win() == -1 || c_win() == 1 || c_win() == 2)
{
break;
}
c_Cplay();
}
default:
break;
}
if (c_win() == -1)
{
printf("计算机赢了!");
}
else if (c_win() == 1)
{
printf("你赢了!");
}
else
{
printf("平局!");
}
system("pause");
return 0;
}
【C语言】三子棋游戏
最新推荐文章于 2023-02-06 20:25:48 发布