You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++战舰游戏开发:文本文件数据加载至二维数组问题求助

解决战舰游戏中文件数据加载到二维数组的问题

我来帮你搞定这个文件加载的难题!先梳理下你代码里的小问题,再一步步实现完整的加载逻辑:

先修正代码里的基础错误

  1. 文件路径转义问题:C++里反斜杠\是转义字符,所以路径里的每个\都要写成\\,你的路径应该改成:
    ifstream file("C:\\Project Files\\Proj01_files\\in1.txt");
    
  2. 文件打开判断不完整:你写的file.is_...应该补全为file.is_open(),用来检查文件是否成功打开。

完整的文件加载到二维数组实现

假设你的棋盘是12x12的(和你定义的row=12对应),我们用二维字符数组来存储数据,完整代码如下:

#include "stdafx.h"
#include "openconfigfile.h"
#include <iostream>
#include <fstream>
#include <string>
using namespace std;

// 定义棋盘尺寸,方便后续修改
const int BOARD_SIZE = 12;

void openconfigfile() {
    // 初始化二维数组,用0填充默认值
    char guessBoard[BOARD_SIZE][BOARD_SIZE] = {0};
    ifstream file("C:\\Project Files\\Proj01_files\\in1.txt");

    // 检查文件是否成功打开
    if (!file.is_open()) {
        cerr << "无法打开用户猜测文件!" << endl;
        return;
    }

    string line;
    int currentRow = 0;
    // 逐行读取文件内容
    while (getline(file, line) && currentRow < BOARD_SIZE) {
        // 处理每行内容:长度不足补默认字符,过长则截断
        for (int col = 0; col < BOARD_SIZE; ++col) {
            if (col < line.size()) {
                guessBoard[currentRow][col] = line[col];
            } else {
                // 用空格填充长度不足的位置
                guessBoard[currentRow][col] = ' ';
            }
        }
        currentRow++;
    }

    // 可选:验证加载结果,打印数组
    cout << "加载的用户猜测棋盘:" << endl;
    for (int i = 0; i < BOARD_SIZE; ++i) {
        for (int j = 0; j < BOARD_SIZE; ++j) {
            cout << guessBoard[i][j] << " ";
        }
        cout << endl;
    }

    file.close();
}

船只位置文件的加载逻辑

加载船只位置文件的逻辑和上面完全一致,你可以封装成通用函数,避免重复代码:

void loadShipsBoard(char shipBoard[BOARD_SIZE][BOARD_SIZE]) {
    ifstream shipFile("C:\\Project Files\\Proj01_files\\ships.txt");
    if (!shipFile.is_open()) {
        cerr << "无法打开船只位置文件!" << endl;
        return;
    }

    string line;
    int currentRow = 0;
    while (getline(shipFile, line) && currentRow < BOARD_SIZE) {
        for (int col = 0; col < BOARD_SIZE; ++col) {
            shipBoard[currentRow][col] = (col < line.size()) ? line[col] : ' ';
        }
        currentRow++;
    }
    shipFile.close();
}

获胜判断的简单思路

加载完两个数组后,遍历每个位置对比即可:

  • 假设船只位置数组用'S'标记有船,用户猜测数组用'H'标记命中
  • 检查所有'S'对应的猜测位置是否都是'H',如果是则用户获胜

示例代码:

bool checkWin(char guessBoard[BOARD_SIZE][BOARD_SIZE], char shipBoard[BOARD_SIZE][BOARD_SIZE]) {
    for (int i = 0; i < BOARD_SIZE; ++i) {
        for (int j = 0; j < BOARD_SIZE; ++j) {
            // 存在未被命中的船,返回失败
            if (shipBoard[i][j] == 'S' && guessBoard[i][j] != 'H') {
                return false;
            }
        }
    }
    // 所有船都被命中,返回胜利
    return true;
}

内容的提问来源于stack exchange,提问作者123556666

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 03:09:22