有赢家时如何打破循环?

How to break a loop when there is a winner?

我正在编写一个 5x5 井字游戏,玩家可以在其中与计算机对战。这是一个非常简单和容易的游戏,因为计算机会随机选择在哪里玩。在主循环中有一个函数检查是否有赢家,如果有则 returns True。当有赢家时,break 语句应该停止 while 循环,但由于某种原因,即使函数 checkWinner 确认了赢家,它也会继续循环。我真的不知道我做错了什么或者是否遗漏了什么。

这是我的代码:

    #................Part 2: Display Board..............
def displayBoard(board):
    print(board[0], " |", board[1], " |", board[2], " |", board[3], " |", board[4])
    #print("---+----+----+----+---")
    print(board[5], " |", board[6], " |", board[7], " |",  board[8], " |", board[9])
    #print("---+----+----+----+---")
    print(board[10], "|", board[11], "|", board[12], "|", board[13], "|", board[14])
    #print("---+----+----+----+---")
    print(board[15], "|", board[16], "|", board[17], "|", board[18], "|", board[19])
    #print("---+----+----+----+---")
    print(board[20], "|", board[21], "|", board[22], "|", board[23], "|", board[24])
def drawBoard_Enhanced(board, board_size):
    n = 25 
    fill_values = np.arange(1, n+1)
    board = fill_values.tolist()
    print(board)
    grid_size = 5
    c = 65
    for i in range(grid_size):
            
            for j in range(grid_size):
                print(f"| {board[i*5 + j]} ", end='')
            print(f"| ", end='')
            print()
            print(f'{(5*5)*"-"}')            
            


#.................Part 3: Check if move is legal.....................
def checklfLegal(number, board):
    if number not in range(1, len(board)+1):
        print('Your move is not legal as the number you entered is out of the defined range of the board. Please enter a new number.')
        return False 
    
    elif board[number-1] == "X" or board[number-1] == "O": 
        print('Your move is not legal as the number you entered has already been replaced. Please enter a new number')
        return False
    
    else: 
        position = board.index(number)
        board[position] = "X"
        return True
    
    
#..................Part 4: Check if move is winner...................

#This function checks if all elements in a list are the same
def checklist(list):
    first = list[0]
    for elem in list:
        if elem != first:
            return False
            break
    return True, first


#Check Rows
def checkrows(board):
    r = []
    for i in range(0, 24, 5): 
        r.append(board[i:i+5]) #Fills the list with lists containing the rows
    #print(r)
    for i in r: #iterates through the rows
        if checklist(i):
            if i[0] == "X":
                print("Player wins. Congratulations!")
            elif i[0]== "O":
                print("Computer wins. Try again!")

#Check Columns
def checkcolumns(board):
    c = [] 
    for i in range(0, 5): 
        c.append(board[i:25:5]) #Fills the list with lists containing the columns
    #print(c)    
    for i in c: #iterates through the columns
        if checklist(i):
            if i[0] == "X": 
               print("Player wins. Congratulations!")
            elif i[0] == "O":
                print("Computer wins. Try again!")
#Check Diagonals
def checkdiag(board):
    d1= board[0:25:6] #List of first diagonal
    d2= board[4:21:4] #List of second diagonal
    d = [d1, d2] #Appends both diagonals into a single list
    #print(d)
    for i in d: #iterates through the diagonals
        if checklist(i):
            if i[0] == "X": 
               print("Player wins. Congratulations!")
            elif i[0] == "O":
                print("Computer wins. Try again!")
          

#Function that checks winner by checking rows, columns and then diagonals
def checkWinner(board):
    if checkrows(board):
        return True
    elif checkcolumns(board):
        return True
    elif checkdiag(board):
        return True
    else: 
        return False
 

#..........Part 5: Computer move ..............................................
def computerMove(board):
    arr = np.arange(len(board))
    possible_values = arr.tolist()
    legal = False
    while legal == False:
        cpu = secrets.choice(possible_values)
        if board[cpu] == "X" or board[cpu] == "O" : 
            legal = False
        else: legal = True
    board[cpu] = "O"
    print("This is the computer's move:")
    displayBoard(board)
    


#................Part 1: Main Game Loop.......................................
def main():
    print("Hello and welcome to the Tic-Tac-Toe challenge: Player against computer.")
    print("The board is numbered from 1 to 25 as per the following:")
    fill_values = np.arange(1, 26)
    board0 = fill_values.tolist()
    displayBoard(board0)
    board = board0
    print("Player starts first. Simply input the number of the cell you want to occupy. Player's move is marked with X. Computer's move is marked with O.")
    
    start = input("Start? (y/n):")
    if start == "n":
        print("Thank you. Goodbye!")
    else: 
        turn = 0
        while turn <= 25:
            number = int(input("Which cell would you like to occupy:"))
            if checklfLegal(number, board) == False: 
                continue
            if checkWinner(board):
                break
            displayBoard(board)
            turn = turn + 1
            if turn ==25:
                print("It's a tie! Please try again.")
                break
            computerMove(board)
            if checkWinner(board):
                break
            turn = turn + 1
            if turn ==25:
                print("It's a tie! Please try again.")
                break
        print("Game over.")      
            
main()

让我指出 print( " | ".join(board[0:5]) ) 会简化事情。

您的问题是 checkrowscheckcolumnscheckdiag return 都没有。他们总是return None,这将被视为错误。