CS 463G & 663: (Intro to) AI
  • Schedule
  • About
  • Assignments
  • Resources
    • AIMA textbook
    • UK Academic Calendar
    • UK Examination Schedule

Homework 2 Starter Files

PySide6 Reversi Game

Browse every file included in the Homework 2 starter package.

Select a filename below to show its complete contents. These are the same files included in the downloadable ZIP, so this page can be used for a live walkthrough in class.

AssignmentDownload ZIP
  • README.md
  • ai.py
  • main.py
  • main_window.py
  • setting_window.py
  • board_widget.py
  • info_widget.py
  • game_logic.py
# Homework 2 starter

This is the PySide6 Reversi game from Spring 2025 Homework 2.

## First steps

Install PySide6, then run the game from this folder:

```bash
python -m pip install PySide6
python main.py
```

The settings window lets you choose a human or AI player for each side. You can use human and random players before completing the assignment.

## Files

- `ai.py`: the original unfinished AI starter, with `utility`, `greedy_ai`, `minimax_ai`, and `alpha_beta_ai` to complete.
- `main.py`: launches the PySide6 application.
- `main_window.py`: connects the game, player settings, and AI agents.
- `setting_window.py`: player selection window.
- `board_widget.py`: board drawing, mouse input, and piece animations.
- `info_widget.py`: score and move history display.
- `game_logic.py`: Reversi game rules.

Complete the four functions in `ai.py` before selecting their corresponding AI players. Follow the Homework 2 assignment for the experiments and report requirements.
import random
def is_valid_move(row, col, board, player):
    if board[row][col] is not None:
        return False

    opponent = "black" if player == "white" else "white"
    directions = [(0, 1), (1, 0), (0, -1), (-1, 0), (1, 1), (-1, -1), (1, -1), (-1, 1)]

    for d_row, d_col in directions:
        r, c = row + d_row, col + d_col
        if not (0 <= r < len(board) and 0 <= c < len(board)) or board[r][c] != opponent:
            continue

        r += d_row
        c += d_col
        while 0 <= r < len(board) and 0 <= c < len(board):
            if board[r][c] is None:
                break
            if board[r][c] == player:
                return True
            r += d_row
            c += d_col

    return False


def change_pieces(row, col, board, player):
    opponent = "black" if player == "white" else "white"
    directions = [(0, 1), (1, 0), (0, -1), (-1, 0), (1, 1), (-1, -1), (1, -1), (-1, 1)]

    for d_row, d_col in directions:
        r, c = row + d_row, col + d_col
        if not (0 <= r < len(board) and 0 <= c < len(board)) or board[r][c] != opponent:
            continue

        r += d_row
        c += d_col
        while 0 <= r < len(board) and 0 <= c < len(board):
            if board[r][c] is None:
                break
            if board[r][c] == player:
                r, c = row + d_row, col + d_col
                while board[r][c] == opponent:
                    board[r][c] = player
                    r += d_row
                    c += d_col
                break
            r += d_row
            c += d_col




def random_ai(board, player):
    valid_moves = []
    for row in range(len(board)):
        for col in range(len(board)):
            if is_valid_move(row, col, board, player):
                valid_moves.append((row, col))

    if not valid_moves:
        return None

    return random.choice(valid_moves)

def utility(board, player):
    # Your code here
    pass

def greedy_ai(board, player):
    # Your code here
    pass

def minimax_ai(board, player, depth):
    # Your code here
    pass

def alpha_beta_ai(board, player, depth):
    # Your code here
    pass
import sys
from PySide6.QtWidgets import QApplication
from main_window import MainWindow


def main():
    app = QApplication(sys.argv)
    window = MainWindow()
    window.show()
    sys.exit(app.exec())


if __name__ == "__main__":
    main()
from PySide6.QtWidgets import QMainWindow
from board_widget import BoardWidget
from setting_window import SettingWindow
from game_logic import ReversiGame
from info_widget import InfoWidget

from ai import greedy_ai, random_ai, minimax_ai, alpha_beta_ai
from PySide6.QtWidgets import QHBoxLayout, QWidget
import time
from concurrent.futures import ThreadPoolExecutor, TimeoutError


