我正在制作一个拾取棒游戏的程序。我仍然对整个事物的逻辑感到困惑。我最大的问题是我有多个嵌套的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"。 任何帮助/提示将不胜感激!甚至是编写程序的简单方法。
答案 0 :(得分:1)
我总是发现为多玩家回合制游戏构建状态机有很大帮助。因为它提供了一种清晰简便的方法来分解逻辑,避免在嵌套循环中使用大量break
和continue
甚至goto
。
对于每个州,都有一个处理函数,它将根据当前玩家,操纵杆和用户输入决定接下来的状态(甚至是其自身):
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)