Python Colorful Tic Tac Toe Game using PyQt GUI

By | October 30, 2023

Python Colorful Tic Tac Toe Game – This version of the Tic Tac Toe program provides a complete and functional game with the ability to check for a winner, highlight the winning row, announce a draw, reset the game, and exit the application. Players can take turns clicking the buttons to play the game.

Python Colorful Tic Tac Toe Game using PyQt GUI

Python Colorful Tic Tac Toe Game using PyQt GUI

Source Code

import sys
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QVBoxLayout, QLabel, QHBoxLayout, QMessageBox

class TicTacToe(QWidget):
    def __init__(self):
        super().__init__()
        self.init_ui()

    def init_ui(self):
        self.setWindowTitle("Tic Tac Toe")
        self.setGeometry(100, 100, 300, 400)
        self.setStyleSheet("background-color: lightgreen;")

        self.buttons = [None] * 9
        self.turn = 'X'
        self.winning_row = None

        main_layout = QVBoxLayout()

        self.turn_label = QLabel("It's Your Turn: Player 1", self)
        self.turn_label.setStyleSheet("font-size: 16px; color: blue;")
        main_layout.addWidget(self.turn_label)

        for row in range(3):
            row_layout = QHBoxLayout()
            for col in range(3):
                index = row * 3 + col
                button = QPushButton('', self)
                button.setStyleSheet("font-size: 24px; height: 60px; background-color: lightblue; color: red;")
                button.clicked.connect(lambda state, button=button, i=index: self.button_clicked(button, i))
                self.buttons[index] = button
                row_layout.addWidget(button)
            main_layout.addLayout(row_layout)

        reset_button = QPushButton('Reset', self)
        reset_button.clicked.connect(self.reset_board)
        reset_button.setStyleSheet("font-size: 16px; background-color: orange; color: white;")
        main_layout.addWidget(reset_button)

        exit_button = QPushButton('Exit', self)
        exit_button.clicked.connect(self.close)
        exit_button.setStyleSheet("font-size: 16px; background-color: red; color: white;")
        main_layout.addWidget(exit_button)

        self.setLayout(main_layout)

    def button_clicked(self, button, index):
        if button.text() == '' and self.winning_row is None:
            button.setText(self.turn)
            button.setDisabled(True)
            if self.check_winner():
                self.highlight_winning_row()
                QMessageBox.information(self, 'Tic Tac Toe', f'Player {self.turn} wins!')
            else:
                self.turn = 'O' if self.turn == 'X' else 'X'
                self.turn_label.setText(f"It's Your Turn: {'Player 1' if self.turn == 'X' else 'Player 2'}")
            if all(button.text() != '' for button in self.buttons) and not self.winning_row:
                self.announce_draw()

    def check_winner(self):
        for line in ((0, 1, 2), (3, 4, 5), (6, 7, 8), (0, 3, 6), (1, 4, 7), (2, 5, 8), (0, 4, 8), (2, 4, 6)):
            a, b, c = line
            if self.buttons[a].text() == self.buttons[b].text() == self.buttons.text() != '':
                self.winning_row = line
                return True
        return False

    def highlight_winning_row(self):
        if self.winning_row:
            for index in self.winning_row:
                self.buttons[index].setStyleSheet("font-size: 24px; height: 60px; background-color: yellow; color: red")

    def announce_draw(self):
        self.turn_label.setText("It's a Draw!")

    def reset_board(self):
        for button in self.buttons:
            button.setText('')
            button.setDisabled(False)
            button.setStyleSheet("font-size: 24px; height: 60px; background-color: lightblue; color: red")
        self.turn = 'X'
        self.turn_label.setText("It's Your Turn: Player 1")
        self.winning_row = None

if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = TicTacToe()
    window.show()
    sys.exit(app.exec_())

Explanation

I’d be happy to explain the last version of the Tic Tac Toe program. This version includes various features, including a way to check for a draw, highlight the winning row, and reset the game. Here’s a breakdown of the key components and functionality:

  1. Importing Required Libraries:
    • We start by importing the necessary libraries. In this program, we use PyQt5 for the graphical user interface.
  2. TicTacToe Class:
    • We create a class named TicTacToe that inherits from QWidget, which is the base class for all user interface objects in PyQt.
  3. Initialization (__init__):
    • In the constructor, we initialize the application and define the initial state of the game.
  4. User Interface Initialization (init_ui):
    • This method sets up the graphical user interface for the game.
    • It creates a window with the title “Tic Tac Toe” and a light green background.
    • It creates a label to display whose turn it is and sets its initial text to “It’s Your Turn: Player 1.”
    • It creates a grid of nine buttons for the game board, each with a large font and colorful styling.
    • It also creates “Reset” and “Exit” buttons at the bottom of the window.
  5. Button Click Handling (button_clicked):
    • The button_clicked method is called when a game button is clicked.
    • It checks if the clicked button is empty and if there is no winner.
    • If both conditions are met, it sets the button’s text to the current player’s symbol (either X or O), disables the button, and checks for a winner.
    • If a winner is found, it highlights the winning row, displays a message indicating the winner, and prevents further moves.
    • If there is no winner and all buttons are filled, it announces a draw.
    • It then updates the current player’s turn.
  6. Checking for a Winner (check_winner):
    • The check_winner method examines the board for a winning combination.
    • It checks all possible combinations of three buttons to determine if any of them are occupied by the same player’s symbol (either X or O).
    • If a winning combination is found, it returns True; otherwise, it returns False.
  7. Highlighting the Winning Row (highlight_winning_row):
    • When a winning combination is detected, this method highlights the buttons in the winning row.
    • It changes the background color of the winning buttons to yellow.
  8. Announcing a Draw (announce_draw):
    • If there is no winner and all buttons are filled, this method updates the label to announce a draw.
  9. Resetting the Board (reset_board):
    • The reset_board method resets the game by clearing all button texts, enabling all buttons, restoring their default style, and resetting the turn label to “It’s Your Turn: Player 1.”
  10. Main Execution (if __name__ == '__main__':):
    • This section creates an instance of the TicTacToe class, shows the application’s window, and starts the main event loop.

 

Loading

Leave a Reply

Your email address will not be published. Required fields are marked *