简体   繁体   English

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

[英]Beginner problem, writing my first code. Not sure about this problem

I'm a beginner coder learning how to use Python and writing my first tic-tac-toe code.我是一名初学者,正在学习如何使用 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"

So what I am trying to do is once a player selects whether they're either X or O. I'm trying to assign that to the player.所以我想做的是一旦玩家选择他们是X还是O。我试图将其分配给玩家。

When I type X, the code runs fine but if I type OI get the following error:当我键入 X 时,代码运行正常,但如果我键入 OI,则会收到以下错误:

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

Can someone explain how this works?有人可以解释这是如何工作的吗?

Here is the entire code that I've done so far:这是我到目前为止所做的全部代码:

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

Change改变

   player1 == FirstQ
   player2 == "X"

to

  player1 = FirstQ
  player2 = "X"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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