python - 在 Python 中创建游戏配置/选项 (config.cfg) 文件

标签 python pygame config settings

我现在在 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 的配置解析器

如果您正在寻找更灵活的东西,请尝试 YAMLPyYAML

关于python - 在 Python 中创建游戏配置/选项 (config.cfg) 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19925056/

相关文章:

python - 在 Python 中打开文件以进行独占访问的最佳方法是什么?

python - 为什么绘制一个具有很厚边框的 PyGame 矩形会绘制一个加号形状?

ios - 是否可以创建配置文件 "on"iphone?

c# - 当 exe 更改位置时应用程序设置重置

asp.net - TicketCompatibilityMode 上的 IIS 配置错误

python - Google App Engine 和 Cloud SQL : Lost connection to MySQL server at 'reading initial communication packet' SQL 2nd Gen

python - 遍历多维列表

python - 带 spacy 的德语小写词形还原

python - Pygame 简单程序测试显示卡住

python pygame 背景图像随屏幕大小变化