gpt4 book ai didi

python - 如何打破多个 while 循环

转载 作者:太空宇宙 更新时间:2023-11-03 14:40:19 26 4
gpt4 key购买 nike

我正在制作一个程序,它是一个捡棍子的游戏。我对整个事情的逻辑仍然很困惑。我最大的问题是我有多个嵌套的 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”后结束。任何帮助/提示将不胜感激!或者甚至是一种更简单的编写程序的方法。

最佳答案

我总是发现为多人回合制游戏构建状态机有很大帮助。因为它提供了一种清晰、简单的方法来分解逻辑,并避免在嵌套循环中使用大量 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]()

关于python - 如何打破多个 while 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46597599/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com