初学者的问题,写我的第一个代码。不确定这个问题

时间:2020-04-11 08:07:13

标签: python variables tic-tac-toe

我是一名初学者,正在学习如何使用Python并编写我的第一个井字游戏代码。

FirstQ = input("Welcome to Tic Tac Toe!" + "\n" + "Player 1: Do you want to be X or O? ")

def place_marker(): #This function will now attempt to place an X onto the board
if FirstQ == "X":
    player1 = FirstQ
    player2 = "O"
elif FirstQ == "O":
    player1 == FirstQ
    player2 == "X"

所以我想做的是一旦玩家选择了他们是X还是O。我试图将其分配给玩家。

当我输入X时,代码运行良好,但是如果输入O,则会出现以下错误:

Traceback (most recent call last):
File "D:/Python/Projects/TIC TAC TOE.py", line 46, in <module>

place_marker()



File "D:/Python/Projects/TIC TAC TOE.py", line 36, in place_marker


UnboundLocalError: local variable 'player1' referenced before assignment

有人可以解释它的工作原理吗?

这是到目前为止我完成的全部代码:

#Global Variables
testboard = ([' ',' ',' ',' ',' ',' ',' ',' ',' '])
player1 = input("Welcome to Tic Tac Toe!" + "\n" + "Player 1: Do you want to be X or O? ")

def display_board(board): #Function for designing the board
    print ('   |   |   ')
    print ('{}  | {} | {} '.format(board[6],board[7],board[8])) #This is where the X and O will go
    print ("   |   |   ")
    print ("-----------")
    print ("   |   |   ")
    print ('{}  | {} | {} '.format(board[3],board[4],board[5])) #This is where the X and O will go
    print ("   |   |   ")
    print ("-----------")
    print ("   |   |   ")
    print ('{}  | {} | {} '.format(board[0],board[1],board[2])) #This is where the X and O will go
    print ("   |   |   ")

    pass

def player_input(): #Function for assigning the player whether they will be X or O
    if player1 == "X":
        return ("Player 1 will start first as X")
    elif player1 == "O":
        return ("Player 1 will start first as O")
   # else:
        #return ("Sorry, please enter in either X or O"  ||Work on this Later
        #print (player_input())

def place_marker(): #This function will now attempt to place an X onto the board
    if player1 == "X":
        player2 = "O"
    elif player1 == "O":
        player2 == "X"

    print ("The positions on the Tic Tac Toe will be similar to that of the Numpad. ")
    Marker1 = input("Please enter a number between 1 - 9 to place your {} in the corresponding position ".format(player1))


print (player_input())
print ("\n")
display_board(testboard)
place_marker()

1 个答案:

答案 0 :(得分:0)

更改

   player1 == FirstQ
   player2 == "X"

  player1 = FirstQ
  player2 = "X"