I have some code where I want the inputted position to be replaced with the desired string but I can’t find a way for it to happen from input.
pos1 = ("_")
pos2 = ("_")
pos3 = ("_")
pos4 = ("_")
pos5 = ("_")
pos6 = ("_")
pos7 = ("_")
pos8 = ("_")
pos9 = ("_")
def board():
print(pos1,pos2,pos3)
print(pos4,pos5,pos6)
print(pos5,pos6,pos9)
while True:
board()
print("player one you are x\n")
choice = input("player one enter a position.")
choice = ("x")
I want to have the position that they choose replace the original variable. For example if the user inputs pos1 then the value of pos1 becomes "x".
>Solution :
I think a dictionary is a good way to go here.
- First store the board represented in a dictionary (All positions are empty
"_") - Create a function for printing the board
- Ask the user for input and change the given position to "x" or "o"
Here is a code snippet:
# Initialize the board, represented as a dictionary
pos = {"pos1":"_",
"pos2":"_",
"pos3":"_",
"pos4":"_",
"pos5":"_",
"pos6":"_",
"pos7":"_",
"pos8":"_",
"pos9":"_",
}
def board():
# Function to print the current status of the board
print(pos["pos1"],pos["pos2"],pos["pos3"])
print(pos["pos4"],pos["pos5"],pos["pos6"])
print(pos["pos7"],pos["pos8"],pos["pos9"])
# Run loop
while True:
board()
print("player one you are x\n")
choice = input("player one enter a position.")
pos[choice] = "x" # Modify the board, by assigning an x to the players choice