簡體   English   中英

如何在 Python 中與外部 function 結束循環?

[英]How to end loop with outside function in Python?

我在 function 外部結束循環時遇到問題。 這是我的蜱蟲游戲。 下面是我的代碼的一部分,我的 function win(x) 有條件獲勝,我希望它完成“while game”循環。 我嘗試了很多方法,如果滿足 win_x() 的條件,它會打印“X wins”,但循環繼續按 range(5) 如何更改 win_x() function 以結束循環?

def win_x():
  global game
  global win
  global board_numbers
  if board_numbers[30]=="X" and board_numbers[62]=="X" and board_numbers[94]=="X":
    os.system('clear')
    print(board_numbers)
    print("X wins")


game=True
while game:
  os.system('clear')
  print(board_numbers)
  for i in range(5):
    if player_marker=="X" or player_marker=="x":
      player_X()
      os.system('clear')
      win_x()
      computer_O()

    else:
      os.system('clear')
      computer_X()
      player_O()

我一直在嘗試,我想通了。 代碼看起來很傻但有效:

def win_x():
  global game
  global board_numbers
  if board_numbers[30]=="X" and board_numbers[62]=="X" and board_numbers[94]=="X":
    os.system('clear')
    print(board_numbers)
    print("X wins")
    game=False     #placing just game=False on its own didn't help

game=True

while game:
  os.system('clear')
  print(board_numbers)
  for i in range(5):
    if player_marker=="X" or player_marker=="x":
      player_X()
      os.system('clear')
      win_x()
      if game==False:    #it is still weird as game=False was in above function
        break            #so I am not sure why I had to state it here
      computer_O()

    else:
      os.system('clear')
      computer_X()
      player_O()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM