如果玩家1拿到最后一个标志,我希望它退出,但会发生的是它询问玩家2并且它不会退出。
while (flags>0):
print "There are",flags,"flags left."
print "Next player is 1"
selection=input("Please enter the number of flags you wish to take: ")
if (selection<1)or (selection>3):
print "You may only take 1, 2 or 3 flags."
selection=input("Please enter the number of flags you wish to take: ")
else:
flags=flags-selection
print "There are",flags,"flags left."
print "Next player is 2"
selection=input("Please enter the number of flags you wish to take: ")
if (selection<1)or (selection>3):
print "You may only take 1, 2 or 3 flags."
selection=input("Please enter the number of flags you wish to take: ")
else:
flags=flags-selection
else:
if (flags<0) or (flags==0):
print "You are the winner!"
答案 0 :(得分:0)
您可以使用while
提前退出break
循环,也可以在要求玩家2选择标记之前测试剩余的标记数。
例如
print "Next player is 1"
selection=input("Please enter the number of flags you wish to take: ")
if (selection<1)or (selection>3):
print "You may only take 1, 2 or 3 flags."
selection=input("Please enter the number of flags you wish to take: ")
else:
flags=flags-selection
print "There are",flags,"flags left."
if flags <= 0:
print "Player 1 is the winner!"
break
您可能希望重新构建代码以在玩家之间切换:
player = 1
while True:
print "Next player is {}".format(player)
selection = input("Please enter the number of flags you wish to take: ")
if not 1 <= selection <= 3:
print "You may only take 1, 2 or 3 flags."
selection = input("Please enter the number of flags you wish to take: ")
else:
flags = flags - selection
print "There are",flags,"flags left."
if flags <= 0:
print "Player {} is the winner!".format(player)
break
player = 3 - player # swap players; 2 becomes 1, 1 becomes 2