Tic-tac-toe is a very interesting and fun game that many of us have played and enjoyed over the years. However, sometimes we want to make things more challenging by adding a blocker to the game. In this Answer, we’ll make a tic-tac-toe game with a blocker in Python.
We will break down the whole process into small sections, and the whole code will be joined together at the end.
To start, let’s create a tic-tac-toe board using a nested list:
board = [[" ", " ", " "],[" ", " ", " "],[" ", " ", " "]]
The nested list represents a 3x3 grid, where each cell is initially set to " "
. We can print the board using a for
loop, as shown below:
def print_board():for row in board:print("|".join(row))
Next, we want to add a blocker to the game. The blocker is a cell that cannot be filled by either player, and it is typically placed in the center of the board. We can add the blocker to the board by setting the center cell to "X"
, as shown below:
board[1][1] = "X"
Now, let's create a function to check if a move is valid. A move is valid if the cell is not already occupied and it is not the blocker cell:
def is_valid_move(row, col):if board[row][col] != " ":return Falseif row == 1 and col == 1:return Falsereturn True
We can now create a function to make a move. The function takes the row, column, and player as arguments and sets the cell to the player’s symbol ("X"
or "O"
):
def make_move(row, col, player):if is_valid_move(row, col):board[row][col] = playerreturn Truereturn False
Next, we need to check if a player has won the game. We can do this by checking if any of the rows, columns, or diagonals contain three of the same symbol:
def has_won(player):# Check rowsfor row in board:if row.count(player) == 3:return True# Check columnsfor col in range(3):if board[0][col] == player and board[1][col] == player and board[2][col] == player:return True# Check diagonalsif board[0][0] == player and board[1][1] == player and board[2][2] == player:return Trueif board[0][2] == player and board[1][1] == player and board[2][0] == player:return Truereturn False
Finally, we can create a main game loop that alternates between players and prompts them to enter their moves:
def play_game():print("Welcome to Tic Tac Toe!")print_board()player = "X"moves_remaining = 8 # Tracks the number of moves remaining (excluding board[1][1])while True:try:row = int(input(f"{player}, enter row (0-2): "))col = int(input(f"{player}, enter column (0-2): "))if row < 0 or row > 2 or col < 0 or col > 2:raise ValueError("Invalid input. Row and column must be between 0 and 2.")if make_move(row, col, player):moves_remaining -= 1print_board()if has_won(player):print(f"{player} has won!")breakif moves_remaining == 0:print("It's a tie!")breakplayer = "O" if player == "X" else "X"else:print("Invalid move. Try again.")except ValueError as e:print(str(e))except KeyboardInterrupt:print("\nGame interrupted. Exiting...")break
With this code, we have created a fully functional tic-tac-toe game with a blocker. To play the game, run the play_game()
function. The game will prompt the first player (X) to enter their move, followed by the second player (O), and so on, until a player wins or the game ends in a tie.
We will add a try-except
block around the user input section. Its job is to catch potential ValueError
exceptions if the user enters an invalid row or column value, such as row 3, or column 2. If an invalid input is detected, it raises a ValueError
exception with an appropriate error message, which is then caught and printed.
We also add an exception for KeyboardInterrupt
(“Ctrl” + “C”) so that if the user interrupts the game, it prints a message and exits gracefully.
The full code is shown below:
board = [[" ", " ", " "], [" ", " ", " "], [" ", " ", " "]] def print_board(): for row in board: print("|".join(row)) def is_valid_move(row, col): if board[row][col] != " ": return False if row == 1 and col == 1: return False return True def make_move(row, col, player): if is_valid_move(row, col): board[row][col] = player return True return False def has_won(player): # Check rows for row in board: if row.count(player) == 3: return True # Check columns for col in range(3): if board[0][col] == player and board[1][col] == player and board[2][col] == player: return True # Check diagonals if board[0][0] == player and board[1][1] == player and board[2][2] == player: return True if board[0][2] == player and board[1][1] == player and board[2][0] == player: return True return False def play_game(): print("Welcome to Tic Tac Toe!") print_board() player = "X" moves_remaining = 8 # Tracks the number of moves remaining (excluding board[1][1]) while True: try: row = int(input(f"{player}, enter row (0-2): ")) col = int(input(f"{player}, enter column (0-2): ")) if row < 0 or row > 2 or col < 0 or col > 2: raise ValueError("Invalid input. Row and column must be between 0 and 2.") if make_move(row, col, player): moves_remaining -= 1 print_board() if has_won(player): print(f"{player} has won!") break if moves_remaining == 0: print("It's a tie!") break player = "O" if player == "X" else "X" else: print("Invalid move. Try again.") except ValueError as e: print(str(e)) except KeyboardInterrupt: print("\nGame interrupted. Exiting...") break play_game()
In this Answer, we have learned how to make a tic-tac-toe game with a blocker using Python. We have used nested lists to create the game board and implemented functions to check for valid moves, make moves, and check for winning conditions. We can apply this knowledge to get hands-on experience in different and customized tic-tac-toe games with varying difficulty levels.
Free Resources