用C语言编写三子棋小游戏
程序员文章站
2024-03-18 13:44:58
...
三子棋游戏编写
#define row 3
#define col 3
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
void player(char arr[row][col], int rows, int cols)//玩家下棋
{
int i = 0;
int j = 0;
while (1)
{
printf("请输入坐标1到3下棋\n");
scanf_s("%d%d", &i, &j);//输入坐标
if (((i > 0) && (j <= 3)) && ((j > 0) && (i <= 3)))
{
if (arr[i - 1][j - 1] == ' ')
{
arr[i-1][j-1] = '*';
break;
}
else
{
printf("此格已有棋子");
}
}
else
{
printf("输入错误,请重新输入");
}
}
}
static int over(char arr[row][col], int rows, int cols)//判断棋盘是否还有空格
{
int i = 0;
int j = 0;
for(i=0;i<row;i++)
for (j = 0; j < col; j++)
{
if(arr[i][j] == ' ')
return 0;
}
return 1;
}
char win(char arr[row][col],int rows,int cols))//判断输赢
{
int i = 0;
for (i = 0; i < row; i++)
{
if ((arr[i][0] == arr[i][1]) && (arr[i][1] == arr[i][2]) && (arr[i][1] != ' '))
{
return arr[i][1];
}
}
for (i = 0; i < col; i++)
{
if ((arr[0][i] == arr[1][i]) && (arr[1][i] == arr[2][i]) && (arr[1][i] != ' '))
{
return arr[1][i];
}
}
if ((arr[0][0] == arr[1][1]) && (arr[2][2] == arr[1][1]) && (arr[1][1] != ' '))
{
return arr[1][1];
}
if ((arr[0][2] == arr[1][1]) &&( arr[2][0] == arr[1][1]) &&( arr[1][1] != ' '))
{
return arr[1][1];
}
if (over(arr, row, col))
{
return 'f';
}
return ' ';
}
void computer(char arr[row][col], int rows, int cols)//电脑下
{
srand((unsigned int )time(NULL));
while (1)
{
int i = rand() % 3;
int j = rand() % 3;
if (arr[i][j] == ' ')
{
arr[i][j] = '0';
break;
}
}
}
void display_board(char arr[row][col], int rows, int cols)//生成棋盘
{
int i = 0;
for (i = 0; i < row; i++)
{
printf(" %c | %c | %c \n", arr[i][0], arr[i][1], arr[i][2]);
if (i != 2)
printf("---|---|---\n");
}
}
void init_board(char arr[row][col], int rows, int cols)//初始化棋盘
{
int i = 0;
int j = 0;
for (i = 0; i < rows; i++)
{
for (j = 0; j < cols; j++)
{
arr[i][j] = ' ';
}
}
}
int menu()//菜单
{
printf("------------------------------\n");
printf("---------1、玩一玩------------\n");
printf("---------2、 滚蛋 ------------\n");
printf("------------------------------\n");
printf("请选择>");
int i = 0;
scanf_s("%d", &i);
return i;
}
void game()
{
int ret = 0;
char arr[row][col];
init_board(arr, row, col);
display_board(arr, row, col);
while (1)
{
printf("玩家下\n");
player(arr, row, col);
if ((ret = win(arr, row, col)) != ' ')
{
break;
}
display_board(arr, row, col);
printf("电脑下\n");
computer(arr, row, col);
if ((ret = win(arr, row, col)) != ' ')
{
break;
}
display_board(arr, row, col);
}
display_board(arr, row, col);
if (ret == '*')
{
printf("玩家赢\n");
}
else if (ret == '0')
{
printf("电脑赢\n");
}
else if (ret == 'f')
{
printf("平局\n");
}
}
int main()
{
printf("三子棋\n");
do {
int choose = menu();
switch (choose)
{
case 1:
game();
break;
case 2:
printf("退出游戏\n");
break;
default:
printf("输入错误\n");
}
} while (1);
system("pause");
return 0;
}