diff --git a/tictactoe/tictactoe.py b/tictactoe/tictactoe.py index 18bb718..61dd5fe 100644 --- a/tictactoe/tictactoe.py +++ b/tictactoe/tictactoe.py @@ -1,4 +1,11 @@ from random import randrange +import os + +# ANSI escape codes for colors and bold text +RED_BOLD = "\033[1;31m" +BLUE_BOLD = "\033[1;34m" +RESET = "\033[0m" + # display_board(board) to print the board # victory_for(board) to check if a player has won @@ -8,14 +15,27 @@ # person_move(board,sign) to draw the player's move # game_round(option) to initialize the game +def clear_screen(): + os.system('cls' if os.name == 'nt' else 'clear') + def display_board(board): + clear_screen() # Clears the terminal before displaying the board # The function accepts one parameter containing the board's current status # and prints it out to the console. for row in range(3): print("+-------+-------+-------+") print("| | | |") - print("| {} | {} | {} |".format(board[row][0],board[row][1],board[row][2])) - print("| | | |") + print("|", end="") + for col in range(3): + cell = board[row][col] + if cell == 'x': + cell_display = f"{RED_BOLD}X{RESET}" + elif cell == 'o': + cell_display = f"{BLUE_BOLD}O{RESET}" + else: + cell_display = str(cell) + print(f" {cell_display} |", end="") + print("\n| | | |") print("+-------+-------+-------+") def victory_for(board): @@ -53,13 +73,34 @@ def number_available(board,n): return False def computer_move(board): - # The function draws the computer's move and updates the board. - found = False - while not found: - n = randrange(1,10) - if number_available(board,n): found = True + def check_win_or_block(sign): + for i in range(3): + for j in range(3): + if isinstance(board[i][j], int): # Check if the cell is empty + original = board[i][j] + board[i][j] = sign + if victory_for(board): + board[i][j] = original # Revert after check + return (i, j) + board[i][j] = original # Revert after check + return None + + # Step 1: Try to win + move = check_win_or_block('x') + + # Step 2: Try to block the player from winning + if not move: + move = check_win_or_block('o') + + # Step 3: Random move if no win or block + if not move: + empty = [(i, j) for i in range(3) for j in range(3) if isinstance(board[i][j], int)] + move = empty[randrange(len(empty))] + + i, j = move + board[i][j] = 'x' + display_board(board) - calculate(board,n,'x') def person_move(board,sign=''): # The function accepts the board's current status, asks the user about their move,