0

好的。我正在设计一个基于文本的小型 RPG,但是,我需要让玩家能够保存游戏。我已经通过使用 pickle 模块成功地做到了这一点,但我试图让玩家能够通过使用这个我称之为“storypointe”的变量回到故事情节中的前一个点。基本上它会像这样工作:

if storypointe == 0:
    #Story, story, stuff happens here...
    storypointe += 1

if storypointe == 1:
    #More story, more story, more stuff happens here....

然后我会腌制变量storypointe,当游戏加载时(意味着使用pickle.load从我腌制到的任何文件中获取玩家统计数据和故事点),理想情况下它会从故事点对应的任何代码块开始。实际代码对作者和(也许)读者来说工作量太大,所以我编写了以下代码来模拟相同的环境并复制相同的问题。

storypointe = 0
jump = 0
spin = 0
dive = 0
roar = 0
savefile = "C:\Users\Sammu\The Folder\databin.txt"
import pickle, sys



def save ():
    with open(savefile, 'w') as savebin:
        actions = [jump, spin, dive, roar, storypointe]
        pickle.dump (actions, savebin)

def load ():
    with open(savefile, 'r') as loadbin:
        actions2 = pickle.load (loadbin)
        print actions2

        jump = actions2[0]
        spin = actions2[1]
        dive = actions2[2]
        roar = actions2[3]
        storypointe = actions2[4]


#Begin the code#

gameIO = raw_input ('Would you like to load previous game?\n>>> ')

if gameIO in ['yes', 'load', 'load game', 'Yes', 'Load', 'Load game']:
    load () 

if storypointe == 0:
    action = raw_input ('Would you like to jump, spin, dive or roar?\n>>> ')

    if action in ['jump', 'Jump']:
        jump += 1
        print jump

    if action in ['spin', 'Spin']:
        spin += 1
        print spin

    if action in ['dive', 'Dive']:
        dive += 1
        print dive

    if action in ['roar', 'Roar']:
        roar += 1
        print roar


    storypointe += 1

if storypointe == 1:
    print "\n\nYou have progressed to the next stage"
    save ()

所以如果storypointe等于actions2[4],那么这一定意味着它应该等于1。但这里的问题是它总是跟随第一个代码块,从

action = raw_input ('#yadayadayada')

代替:

print "You have progressed to the next stage"
4

2 回答 2

2

我认为您对 Python 作用域感到困惑。

在这里,您在模块级别创建了一个新变量:

storypointe = 0

[...]

但在这儿:

def load ():
    with open(savefile, 'r') as loadbin:
        actions2 = pickle.load (loadbin)

[...]
        storypointe = actions2[4]

您只需在函数中创建一个新的本地名称“storypointe” load。它不会影响storypointe模块级别的内容。我会将您的变量存储在一个类或一个字典中,这也将避免不得不做这些actions2[i]事情。

于 2012-08-19T16:14:07.667 回答
1

与其将您的叙述表达为一堆 if 语句,不如将其视为一个状态机,如果您将故事情节表达为一棵树,那么您可以轻松地将游戏中的路线存储为node树中下一个的参考,您还可以存储每个节点的引用(唯一),允许轻松保存和加载位置。

参见例如

class Node(object):
    def __init__(self, parent, children=None):
        self.parent = parent
        self.children = children or {}

story = {}
story['a'] = Node(None)
story['b'] = Node(a)
story['a'].children['b'] = story['b']
于 2012-08-19T16:09:59.277 回答