Tic Tac Toe is a classic two-player game where the objective is to get three of one's own symbols (either 'X' or 'O') in a row, whether horizontally, vertically, or diagonally, on a 3x3 grid. Let's dive into creating this game in Python!
1. Introduction
Python, with its simple and readable syntax, is a great language for beginner projects such as the Tic Tac Toe game. This project will be implemented using a class-based approach, where the game mechanics and methods related to the Tic Tac Toe board are encapsulated within a class.
2. The Code
class TicTacToe:
def __init__(self):
self.board = [' '] * 9
self.current_winner = None
def print_board(self):
for row in [self.board[i*3:(i+1)*3] for i in range(3)]:
print('| ' + ' | '.join(row) + ' |')
@staticmethod
def print_board_nums():
number_board = [[str(i) for i in range(j*3, (j+1)*3)] for j in range(3)]
for row in number_board:
print('| ' + ' | '.join(row) + ' |')
def available_moves(self):
return [i for i, spot in enumerate(self.board) if spot == ' ']
def make_move(self, square, letter):
if self.board[square] == ' ':
self.board[square] = letter
if self.check_winner(square, letter):
self.current_winner = letter
return True
return False
def check_winner(self, square, letter):
# Check row
row_ind = square // 3
row = self.board[row_ind*3:(row_ind+1)*3]
if all([s == letter for s in row]):
return True
# Check column
col_ind = square % 3
col = [self.board[col_ind+i*3] for i in range(3)]
if all([s == letter for s in col]):
return True
# Check diagonals
if square % 2 == 0:
diag1 = [self.board[i] for i in [0, 4, 8]]
if all([s == letter for s in diag1]):
return True
diag2 = [self.board[i] for i in [2, 4, 6]]
if all([s == letter for s in diag2]):
return True
return False
if __name__ == '__main__':
t = TicTacToe()
t.print_board_nums()
current_player = "X"
while ' ' in t.board:
try:
move = int(input(f"Enter your move for {current_player} (0-8): "))
if move in t.available_moves():
t.make_move(move, current_player)
t.print_board()
if t.current_winner:
print(f"{current_player} wins!")
break
current_player = "O" if current_player == "X" else "X"
else:
print("Invalid move! Try again.")
except ValueError:
print("Please enter a number between 0 and 8.")
else:
print("It's a tie!")
3. Key Components
Game Board: The board is represented as a list with nine elements.
Displaying the Board: We have methods to print the board to the console.
Gameplay Mechanics: We keep track of available moves and also check if a particular move results in a win.
Winner Check: After each move, the game checks for a win condition, i.e., three of the same symbols in a row.
4. How to Play
Players take turns to enter their desired positions (from 0 to 8) on the board. The positions are as follows:
| 0 | 1 | 2 |
| 3 | 4 | 5 |
| 6 | 7 | 8 |
When a player gets three of their symbols in a row, they win. If the board fills up without a winner, the game ends in a tie.
5. Output
| 0 | 1 | 2 |
| 3 | 4 | 5 |
| 6 | 7 | 8 |
Enter your move for X (0-8): 0
| X | | |
| | | |
| | | |
Enter your move for O (0-8): 1
| X | O | |
| | | |
| | | |
Enter your move for X (0-8): 4
| X | O | |
| | X | |
| | | |
Enter your move for O (0-8): 5
| X | O | |
| | X | O |
| | | |
Enter your move for X (0-8): 6
| X | O | |
| | X | O |
| X | | |
Enter your move for O (0-8): 8
| X | O | |
| | X | O |
| X | | O |
Enter your move for X (0-8): 3
| X | O | |
| X | X | O |
| X | | O |
X wins!
>
6. Conclusion
Building a Tic Tac Toe game in Python is a wonderful exercise to familiarize oneself with fundamental programming concepts such as loops, conditions, and data structures like lists. Not only does it improve coding skills, but the end result is also a fun, interactive game to play. Additionally, this project can be expanded further. Consider adding a graphical user interface (GUI) using Python libraries like Tkinter or Pygame, or even an AI opponent using basic AI algorithms. The possibilities are endless, and the learning never stops!