运行函数时无限循环复位

时间:2012-09-13 02:33:04

标签: python

我只是想知道我是否可以在文本游戏中删除一些帮助功能的冗余。我现在所拥有的是每个函数hint = 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\"."

2 个答案:

答案 0 :(得分: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这样的函数调用

答案 1 :(得分: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