this is a function from my tic tac toe. when i run this functions in a while loop multiple times, the values of the keys in dic always remain the same (1,2,3,...) I wanted them to change after "dic[field] = current_player" and stay in this condition
def user_input():
dic = {
"empty_1": "1",
"empty_2": "2",
"empty_3": "3",
"empty_4": "4",
"empty_5": "5",
"empty_6": "6",
"empty_7": "7",
"empty_8": "8",
"empty_9": "9",
}
print(dic["empty_2"]) # always prints out 2
line = "----------"
x1 = dic["empty_1"] " | " dic["empty_2"] " | " dic["empty_3"]
x2 = dic["empty_4"] " | " dic["empty_5"] " | " dic["empty_6"]
x3 = dic["empty_7"] " | " dic["empty_8"] " | " dic["empty_9"]
playground = x1 "\n" line "\n" x2 "\n" line "\n" x3 "\n"
check = "123456789"
count = 2
player_1 = "X"
player_2 = "O"
current_player = ""
flag = False
print(playground)
decision = str(input("Enter field-number: "))
if count % 2 == 0:
current_player = player_1
else:
current_player = player_2
field = "empty_" decision
if dic[field] in check:
dic[field] = current_player
print(dic["empty_2"]) # prints out "X"
flag = True
else:
print("Can´t place there!")
print()
count = 1
flag = False
return dic
CodePudding user response:
For the ease of understanding let's do a review on your code
Code review
def user_input():
# Just Define the `dic` at the beginning of the function
dic = {
"empty_1": "1",
"empty_2": "2", # Here "empty_2" is "2",
# Otherwise "2" is assigned into dic["empty_2"]
"empty_3": "3",
"empty_4": "4",
"empty_5": "5",
"empty_6": "6",
"empty_7": "7",
"empty_8": "8",
"empty_9": "9",
}
print(dic["empty_2"]) # And here you are Just calling the value of
# dic["empty_2"] just right after assigning "2"
# as its value
# So the result is "2"
line = "----------"
How to fix the mistake you have done?
Right now the dic
is a private variable inside the function. You have to define the dic
outside of this function as a global variable and remove the dic = {...
part from the function.
CodePudding user response:
Not exactly sure what you intended to do with the dict but if it should track, which board location is occupied by which player you might want to restructure your dict like this:
board = { "1" : "empty","2" : "empty","3" : "empty",
"4" : "empty","5" : "empty","6" : "empty",
"7" : "empty","8" : "empty","9" : "empty"
}
And later in your code when the curent player "claims" a position you can just get the board position by doing:
board["1"] = "Player1"
After each pick you check if the target state (3 in a row or non empty) is reached.
About your problem i would say you might want to have a look at poping values if you truly want to get rid of key-value pairs because otherwise those keys stay in the dict until the reference to it is destructet (dic = None).
As stated i am not 100% sure what you tried to achieve with the dict.