class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("Reversi Game")
        self.setGeometry(100, 100, 600, 600)

        # call the setting window
        self.handle_settings()

        # status bar
        self.statusBar().showMessage("Welcome to Reversi Game")

        # menu bar
        self.menu = self.menuBar()
        self.game_menu = self.menu.addMenu("Game")
        self.new_game_action = self.game_menu.addAction("New Game")
        self.new_game_action.triggered.connect(self.handle_settings)
        self.undo_action = self.game_menu.addAction("Undo")
        self.undo_action.triggered.connect(self.handle_undo)

    def create_new_game(self):
        # create the game logic
        self.game = ReversiGame()

        # Create a central widget and set the layout
        central_widget = QWidget()
        self.setCentralWidget(central_widget)
        layout = QHBoxLayout(central_widget)

        # Create and add the board widget to the layout
        self.board = BoardWidget(self)
        layout.addWidget(self.board)

        # Create and add the info widget to the layout
        self.info_widget = InfoWidget()
        layout.addWidget(self.info_widget)

        # calibrate the window size
        self.board_size = self.board.board_size
        self.cell_size = self.board.cell_size
        self.resize(self.board_size * self.cell_size, self.board_size * self.cell_size)

        self.board.animationFinished.connect(self.handle_animation_finished)

    def handle_settings(self):
        # create a setting window and move it to the top
        self.setting_window = SettingWindow()
        self.setting_window.settings_applied.connect(self.apply_settings)
        self.setting_window.show()

    def apply_settings(self, player1, player2):
        self.players = {"black": player1, "white": player2}
        print(self.players)
        self.human_player = []
        if player1 == "human":
            self.human_player.append("black")
        if player2 == "human":
            self.human_player.append("white")
        self.create_new_game()
        self.handle_animation_finished()

    def handle_undo(self):
        # undo the last move
        pass

    def handle_animation_finished(self):
        # update the info widget
        black_score, white_score = self.game.get_score()
        self.info_widget.update_score(black_score, white_score)
        if self.game.history_moves:
            p, r, c = self.game.history_moves[-1]
            self.info_widget.update_history(f"{p.capitalize()}: ({r}, {c})")

        if self.game.is_game_over():
            print("Game Over")
            return
        # check whether there is a valid move for the current player
        if self.game.get_valid_moves(self.game.board, self.game.current_player) == []:
            self.game.switch_player()
            self.board.update_drawing()
        if self.players[self.game.current_player] == "human":
            self.board.user_click_permit = True
        elif self.players[self.game.current_player] == "greedy":
            row, col = greedy_ai(self.game.board, self.game.current_player)
            self.board.place_piece(row, col)
        elif self.players[self.game.current_player] == "random":
            row, col = random_ai(self.game.board, self.game.current_player)
            self.board.place_piece(row, col)
        elif self.players[self.game.current_player] == "minimax" or self.players[self.game.current_player] == "alpha_beta":
            # '''
            def minimax_with_timeout(board, player, depth):
                try:
                    if self.players[player] == "minimax":
                        return minimax_ai(board, player, depth)
                    else:
                        # Implement alpha-beta pruning
                        return alpha_beta_ai(board, player, depth)
                except Exception as e:
                    print(f"Error during minimax execution: {e}")
                    return None

            best_move = None
            depth = 1
            start_time = time.time()
            time_limit = 0.5
            with ThreadPoolExecutor(max_workers=1) as executor:
                while time.time() - start_time < time_limit:
                    future = executor.submit(minimax_with_timeout, self.game.board, self.game.current_player, depth)
                    try:
                        move = future.result(timeout=time_limit - (time.time() - start_time))  # Adjust timeout to ensure total time is within 1 second
                        if move:
                            best_move = move
                        # count how many empty squares are left
                        empty_squares = sum(row.count(None) for row in self.game.board)
                        if depth >= empty_squares:
                            print("Reached maximum depth")
                            break
                        depth += 1
                    except TimeoutError:
                        # terminate the thread
                        executor._threads.clear()
                        break
            print(f"depth: {depth}")
            if best_move:
                row, col = best_move
            else:
                print("No valid move found within the time limit")
                row, col = -1, -1  # Indicate no valid move found
            self.board.place_piece(row, col)
