Python text game: how to make a save feature?

2019-02-03 20:55发布

问题:

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.

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

回答1:

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:

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 pickle at what actually needs saving by using the corresponding protocol.



回答2:

First, don't overthink this. You don't need to use anything complicated. As a preliminary step, research basic file input/output in 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.

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.



回答3:

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:

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.



回答4:

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 :

import sqlite3

holp that helps. :)

here is an example to use sqlite3 in python:

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','Jack',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.



回答5:

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

   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



标签: python save