Search code examples
pythonlistpython-3.xtic-tac-toe

how to implement a list


im trying to create a tic-tac-toe game; but im having a little bit of trouble. I have created a list with numbers in it, so when that number is chosen it changes to an x or o. however when my board prints it has the numbers 0,1,2,3,4,5,6,7,8 in them and I don't want them to be like that. my question would be how can I change the characters in an empty list ? would I use indexes or is there another way of doing it

board = [0,1,2,
         3,4,5,
         6,7,8]

def gameBoard():
    print("    " "a" "   " "b" "   " "c")
    print("  ""-------------")
    print(("1"),("|"),board[0],"|",board[1], "|" ,board[2], "|")
    print("  ""-------------")
    print(("2"),("|"),board[3],"|",board[4], "|" ,board[5], "|")
    print("  ""-------------")   
    print(("3"),("|"),board[6],"|",board[7], "|" ,board[8], "|")
    print("  ""-------------")    


while True:
    user_input = input("Enter your move: ")
    if user_input == "a1":
        user_input = "0"
    elif user_input == "a2":
        user_input = "3" 
    elif user_input == "a3":
        user_input="6"
    elif user_input == "b1":
        user_input = "1"
    elif user_input == "b2":
        user_input = "4"
    elif user_input== "b3":
        user_input = "7"
    elif user_input == "c1":
        user_input = "2"
    elif user_input == "c2":
        user_input = "5"
    elif user_input == "c3":
        user_input = "8"
    else:
        print("invalid coordinates")
    user_input= int(user_input)

Solution

  • From your code, you are filling the board with ints 0 - 8. If you check board[7] it will return 7.

    I think you want to intialize the board with spaces, so that board[7] will return ' ' (blank space).

    You can do board = [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ']

    Or more cleanly,

    board = [' '] * 9

    Hope this helps :) Using a matrix is also not a bad idea for implementation, but is different than this problem you are trying to solve