from PySide6.QtWidgets import (
    QApplication,
    QMainWindow,
    QComboBox,
    QLabel,
    QVBoxLayout,
    QWidget,
    QPushButton,
    QMessageBox,
)
from PySide6.QtCore import Signal
from PySide6.QtCore import Qt


class SettingWindow(QMainWindow):
    settings_applied = Signal(str, str)

    def __init__(self):
        super().__init__()
        self.setWindowTitle("Settings")
        self.setGeometry(200, 200, 300, 300)
        # always put the window on top
        self.setWindowFlag(Qt.WindowStaysOnTopHint)

        self.initUI()
        # resize the window to fit the content
        # set minimum width to prevent resizing
        self.setMinimumWidth(300)
        self.adjustSize()

    def initUI(self):
        layout = QVBoxLayout()

        self.player1_label = QLabel("Player 1 (Black):")
        layout.addWidget(self.player1_label)

        all_players = ['human', 'greedy', 'random', 'minimax', 'alpha_beta']

        self.player1_combo = QComboBox()
        self.player1_combo.addItems(all_players)
        layout.addWidget(self.player1_combo)

        self.player2_label = QLabel("Player 2 (White):")
        layout.addWidget(self.player2_label)

        self.player2_combo = QComboBox()
        self.player2_combo.addItems(all_players)
        layout.addWidget(self.player2_combo)

        self.save_btn = QPushButton("Save Settings")
        self.save_btn.clicked.connect(self.save_settings)
        layout.addWidget(self.save_btn)

        container = QWidget()
        container.setLayout(layout)
        self.setCentralWidget(container)

    def save_settings(self):
        player1 = self.player1_combo.currentText()
        player2 = self.player2_combo.currentText()

        # emit a signal to the main window to apply the settings
        self.settings_applied.emit(player1, player2)
        self.close()


if __name__ == "__main__":  # test the SettingWindow class
    app = QApplication([])
    window = SettingWindow()
    window.show()
    app.exec()
from PySide6.QtWidgets import QWidget
from PySide6.QtGui import QPainter, QColor, QMouseEvent
from PySide6.QtCore import QThread
from PySide6.QtCore import Qt
from PySide6.QtCore import Signal


