我现在在 Python 和 Pygame 方面比较有经验,可以创建一些基本的 2D 图形游戏。现在我希望能够创建一个配置文件 (config.cfg),以便我可以永久存储游戏的设置和配置,例如窗口宽度和高度以及 FPS 计数。该文件应垂直阅读,例如
FPS = 30
WINDOW_WIDTH = 1280
WINDOW_HEIGHT = 720
etc.
显然,我需要能够从我的游戏中读取(和创建)这个文件,并在不触及文本标签的情况下编辑值。尽管我曾在 Python 中使用过文本文件,但我之前没有接触过这些东西,所以我需要尽可能多的指导。我在 Windows 8 Pro x64 上使用 Python 3.3 和 Pygame 1.9。
最佳答案
我的配置文件:
[info]
Width = 100
Height = 200
Name = My Game
在 python 中解析:
import ConfigParser
configParser = ConfigParser.RawConfigParser()
configFilePath = os.path.join(os.path.dirname(__file__), 'myConfig.cfg')
configParser.read(configFilePath)
gameName = configParser.get("info","Name")
gameWidth = configParser.get("info","Width")
gameHeight = configParser.get("info","Height")
configParser.set('info', 'Name', 'newName')
config.write(configFilePath)
解释:
首先我们创建了一个 ConfigParser
的实例,然后我们告诉实例 .cfg
文件所在的位置,之后它只是读取。
第二部分我们负责写作。
更多信息:
来自 Docs 的配置解析器
关于python - 在 Python 中创建游戏配置/选项 (config.cfg) 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19925056/