2015-07-21 93 views
0

我正在制作一个基于python的文本游戏,我在制作保存游戏功能时遇到了一些麻烦。我找到了这个页面; Python text game: how to make a save feature?我把这些功能放进去了,但我不确定如何让它达到最后一个玩家的水平。Python获取关卡设置

例子:

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

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

level_state变量告诉代码什么水平的球员是对的,但我怎么得到它去那个水平?

对不起 - 我是一个noob在这。游戏从简短的介绍开始,然后要求新的或加载的游戏。

load = input('New game or load game?\n') 
if load in ('new','new game'): 
    print('You have started a new game.') 
    time.sleep(2) 
    print("Don't forget to save before you quit.") 
    time.sleep(2) 
    level1() #this starts the game from the beginning 
elif load in ('load','load game'): 
    loadname = input('What is your name?\n') 
    with open('%s_game.dat' % loadname, 'rb') as f: 
     name, level = pickle.load(f) 

加载游戏后,我希望代码在保存在文件中的级别上恢复。例如,执行level1()或level2()。

+0

的'player'并在链接的问题'level_state'变量只是例子来说明如何保存和恢复两个变量。实现一个保存机制取决于你,完全取决于你的游戏细节以及它的状态。 –

+0

我为我的游戏改变了'player'和'level_state'变量 - 我放入的例子是变量是如何改变的。我只需要一种让变量进入保存级别的方法。 – jpeace

+2

我不可能告诉你该怎么做,因为你没有告诉我任何关于你的游戏的事情!什么是“水平”?它在你的代码中是如何定义和使用的?当问题缺乏答案所需的任何细节时,您无法期待答案。 –

回答

0

很难说出你需要什么,但是你可以做的最通用的事情是使用dill.dump_sessiondill.load_session来将你的整个python会话转储并加载到一个文件中,然后用你所有的对象重新启动它有生活。从本质上讲,每当你完成(或开始)一个关卡时,你可以将整个会话保存到一个文件中......然后如果你想重新启动,只需用`dill.load_session加载文件即可。

Python 2.7.10 (default, May 25 2015, 13:16:30) 
[GCC 4.2.1 Compatible Apple LLVM 5.1 (clang-503.0.40)] on darwin 
Type "help", "copyright", "credits" or "license" for more information. 
>>> 
>>> import dill 
>>> 
>>> squared = lambda x:x**2 
>>> import numpy 
>>> x = numpy.arange(10) 
>>> dill.dump_session('level1.pkl') 
>>> 

然后,退出并重新启动...

Python 2.7.10 (default, May 25 2015, 13:16:30) 
[GCC 4.2.1 Compatible Apple LLVM 5.1 (clang-503.0.40)] on darwin 
Type "help", "copyright", "credits" or "license" for more information. 
>>> import dill 
>>> dill.load_session('level1.pkl') 
>>> y = squared(x) 
>>> y 
array([ 0, 1, 4, 9, 16, 25, 36, 49, 64, 81])