三子棋游戏
一、首先编写菜单部分
void menu()
{
printf("*******************************\n");
printf("********** 1.play *************\n");
printf("********** 2.exit *************\n");
printf("*******************************\n");
}
二、编写输入逻辑
do
{
menu();
printf("请选择------>: ");
scanf("%d", &input);
switch(input)
{
case 0 :
break;
case 1:
game();
break;
default:
printf("输入操作错误,请重新输入\n");
break;
}
} while (input);
三、开始下棋
while (1)
{
PlayerMove(board, ROW, COL);
DisplayBoard(board, ROW, COL);
ret = IsWin(board, ROW, COL);
if (ret != 'C')
{
break;
}
ComputerMove(board, ROW, COL);
DisplayBoard(board, ROW, COL);
ret = IsWin(board, ROW, COL);
if (ret != 'C')
{
break;
}
}
void PlayerMove(char board[ROW][COL], int row, int col)
{
while (1)
{
int x, y;
printf("请输入要下棋的坐标 > ");
scanf("%d %d", &x, &y);
if (x >= 1 && x <= row && y >= 1 && y <= col)
{
if (board[x - 1][y - 1] == ' ')
{
board[x - 1][y - 1] = '*';
break;
}
else
printf("该位置已被占,请重新选择");
}
else
{
printf("输入坐标有误,请重新输入\n");
}
}
}
void ComputerMove(char board[ROW][COL], int row, int col)
{
printf("电脑下棋> \n");
while (1)
{
int x = rand() % row;
int y = rand() % col;
if (board[x][y] == ' ')
{
board[x][y] = '#';
break;
}
}
}
char IsWin(char board[ROW][COL], int row, int col)
{
for (int i = 0; i < row; i++)
{
if (board[i][0] != ' ' && board[i][0] == board[i][1] && board[i][1] == board[i][2])
return board[i][0];
}
for (int i = 0; i < col; i++)
{
if (board[0][i] != ' ' && board[0][i] == board[1][i] && board[1][i] == board[2][i])
return board[0][i];
}
if (board[0][0] != ' ' && board[0][0] == board[1][1] && board[1][1] == board[2][2])
return board[0][0];
if (board[0][2] != ' ' && board[0][2] == board[1][1] && board[1][1] == board[2][0])
return board[0][2];
if (IsFull(board, ROW, COL))
{
return 'Q';
}
return 'C';
}
总结:2023年9月10日,有志者事竟成!!!