如何将批处理文件游戏的变量保存到文本文件或从文本文件加载变量? [已关闭]

问题描述 投票:0回答:1

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

windows batch-file cmd text-files
1个回答
0
投票

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

@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
的行是备注(注释),可以在实际批处理文件中删除。

要了解所使用的命令及其工作原理,请打开命令提示符窗口,执行以下命令,并完整、仔细地阅读每个命令显示的帮助页面。

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

阅读有关 使用命令重定向运算符的 Microsoft 文档,了解

2>nul
的说明。

© www.soinside.com 2019 - 2024. All rights reserved.