如何循环回某些代码

时间:2015-04-14 23:27:42

标签: python loops

所以我正在创建一个生存游戏,我需要知道如何循环回到代码中的某个点。我把整个游戏包裹在一个函数中,但是 - 现在在运行它时 - 它只是重新开始。

import random
def game(choice1):
    print "You need to build a fire. the recipe is 5 stick and 3 coal."
    choice1 = raw_input("There are trees to your left and rocks to your right. Which way will you go?")
    if choice1 == "left" or choice1 == "Left":
        choice2a = raw_input("You go to the tree. Would you like to punch it?")
        if choice2a == "yes" or choice2a == "Yes":
            R = random.randint(1,11)
            print "You punched the tree " + str(R) + " times."
            if R <= 5:
                print "It did not fall down"
            elif R > 5:
                R2 = random.randint(0, 5)
                print"It fell down. It dropped " + str(R2) + " sticks."
            elif choice2a == "no" or choice2a == "No":
                game(choice1)
    if choice1 == "right" or choice1 == "Right":
        choice2b = raw_input("You go to the rocks. Would you like to pick up the coal in them?")
    return game(choice1)

3 个答案:

答案 0 :(得分:0)

我想你想回到第一个 raw_input 语句,如果是这种情况,你可以使用 while循环,正如Celeo指出的那样。 完成循环后,您将不得不使用退出条件来转义while循环。如果您想循环回程序的不同部分,那么我建议您将代码块作为函数编写并根据需要调用它们。

答案 1 :(得分:0)

尝试阅读有关while循环的信息: http://www.tutorialspoint.com/python/python_while_loop.htm

while循环允许您根据条件重复代码(满足条件时,返回到开头)。

答案 2 :(得分:0)

为了制作这样的游戏,我建议使用(决定)状态机。如果游戏处于某种状态,则向玩家询问相应的问题,并根据答案将游戏移动到其他状态。每个状态都应该独立于其他状态实现,即避免深度嵌套的if / else结构,这可以避免错误并帮助您掌握最重要的事情。您还可以将游戏决策计划可视化/绘制为图形,其中每个节点代表一个状态(或决策),每个决策将节点连接到另一个状态。

对于您的具体示例,您还需要跟踪玩家到目前为止收集的内容,这实际上是另一个州系统。

要实现这种基于状态的游戏,您可以(ab-)使用生成器的python概念。生成器基本上是一个对象,当使用yield查询时返回带有next()的“项目”。生成器可以提供有限或无限量的“项目”,它还可以使用yield from从其他生成器返回“项目”。

这是您游戏的示例实现: 请注意,此代码仅适用于python3!应该可以将其转换为python2(可能甚至是自动),但我觉得没有强烈要求这样做ATM;)

import random
import collections


def main(backpack):    
    print("You need to build a fire. the recipe is 5 stick and 3 coal.")
    print("You have the following items in your backpack:")
    for k,v in backpack.items():
        print('  % 3d %s' % (v,k))

    #TODO: add check if we have collected enough here

    yield from choice1(backpack)

# tree or stone
def choice1(backpack):
    answer = input("There are trees to your left and rocks to your right. Which way will you go?")
    if answer.lower() in ('l', 'left'):
        yield from choice2a(backpack)
    elif answer.lower() in ('r', 'right'):
        yield from choice2b(backpack)
    else:
        print('I could not understand you. Answer with either "left" or "right".')
        yield from choice1(backpack)

# punch or not
def choice2a(backpack):
    answer = input("You go to the tree. Would you like to punch it?")
    if answer.lower() in ('y', "yes"):
        R = random.randint(1,11)
        print( "You punched the tree " + str(R) + " times.")
        if R <= 5:
            print("It did not fall down")
        else:
            R2 = random.randint(0, 5)
            print("It fell down. It dropped " + str(R2) + " sticks.")
            backpack['stick'] += R2
        yield from choice2a(backpack)
    elif answer.lower() in ('n', "no"):
        yield from main(backpack)
    else:
        print('I could not understand you. Answer with either "yes" or "no".')
        yield from choice2a(backpack)

# pick up or not      
def choice2b(backpack):
    answer = input("You go to the rocks. Would you like to pick up the coal in them?")

    # TODO: implement this
    yield main(backpack)



if __name__ == '__main__':

    backpack=collections.defaultdict(int)
    while True:
        next(main(backpack))

每个函数都是生成器函数,即返回生成器的函数。他们每个人都代表一个需要做出决定的游戏状态。玩家状态(即玩家到目前为止收集的内容)作为backpack传递,这是一个包含每个项目金额的字典。

yield from xyz()可以解释为一种goto命令。)