-1

我只是想知道是否可以为文本游戏中的帮助功能删除一些冗余。我现在拥有的是在每个函数提示 = 0 的开头,每次输入无效答案时提示都会增加一个。

这是我目前拥有的(在每个函数中):

hint = 0
    valid = False
    while valid == False:

        print "Would you like to begin?"

        begin = raw_input("> ")

        if "yes" in begin:
            valid = True
            print "Great!\n"
            start.start()
        elif "no" in begin:
            quit.quit()
        else:
            error.error(1)
            hint += 1

        if hint > 4:
            print "\nYou may choose from \"yes\" and \"no\"."
4

2 回答 2

0
from itertools import count
for hint in count()
    print "Would you like to begin?"

    begin = raw_input("> ")

    if "yes" in begin:
        print "Great!\n"
        start.start()
        break

    elif "no" in begin:
        quit.quit()
    else:
        error.error(1)

    if hint > 4:
        print "\nYou may choose from \"yes\" and \"no\"."

现在下一个问题是start.start()做什么?看起来/感觉您可能正在使用 GOTO 之类的函数调用

于 2012-09-13T03:04:28.890 回答
0

以下代码使用装饰器将提示逻辑和命令逻辑分开。每个命令都由一个可以由 Hint 对象修饰的函数处理。

当函数返回 False 时,Hint 对象中的计数会增加,当它大于限制时,它会打印出一条提示消息。

当函数返回一个元组时,它将被主循环调用。

class Hint(object):
    def __init__(self, n, msg):
        self.n = n
        self.msg = msg

    def __call__(self, f):
        def wrap(*args, **kw):
            count = 1
            while True:
                ret = f(*args, **kw)
                if ret == False:
                    count += 1
                    if count > self.n:
                        print self.msg
                        count = 0
                else:
                    break
            return ret
        return wrap

def start_at(place):
    print "start at %d" % place
    return "start"

@Hint(3, "You may choose from 1, 2, 3.")
def start():
    print "What place will you start?"
    cmd = raw_input("> ")
    try:
        place = int(cmd)
        if place not in (1,2,3):
            return False
        else:
            return start_at, (place,)
    except ValueError:
        return False

def quit():
    print "I will quit"
    return "quit"

@Hint(4, "You may choose from yes and no.")
def begin():
    print "Would you like to begin?"
    cmd = raw_input("> ")
    if "yes" in cmd:
        print "Great!\n"
        return start, ()
    elif "no" in cmd:
        print "Bad!\n"
        return quit, ()
    else:
        return False

call_func, args = begin, ()
while True:        
    ret = call_func(*args)
    if isinstance(ret, tuple):
        call_func, args = ret
    else:
        break

这是一些测试:

Would you like to begin?
> abc
Would you like to begin?
> def
Would you like to begin?
> 123
Would you like to begin?
> 345
You may choose from yes and no.
Would you like to begin?
> yes
Great!

What place will you start?
> 5
What place will you start?
> fg
What place will you start?
> sd
You may choose from 1, 2, 3.
What place will you start?
> 2
start at 2
于 2012-09-13T03:39:12.353 回答