简体   繁体   中英

While loop for starting the game again

I designed a game for tic tac toe. The game runs well. However, I can not use the while loop to start the game over again at the very end with the Main. It starts with the board that breaks from the previous game intead of starting from a new and clean board.

Could anyone take a look at it? Thank you all in advance.

"""
Tic Tac Toe Helper: provides two functions to be used for a game of Tic Tac Toe
1) Check for winner: determines the current state of the board
2) Print ugly board: prints out a tic tac toe board in a basic format
"""


# Given a tic, tac, toe board determine if there is a winner
# Function inputs:
#     board_list: an array of 9 strings representing the tic tac toe board
#     move_counter: an integer representing the number of moves that have 
been made
# Returns a string:
#     'x' if x won
#     'o' if o won
#     'n' if no one wins
#     's' if there is a stalemate

board_list=["0","1","2","3","4","5","6","7","8"]
move_counter=0



def checkForWinner(board_list, move_counter):
    j = 0
    for i in range(0, 9, 3):
        # Check for 3 in a row
        if board_list[i] == board_list[i+1] == board_list[i+2]:
            return board_list[i]

        # Check for 3 in a column
        elif board_list[j] == board_list[j+3] == board_list[j+6]:
            return board_list[j]

        # Check the diagonal from the top left to the bottom right
        elif board_list[0] == board_list[4] == board_list[8]:
            return board_list[0]

        # Check the diagonal from top right to bottom left
        elif board_list[2] == board_list[4] == board_list[6]:
            return board_list[2]
        j += 1

    # If winner was not found and board is completely filled up, return stalemate
    if move_counter > 8:
        return "s"

    # Otherwise, 3 in a row anywhere on the board
    return "n"




 # Print out the tic tac toe board
 # Input: list representing the tic tac toe board
 # Return value: none
 def printUglyBoard(board_list):
     print()
    counter = 0
    for i in range(3):
        for j in range(3):
            print(board_list[counter], end="  ")
            counter += 1
        print()

#check if the move is valid
def isValidMove(board_list,spot):
#only the input in the range of [0:8}, not occupied by x or o is valid
    if 0<= spot <= 8 and board_list[spot]!='x' and board_list[spot]!='o':
         print("True")

         return True
    else:
         print("Invaild. Enter another value.")
         return False

 #update the board with the input
 def updateBoard(board_list,spot,playerLetter):
    result=isValidMove(board_list,spot,)

    if result==True and playerLetter=='x':
        board_list[spot]='x'
        playerLetter='o'
    elif result==True and playerLetter=='o':
        board_list[spot]='o'
        playerLetter='x'
    print(board_list)
    print(playerLetter)
    printUglyBoard(board_list)
    return playerLetter




def play():
#use the print function to show the board
    printUglyBoard(board_list)
    playerLetter='x'
    move_counter=0
#while loop for keeping the player inputting till a valid one and switch player after a valid input is recorded
    while True:
        if playerLetter=='x':
            spot = int(input('Player x,enter the value:'))
        elif playerLetter=='o':
            spot = int(input('Player o,enter the value:'))
        isValidMove(board_list,spot)
        result=isValidMove(board_list,spot,)
 #count the move for checking the winner purposes
        if result==True:
            move_counter+=1
        playerLetter=updateBoard(board_list,spot,playerLetter)
        print(move_counter)
#check the winner 
        winner=checkForWinner(board_list, move_counter)
#determine the winner
        if winner=='o':
            print('o win')
            break
        if winner=='x':
            print('x won')
            break
       if winner=='s':
           print("Tie")
           break

 def main():
     print("Welcome to Tic Tac Toe!")
 #while loop for the contining the game 
     while True:
         play()
        choice=input("Would you like to play another round? (y/n)")
        if choice=='y'.lower():
            play()
        elif choice=='n'.lower():
            print("Goodbye")
            break

main()

An easy fix for your problem is putting the variable initialization inside of the function play() like this:

def play():
    board_list=["0","1","2","3","4","5","6","7","8"]
    #rest of your code...

This way every time you loop and call play you reset the board to its original position. really board_list should not be declared outside a function (globaly) because it's only used inside play and passed to the rest of the functions that use it.
Declaring the variables a function use only inside a function makes sure they are set correctly every time and improve the codes readability by showing all the pieces in play in that function

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