同时循环再次开始游戏

时间:2018-02-18 22:00:05

标签: python while-loop tic-tac-toe

我为tic tac toe设计了一款游戏。 游戏运行良好。 但是,我不能使用while循环在Main的最后再次开始游戏。它从董事会开始,从一个新的干净的董事会开始打破以前的游戏。

有人可以看一下吗? 提前谢谢大家。

"""
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()

1 个答案:

答案 0 :(得分:1)

对您的问题进行简单的修复就是将变量初始化放在函数play()中,如下所示:

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

这样,每次循环并调用play时,都会将电路板重置为原始位置。 真的board_list不应该在函数外声明(全局),因为它只在play中使用并传递给使用它的其余函数。
声明函数仅在函数内部使用的变量确保每次都正确设置它们并通过显示该函数中的所有部分来提高代码的可读性