这个程序是我的GCSE计算机科学的蛇和梯子程序(不用担心,这只是练习),而且我在使用循环内部存在的函数打破while循环时遇到问题。这是代码:
win = False
while win == False:
print("Player 1 goes first.")
def dice():
roll = random.randint(1,6)
return roll
roll = dice()
print("They roll a...",roll)
player1+=roll
def check():
if player1 in ladders or player2 in ladders:
print("A ladder has moved the player to a new position.")
elif player1 in snakes or player2 in snakes:
print("A snake has moved the player to a new position.")
elif player1 >= 36:
print("Congratulations. Player 1 has won the game.")
win = True
elif player2 >= 36:
print("Congratulations. Player 2 has won the game.")
win = True
check()
print("Player 1 is on square",player1)
它显然还没有完成,而且并不是所有的代码。在那之后,它与播放器2一样。上面有一个元组,检查功能检查玩家是否落在蛇或梯子上,但我还没有添加实际上将玩家上下移动梯子/蛇的代码。 / p>
错误是while循环是一个无限循环。
我尝试将整个win = False或True更改为True,然后使用break我说win = True,然后它返回错误' break out loop'即使突破显然在循环内部。我不知道是不是因为我需要从函数中返回一些东西,但我不太清楚该怎么做。简单地说“返回胜利”#39;下面两个win = True并没有改变任何东西,而while循环仍然无限期地继续。
答案 0 :(得分:1)
之所以发生这种情况是因为当您在函数中赋值变量时,它使用局部变量。因此,为了快速修复,您可以在检查功能中添加global win
:
def check():
global win
if player1 in ladders or player2 in ladders:
print("A ladder has moved the player to a new position.")
elif player1 in snakes or player2 in snakes:
print("A snake has moved the player to a new position.")
elif player1 >= 36:
print("Congratulations. Player 1 has won the game.")
win = True
elif player2 >= 36:
print("Congratulations. Player 2 has won the game.")
win = True
您可以在此处详细了解变量类型 - http://www.python-course.eu/python3_global_vs_local_variables.php
同样,将函数存储在内部并不是一个好主意,因为它会在每次迭代时创建函数,这是不好的。所以更好的是在循环之外定义它们。
答案 1 :(得分:1)
也许这就是你要找的东西?注意我是如何将这些函数从循环中取出来的。然后我完全抛弃了一个布尔变量,因为它有更简洁的方法。如果满足特定条件,您可以使用while True
,然后只使用break
。如果您希望循环在满足特定条件时返回起点,则可以使用continue
。
def dice():
return random.randint(1,6)
def check():
if player1 in ladders or player2 in ladders:
print("A ladder has moved the player to a new position.")
elif player1 in snakes or player2 in snakes:
print("A snake has moved the player to a new position.")
elif player1 >= 36:
print("Congratulations. Player 1 has won the game.")
return True
elif player2 >= 36:
print("Congratulations. Player 2 has won the game.")
return True
while True:
print("Player 1 goes first.")
roll = dice()
print("They roll a...",roll)
player1 += roll
if check():
break
print("Player 1 is on square",player1)
我没有触及逻辑,但将玩家得分传递给check
会有意义。