0

This code is part of a Tic-Tac-Toe script, in which a player inputs a number based on what space they wish to place their marker. To test the script out, I only wrote code for board[1].

board = ['','','','','','','','','','']
count = 0
turn_counter = 1

def print_board():
    print(board[1] +  "  |"  + board[2]  +  "  |"  +  board[3])
    print("--+--+--")
    print(board[4] +  "  |"  + board[5]  +  "  |"  +  board[6])
    print("--+--+--")
    print(board[7] +  "  |"  + board[8]  +  "  |"  +  board[9])

def main_operator(board_val):
    global turn_counter
    global count
 
    if turn_counter == 1:
        board_val = 'X'
        count = count + 1
        turn_counter = turn_counter + 1

    elif turn_counter == 2:
        board_val = 'O'
        count = count + 1
        turn_counter = turn_counter - 1
    
def game_start():
    user_input = int(input("Player " + str(turn_counter) + ", choose a space"))
    if user_input == 1:
    main_operator(board[1])

for i in range(9):
    print_board()
    game_start()

However, the main_operator() function does not change the value for board[1], instead leaving it unchanged. What am I doing wrong?

  • 1
    If you had instead called, say, `main_operator('X')`, what would you expect to happen? Should that cause the alphabet to change? – Karl Knechtel Nov 25 '20 at 20:45
  • 1
    The linked "duplicate" includes an explanation of *how parameter passing works*. You should also read https://nedbatchelder.com/text/names1.html . But to solve the problem in your case, the simplest approach is to pass the entire `board` as well as the desired index, and have the function do the indexing (since assigning to the index is a mutating operation). – Karl Knechtel Nov 25 '20 at 20:48
  • When you assign `board_val = 'X'` then the value of `board_val` is no longer bound to your global `board[1]`. Think you want to do some changes to the values IN `board_val` like maybe `board_val[1] = 'X'`and pass the whole list to main_operator. – Andrew Allaire Nov 25 '20 at 20:48

0 Answers0