c语言写一个代码五子棋游戏
时间: 2024-10-11 12:14:36 浏览: 32
五子棋游戏是一种经典的策略性游戏,下面是使用C语言实现五子棋游戏的一个简单示例代码:
```c
#include <stdio.h>
#define SIZE 15 // 棋盘大小
void init_board(char board[SIZE][SIZE]); // 初始化棋盘
void print_board(char board[SIZE][SIZE]); // 打印棋盘
int is_win(char board[SIZE][SIZE], char player, int x, int y); // 判断胜负
int player_move(char board[SIZE][SIZE], char player); // 玩家落子
int computer_move(char board[SIZE][SIZE], char computer); // 计算机落子
int main()
{
char board[SIZE][SIZE]; // 棋盘数组
char player = 'X'; // 玩家执棋
char computer = 'O'; // 计算机执棋
int turn = 0; // 回合数
init_board(board); // 初始化棋盘
while (1)
{
print_board(board); // 打印棋盘
if (player_move(board, player)) // 玩家落子
{
printf("Player %c win!\n", player);
break;
}
turn++;
if (turn == SIZE * SIZE) // 判断平局
{
printf("Tie game!\n");
break;
}
if (computer_move(board, computer)) // 计算机落子
{
printf("Computer %c win!\n", computer);
break;
}
turn++;
}
return 0;
}
void init_board(char board[SIZE][SIZE])
{
int i, j;
for (i = 0; i < SIZE; i++)
{
for (j = 0; j < SIZE; j++)
{
board[i][j] = ' ';
}
}
}
void print_board(char board[SIZE][SIZE])
{
int i, j;
printf(" ");
for (i = 0; i < SIZE; i++)
{
printf("%2d ", i + 1);
}
printf("\n");
for (i = 0; i < SIZE; i++)
{
printf("%2d ", i + 1);
for (j = 0; j < SIZE; j++)
{
printf("[%c]", board[i][j]);
}
printf("\n");
}
}
int is_win(char board[SIZE][SIZE], char player, int x, int y)
{
int i, j, k;
int count;
// 水平方向
count = 1;
for (i = x - 1; i >= 0 && board[y][i] == player; i--)
{
count++;
}
for (i = x + 1; i < SIZE && board[y][i] == player; i++)
{
count++;
}
if (count >= 5)
{
return 1;
}
// 竖直方向
count = 1;
for (i = y - 1; i >= 0 && board[i][x] == player; i--)
{
count++;
}
for (i = y + 1; i < SIZE && board[i][x] == player; i++)
{
count++;
}
if (count >= 5)
{
return 1;
}
// 左上到右下方向
count = 1;
for (i = x - 1, j = y - 1; i >= 0 && j >= 0 && board[j][i] == player; i--, j--)
{
count++;
}
for (i = x + 1, j = y + 1; i < SIZE && j < SIZE && board[j][i] == player; i++, j++)
{
count++;
}
if (count >= 5)
{
return 1;
}
// 左下到右上方向
count = 1;
for (i = x - 1, j = y + 1; i >= 0 && j < SIZE && board[j][i] == player; i--, j++)
{
count++;
}
for (i = x + 1, j = y - 1; i < SIZE && j >= 0 && board[j][i] == player; i++, j--)
{
count++;
}
if (count >= 5)
{
return 1;
}
return 0;
}
int player_move(char board[SIZE][SIZE], char player)
{
int x, y;
printf("Player %c's turn:\n", player);
do
{
printf("Enter row and column numbers: ");
scanf("%d %d", &y, &x);
x--;
y--;
if (board[y][x] != ' ')
{
printf("Invalid move, try again.\n");
continue;
}
board[y][x] = player;
break;
} while (1);
return is_win(board, player, x, y);
}
int computer_move(char board[SIZE][SIZE], char computer)
{
int x, y;
printf("Computer %c's turn:\n", computer);
do
{
x = rand() % SIZE;
y = rand() % SIZE;
if (board[y][x] != ' ')
{
continue;
}
board[y][x] = computer;
break;
} while (1);
return is_win(board, computer, x, y);
}
```
这个代码使用了一个二维数组来表示棋盘,并通过逐个遍历来判断是否有五子连珠,玩家使用`X`作为棋子,计算机使用`O`作为棋子。玩家和计算机每次都在没有被占用的空位上下棋。
阅读全文