用c语言或者c++编写一个五子棋游戏,且应给出相应提示且比赛中能随时存储当前棋局。
时间: 2024-03-09 17:47:59 浏览: 56
好的,以下是一个用 C++ 编写的五子棋游戏,实现了相应提示和能够随时存储当前棋局的功能。
```c++
#include <iostream>
#include <fstream>
#include <cstring>
using namespace std;
const int N = 15; // 棋盘大小
const int WIN = 5; // 获胜所需棋子数
char board[N][N]; // 棋盘
bool player; // 当前下子的玩家,true 表示先手,false 表示后手
bool saved; // 当前棋局是否已经保存
// 初始化棋盘
void init_board() {
memset(board, '.', sizeof(board));
}
// 显示棋盘
void print_board() {
cout << " ";
for (int i = 0; i < N; i++) {
cout << i << " ";
}
cout << endl;
for (int i = 0; i < N; i++) {
cout << i << " ";
for (int j = 0; j < N; j++) {
cout << board[i][j] << " ";
}
cout << endl;
}
}
// 判断是否下子越界
bool is_valid(int x, int y) {
return x >= 0 && x < N && y >= 0 && y < N;
}
// 判断是否下子位置已有棋子
bool is_empty(int x, int y) {
return board[x][y] == '.';
}
// 下子
void move(int x, int y) {
if (is_valid(x, y) && is_empty(x, y)) {
board[x][y] = player ? 'X' : 'O';
player = !player;
saved = false;
}
}
// 判断是否有获胜者
bool has_winner() {
char ch = player ? 'X' : 'O';
// 横向
for (int i = 0; i < N; i++) {
for (int j = 0; j < N - WIN + 1; j++) {
bool flag = true;
for (int k = 0; k < WIN; k++) {
if (board[i][j+k] != ch) {
flag = false;
break;
}
}
if (flag) return true;
}
}
// 纵向
for (int i = 0; i < N - WIN + 1; i++) {
for (int j = 0; j < N; j++) {
bool flag = true;
for (int k = 0; k < WIN; k++) {
if (board[i+k][j] != ch) {
flag = false;
break;
}
}
if (flag) return true;
}
}
// 对角线
for (int i = 0; i < N - WIN + 1; i++) {
for (int j = 0; j < N - WIN + 1; j++) {
bool flag = true;
for (int k = 0; k < WIN; k++) {
if (board[i+k][j+k] != ch) {
flag = false;
break;
}
}
if (flag) return true;
}
}
// 反对角线
for (int i = 0; i < N - WIN + 1; i++) {
for (int j = WIN - 1; j < N; j++) {
bool flag = true;
for (int k = 0; k < WIN; k++) {
if (board[i+k][j-k] != ch) {
flag = false;
break;
}
}
if (flag) return true;
}
}
return false;
}
// 保存当前棋局
void save_board() {
ofstream fout("board.txt");
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
fout << board[i][j];
}
fout << endl;
}
fout.close();
saved = true;
cout << "Current board saved." << endl;
}
// 加载上次存储的棋局
void load_board() {
ifstream fin("board.txt");
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
fin >> board[i][j];
}
}
fin.close();
saved = true;
cout << "Last saved board loaded." << endl;
}
int main() {
init_board();
player = true;
saved = true; // 初始时没有下子,已经保存
while (true) {
print_board();
int x, y;
cout << "Player " << (player ? "X" : "O") << " move (x y): ";
cin >> x >> y;
move(x, y);
if (has_winner()) {
print_board();
cout << "Player " << (player ? "O" : "X") << " wins!" << endl;
break;
}
if (!saved) {
char c;
cout << "Do you want to save the current board? (y/n): ";
cin >> c;
if (c == 'y' || c == 'Y') {
save_board();
} else {
saved = true;
}
}
}
return 0;
}
```
该程序在原有的基础上,增加了保存当前棋局和加载上次存储的棋局的功能。当有玩家获胜时,程序会提示胜利信息并结束游戏。通过按下 'y' 或 'Y' 键,玩家可以选择保存当前棋局。该程序将棋局保存在文件 "board.txt" 中,每个字符表示一个棋子。在加载上次存储的棋局时,程序将会从文件 "board.txt" 中读取棋子信息并恢复棋局。
阅读全文