如何使用函数重构代码?

时间:2018-09-19 21:33:22

标签: python

这是我为学校设计的一款简单的迷宫游戏。我尝试了不同的解决方案,但仍然不知道如何解决。我不一定需要完整的解决方案。任何提示都会有所帮助。

x = 1
y = 1
valid_selection = True

while True:
    if x == 1 and y == 1:
        if valid_selection == True:
            print("You can travel: (N)orth.")
        valid_selection = True
        choice = input("Direction: ")
        if choice.lower() == "n":
            y += 1
        else:
            print("Not a valid direction!")
            valid_selection = False
    elif x == 1 and y == 2:
        if valid_selection == True:
            print("You can travel: (N)orth or (E)ast or (S)outh.")
        valid_selection = True
        choice = input("Direction: ")
        if choice.lower() == "n":
            y += 1
        elif choice.lower() == "e":
            x += 1
        elif choice.lower() == "s":
            y -= 1
        else:
            print("Not a valid direction!")
            valid_selection = False
    elif x == 3 and y == 1:
        print("Victory!")
        break

2 个答案:

答案 0 :(得分:0)

您可以让您的函数接收xy作为参数,删除While While True并将其替换为其创建内容,例如def MyFunc(x,y),将valid_selection变量放入其中并删除xy的归属。然后在代码末尾调用它,将11作为您想要的参数,例如MyFunc(1,1)

答案 1 :(得分:-1)

有很多创建函数的方法。 首先,您需要抽象程序的功能。函数的名称必须表达这一点。 其次,您需要知道什么是输入。在您的情况下,输入必须为x和y,或这些输入的专有名称。

您的函数将返回的答案是一个重要的知识。用户将看到打印件,或者该功能的用户将使用数字,字符串或其他对象来提供其他功能。

我希望这不要混淆。