Building My First Game in Python: A Journey of Learning and Progress
Tags: beginners, python, programming, computerscience
Published: 2023-07-06 21:09:37

As a student of computer science, I embarked on an exciting journey to learn and apply my programming skills. One of my first projects was to build a Tic Tac Toe game using Python, which allowed me to showcase my progress and newfound knowledge of the language.

Through the development of this Tic Tac Toe game, I learned about fundamental concepts such as data structures, conditional statements, user input, and game logic. I was able to apply these concepts to create a functional game that provided an enjoyable user experience.

![Tic Tac Toe Command-Line](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bmywsvge7uqmim402oz1.PNG)

This is my Python implementation of a Tic Tac Toe Game. Basically, it consists of two clases: **`TicTacToe`** and **`Player`**

```python
class TicTacToe:
    def __init__(self):
        self.available_cells = ['A1', 'A2', 'A3', 'B1', 'B2', 'B3', 'C1', 'C2', 'C3']
        self.players = []
        self.table = """
            A   B   C

        1   A1  B1  C1

        2   A2  B2  C3

        3   A3  B3  C3"""
        self.winner = ''
        self.last_played = ''
        self.combinations_to_win = [
            ['A1', 'A2', 'A3'],
            ['B1', 'B2', 'B3'],
            ['C1', 'C2', 'C3'],
            ['A1', 'B1', 'C1'],
            ['A2', 'B2', 'C2'],
            ['A3', 'B3', 'C3'],
            ['A1', 'B2', 'C3'],
            ['A3', 'B2', 'C1']
        ]
```

The **`TicTacToe`** class handles the game logic and flow. It keeps track of the available cells, players, game table, winner, and the last played move. It also includes a list of combinations needed to win the game. 

```python
def start_game(self, phase = 0):
        self.available_cells = ['A1', 'A2', 'A3', 'B1', 'B2', 'B3', 'C1', 'C2', 'C3']
        self.table = """
            A   B   C

        1   A1  B1  C1

        2   A2  B2  C3

        3   A3  B3  C3"""
        self.winner = ''
        self.last_played = ''
        if phase == 0:
            self.players = []
            print("Welcome to Sebas TicTacToe made in Python 3, hope you enjoy while playing!")
            print("Let's begin by setting your names")
            player1 = Player(input("Player1's name: "), self)
            player2 = Player(input("Player2's name: "), self)
            self.players.extend([player1, player2])
            print("Let's start!")
            self.start_game(1)
        if phase == 1:
            player1 = self.get_player(1)
            player2 = self.get_player(2)
            while self.check_winner() == False:
                self.draw_table()
                if self.last_played == self.get_player(1):
                    player2.play_round()
                else:
                    player1.play_round()
            self.draw_table()
            print("We have a winner!")
            print("Congratulations on winning {winner_name}".format(winner_name=self.winner))
            play_again = input("Do you wish to play again? (Y/N) ")
            if play_again == 'Y':
                for player in self.players:
                    player.played_cells = []
                self.start_game(1)
            else:
                print("Okay! Have a great day.")
```

The **`start_game`** method initializes the game, allows players to enter their names, and resets the game once it's over. 

```python
def draw_table(self):
        table_to_draw = self.table
        for cell in self.available_cells:
            table_to_draw = table_to_draw.replace(cell, ' ')
        print(table_to_draw)
```

The **`draw_table`** method displays the current state of the game board. 

```python
def check_winner(self):
        for player in self.players:
            for combination in self.combinations_to_win:
                if all(cell in player.played_cells for cell in combination):
                    self.winner = player.name
                    return True
        return False
```

The **`check_winner`** method checks if a player has won the game by comparing the played cells against the winning combinations.

```python
class Player:
    def __init__(self, name, game):
        self.name = name
        self.game = game
        self.played_cells = []
```

The **`Player`** class represents a player in the game. Each player has a name, the game instance they are on, and a list of played cells.

```python
def play_round(self):
        print("{player_name} it's your turn".format(player_name=self.name))
        selected_cell = input("Select one cell (Ex: A1, B2, C3): ")
        while selected_cell not in self.game.available_cells:
            print("Please select a valid cell")
            selected_cell = input("Select one cell (Ex: A1, B2, C3): ")
        self.played_cells.append(selected_cell)
        self.game.available_cells.remove(selected_cell)
        if self.is_o():
            self.game.table = self.game.table.replace(selected_cell, 'O ')
        elif self.is_x():
            self.game.table = self.game.table.replace(selected_cell, 'X ')
        self.game.last_played = self
```

The **`play_round`** method allows the player to select a cell to play and updates the game board accordingly.

{% embed https://github.com/sebasxm00/Sebas-TicTacToe %}

In conclusion, this Tic Tac Toe project serves as a significant milestone in my journey as a computer science student. Through the development of this game, I had the opportunity to apply my Python skills, reinforce my understanding of programming concepts, and enhance my problem-solving abilities.

Moving forward, I look forward to expanding my skill set, exploring new technologies, and taking on more challenging projects. This Tic Tac Toe game is just the beginning, and I am excited to continue my learning journey in the world of programming.

Thank you for joining me on this journey of building a Tic Tac Toe game in Python. I invite you to share your thoughts, suggestions, and contributions.

Happy coding!