![](/img/trans.png)
[英](Python 3.3) Can not figure out why function creates infinite loop when value gets to 5
[英]Stuck in infinite loop, cant figure out why - python
當這段代碼運行時,它應該在玩家和計算機之間交替,但是當輪到計算機時,它只是完成了游戲。 我反復檢查了縮進級別,但找不到問題所在。
你寫這個的方式讓你很難真正弄清楚控制流是如何進行的。 有很多重復對於游戲來說並不是真正必要的,這增加了復雜性。 一個主要的事情是你有四個位置可以詢問玩家是否重新開始游戲。 如果您只確保擁有一次,那么您已經可以大大簡化一切。
然后你會注意到的第一件事是結構是這樣的:
while winFlag == False:
# player move
while sticksOnBoard != 0:
# evaluate winner
# AI move
# evaluate winner
因此,除非任何玩家已經通過低於 0 棒而獲勝,否則 AI 移動將一遍又一遍地發生,直到有人獲勝。 但是玩家再也沒有機會移動了。 相反,您可能希望完全移除winFlag
因為當棋盤上沒有更多木棍時,游戲就結束了。 所以你會像這樣:
while sticksOnBoard > 0:
# player move
if sticksOnBoard <= 0:
# evaluate winner
# AI move
# evaluate winner
或者要刪除重復的評估,您只需切換活動播放器:
isPlayerMove = True
while sticksOnBoard > 0:
if isPlayerMove:
# player move
else:
# AI move
isPlayerMove = not isPlayerMove # toggle current player
# evaluate winner
這就是我制作這款游戲的方式,減少所有重復:
def playerVsAiGame (sticksOnBoard):
# main game loop
while True:
sticks = sticksOnBoard
isPlayerMove = True
# only ask when there are more than 3 left; otherwise the current
# player can just choose the remaining number and win
while sticks > 3:
print('There are {} sticks on the board.'.format(sticks))
if isPlayerMove:
move = int(input('How many sticks would you like to take? (1-3) '))
else:
# the computer just chooses randomly between 1, 2, and 3 sticks
# this is where you could add additional game logic to make the AI
# smarter
move = random.choice((1, 2, 3))
print('The computer takes {} sticks.'.format(move))
sticks -= move
isPlayerMove = not isPlayerMove
# the current player wins
print('There are {} sticks on the board.'.format(sticks))
if isPlayerMove:
print('You win!')
else:
print('The computer wins!')
# break the main loop unless the player wants to play again
if input('Play again? Yes (1) / No (0) ').lower() not in ('1', 'yes', 'y'):
break
我認為你在這段代碼中得到了一些非常錯誤的東西。
你永遠不會在你的內部循環中請求用戶輸入。
您檢查sticksOnBoard
是否小於0,並檢查它是否為1。但是,在大多數情況下, sticksOnBoard
只會具有更大的值,因此, while sticksOnBoard != 0
將循環直到您的游戲結束。
同時,您的基本 AI 將不斷地從棋盤上抽出棍棒,而無需用戶做任何事情。
看來你對編程不是很熟悉(這沒問題,大家都開始了)。 這就是為什么我會建議您帶上筆和紙,並逐步完成您的函數的示例運行。 這樣,程序無法按您想要的方式運行的原因就很明顯了。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.