[英]Python text game: how to make a save feature?
我正在用 Python 制作一个基于文本的游戏,我已经有了大致的想法。 但是我要让游戏深入到一个地步,比一个人坐下来完成它需要更长的时间。 所以我希望能够让游戏在退出时将变量列表(玩家健康、黄金、房间位置等)保存到文件中。 然后如果播放器要加载文件,他们会转到加载菜单,它会加载文件。
我目前使用的是 Python 2.7.5 版,并且在 Windows 上。
如果我正确理解了这个问题,那么您是在询问一种序列化对象的方法。 最简单的方法是使用标准模块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)
具有任何嵌套级别的标准 Python 对象和简单类都可以通过这种方式存储。 如果您的类具有一些重要的构造函数,则可能需要通过使用相应的协议来提示pickle
实际需要保存的内容。
首先,不要想太多。 你不需要使用任何复杂的东西。 作为第一步,研究python中的基本文件输入/输出。
其次,我假设你的游戏中有一个玩家类? 或者可能是一个跟踪游戏状态的整体类。 好吧,让该类为您的变量(如健康、黄金等)存储默认值。然后有一个方法可以修改此类,例如def load_stats(player):
或def load_stats(game):
东西。 并从保存文件中读取它,该文件可以具有您喜欢的任何格式并修改您的玩家/游戏状态的变量。
首先测试游戏文件的加载并确保您可以获取它以便修改您的播放器类。
然后您所要做的就是添加一个保存游戏功能,让您可以将这些变量输出回目录系统中某处的文件。
尝试这样做,如果您事后需要任何帮助,请告诉我。
要添加到 Bogdan 的答案,一种更容易理解的方法是将所有数据存储在字典中。 所以如果你有这个:
import pickle
data = {'health':100, 'gold': 1560, 'name': 'mariano'}
你会这样做:
with open('savefile', 'w') as f:
pickle.dump(data, f)
with open('savefile') as f:
data = pickle.load(f)
它应该加载。
我觉得你可以用一个txt文件来记录你在游戏中需要的东西,只需使用file()和open()函数。或者你可以使用python中的sqlite3模块来保存你的记录。 试一试 :
导入 sqlite3
帮助。 :)
这是在python中使用sqlite3的示例:
只需更改您想要保存到文件的内容:
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()
或者我认为,如果您的游戏不是很复杂,只需使用 file() 函数。
我一直在做这样的事情。 它使用 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'])
这是我在所有项目中使用的文件保存系统。 我希望它有帮助
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);
这是我自己的一些用于将变量存储到外部文本文件的代码。 唯一的问题是您必须单独存储每个并单独查找每个。 我将它用于我自己的 python 游戏地牢任务,它似乎工作得很好
好吧,我用 Python 制作了一个点击游戏,没有使用泡菜或其他东西。 1. 制作一个关卡变量,在关卡开始时会发生变化。
def level1():
level = 1
#this is the level1 command part
with open ("level.txt", "w") as level_data:
level_data.write(str(level))
#not the level1 command part
import os
data_check = os.path.exists("level.txt")
if data_check == True:
data_load = open("level.txt", "r")
level = int(data_load.read())
else:
level = 0
我在我的游戏中也使用了这样的东西:
with open("game_data.txt", "w") as f:
f.write(str(amount_of_gold) + "\n")
现在这将返回一个list()
。 然后,你想在里面写点东西。 您可以使用write()
函数执行此操作。 注意:不要忘记str()
并在每行后添加一个\\n
。 这是保存数据。 现在阅读:
import os
if os.path.getsize("game_data.txt") > 0:
with open("game_data.txt", "r") as f:
data = f.read().splitlines()
amount_of_gold = int(data[0])
等等... 注意:不要忘记使用int()
。 您必须使用os.path.getsize()
否则游戏将读取一个空文件(即当玩家第一次启动游戏时)并且您将收到一个Index Error
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.