用C语言写一个五子棋游戏在linux上运行
时间: 2024-03-12 12:50:20 浏览: 102
C语言写的五子棋游戏
好的,以下是一个简单的五子棋游戏的C语言实现,可以在Linux系统上运行。代码注释中有详细的解释。
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define ROW 15
#define COL 15
char board[ROW][COL]; // 棋盘
char player = 'X'; // 先手玩家
char winner = '\0'; // 胜者
void init_board(); // 初始化棋盘
void display_board(); // 显示棋盘
void play_game(); // 开始游戏
int is_valid_input(int row, int col); // 判断输入是否合法
int is_win(); // 判断是否胜利
int main()
{
init_board();
display_board();
play_game();
return 0;
}
void init_board()
{
int i, j;
for (i = 0; i < ROW; i++) {
for (j = 0; j < COL; j++) {
board[i][j] = '+';
}
}
}
void display_board()
{
int i, j;
printf(" ");
for (i = 0; i < COL; i++) {
printf("%d ", i);
}
printf("\n");
for (i = 0; i < ROW; i++) {
printf("%2d ", i);
for (j = 0; j < COL; j++) {
printf("%c ", board[i][j]);
}
printf("\n");
}
}
void play_game()
{
int row, col;
printf("Player %c goes first.\n", player);
while (1) {
printf("Player %c's turn. Enter row and column: ", player);
scanf("%d %d", &row, &col);
if (!is_valid_input(row, col)) {
printf("Invalid input. Try again.\n");
continue;
}
board[row][col] = player;
display_board();
if (is_win()) {
printf("Player %c wins!\n", winner);
break;
}
player = player == 'X' ? 'O' : 'X'; // 切换玩家
}
}
int is_valid_input(int row, int col)
{
// 判断输入是否在棋盘范围内,并且该位置是否为空
if (row < 0 || row >= ROW || col < 0 || col >= COL || board[row][col] != '+') {
return 0;
}
return 1;
}
int is_win()
{
int i, j, k;
// 判断横向是否有五个相同颜色的棋子
for (i = 0; i < ROW; i++) {
for (j = 0; j < COL - 4; j++) {
if (board[i][j] != '+' && board[i][j] == board[i][j+1] && board[i][j] == board[i][j+2] && board[i][j] == board[i][j+3] && board[i][j] == board[i][j+4]) {
winner = board[i][j];
return 1;
}
}
}
// 判断纵向是否有五个相同颜色的棋子
for (i = 0; i < ROW - 4; i++) {
for (j = 0; j < COL; j++) {
if (board[i][j] != '+' && board[i][j] == board[i+1][j] && board[i][j] == board[i+2][j] && board[i][j] == board[i+3][j] && board[i][j] == board[i+4][j]) {
winner = board[i][j];
return 1;
}
}
}
// 判断左斜向是否有五个相同颜色的棋子
for (i = 0; i < ROW - 4; i++) {
for (j = 0; j < COL - 4; j++) {
if (board[i][j] != '+' && board[i][j] == board[i+1][j+1] && board[i][j] == board[i+2][j+2] && board[i][j] == board[i+3][j+3] && board[i][j] == board[i+4][j+4]) {
winner = board[i][j];
return 1;
}
}
}
// 判断右斜向是否有五个相同颜色的棋子
for (i = 0; i < ROW - 4; i++) {
for (j = 4; j < COL; j++) {
if (board[i][j] != '+' && board[i][j] == board[i+1][j-1] && board[i][j] == board[i+2][j-2] && board[i][j] == board[i+3][j-3] && board[i][j] == board[i+4][j-4]) {
winner = board[i][j];
return 1;
}
}
}
return 0;
}
```
您可以将以上代码保存为一个名为`gobang.c`的文件,并使用gcc编译器进行编译,命令如下:
```bash
gcc gobang.c -o gobang
```
编译完成后,运行程序即可开始玩五子棋游戏。
阅读全文