I'm making a simple tic tac toe game in Python. I thought it would be easier for the user if I made the Xs and Os colored. During gameplay, the first few iterations work fine, but then after a full row is in color, the string gets distorted and I can't figure out why.
The initial board is a string that I format like this:
def get_board():
board = ""
for i in range(9):
if i == 1 or i == 4 or i == 7:
board += f" {i} | {i+1} | {i+2} \n"
else:
board += " |" * 2 + " \n"
if i == 2 or i == 5:
board += "- " * 7 + "-\n"
return board
And then gameplay works like this:
def play_move(number, player, board):
PURPLE = '\033[35m'
YELLOW = '\033[33m'
ENDC = '\033[0m'
player = f"{PURPLE}{player}{ENDC}" if player == 'o' else f"{YELLOW}{player}{ENDC}"
return board.replace(number, player)
def main():
filled_spaces = []
players = ["o", "x"]
x = 0
board = get_board()
print(board)
while x < 9:
space = input(
f"Enter a space on the board for player '{players[x%2]}'\n")
board = play_move(space, players[x % 2], board)
filled_spaces.append(space)
x += 1
print(board)
And then here's what happens
First round: o chooses 1
Second round: x chooses 2
Third round: o chooses 3
This is the full code if you want to try:
import sys
def get_board():
board = ""
for i in range(9):
if i == 1 or i == 4 or i == 7:
board += f" {i} | {i+1} | {i+2} \n"
else:
board += " |" * 2 + " \n"
if i == 2 or i == 5:
board += "- " * 7 + "-\n"
return board
def play_move(number, player, board):
PURPLE = '\033[35m'
YELLOW = '\033[33m'
ENDC = '\033[0m'
player = f"{PURPLE}{player}{ENDC}" if player == 'o' else f"{YELLOW}{player}{ENDC}"
return board.replace(number, player)
def main():
filled_spaces = []
players = ["o", "x"]
x = 0
board = get_board()
print(board)
while x < 9:
space = input(
f"Enter a space on the board for player '{players[x%2]}'\n")
if space not in filled_spaces:
board = play_move(space, players[x % 2], board)
filled_spaces.append(space)
x += 1
else:
print(
f"\nERROR: {space} has already been taken, choose a different space\n")
print(board, flush=True)
print("GAME OVER")
if __name__ == "__main__":
main()




Let the grid just contain the moves, and do the formatting when you print: