📘 Premium Read: Access my best content on Medium member-only articles — deep dives into Java, Spring Boot, Microservices, backend architecture, interview preparation, career advice, and industry-standard best practices.
🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.
▶️ Subscribe to My YouTube Channel (176K+ subscribers): Java Guides on YouTube
▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube
Building a Tic-Tac-Toe game in Python is an excellent way to get comfortable with Python basics and learn about game development. This tutorial will guide you through creating a console-based game that allows two players to play against each other.
Step 1: Set Up The Game Board
First, create a representation of the game board. A simple approach is to use a list.
def initialize_board(): return [" " for _ in range(9)]
Step 2: Display The Board
Next, create a function to display the current state of the board to the console.
def display_board(board): for i in range(3): print("|".join(board[i*3:i*3+3])) if i < 2: print("-----")
Step 3: Player Move
Write a function to allow players to make a move. Ensure the move is valid (i.e., within the board and not on a taken spot).
def player_move(board, player): valid_move = False while not valid_move: move = input(f"Player {player}, enter your move (1-9): ") if not move.isdigit() or not 1 <= int(move) <= 9: print("Invalid input. Please enter a number between 1 and 9.") elif board[int(move)-1] != " ": print("This space is already taken.") else: valid_move = True board[int(move)-1] = player
Step 4: Check for a win or Tie
Implement a function to check if the game has been won or if it's a tie.
def check_win(board): win_conditions = [(0, 1, 2), (3, 4, 5), (6, 7, 8), (0, 3, 6), (1, 4, 7), (2, 5, 8), (0, 4, 8), (2, 4, 6)] for condition in win_conditions: if board[condition[0]] == board[condition[1]] == board[condition[2]] != " ": return board[condition[0]] return None def check_tie(board): return " " not in board
Step 5: Switch Player
Create a simple mechanism to switch the current player after each move.
def switch_player(player): return "X" if player == "O" else "O"
Step 6: The Main Game Loop
Combine all the functions in a main function to control the game's flow.
def play_game(): board = initialize_board() current_player = "X" winner = None tie = False while not winner and not tie: display_board(board) player_move(board, current_player) winner = check_win(board) tie = check_tie(board) if not winner and not tie: current_player = switch_player(current_player) display_board(board) if winner: print(f"Player {winner} wins!") else: print("It's a tie!")
Step 7: Start The Game
Finally, ensure the game starts by calling play_game() when the script is executed directly.
if __name__ == "__main__": play_game()
Complete Code
Combine all the snippets above into a single Python file to complete your Tic Tac Toe game. Players take turns entering their moves, prompted by the console. The game checks for a win or tie after each move, displaying the appropriate message at the end.
# Function to initialize the game board def initialize_board(): return [" " for _ in range(9)] # Function to display the game board def display_board(board): for i in range(3): print("|".join(board[i*3:i*3+3])) if i < 2: print("-----") # Function to handle player moves def player_move(board, player): valid_move = False while not valid_move: try: move = int(input(f"Player {player}, enter your move (1-9): ")) - 1 if board[move] == " ": board[move] = player valid_move = True else: print("This space is already taken.") except (ValueError, IndexError): print("Invalid input. Please enter a number between 1 and 9.") # Function to check for a win def check_win(board): win_conditions = [(0, 1, 2), (3, 4, 5), (6, 7, 8), (0, 3, 6), (1, 4, 7), (2, 5, 8), (0, 4, 8), (2, 4, 6)] for condition in win_conditions: if board[condition[0]] == board[condition[1]] == board[condition[2]] != " ": return board[condition[0]] return None # Function to check for a tie def check_tie(board): return " " not in board # Function to switch the current player def switch_player(player): return "X" if player == "O" else "O" # Main game loop def play_game(): board = initialize_board() current_player = "X" winner = None tie = False while not winner and not tie: display_board(board) player_move(board, current_player) winner = check_win(board) tie = check_tie(board) if not winner and not tie: current_player = switch_player(current_player) display_board(board) if winner: print(f"Player {winner} wins!") else: print("It's a tie!") # Start the game if __name__ == "__main__": play_game()
Output:
| | ----- | | ----- | | Player X, enter your move (1-9): 1 X| | ----- | | ----- | | Player O, enter your move (1-9): 2 X|O| ----- | | ----- | | Player X, enter your move (1-9): 5 X|O| ----- |X| ----- | | Player O, enter your move (1-9): 9 X|O| ----- |X| ----- | |O Player X, enter your move (1-9): 4 X|O| ----- X|X| ----- | |O Player O, enter your move (1-9): Invalid input. Please enter a number between 1 and 9. Player O, enter your move (1-9): 7 X|O| ----- X|X| ----- O| |O Player X, enter your move (1-9): 6 X|O| ----- X|X|X ----- O| |O Player X wins! === Code Execution Successful ===
Conclusion
Congratulations! You've built a simple Tic Tac Toe game in Python. This project covers fundamental Python programming concepts, including functions, loops, conditionals, and managing game state. As an extension, consider adding features like replayability, a computer opponent, or even a graphical user interface using a library like Tkinter.
Comments
Post a Comment
Leave Comment