简体   繁体   中英

doesn't clear the board

I'm making a game of tic tac toe and at the start and end it asks if you "would like to play a game y/n?", if you press yes it works perfectly and if you press no it says "Goodbye" and closes the program like its suppose too, however if you press "yes" just after you've played your first game it doesn't reprint the board, only gives you the one you already filled in. Is there a way to clear the board that anyone can help me with?

board = [" " for x in range(10)]

#insert letter into the board

def insertLetter(letter, pos):
    board[pos] = letter

# Is that space avalible?

def spaceIsFree(pos):
    return board[pos] == " "

# Prints the board

def printBoard(board):

    #Board set up

    print("   |   |")
    print(" " + board[1] + " | " + board[2] + " | " + board[3])
    print("   |   |")
    print("-----------")
    print("   |   |")
    print(" " + board[4] + " | " + board[5] + " | " + board[6])
    print("   |   |")
    print("-----------")
    print("   |   |")
    print(" " + board[7] + " | " + board[8] + " | " + board[9])
    print("   |   |")

def isWinner(bo, le):

    #Look for winner!

    return ((bo[7] == le and bo[8] == le and bo[9] == le) or # across the top
    (bo[4] == le and bo[5] == le and bo[6] == le) or # across the middle
    (bo[1] == le and bo[2] == le and bo[3] == le) or # across the bottom
    (bo[7] == le and bo[4] == le and bo[1] == le) or # down the left side
    (bo[8] == le and bo[5] == le and bo[2] == le) or # down the middle
    (bo[9] == le and bo[6] == le and bo[3] == le) or # down the right side
    (bo[7] == le and bo[5] == le and bo[3] == le) or # diagonal
    (bo[9] == le and bo[5] == le and bo[1] == le)) # diagonal
 

def playerMove():

    #Grabs player move, cheak for valid input

    run = True

    while run:
        move = input("Please select a position place an \"X\" (1-9): ")
    
        try:
            move = int(move)

            if move > 0 and move < 10:
            
                if spaceIsFree(move):
                    run = False
                    insertLetter("X", move)

                else:
                    print ("Sorry, this space is already taken!")

            else:
                print ("Please type a number within the range!")
        
        except:
               print("Please type a number!")
    

def compMove():

    # Computers move
        
    possibleMoves = [x for x, letter in enumerate(board) if letter == " " and x != 0]
    move = 0

    #check for a possible win

    for let in ["O", "X"]:
    
        for i in possibleMoves:
            boardCopy = board[:]
            boardCopy[i] = let
    
            if isWinner (boardCopy, let):
                move = i
                return move
        
    #check for open corners

    cornersOpen = []

    for i in possibleMoves:
        if i in [1,3,7,9]:
        cornersOpen.append(i)
         
    if len(cornersOpen) > 0:
        move = selectRandom(cornersOpen)
        return move

    #check for center move

    if 5 in possibleMoves:
        move = 5
        return move

    #check for open edges

    edgesOpen = []
    for i in possibleMoves:
        if i in [2,4,6,8]:
            edgesOpen.append(i)
        
    if len(edgesOpen) > 0:
        move = selectRandom(edgesOpen)
    
    return move

def selectRandom(li):

 # Selects random numbers

    import random
    ln = len(li)
    r = random.randrange(0,ln)
    return li[r]

def isBoardFull(board):

    #See if the board is full

    if board.count(" ") > 1:
        return False

    else:
        return True 

def main():
    print("Welcom to Tic Tac Toe!")
    print ()
    printBoard(board)

    while not (isBoardFull(board)):

        # Do a player move,

        # Check if O wins
    
        if not (isWinner(board, "O")):
            playerMove()
            printBoard(board)
            
        else:
            print("Sorry, O's won this time!")
            break

        # Check If X wins
    
        if not (isWinner(board, "X")):
            move = compMove()

            if move == 0:
                print("Tie Game!")

            else:
                insertLetter("O", move)
                print("Computer placed an O in position", move ,":")
                printBoard(board)
        
        else:
            print("X's won this time! Good Job")
            break

        # No one wins - it's a tie
    
    if isBoardFull(board):
        print ("Tie Game!")
    

while True:

    # Start/Play again
        
    replay = input ("Would you like to play a game? y/n: ")

    if replay == "no":
        print ("Goodbye")
        break

    else:
        print()
        main()    

You only create the board once at the top, then never reset it.

The easiest way to reset the state is simply to not save it globally. Reconfigure your code so board only exists in main , and it manually passed to every function that needs it. Then, when main exits, the board is destroyed and recreated each time that main runs.

To patch your existing code so it works though, I'd just create a function that creates a new board:

def new_board():
    return [" " for x in range(10)]

Then, at the top of main , reset it:

def main():
    global board
    board = new_board()
    print("Welcom to Tic Tac Toe!")
    print ()
    printBoard(board)

I can't recommend this in the long-term, but it's a quick fix.

board is defined in the global scope, so calling main again won't affect it, and you'll remain with the previous data. One option is to explicitly reinitialize it:

else:
    board = [" " for x in range(10)]
    print()
    main()

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