Python Forum

Full Version: tic tac toe loop
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I've been having troubles with getting a loop for tic tac toe
here is the code
board = [1, 2, 3, 4, 5, 6, 7, 8, 9]
print("Welcome to Tic-Tac-Toe!")
print(" " + str(board[0]) + " | " + str(board[1]) + " | " + str(board[2]) + " ")
print("-----------")
print(" " + str(board[3]) + " | " + str(board[4]) + " | " + str(board[5]) + " ")
print("-----------")
print(" " + str(board[6]) + " | " + str(board[7]) + " | " + str(board[8]) + " ")

board_location = input("Enter the board location to play for player X: ")
board_location = int(board_location)
board_index = board_location - 1
board[board_index] = "X"
print(" " + str(board[0]) + " | " + str(board[1]) + " | " + str(board[2]) + " ")
print("-----------")
print(" " + str(board[3]) + " | " + str(board[4]) + " | " + str(board[5]) + " ")
print("-----------")
print(" " + str(board[6]) + " | " + str(board[7]) + " | " + str(board[8]) + " ")

board_location = input("Enter the board location to play for player O: ")
board_location = int(board_location)
board_index = board_location - 1
board[board_index] = "O"
print(" " + str(board[0]) + " | " + str(board[1]) + " | " + str(board[2]) + " ")
print("-----------")
print(" " + str(board[3]) + " | " + str(board[4]) + " | " + str(board[5]) + " ")
print("-----------")
print(" " + str(board[6]) + " | " + str(board[7]) + " | " + str(board[8]) + " ")
You can find details on how to loop code here
If you know how to create functions you can move a lot of your repetitive code into functions.
For example, the way you display the board can be shortened by using a for loop. For loops look like
for item in iterable:
followed by the code you wish to repeat.

Range gives you an iterable, good to read up on the options with that. range(start, end, step) would be useful here. If you step by 3 you can do something like
for position in range(0,7,3):
    print(" " + str(board[position]) + " | " + str(board[position+1]) + " | " + str(board[position+2]) + " ")
First time through the loop it prints the first 3 positions. Second time it does the next 3, and third time through get the final 3. Note that range does not include the end value, so that is why it is 7 rather than 6.

Yoriz is absolutely right that using functions would help even more. Move that loop into a function called board_update() and your code shrinks even more. You just get the "move", call board_update which you have crafted to draw the board, and do that repeatedly for the turns.

However, if you are just learning loops you are probably not to the point of functions.

So, then think about what kind of loop you want to you to cycle back and forth between the X player and the O player. Maybe a while, and check the input to be sure the user has not entered a special value like "quit"?

You need to write the code, but there are some ideas for you. We are here if needed.