Python文本游戏:如何制作保存功能?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18606097/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 11:13:52  来源:igfitidea点击:

Python text game: how to make a save feature?

pythonsave

提问by Nick56x

I am in the process of making a text based game with Python, and I have the general idea down. But I am going to make the game in depth to the point where, it will take longer than one sitting to finish it. So I want to be able to make the game to where, on exit, it will save a list of variables (player health, gold, room place, etc) to a file. Then if the player wants to load the file, they go to the load menu, and it will load the file.

我正在用 Python 制作一个基于文本的游戏,我已经有了大致的想法。但是我要让游戏深入到一个地步,比一个人坐下来完成它需要更长的时间。所以我希望能够让游戏在退出时将变量列表(玩家健康、黄金、房间位置等)保存到文件中。然后如果播放器要加载文件,他们会转到加载菜单,它会加载文件。

I am currently using version 2.7.5 of Python, and am on Windows.

我目前使用的是 Python 2.7.5 版,并且在 Windows 上。

回答by user2549846

I think you can just use a txt file to record the things you need in the game,just use file() and open() function.Or you can use the sqlite3 module in python to save your record. just try :

我觉得你可以用一个txt文件来记录你在游戏中需要的东西,只需使用file()和open()函数。或者你可以使用python中的sqlite3模块来保存你的记录。你试一试 :

import sqlite3

导入 sqlite3

holp that helps. :)

帮助。:)

here is an example to use sqlite3 in python:

这是在python中使用sqlite3的示例:

just change as you want to save to the file:

只需更改您想要保存到文件的内容:

    import sqlite3
    cx=sqlite3.connect("stu.db") # get a connect object
    cu=cx.cursor() # get a cursor


    cu.execute("""create table stu
    (
            number char(10) primary key not null,
            name char(10) not null,
            sex int not null default 1 check (sex in (1,0)),
            major char(5) not null,
            mark int not null,
            birthday datetime not null
    )""")

    cu.execute("insert into stu values ('010011','Jim',1,'computer',58,'1989-01-01')")
    cu.execute("insert into stu values ('080011','Jimmy',1,'computer',59,'1990-02-25')")
    cu.execute("insert into stu values ('080001','Hyman',1,'computer',58,'1989-10-01')")
    cu.execute("insert into stu values ('081102','Zimmer',1,'computer',60,'1990-01-01')")
    cu.execute("insert into stu values ('081103','Hans',1,'computer',58,'1991-2-08')")
    cu.execute("insert into stu values ('090210','Lily',0,'computer',58,'1990-05-31')")
    cu.execute("insert into stu values ('090125','Mary',0,'computer',59,'1992-07-08')")
    cu.execute("insert into stu values ('080136','Tom',1,'computer',58,'1989-01-01')")
    cu.execute("insert into stu values ('090012','Lisa',0,'software',59,'1990-04-05')")
    cu.execute("insert into stu values ('080028','Lee',0,'software',58,'1990-05-07')")

    cx.commit()# commit the sql

    cu.execute("select * from stu") #get the all records
    cu.fetchone() # fetch one
    cu.execute("select mark from stu where name='Jim'")

    cu.execute("""select name=
            case
                    when mark >55 and mark<60 then 'ok'
                    when mark=60 then 'good'
                    else 'unkown'
            end
            from stu""")

    cu.execute("""update stu      
            set major='software'
                    where name='Jim'
    """)# update one

    cu.execute("""select min(mark) from stu""")#get the min
    cu.execute("select count(*) from stu") #get the number of stu
    cu.execute("select avg(mark) from stu") #get ave
    cu.execute("select * from stu where name='Jim'")#look jim
    cu.execute("select * from stu where mark=60")
    cu.execute("select * from stu where name like 'Li__'")
    cu.execute("select * from stu where Birthday not between '1989-01-01' and '1989-12-31'") 


    cx.commit()

    res=cu.fetchall()#get all 
    #cu.fetchone()
    for i in res:
            print i

    cu.close()
    cx.close()

Or I think, If your game is not very Complex, Just use file() function.

或者我认为,如果您的游戏不是很复杂,只需使用 file() 函数。

回答by Shashank

First, don't overthink this. You don't need to use anything complicated. As a preliminary step, research basic file input/output in python.

首先,不要想太多。你不需要使用任何复杂的东西。作为第一步,研究python中的基本文件输入/输出。

Second, I'm assuming you have a player class in your game? Or possibly an overall class which keeps track of game state. Well have that class store default values for your variables like health, gold etc. Then have a method which can modify this class like def load_stats(player):or def load_stats(game):something. and have it read in from a save file which can have any format you like and modify the variables of your player/game state.

其次,我假设你的游戏中有一个玩家类?或者可能是一个跟踪游戏状态的整体类。那么有类本店默认值的变量,如医疗,黄金等,然后有可以修改这个类像一个方法def load_stats(player):def load_stats(game):什么的。并从保存文件中读取它,该文件可以具有您喜欢的任何格式并修改您的玩家/游戏状态的变量。

First test loading of game files and make sure you can get it so that your player class gets modified.

首先测试游戏文件的加载并确保您可以获取它以便修改您的播放器类。

Then all you have to do is add a save game feature that lets you output these variables back to a file in your directory system somewhere.

然后您所要做的就是添加一个保存游戏功能,让您可以将这些变量输出回目录系统中某处的文件。

Try doing this and let me know if you need any help afterwards.

尝试这样做,如果您事后需要任何帮助,请告诉我。

回答by fjarri

If I understand the question correctly, you are asking about a way to serialize objects. The easiest way is to use the standard module pickle:

如果我正确理解了这个问题,那么您是在询问一种序列化对象的方法。最简单的方法是使用标准模块pickle

import pickle

player = Player(...)
level_state = Level(...)

# saving
with open('savefile.dat', 'wb') as f:
    pickle.dump([player, level_state], f, protocol=2)

# loading
with open('savefile.dat', 'rb') as f:
    player, level_state = pickle.load(f)

Standard Python objects and simple classes with any level of nesting can be stored this way. If your classes have some nontrivial constructors it may be necessary to hint pickleat what actually needs saving by using the corresponding protocol.

具有任何嵌套级别的标准 Python 对象和简单类都可以通过这种方式存储。如果您的类具有一些重要的构造函数,则可能pickle需要通过使用相应的协议来提示实际需要保存的内容。

回答by Mariano Sorgente

To add to Bogdan's answer, an easier to understand way to just be to store a dictionary with all your data. So if you have this:

要添加到 Bogdan 的答案,一种更容易理解的方法是将所有数据存储在字典中。所以如果你有这个:

import pickle
data = {'health':100, 'gold': 1560, 'name': 'mariano'}

you would just do:

你会这样做:

with open('savefile', 'w') as f:
    pickle.dump(data, f)

with open('savefile') as f:
    data = pickle.load(f)

and it should load.

它应该加载。

回答by James Bond

I have been working on something like this. It uses JSON for ease of use and scalablity. here it is:

我一直在做这样的事情。它使用 JSON 来实现易用性和可扩展性。这里是:

   import json
//save files below
def save_file():
//to enter a name for your file
//if you don't want to just make it a string
    save_name = input("savename: ")
    path = 'path_to_dir{0}.json'.format(save_name)
    data = {
        'name': save_name
    }
    with open(path, 'w+') as f:
        json.dump(data, f)


def load_file():
    load_name = save_name
   path_two = 'path_to_dir{0}.json'.format(load_name)
    with open(path_two, 'r') as f:
        j = json.load(f)
        name = str(j['name'])

this is the file save system i use in all my projects. i hope it helps

这是我在所有项目中使用的文件保存系统。我希望它有帮助

回答by Sparkletinkercat

def cache (filename):
    global c,code
    try:
        c = open(filename + " cache.txt", "rt")
        code = eval(c.read())
        c.close()
    except:
        c = open(filename + " cache.txt", "wt")
        c.write("{'': ''}")
        c.close()

        c = open(filename + " cache.txt", "rt")
        code = eval(c.read())
        c.close()

def find(filename,variable):
    global c,code
    c = open(filename + " cache.txt", "rt")
    code = eval(c.read())
    c.close()
    variable2 = code.get(variable)
    return variable2

def store(filename,variable,info):
    global c,code
    code[variable] = info
    c = open(filename + " cache.txt", "wt")
    c.write(str(code))
    c.close()

def clearcache(filename):
    c = open(filename + " cache.txt", "w")
    c.write("{'': ''}")
    c.close()

file = "DungeonQuest"

#Creates the file for storage
cache (file);

#Stores a variable for later use
x = 15
store(file,"x",x);

#Finds a stored variable
x = find(file,"x");

#Clears all stored variables in the cache
clearcache(file);

Here is some of my own code for storing variables to an external text file. The only problem is that you have to store each one individually and find each one separately. I used this for my own python game dungeon quest and it seems to work just fine

这是我自己的一些用于将变量存储到外部文本文件的代码。唯一的问题是您必须单独存储每个并单独查找每个。我将它用于我自己的 python 游戏地牢任务,它似乎工作得很好