如何save/load一个批处理文件游戏的变量to/from一个文本文件?

How to save/load variables of a batch file game to/from a text file?

为了好玩,我正在批量制作一个基本游戏,我想将游戏数据存储在一个文本文件中。我已经知道如何将文本添加到我的文本文件以及如何创建文本文件。但我不知道如何让它读取 文本文件中的行。我想让它一次读取一行,这样我就可以让它一次读取一行数据。

批处理文件游戏的环境变量加载和保存非常容易。

@echo off
setlocal EnableExtensions DisableDelayedExpansion

rem If the file with saved values for the batch game exists at all,
rem read the lines with variable name and associated value and set
rem them in current execution environment.

if exist "%APPDATA%\WebsterGames\%~n0.ini" for /F "usebackq delims=" %%I in ("%APPDATA%\WebsterGames\%~n0.ini") do set "%%I"

rem Define all environment variables not defined now because of there is no
rem file with variable names and values stored from a previous execution of
rem the batch file game like on first run of the batch file by the current
rem user or some variables are missing after load from file like on batch
rem file is updated in comparison to previous execution and has now more
rem variables and values to save/load than the previous version of the game.

if not defined Health set "Health=100"
if not defined Money  set "Money=50"
if not defined Player set "Player=Colton Webster"
rem ... and so on for the other variables.

rem Here is the code for the batch file game.

rem Save all variables with their values into a subdirectory with name
rem WebsterGames in the application data directory of the current user with
rem the file name being the batch file name with file extension being .ini.

md "%APPDATA%\WebsterGames" 2>nul
if exist "%APPDATA%\WebsterGames\" (
    set Health
    set Money
    set Player
    rem ... and so on for the other variables.
)>"%APPDATA%\WebsterGames\%~n0.ini"
endlocal

带有命令rem的行是remarks(注释),可以在真正的批处理文件中去掉。

为了了解使用的命令及其工作原理,请打开 command prompt window,在其中执行以下命令,并仔细阅读为每个命令显示的所有帮助页面。

  • call /? ... 解释 %~n0 ... 参数 0 的文件名,它是不带文件扩展名的批处理文件名。
  • echo /?
  • endlocal /?
  • for /?
  • if /?
  • md /?
  • rem /?
  • set /?
  • setlocal /?

阅读有关 Using command redirection operators 的 Microsoft 文档,了解 2>nul 的解释。