Python while循环在while循环内不会中断

时间:2020-04-18 08:17:41

标签: python while-loop

这是一个井字游戏。在本节中,该功能检查板上是否有未填充的单元(第一个while循环,它起作用),然后检查o是否赢了(第二个while循环,它起作用)。

如果o获胜,它将中断循环并显示“ yey o”。与检查x是否赢取相同,第三个循环也起作用,除了循环中断时,它会打印“祝贺x”到无穷大。

我尝试在第二个循环的级别上添加一个break语句(例如,“ x赢了,所以x打破了,o打破了),但是没有成功。我在做什么错了?

def place_marker():
    while any(isinstance(x, int) for x in board):
        while not win_check_o():
            while not win_check_x():
                # does stuff
            else:
                print("congrats x")
                break
        else:
            print("yey o")
            break

    print(board)

2 个答案:

答案 0 :(得分:2)

break语句仅从其包含循环退出。如果内部循环中有两个嵌套循环和一个break语句,您将返回到外部循环。

while True:
    while True:
        break
    print('This will repeat forever.')

要解决此问题,请将循环放入函数中,然后使用return语句。

答案 1 :(得分:2)

break仅从一个循环中中断。您应该将逻辑拼合为一个循环-您可以可以创建一些布尔值并标记它们,以记住完全爆发(非常糟糕的风格):

a, SomeOtherCondition, thatCondition, SomeThing  = True, True, True, True

# contrieved bad example
while a and SomeOtherCondition:
    while a and thatCondition:
        while a and SomeThing:
            a = False
            print("Breaking")
            break
        # any code here will be executed once
        print("Ops") 
    # any code here will also be executed once
    print("Also ops")

输出:

Breaking
Ops
Also ops

最好构造代码并展平循环:

一些辅助方法

def any_tile_left(board):
    return any(isinstance(x, int) for x in board)  


def win_check(who, board):
    conditions = [(0,1,2),(3,4,5),(6,7,8), # horizontal
                  (0,3,6),(1,4,7),(2,5,8), # vertical
                  (0,4,8),(2,4,6)]         # diagonal
    for c in conditions:
        if all(board[i] == who for i in c):
            return True
    return False


def print_board(board):
    for row in range(0,9,3):
        print(*board[row:row + 3], sep = "   ")

游戏:

whos_turn = "X"
boardrange = range(1,10)
board = list(boardrange)

while True: 
    print_board(board) 
    try:
       pos = int(input(whos_turn + ": Choose a tile? "))
    except ValueError:
        print("impossible move. ", whos_turn,  "is disqualified and lost.")
        break

    if pos in boardrange and str(board[pos-1]) not in "XO":
        board[pos-1] = whos_turn
        if win_check(whos_turn, board):
            print(whos_turn, " won.")
            break
        whos_turn = "O" if whos_turn=="X" else "X"
    else:
        print("impossible move. ", whos_turn,  "is disqualified and lost.")
        break

    if not any_tile_left(board):
        print("Draw")
        break

它应该适合井字游戏。小心不要输入可能无法完成的内容,否则会松动。

相关问题