Python游戏保存文件 [英] Python game save file

查看:161
本文介绍了Python游戏保存文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用Python编写游戏,现在我需要一种方法来保存玩家的进度.我当时想让脚本创建一个文本文件,并在玩家退出游戏时写几行(用于存储统计变量和房间号).但是我还需要它来检查该文件是否在启动时退出,如果是,则将存储的值应用于相应的变量.有人可以帮忙吗?

I'm writing a game in Python and have come to the point where I need a way of saving the players progress. I was thinking of having the script create a text file and write a couple of lines (for storing stat variables, and the room number) when the player exits the game. But I also need it to check if that file exits on startup and, if so, apply the stored values to the corresponding variables. Can anybody help?

推荐答案

此处有两个不同的问题:

Two different issues here:

  1. 文件中存储什么以及如何存储
  2. 何时存储和何时加载的逻辑

第一个问题更通用,因此更易于解决.您在这里有几个不错的选择:一种是在Windows .ini上使用Python的ConfigParser类-类似于配置文件.或者,您可以使用pickle来简单地转储某种类型的配置/设置数据结构(可能是嵌套字典).然后是内置的SQLite绑定.还有其他选项-取决于您想要的复杂程度.

The first issue is simpler to address as it's more generic. You have several good options here: one is using Python's ConfigParser class for Windows .ini - like configuration files. Alternatively you can use pickle to simply dump some sort of a configuration/settings data structure (may be a nested dict). Then there's the built-in SQLite binding. There are other options - it all depends on the level of complexity you want.

第二个问题更特定于您的应用程序.您可以尝试在启动时打开配置文件,如果存在,请阅读其内容.以后,您可以定期将设置/进度存储到其中.提建议:始终将 complete 设置集保持在一致的数据结构中-即使在读取配置文件时只有一部分设置位于配置文件中(由于某些原因) ,并为您的设置设置默认值.

The second issue is more specific to your application. You can try to open the config file on startup and if it's there, read its contents. Later, you can periodically store the settings/progress into it. A word of advice: keep the complete set of settings in a consistent data structure at all times - even if only part of the settings are in the config file when you're reading it (for some reason), have default values for your settings.

这篇关于Python游戏保存文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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