class BoardWidget(QWidget):
    animationFinished = Signal()

    def __init__(self, parent=None):
        super().__init__(parent)
        self.board_size = parent.game.board_size
        self.cell_size = 70  # Cell size in pixels
        self.padding_size = self.cell_size // 7  # Padding size of each cell in pixels
        self.hint_size = 10
        self.setMinimumSize(
            self.board_size * self.cell_size, self.board_size * self.cell_size
        )
        self.game = parent.game
        self.human_player = parent.human_player
        self.parent = parent
        self.changed_pieces = []
        self.animation_frames = 20
        self.animation_step = 0
        self.old_board = [row[:] for row in self.game.board]
        self.current_move = None
        self.user_click_permit = False  # Permit user to click on the board

    def paintEvent(self, event):
        painter = QPainter(self)
        painter.setRenderHint(QPainter.Antialiasing)
        painter.setPen(Qt.NoPen)
        cell_color = [QColor("green"), QColor("darkgreen")]

        # Draw the old board
        for row in range(self.board_size):
            for col in range(self.board_size):
                color = cell_color[(row + col) % 2]
                painter.fillRect(
                    col * self.cell_size,
                    row * self.cell_size,
                    self.cell_size,
                    self.cell_size,
                    color,
                )

                if (row, col) in self.changed_pieces:
                    continue

                if self.old_board[row][col] == "black":
                    color = QColor("black")
                elif self.old_board[row][col] == "white":
                    color = QColor("white")
                if self.old_board[row][col] is not None:
                    painter.setBrush(color)
                    painter.drawEllipse(
                        col * self.cell_size + self.padding_size,
                        row * self.cell_size + self.padding_size,
                        self.cell_size - 2 * self.padding_size,
                        self.cell_size - 2 * self.padding_size,
                    )



        # Highlight all possible moves
        possible_moves = self.game.get_valid_moves(
            self.game.board, self.game.current_player
        )
        for move in possible_moves:
            row, col = move
            painter.setBrush(QColor("red"))
            painter.drawEllipse(
                col * self.cell_size + self.cell_size // 2 - self.hint_size // 2,
                row * self.cell_size + self.cell_size // 2 - self.hint_size // 2,
                self.hint_size,
                self.hint_size,
            )

        if self.current_move:
            row, col = self.current_move
            painter.setBrush(QColor(self.game.board[row][col]))
            painter.drawEllipse(
                col * self.cell_size + self.padding_size,
                row * self.cell_size + self.padding_size,
                self.cell_size - 2 * self.padding_size,
                self.cell_size - 2 * self.padding_size,
            )
            # highlight the current move
            painter.setBrush(QColor("blue"))
            painter.drawEllipse(
                col * self.cell_size + self.cell_size // 2 - self.hint_size // 2,
                row * self.cell_size + self.cell_size // 2 - self.hint_size // 2,
                self.hint_size,
                self.hint_size,
            )
        painter.end()
        # Start the animation for changed pieces
        if self.changed_pieces:

            duration = 500  # Duration in milliseconds
            interval = duration // self.animation_frames
            step = self.animation_step
            painter = QPainter(self)
            painter.setRenderHint(QPainter.Antialiasing)
            painter.setPen(Qt.NoPen)
            alpha = min(255, int(255 * (step + 1) / self.animation_frames))
            for row, col in self.changed_pieces:
                new_color = self.game.board[row][col]
                color = QColor("black") if new_color == "black" else QColor("white")
                color.setAlpha(alpha)
                painter.setBrush(color)
                painter.drawEllipse(
                    col * self.cell_size + self.padding_size,
                    row * self.cell_size + self.padding_size,
                    self.cell_size - 2 * self.padding_size,
                    self.cell_size - 2 * self.padding_size,
                )
            painter.end()

            if not self.animation_step >= self.animation_frames:
                self.animation_step += 1
                self.update()
                QThread.msleep(interval)
            else:
                # Update old board after animation ends
                self.old_board = [row[:] for row in self.game.board]
                self.animation_step = 0
                self.changed_pieces = []
                self.animationFinished.emit()  # emit a signal showing the animation is finished

    def update_drawing(self):
        self.update()
        # emit a signal to the main window to update the status bar
        black_score, white_score = self.game.get_score()
        self.parent.statusBar().showMessage(
            f"{self.game.current_player.capitalize()}'s Turn - Black: {black_score}, White: {white_score}"
        )

    def place_piece(self, row, col):
        self.changed_pieces = self.game.place_piece(row, col)
        self.current_move = (row, col)
        self.update_drawing()

    def mousePressEvent(self, event: QMouseEvent):
        # if not the player's turn, do nothing
        if self.game.current_player not in self.human_player or not self.user_click_permit:
            return
        col = event.x() // self.cell_size
        row = event.y() // self.cell_size
        if not self.game.is_valid_move(
            row, col, self.game.board, self.game.current_player
        ):
            return
        self.user_click_permit = False
        self.place_piece(row, col)
from PySide6.QtWidgets import QApplication, QWidget, QVBoxLayout, QLabel, QListWidget

class InfoWidget(QWidget):
    def __init__(self):
        super().__init__()
        self.history_moves = []
        self.current_score = {'Black': 0, 'White': 0}

        self.layout = QVBoxLayout(self)

        self.history_label = QLabel("History Moves")
        self.layout.addWidget(self.history_label)

        self.history_listbox = QListWidget()
        self.layout.addWidget(self.history_listbox)

        self.score_label = QLabel("Current Score")
        self.layout.addWidget(self.score_label)

        self.score_text = QLabel(f"Black: {self.current_score['Black']}  White: {self.current_score['White']}")
        self.layout.addWidget(self.score_text)

    def update_history(self, move):
        self.history_moves.append(move)
        self.history_listbox.addItem(move)

    def update_score(self, black_score, white_score):
        self.current_score['Black'] = black_score
        self.current_score['White'] = white_score
        self.score_text.setText(f"Black: {self.current_score['Black']}  White: {self.current_score['White']}")

