如何打破多个while循环

时间:2017-10-06 02:55:48

标签: python if-statement while-loop

我正在制作一个拾取棒游戏的程序。我仍然对整个事物的逻辑感到困惑。我最大的问题是我有多个嵌套的while循环并希望结束所有这些循环。这是我的代码。

x = 1

while x == 1:
   sticks = int(input('How many sticks are on the tables (10 to 100): '))


   if sticks not in range(10,101):
        print('Invalid.')
        continue
   while x == 1:
        print('There are',sticks,'sticks on the table.')
        print('Player 1')
        p1 = int(input('How many sticks do you want to remove?'))
        if p1 == sticks:
            print('Player one wins.')
            x == 2
            break
        elif p1 not in range(1,4):
            print('Invalid.')
            continue
        else:
            while x == 1:
                sticks -= p1
                print('There are',sticks,'sticks on the table.')
                print('Player 2.')
                p2 = int(input('How many sticks do you want to remove?'))
                if p2 == sticks:
                        print('Player two wins.')
                        x == 2 
                        break

                elif p2 not in range(1,4):
                    print('Invalid.')
                    continue
                else:
                    sticks -= p2

我的输出继续提示玩家1和2输入。

我希望程序在打印后结束" Player _ wins"。 任何帮助/提示将不胜感激!甚至是编写程序的简单方法。

2 个答案:

答案 0 :(得分:1)

我总是发现为多玩家回合制游戏构建状态机有很大帮助。因为它提供了一种清晰简便的方法来分解逻辑,避免在嵌套循环中使用大量breakcontinue甚至goto

例如,这是一个状态机,它有4种状态: enter image description here

对于每个州,都有一个处理函数,它将根据当前玩家,操纵杆和用户输入决定接下来的状态(甚至是其自身):

def initialize():
    global sticks, state
    n = int(input('How many sticks are on the tables (10 to 100): '))
    if n not in range(10, 101):
        print('Invalid. It should be between 10 ~ 100.')
    else:
        state = 'ask_player1'
        sticks = n


def ask_player1():
    global sticks, state
    print('There are', sticks, 'sticks on the table.')
    print('Player 1')
    n = int(input('How many sticks do you want to remove?'))
    if n not in range(1, 4):
        print('Invalid. It should be between 1 ~ 4')
    else:
        sticks -= n
        if sticks == 0:
            print('Player one wins.')
            state = 'end'
        else:
            state = 'ask_player2'


def ask_player2():
    global sticks, state
    print('There are', sticks, 'sticks on the table.')
    print('Player 2')
    n = int(input('How many sticks do you want to remove?'))
    if n not in range(1, 4):
        print('Invalid. It should be between 1 ~ 4')
    else:
        sticks -= n
        if sticks == 0:
            print('Player two wins.')
            state = 'end'
        else:
            state = 'ask_player1'


state_machine = {
    'initialize': initialize,
    'ask_player1': ask_player1,
    'ask_player2': ask_player2,
}

sticks = 0
state = 'initialize'
while state != 'end':
    state_machine[state]()

答案 1 :(得分:0)

您最好的选择可能是将代码移动到返回的函数中。多次休息已多次proposed次,且为rejected次。您可以将整个代码放入“Player _ wins”之后返回的函数中,因此它不会继续运行。其他替代方案是使用一个标志变量,该标志变量在玩家获胜并提出随后处理的异常后设置。