Tic-Tac-Toe, also known as Noughts and Crosses, is a classic two-player game often played on a grid of 3×3 squares. It’s a great project for beginners to practice Python programming skills. In this blog post, we’ll walk through the process of creating a simple console-based Tic-Tac-Toe game in Python.
The Basics
Tic-Tac-Toe is played on a 3×3 grid, where two players take turns marking a square with their symbol (X or O). The first player to get three of their symbols in a row (horizontally, vertically, or diagonally) wins the game. If all squares are filled without a winner, the game is a draw.
Setting Up the Game Board
We’ll start by setting up the game board as a 3×3 grid represented by a list of lists. Initially, all squares will be empty, represented by spaces. Here’s the code to create the empty board:
board = [[" " for _ in range(3)] for _ in range(3)]
Printing the Board
To display the game board to the players, we’ll create a function called print_board()
. This function will iterate through the grid and print each row with appropriate formatting:
def print_board(board):
for row in board:
print(" | ".join(row))
print("-" * 9)
Checking for a Winner
We need a way to check if a player has won the game. We’ll create a function called check_winner()
that examines the rows, columns, and diagonals to see if a player has three symbols in a row:
def check_winner(board, player):
# Check rows, columns, and diagonals for a win
for i in range(3):
if all(board[i][j] == player for j in range(3)):
return True
if all(board[j][i] == player for j in range(3)):
return True
if all(board[i][i] == player for i in range(3)) or all(board[i][2 - i] == player for i in range(3)):
return True
return False
Checking for a Draw
We also need to check if the game is a draw (all squares are filled without a winner). We’ll create a function called is_board_full()
for this purpose:
def is_board_full(board):
return all(all(cell != " " for cell in row) for row in board)
Main Game Loop
Now, we’ll create the main game loop that allows players to take turns, make their moves, and checks for a winner or a draw. The loop continues until the game is over:
def main():
# Initialize the board and current player
board = [[" " for _ in range(3)] for _ in range(3)]
current_player = "X"
print("Welcome to Tic-Tac-Toe!")
while True:
# Display the current board
print_board(board)
# Get the player's move
row = int(input(f"Player {current_player}, enter the row (0, 1, or 2): "))
col = int(input(f"Player {current_player}, enter the column (0, 1, or 2): "))
# Check for invalid moves
if row < 0 or row > 2 or col < 0 or col > 2 or board[row][col] != " ":
print("Invalid move. Try again.")
continue
# Update the board with the player's move
board[row][col] = current_player
# Check if the current player wins
if check_winner(board, current_player):
print_board(board)
print(f"Player {current_player} wins!")
break
# Check for a draw
if is_board_full(board):
print_board(board)
print("It's a draw!")
break
# Switch to the other player for the next turn
current_player = "O" if current_player == "X" else "X"
if __name__ == "__main__":
main()
Conclusion
And there you have it! You’ve just created a simple Tic-Tac-Toe game in Python. This project is an excellent way to practice basic Python programming concepts, including lists, loops, conditionals, and functions. Feel free to expand on this game by adding more features, such as keeping track of the score or creating a graphical user interface (GUI) for a more interactive experience.