用C语言写个五子棋代码
时间: 2024-05-24 14:11:25 浏览: 48
用C语言写的五子棋游戏代码
#include <stdio.h>
#include <stdlib.h>
#define ROW 15
#define COL 15
void draw_board(char board[ROW][COL]);
int check_win(char board[ROW][COL], int row, int col);
void player_move(char board[ROW][COL]);
void computer_move(char board[ROW][COL]);
int main()
{
char board[ROW][COL] = {0}; // 初始化棋盘
int winner = 0; // 0表示没有胜者,1表示玩家胜利,-1表示电脑胜利
draw_board(board); // 初始化棋盘
while (1)
{
player_move(board); // 玩家走棋
winner = check_win(board, ROW, COL); // 判断胜负
if (winner != 0) // 如果有胜者,结束游戏
{
break;
}
computer_move(board); // 电脑走棋
winner = check_win(board, ROW, COL); // 判断胜负
if (winner != 0) // 如果有胜者,结束游戏
{
break;
}
}
if (winner == 1)
{
printf("You win!");
}
else if (winner == -1)
{
printf("Computer win!");
}
return 0;
}
// 绘制棋盘
void draw_board(char board[ROW][COL])
{
int i, j;
printf(" ");
for (i = 0; i < COL; i++)
{
printf("%2d", i + 1);
}
printf("\n");
for (i = 0; i < ROW; i++)
{
printf("%2d", i + 1);
for (j = 0; j < COL; j++)
{
if (board[i][j] == 0)
{
printf(" .");
}
else if (board[i][j] == 1)
{
printf(" o");
}
else if (board[i][j] == -1)
{
printf(" x");
}
}
printf("\n");
}
}
// 判断胜负
int check_win(char board[ROW][COL], int row, int col)
{
int i, j;
int count = 0; // 连续棋子数
// 判断每一行是否有五个连续棋子
for (i = 0; i < row; i++)
{
for (j = 0; j < col; j++)
{
if (board[i][j] == 1)
{
count++;
}
else
{
count = 0;
}
if (count >= 5)
{
return 1;
}
}
count = 0;
}
// 判断每一列是否有五个连续棋子
for (j = 0; j < col; j++)
{
for (i = 0; i < row; i++)
{
if (board[i][j] == 1)
{
count++;
}
else
{
count = 0;
}
if (count >= 5)
{
return 1;
}
}
count = 0;
}
// 判断左上到右下的斜线是否有五个连续棋子
for (i = 0; i < row; i++)
{
for (j = 0; j < col; j++)
{
if (i + 4 < row && j + 4 < col)
{
if (board[i][j] == 1 && board[i + 1][j + 1] == 1 && board[i + 2][j + 2] == 1 && board[i + 3][j + 3] == 1 && board[i + 4][j + 4] == 1)
{
return 1;
}
}
}
}
// 判断左下到右上的斜线是否有五个连续棋子
for (i = 0; i < row; i++)
{
for (j = 0; j < col; j++)
{
if (i + 4 < row && j - 4 >= 0)
{
if (board[i][j] == 1 && board[i + 1][j - 1] == 1 && board[i + 2][j - 2] == 1 && board[i + 3][j - 3] == 1 && board[i + 4][j - 4] == 1)
{
return 1;
}
}
}
}
return 0;
}
// 玩家走棋
void player_move(char board[ROW][COL])
{
int row, col;
printf("Please enter row and col (e.g. 3 4): ");
scanf("%d %d", &row, &col);
while (board[row - 1][col - 1] != 0)
{
printf("This position is occupied, please enter again: ");
scanf("%d %d", &row, &col);
}
board[row - 1][col - 1] = 1;
draw_board(board);
}
// 电脑走棋
void computer_move(char board[ROW][COL])
{
int row, col;
printf("Computer move:\n");
while (1)
{
row = rand() % ROW;
col = rand() % COL;
if (board[row][col] == 0)
{
board[row][col] = -1;
break;
}
}
draw_board(board);
}
阅读全文