写出一个c语言编写的具有对局回放功能的五子棋小游戏
时间: 2024-03-23 15:43:35 浏览: 63
好的,以下是简单的五子棋小游戏的C语言代码,其中包含了对局回放功能:
```c
#include <stdio.h>
#include <stdlib.h>
#define ROW 15
#define COL 15
char board[ROW][COL]; // 棋盘
char player1 = 'X'; // 玩家1执黑棋
char player2 = 'O'; // 玩家2执白棋
// 初始化棋盘
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 < ROW; i++) {
printf("%d ", i);
}
printf("\n");
for (i = 0; i < ROW; i++) {
printf("%d ", i);
for (j = 0; j < COL; j++) {
printf("%c ", board[i][j]);
}
printf("\n");
}
}
// 判断是否有五子连珠
int check_win(char player) {
int i, j, count;
// 检查行
for (i = 0; i < ROW; i++) {
count = 0;
for (j = 0; j < COL; j++) {
if (board[i][j] == player) {
count++;
} else {
count = 0;
}
if (count == 5) {
return 1;
}
}
}
// 检查列
for (j = 0; j < COL; j++) {
count = 0;
for (i = 0; i < ROW; i++) {
if (board[i][j] == player) {
count++;
} else {
count = 0;
}
if (count == 5) {
return 1;
}
}
}
// 检查正斜线
for (i = 0; i < ROW-4; i++) {
for (j = 0; j < COL-4; j++) {
count = 0;
while (count < 5) {
if (board[i+count][j+count] == player) {
count++;
} else {
break;
}
}
if (count == 5) {
return 1;
}
}
}
// 检查反斜线
for (i = 0; i < ROW-4; i++) {
for (j = 4; j < COL; j++) {
count = 0;
while (count < 5) {
if (board[i+count][j-count] == player) {
count++;
} else {
break;
}
}
if (count == 5) {
return 1;
}
}
}
return 0;
}
// 玩家下棋
void player_move(char player) {
int row, col;
printf("玩家 %c 下棋:\n", player);
printf("请输入行号和列号(用空格隔开):");
scanf("%d %d", &row, &col);
while (board[row][col] != '+') {
printf("这个位置已经有棋子了,请重新输入:");
scanf("%d %d", &row, &col);
}
board[row][col] = player;
}
// 保存棋谱
void save_record(char player, int row, int col) {
FILE *fp;
fp = fopen("record.txt", "a");
fprintf(fp, "%c %d %d\n", player, row, col);
fclose(fp);
}
// 回放棋谱
void replay_game() {
FILE *fp;
char player;
int row, col;
fp = fopen("record.txt", "r");
while (fscanf(fp, "%c %d %d\n", &player, &row, &col) != EOF) {
board[row][col] = player;
print_board();
}
fclose(fp);
}
int main() {
int i, j, choice;
char player = player1;
init_board();
print_board();
while (!check_win(player1) && !check_win(player2)) {
player_move(player);
save_record(player, i, j);
print_board();
if (player == player1) {
player = player2;
} else {
player = player1;
}
}
printf("玩家 %c 获胜!\n", player);
printf("是否回放对局?(1表示是,0表示否):");
scanf("%d", &choice);
if (choice) {
replay_game();
}
return 0;
}
```
在这个程序中,玩家可以通过输入行号和列号来下棋。每当一方下完棋后,程序会检查是否有五子连珠,如果有,则宣布胜利,并询问是否回放对局。如果选择回放对局,则程序会从记录文件中读取每一步棋的位置,并打印出棋盘。
阅读全文