如何将批处理文件游戏的变量保存到文本文件或从文本文件加载? [英] How to save/load variables of a batch file game to/from a text file?

查看:34
本文介绍了如何将批处理文件游戏的变量保存到文本文件或从文本文件加载?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

推荐答案

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

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

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

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

有关2>nul的说明,请阅读关于Using command redirection operators的Microsoft文档。

这篇关于如何将批处理文件游戏的变量保存到文本文件或从文本文件加载?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