if __name__ == "__main__":
    app = QApplication([])

    info_widget = InfoWidget()
    info_widget.setWindowTitle("Info Widget")
    info_widget.show()

    app.exec()
class ReversiGame:
    def __init__(self):
        self.board_size = 8
        self.board = [
            [None for _ in range(self.board_size)] for _ in range(self.board_size)
        ]
        self.current_player = "black" # black always starts first
        self.history_boards = []
        self.history_moves = []
        self.initialize_board()

    def initialize_board(self):
        mid = self.board_size // 2
        self.board[mid - 1][mid - 1] = "white"
        self.board[mid][mid] = "white"
        self.board[mid - 1][mid] = "black"
        self.board[mid][mid - 1] = "black"

    def switch_player(self):
        self.current_player = "white" if self.current_player == "black" else "black"

    def is_valid_move(self, row, col, board, player):
        if board[row][col] is not None:
            return False

        opponent = "black" if player == "white" else "white"
        directions = [
            (0, 1),
            (1, 0),
            (0, -1),
            (-1, 0),
            (1, 1),
            (-1, -1),
            (1, -1),
            (-1, 1),
        ]

        for d_row, d_col in directions:
            r, c = row + d_row, col + d_col
            if (
                not (0 <= r < self.board_size and 0 <= c < self.board_size)
                or board[r][c] != opponent
            ):
                continue

            r += d_row
            c += d_col
            while 0 <= r < self.board_size and 0 <= c < self.board_size:
                if board[r][c] is None:
                    break
                if board[r][c] == player:
                    return True
                r += d_row
                c += d_col

        return False

    def get_valid_moves(self, board, player):
        valid_moves = []
        for row in range(self.board_size):
            for col in range(self.board_size):
                if self.is_valid_move(row, col, board, player):
                    valid_moves.append((row, col))
        return valid_moves

    def change_pieces(self, row, col, board, player):
        changed_pieces = []
        opponent = "black" if player == "white" else "white"
        directions = [
            (0, 1),
            (1, 0),
            (0, -1),
            (-1, 0),
            (1, 1),
            (-1, -1),
            (1, -1),
            (-1, 1),
        ]
        for d_row, d_col in directions:
            r, c = row + d_row, col + d_col
            if (
                not (0 <= r < self.board_size and 0 <= c < self.board_size)
                or board[r][c] != opponent
            ):
                continue

            r += d_row
            c += d_col
            while 0 <= r < self.board_size and 0 <= c < self.board_size:
                if board[r][c] is None:
                    break
                if board[r][c] == player:
                    r, c = row + d_row, col + d_col
                    while board[r][c] == opponent:
                        changed_pieces.append((r, c))
                        board[r][c] = player
                        r += d_row
                        c += d_col
                    break
                r += d_row
                c += d_col
        return changed_pieces

    def is_game_over(self):
        for row in range(self.board_size):
            for col in range(self.board_size):
                if self.is_valid_move(
                    row, col, self.board, "black"
                ) or self.is_valid_move(row, col, self.board, "white"):
                    return False
        return True

    def get_score(self):
        black_score = sum(row.count("black") for row in self.board)
        white_score = sum(row.count("white") for row in self.board)
        return black_score, white_score

    def place_piece(self, row, col):
        changed_pieces = []
        if self.is_valid_move(row, col, self.board, self.current_player):
            self.history_boards.append([row[:] for row in self.board]) # deep copy the board to save the state
            self.history_moves.append((self.current_player, row, col))
            self.board[row][col] = self.current_player
            changed_pieces = self.change_pieces(
                row, col, self.board, self.current_player
            )
            self.switch_player()
        return changed_pieces
← Homework 2 assignmentDownload package →