c语言五子棋游戏源程序代码,C语言五子棋游戏源代码
时间: 2023-10-11 18:09:35 浏览: 118
C语言五子棋游戏源代码
下面是一个简单的C语言五子棋游戏源代码:
```
#include <stdio.h>
#include <stdlib.h>
#define ROW 15
#define COL 15
char board[ROW][COL]; // 棋盘
char player1 = 'X'; // 玩家1用X表示
char player2 = 'O'; // 玩家2用O表示
// 初始化棋盘
void init_board()
{
int i, j;
for (i = 0; i < ROW; i++) {
for (j = 0; j < COL; j++) {
board[i][j] = '+';
}
}
}
// 打印棋盘
void print_board()
{
int i, j;
printf(" ");
for (i = 0; i < COL; i++) {
printf("%d", i + 1);
}
printf("\n");
for (i = 0; i < ROW; i++) {
printf("%d", i + 1);
for (j = 0; j < COL; j++) {
printf("%c", board[i][j]);
}
printf("\n");
}
}
// 判断是否有五子连珠
int check_win(int row, int col)
{
int i, j, count;
char player = board[row][col];
// 横向判断
count = 0;
for (j = col - 4; j <= col; j++) {
if (j >= 0 && j + 4 < COL) {
if (board[row][j] == player && board[row][j+1] == player &&
board[row][j+2] == player && board[row][j+3] == player &&
board[row][j+4] == player) {
return 1;
}
}
}
// 纵向判断
count = 0;
for (i = row - 4; i <= row; i++) {
if (i >= 0 && i + 4 < ROW) {
if (board[i][col] == player && board[i+1][col] == player &&
board[i+2][col] == player && board[i+3][col] == player &&
board[i+4][col] == player) {
return 1;
}
}
}
// 斜向判断
count = 0;
for (i = row - 4, j = col - 4; i <= row && j <= col; i++, j++) {
if (i >= 0 && i + 4 < ROW && j >= 0 && j + 4 < COL) {
if (board[i][j] == player && board[i+1][j+1] == player &&
board[i+2][j+2] == player && board[i+3][j+3] == player &&
board[i+4][j+4] == player) {
return 1;
}
}
}
// 反斜向判断
count = 0;
for (i = row + 4, j = col - 4; i >= row && j <= col; i--, j++) {
if (i >= 0 && i - 4 < ROW && j >= 0 && j + 4 < COL) {
if (board[i][j] == player && board[i-1][j+1] == player &&
board[i-2][j+2] == player && board[i-3][j+3] == player &&
board[i-4][j+4] == player) {
return 1;
}
}
}
return 0;
}
// 玩家下棋
int player_move(char player)
{
int row, col;
while (1) {
printf("请输入要下棋的位置(行 列):");
scanf("%d %d", &row, &col);
if (row < 1 || row > ROW || col < 1 || col > COL) {
printf("输入的位置超出了棋盘范围,请重新输入!\n");
continue;
}
if (board[row-1][col-1] != '+') {
printf("此位置已有棋子,请重新输入!\n");
continue;
}
board[row-1][col-1] = player;
break;
}
return check_win(row-1, col-1);
}
// 游戏主循环
void game_loop()
{
int i, j, count = 0;
int result;
init_board();
print_board();
while (1) {
// 玩家1下棋
printf("玩家1(X):\n");
result = player_move(player1);
print_board();
if (result) {
printf("玩家1(X)获胜!\n");
break;
}
count++;
if (count == ROW * COL) {
printf("平局!\n");
break;
}
// 玩家2下棋
printf("玩家2(O):\n");
result = player_move(player2);
print_board();
if (result) {
printf("玩家2(O)获胜!\n");
break;
}
count++;
if (count == ROW * COL) {
printf("平局!\n");
break;
}
}
}
// 主函数
int main()
{
game_loop();
return 0;
}
```
这个代码实现了一个简单的五子棋游戏,可以通过命令行输入位置来下棋,判断胜负等等。但是这个代码还有很多可以改进的地方,比如界面可以更美观一些,可以加入悔棋、保存棋谱等功能,这些都可以根据自己的需要进行扩展。
阅读全文