Python Tic Tac Toe Lesson
Tic-Tac-Toe with Python
In this lesson, we will break down a simple Tic-Tac-Toe game implemented in Python. We will use Object-Oriented Programming (OOP) concepts such as classes, inheritance, and methods.
1. The Player Class
class Player:
def __init__(self, name, symbol):
self.name = name
self.symbol = symbol
- Each player has a name and a symbol (
XorO). - The
__init__method is called the constructor, and it initializes the object.
2. The EnhancedPlayer Class (Inheritance)
class EnhancedPlayer(Player):
def __init__(self, name, symbol):
super().__init__(name, symbol)
self.wins = 0
def add_win(self):
self.wins += 1
print(f"{self.name} now has {self.wins} wins!")
- This class inherits from
Playerusingsuper(). - We added a new attribute
winsto track how many games a player has won.
3. The Board Class
class Board:
def __init__(self):
self.grid = [" "] * 9
self.move_count = 0
def display(self):
print("\n")
print(" " + self.grid[0] + " | " + self.grid[1] + " | " + self.grid[2])
print("---+---+---")
print(" " + self.grid[3] + " | " + self.grid[4] + " | " + self.grid[5])
print("---+---+---")
print(" " + self.grid[6] + " | " + self.grid[7] + " | " + self.grid[8])
print("\n")
- The board is represented by a list of 9 spaces.
- The
display()method prints the current board. - Other methods (not shown here yet) include resetting the board, checking if it’s full, and validating moves.
4. The TicTacToe Class (Game Logic)
class TicTacToe:
def __init__(self, player1, player2):
self.board = Board()
self.players = [player1, player2]
self.current_player = player1
self.game_over = False
def switch_player(self):
self.current_player = (
self.players[1] if self.current_player == self.players[0] else self.players[0]
)
print(f"Now it's {self.current_player.name}'s turn!")
- This class controls the game.
- It keeps track of the board, players, whose turn it is, and whether the game has ended.
- The
switch_playermethod changes the turn.
5. Running the Game
print("=== Welcome to Tic-Tac-Toe ===")
p1_name = input("Enter name for Player 1: ")
p2_name = input("Enter name for Player 2: ")
player1 = EnhancedPlayer(p1_name, "X")
player2 = EnhancedPlayer(p2_name, "O")
game = TicTacToe(player1, player2)
game.play()
- At the end, we create two players and start the game.
- The players take turns until someone wins or the game ends in a tie.
6. Board Size
class Board:
def __init__(self, size=3):
self.size = size
self.grid = [" "] * (size * size) # Creates the board cells
self.move_count = 0
self.move_history = []
- Initializes the board grid with the correct number of empty spaces based on the chosen size.
-
Sets up tracking variables like move_count and move_history for gameplay.
- Hack 1
Try to change the board size
- Hack 2
Chnage the amoount of maekings need in a row to win the round