Python获取级别设置

2024-04-25 20:23:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在用python制作一个基于文本的游戏,在制作save游戏功能时遇到了一些麻烦。我找到了这个页面;Python text game: how to make a save feature?我把这些特性放进去了,但是我不确定如何让它达到玩家上一次的水平。你知道吗

示例:

# 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变量告诉代码播放器处于哪个级别,但是如何让它进入那个级别呢?你知道吗

抱歉-我不懂这个。游戏开始时有一个简短的介绍,然后要求一个新的或加载的游戏。你知道吗

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()。你知道吗


Tags: thetogame游戏newsaveaswith
1条回答
网友
1楼 · 发布于 2024-04-25 20:23:20

很难说您需要什么,但是最通用的方法是使用dill.dump_sessiondill.load_session,将整个python会话转储并加载到一个文件中,然后用所有活动对象重新启动它。基本上,当你完成(或开始?)在某种程度上,您可以将整个会话保存到一个文件中…然后如果您想在那里重新启动,只需使用`dill.load\U会话. 你知道吗

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])

相关问题 更多 >