-1

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".

Pranav Hosangadi
  • 23,755
  • 7
  • 44
  • 70
Soapy
  • 13
  • 3
  • Should the past choices, that is past positions on the board be retained? Or should the board be cleared on each iteration? – Dima Chubarov Jun 29 '22 at 14:36
  • Does this answer your question? [How do I create variable variables?](https://stackoverflow.com/questions/1373164/how-do-i-create-variable-variables) – Pranav Hosangadi Jun 29 '22 at 14:38

1 Answers1

3

I think a dictionary is a good way to go here.

  1. First store the board represented in a dictionary (All positions are empty "_")
  2. Create a function for printing the board
  3. 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
Ilmard
  • 86
  • 4