简体   繁体   中英

How to break a loop when there is a winner?

I'm coding a 5x5 tic tac toe game in which the player plays against the computer. It's a very simple and easy game as the computer chooses where to play randomly. Inside the main loop there is a function that checks if there is a winner and returns True if there is. When, there is a winner, the break statement is supposed to stop the while loop but for some reason, it keeps looping even though the function checkWinner confirms a winner. I don't really know what I'm doing wrong or if anything is missing.

Here is my code:

    #................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()

Let me point out that print( " | ".join(board[0:5]) ) would simplify things.

Your PROBLEM is that neither checkrows , checkcolumns , or checkdiag return anything. They always return None , which will be seen as false.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM