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

使用StreamWriter/StreamReader的C#游戏存读程序的两个问题求助

问题解决方案

问题1:保存数据后无法终止程序

当前代码中,用户选择保存(输入Y)后没有退出逻辑,会继续回到主循环。需要修改History.WriteFile方法返回退出状态,再在主循环中根据该状态终止程序。

修改后的History类:

public class History
{
    public const char QUIT = 'Y';
    public const char CONTINUE = 'N';

    // 修改方法,返回是否需要退出程序
    public bool WriteFile(char[] arr)
    {
        // 使用using自动释放文件资源,无需手动Close
        using (FileStream sb = new FileStream("MyFile.txt", FileMode.OpenOrCreate))
        using (StreamWriter sw = new StreamWriter(sb))
        {
            Console.WriteLine($"If you want to save the data, enter {QUIT} | To continue, enter {CONTINUE}");
            char inputGameContinue = char.Parse(Console.ReadLine());
            if (inputGameContinue == QUIT)
            {
                sw.Write(arr);
                Console.WriteLine("The data is saved!");
                return true; // 返回true表示要退出
            }
            return false; // 返回false继续游戏
        }
    }

    // 修改ReadFile,读取存档并赋值给目标数组
    public void ReadFile(char[] targetArr)
    {
        string path = "MyFile.txt";
        Console.WriteLine("New game? >> 1 | Load saved data? >>2 ");
        int command = int.Parse(Console.ReadLine());
        if (command == 2 && File.Exists(path))
        {
            using (StreamReader sr = new StreamReader(path))
            {
                string savedContent = sr.ReadToEnd();
                // 确保存档长度和数组一致,避免越界
                if (savedContent.Length == targetArr.Length)
                {
                    savedContent.CopyTo(0, targetArr, 0, targetArr.Length);
                }
                Console.WriteLine("Loaded saved data successfully!");
            }
        }
    }
}

主程序writeRead.Main修改:

public static void Main(string[] args)
{
    InputClass inputClass = new InputClass();
    ArrayValue arrayValue = new ArrayValue();
    History history = new History();

    Console.WriteLine("Welcome to game!");
    Console.WriteLine("");
    // 传入数组,加载存档到数组中
    history.ReadFile(arrayValue.arr);

    bool shouldExit = false;
    do
    {
        inputClass.inputNumber();
        while (true)
        {
            if (arrayValue.arr[inputClass.input] == '#')
            {
                Console.WriteLine("{0} already marked '#'. Try another.", inputClass.input);
                inputClass.inputNumber();
            }
            else
            {
                arrayValue.arr[inputClass.input] = '#';
                arrayValue.printArray();
                // 获取是否退出的标志
                shouldExit = history.WriteFile(arrayValue.arr);
                break;
            }
        }

        // 用户选择退出则直接跳出循环
        if (shouldExit)
        {
            break;
        }

    } while (checkWhenFinish(arrayValue) != 1);

    if (!shouldExit)
    {
        Console.WriteLine("All letters are marked with '#'");
    }
    Console.Read();
}

问题2:加载存档后重复标记无提示

原代码中ReadFile仅打印存档内容,没有将存档数据赋值给arrayValue.arr,导致数组始终是初始状态,自然无法触发重复标记的错误提示。上面修改的ReadFile方法已解决该问题:读取存档内容后直接复制到目标数组,加载后数组状态与存档一致,再次输入已标记位置时会正确触发提示。

额外优化点

  1. 用using管理文件流,自动释放资源,避免手动Close引发的资源泄漏
  2. 将QUIT和CONTINUE改为const常量,符合代码规范
  3. 加载存档时增加文件存在判断,避免空文件报错
  4. 校验存档长度,防止数组越界

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 09:42:31