2015-07-21 91 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])