-1

I'm making a Tic Tac Toe game using python, so I'm having trouble with the choose_position() function that I made to choose the position by setting row and slot according to the number the player choose (1 to 9) but the row and slot are always 0 so it's always the first component of the first list that changes and does not change and I don't know why.

Here is example when the user chooses 5 (so row should be equal to 1 and slot equal to 2) but still row and slot are both 0:

screenshot

from tabnanny import check


board = [["-","-","-"],["-","-","-"],["-","-","-"]]
def print_board(board):
    for  row in board:
        for slot in row:
            print(f"{slot}",end=" ")
        print()

def current_user(user):
    if user: return "x"
    else:return "o"

def choose_position(choice,row,slot):
    print("this is choice:",choice,type(choice))#just checking the choice value and type
    if choice in [1,2,3]:
        row = 0
        slot = choice-1
    elif choice in [4,5,6]:
        row = 1
        slot = choice-4
    elif choice in [7,8,9]:
        row = 2
        slot = choice -7

def limit(choice):
    if int(choice)>9 or int(choice)<1:
        print("please enter a number between 1 and 9 if you would be so good")
        return True
    else: return False

def isnum(choice):
    if not choice.isnumeric():
        print("Please enter a valid number if you would be so good")
        return True
    else: return False

def check_input(choice):
    if isnum(choice): return True
    if limit(choice): return True
    return False

def quit(choice):
    if choice == "q": return True
    else: return False

user = True #x means true,false means o
turns = 0
row = 0
slot = 0
while turns < 9:
    print(turns)

    print_board(board)
    active_user = current_user(user)
    choice = input("enter a position between 1 and 9:\n")
    if quit(choice):break

    if check_input(choice):
        print("oups wrong")
        continue
    choose_position(int(choice),row,slot)
    print(row,slot)#just checking row and slot values

    board[row][slot] = active_user

    turns+=1
    user = not user

martineau
  • 119,623
  • 25
  • 170
  • 301
gtam18
  • 1
  • 1

1 Answers1

1

Your problem is, that you pass your variables by value. This means that if you call choose_position(int(choice),row,slot), python makes a local copy (which is only valid inside choose_position() ) of the values row and slot. During the function only those local variables are altered and discarded upon return. The "ouside" variables with the same names will never be changed.

You should research "python pass by reference" and the keyword "ref". Or you could return the values as list (or better even a tuple) and assign them to the passed-in values. Like this:

(row, slot) = choose_position(int(choice))

And in your function you would write:

return (row, slot)
Svenito
  • 188
  • 10