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

时间:2013-11-12 09:12:08

标签: python settings pygame config options

我现在在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。

提前致谢, Ilmiont

3 个答案:

答案 0 :(得分:3)

您可以使用configparser(ConfigParser for< Python 3)模块执行此操作。

来自documentation的示例(这使用Python 2. *语法,您必须使用configparser):

import ConfigParser

config = ConfigParser.RawConfigParser()
config.read('example.cfg')

a_float = config.getfloat('Section1', 'a_float')
an_int = config.getint('Section1', 'an_int')
print a_float + an_int

if config.getboolean('Section1', 'a_bool'):
    print config.get('Section1', 'foo')

import ConfigParser

config = ConfigParser.RawConfigParser()

config.add_section('Section1')
config.set('Section1', 'an_int', '15')
config.set('Section1', 'a_bool', 'true')
config.set('Section1', 'a_float', '3.1415')
config.set('Section1', 'baz', 'fun')
config.set('Section1', 'bar', 'Python')
config.set('Section1', 'foo', '%(bar)s is %(baz)s!')

with open('example.cfg', 'wb') as configfile:
    config.write(configfile)

答案 1 :(得分:2)

<强> myConfig.cfg:

[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

答案 2 :(得分:2)

python中的文件处理非常简单。而且,出于您的目的,我建议使用json

您可以编写类似

的代码
import os
import json

# Default settings
default_settings = {'FPS': 30,
                    'WINDOW_HEIGHT': 720,
                    'WINDOWS_WIDTH': 1280
                    }
handle_settings(default_settings)

def handle_settings(settings):
    if os.path.exists(os.path.join(os.getcwd(), 'config.cfg')):
        with open('config.cfg', 'r') as settings_file:
            settings = json.load(settings_file) # load from file
    else:
        with open('config.cfg', 'w') as settings_file:
            json.dump(settings, settings_file)  # write to file

# Changed settings as per user config
handle_settings(changed_settings)