用c语言 写一个 五子棋游戏
时间: 2024-05-28 21:13:09 浏览: 167
很高兴为您服务!我可以为您提供一个简单的五子棋游戏的C语言代码:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int board[3][3] = {0}; // 0表示没有落子,1表示黑棋,2表示白棋
int player = 1; // 当前落子的玩家,1表示黑棋,2表示白棋
int row, col; // 落子的行列号
int i, j; // 循环变量
int flag = 0; // 游戏结束标志,0表示游戏未结束,1表示黑棋赢,2表示白棋赢
// 开始游戏
while (flag == 0)
{
// 打印棋盘
printf("\n\n");
for (i = 0; i < 3; i++)
{
for (j = 0; j < 3; j++)
{
printf("%d ", board[i][j]);
}
printf("\n");
}
// 读取玩家落子
printf("\nPlayer %d, please enter row and col:", player);
scanf("%d %d", &row, &col);
// 检查落子是否合法
if (board[row][col] == 0)
{
board[row][col] = player;
}
else
{
printf("Error! Please enter again.");
continue;
}
// 检查游戏是否结束
if ((board[0][0] == board[0][1] && board[0][1] == board[0][2] && board[0][2] != 0) ||
(board[1][0] == board[1][1] && board[1][1] == board[1][2] && board[1][2] != 0) ||
(board[2][0] == board[2][1] && board[2][1] == board[2][2] && board[2][2] != 0) ||
(board[0][0] == board[1][0] && board[1][0] == board[2][0] && board[2][0] != 0) ||
(board[0][1] == board[1][1] && board[1][1] == board[2][1] && board[2][1] != 0) ||
(board[0][2] == board[1][2] && board[1][2] == board[2][2] && board[2][2] != 0) ||
(board[0][0] == board[1][1] && board[1][1] == board[2][2] && board[2][2] != 0) ||
(board[0][2] == board[1][1] && board[1][1] == board[2][0] && board[2][0] != 0))
{
flag = player;
}
// 改变玩家
if (player == 1)
player = 2;
else
player = 1;
}
// 打印棋盘
printf("\n\n");
for (i = 0; i < 3; i++)
{
for (j = 0; j < 3; j++)
{
printf("%d ", board[i][j]);
}
printf("\n");
}
// 输出游戏结果
if (flag == 1)
printf("\nBlack win!\n");
else
printf("\nWhite win!\n");
return 0;
}
阅读全文