Project Report Artificial Intelligence [CSE3705] Dots & Boxes By: Dhruv Sahgal 210283 Ayan Yezdani 210456 Department of Computer Science and Engineering School of Engineering and Technology BML Munjal University November 2023 Declaration by the Candidates We hereby declare that the project entitled "Dots & Boxes" has been carried out to fulfill the partial requirements for completion of the course Artificial Intelligence offered in the 5th Semester of the Bachelor of Technology (B.Tech) program in the Department of Computer Science and Engineering during AY-2023-24 (odd semester). This experimental work has been carried out by us and submitted to the course instructor Dr. Soharab Hossain Shaikh. Due acknowledgments have been made in the text of the project to all other materials used. This project has been prepared in full compliance with the requirements and constraints of the prescribed curriculum. Dhruv Sahgal Ayan Yezdani Place: BML Munjal University Date: 12th November, 2023 Table of Contents Page No. 1. Introduction & Problem Statement 1 2. Methodology 2.1 Table Driven 2.2 Intelligent Agent 2 3. Implementation - Technology Stack 5 4. Conclusions 6 5. Appendix 7 6. References 11 1) Introduction 1.1Problem Description The Dots and Boxes game is a classic paper-and-pencil game where two players take turns connecting dots to form squares. The player who completes the most squares is the winner. The game is played on a grid of dots, and players connect adjacent dots with horizontal or vertical lines. This project involves the implementation of the Dots and Boxes game, including a human player and an intelligent agent using the Minimax algorithm. 1.2 Background The use of AI in games isn't new, but recent approaches have made game-playing computers smarter. In this project, we're using the Minimax algorithm as an AI tool. It helps the computer make smart moves, making the game more interesting for players. This kind of AI adds a dynamic and flexible touch to the gaming experience, offering players a challenge that adapts to their actions. 1.3 Objectives The primary project goals include: 1) Implementation of the Dots and Boxes game, complete with a user interface for human interaction. 2) Development of an intelligent agent using the Minimac algoritm to act as the second player. 3) User flexibility in specifying the size of the game grid. 4) Display of the game board after each move and conclusive declaration of the winner upon game completion. 2. Methodology 2.1 Table Driven The table-driven methodology in the implementation of the Dots and Boxes game serves as a framework, guiding the intelligent agent's decision-making process. This approach involves the mapping of precepts, representing the current state of the game, to corresponding actions, the moves made by players. The table-driven approach is implemented through functions like make_move and get_best_move These functions use predefined rules and heuristics to determine the agent's actions based on the current state Percepts and Actions Set of Percepts Possible Moves Set of Actions Draw a line Current state of the game board (the placement of dots and lines) Player’s turn Number of boxes completed by each player. Available moves (lines that can be drawn). Game status (ongoing, win, or draw). Draw a horizontal line. Draw a vertical line Draw a diagonal line from top left to bottom right. Draw a diagonal line from top right to bottom left End the game Reset the game Display the current state Display the final result 2.2 Intelligent Agent: Minimax Algorithm The synergy between the table-driven methodology and the Minimax algorithm is crucial for the success of the intelligent agent in the Dots and Boxes game. The table-driven approach provides the foundational structure for percepts and actions, offering clarity and interpretability. Meanwhile, the Minimax algorithm brings a dynamic and strategic element, allowing the agent to navigate the vast decision space with foresight and depth. Intelligent Agent Strategy: a. Minimax Algorithm: The core strategy employed by the intelligent agent is the minimax algorithm, a decision-making algorithm widely used in two-player turn-based games. The minimax algorithm explores the game tree by recursively evaluating possible moves and outcomes. The agent assumes that the opponent plays optimally, alternating between maximizing and minimizing the expected utility (score) of each move. b. Evaluation Function: The agent uses an evaluation function to assess the desirability of a particular game state. In the current implementation, the evaluation function is simple and focuses on the number of completed boxes for the agent. c. Look-Ahead Depth: The look-ahead depth can impact the agent's strategic decision-making. A higher depth generally results in a more thoughtful and strategic agent but requires more computational resources. Conversely, a lower depth might lead to quicker decisions but may not capture the full complexity of the game dynamics. How the Agent Becomes Intelligent: Optimal Decision-Making: The minimax algorithm guarantees optimal decision-making under the assumption that both players play optimally. The agent explores different move sequences to find the best move that maximizes its expected outcome. Strategic Thinking: The agent exhibits strategic thinking by evaluating the consequences of its actions. It aims to maximize its own score while minimizing the opponent's score, leading to a more competitive and intelligent gameplay. Dynamic Look-Ahead Depth: The look-ahead depth could be dynamically adjusted based on the state of the game. For example, the agent might perform a deeper search in critical game situations. 3. Implementation - Technology Stack The successful implementation of the Dots and Boxes game, featuring the innovative fusion of a table-driven methodology and the Minimax algorithm, relies on a robust technology stack. The chosen technologies not only facilitate the development process but also ensure the seamless integration of the intelligent agent's decision-making capabilities into the game environment. Python: The Foundation Python serves as the cornerstone of the technology stack for its readability, versatility, and extensive support for AI and game development libraries. Leveraging Python's simplicity accelerates the implementation process, allowing developers to focus on the intricacies of the intelligent agent and the game's dynamics. AI Libraries: Minimax Algorithm The libraries enhance the efficiency of the Minimax algorithm, enabling rapid computation of game tree evaluations and efficient decision-making. Development Environment: VS Code VS code is utilized for it’s interactive nature, allowing developers to iteratively test and refine the intelligent agent's decision-making logic. The integration of code and visualizations within the coding environment streamlines the debugging and optimization processes. Future Directions and Enhancements Machine Learning Integration: Future iterations could explore the integration of machine learning techniques, enabling the agent to learn and adapt based on experiences garnered in various game scenarios. This would add a dynamic learning element to the intelligent agent's decision-making process. Multiplayer Support: Extending the game to support multiplayer interactions could introduce a new layer of complexity. Enabling the intelligent agent to contend with multiple opponents and diverse playing styles would further challenge its capabilities. Project Impact and Significance Beyond the immediate scope of the Dots and Boxes game, this project serves as a testament to the continual evolution and refinement of intelligent agent strategies in the realms of artificial intelligence and game development. The seamless integration of a versatile technology stack, including Python, AI libraries, and graphical interfaces, contributes to the success of this innovative fusion. 4. Conclusion The integration of an intelligent agent into the Dots and Boxes game emphasizes the significant influence of advanced algorithms on strategic decision-making. This project successfully meets its goals of delivering an engaging and dynamic gaming experience, shedding light on the broader possibilities of enhancing traditional games with technological innovations. Throughout this undertaking, we have delved into the evolving collaboration between human intuition and technological intelligence, making a valuable contribution to the ongoing discourse surrounding the transformative role of technology in shaping various facets of interactive and strategic engagements 5. Appendix Input code: class DotsAndBoxesGame: def __init__(self, size): self.size = size self.board = [[0] * (size - 1) for _ in range(size - 1)] self.players = [1, 2] self.current_player = self.players[0] self.completed_boxes = {1: 0, 2: 0} def get_state(self): return self.board, self.current_player, self.completed_boxes def is_game_over(self): return sum(self.completed_boxes.values()) == (self.size - 1) ** 2 def make_move(self, move): row, col, direction = move if self.board[row][col] == 0: self.board[row][col] = direction box_completed = self.check_for_boxes(row, col) if not box_completed: self.switch_player() def check_for_boxes(self, row, col): box_completed = False # Check horizontally if col > 0 and self.board[row][col - 1] != 0 and row + 1 < len(self.board) and self.board[row + 1][col - 1] != 0 and row + 1 < len(self.board) and self.board[row + 1][col] != 0: box_completed = True self.completed_boxes[self.current_player] += 1 # Check vertically if row > 0 and self.board[row - 1][col] != 0 and col + 1 < len(self.board[0]) and self.board[row - 1][col + 1] != 0 and col + 1 < len(self.board[0]) and self.board[row][col + 1] != 0: box_completed = True self.completed_boxes[self.current_player] += 1 return box_completed def switch_player(self): self.current_player = self.players[0] if self.current_player == self.players[1] else self.players[1] class MinimaxAgent: def __init__(self, player): self.player = player def minimax(self, game, depth, maximizing_player): if depth == 0 or game.is_game_over(): return self.evaluate_state(game) legal_moves = self.get_legal_moves(game) if maximizing_player: max_eval = float('-inf') for move in legal_moves: game_copy = self.copy_game_state(game) game_copy.make_move(move) eval = self.minimax(game_copy, depth - 1, False) max_eval = max(max_eval, eval) return max_eval else: min_eval = float('inf') for move in legal_moves: game_copy = self.copy_game_state(game) game_copy.make_move(move) eval = self.minimax(game_copy, depth - 1, True) min_eval = min(min_eval, eval) return min_eval def get_best_move(self, game): legal_moves = self.get_legal_moves(game) best_move = None best_eval = float('-inf') for move in legal_moves: game_copy = self.copy_game_state(game) game_copy.make_move(move) eval = self.minimax(game_copy, depth=3, maximizing_player=False) if eval > best_eval: best_eval = eval best_move = move return best_move def evaluate_state(self, game): return game.completed_boxes[self.player] def get_legal_moves(self, game): legal_moves = [] for row in range(len(game.board)): for col in range(len(game.board[0])): if game.board[row][col] == 0: legal_moves.append((row, col, 1)) # Horizontal line legal_moves.append((row, col, 2)) # Vertical line return legal_moves def copy_game_state(self, game): game_copy = DotsAndBoxesGame(size=game.size) game_copy.board = [row[:] for row in game.board] game_copy.current_player = game.current_player game_copy.completed_boxes = game.completed_boxes.copy() return game_copy def print_board(game): for row in range(len(game.board)): for col in range(len(game.board[0])): print("+", end="") if game.board[row][col] == 0: print(" +", end="") elif game.board[row][col] == 1: print("___+", end="") elif game.board[row][col] == 2: print(" |", end="") print() for col in range(len(game.board[0])): if game.board[row][col] == 0: print(" ", end="") elif game.board[row][col] == 2 and row < len(game.board) - 1: print(" |", end="") elif row == len(game.board) - 1: print("___+", end="") print() def main(): size = int(input("Enter the size of the game (e.g., 5 for a 5x5 game): ")) game = DotsAndBoxesGame(size=size) agent = MinimaxAgent(player=2) while not game.is_game_over(): print_board(game) if game.current_player == 1: print("Player 1's turn:") print("1. Draw a horizontal line") print("2. Draw a vertical line") row = int(input("Enter row: ")) col = int(input("Enter col: ")) direction = int(input("Enter direction (1 for horizontal, 2 for vertical): ")) move = (row, col, direction) else: print("Player 2's turn (AI):") move = agent.get_best_move(game) game.make_move(move) print_board(game) print("Game Over!") print("Player 1 Score:", game.completed_boxes[1]) print("Player 2 Score:", game.completed_boxes[2]) print("Winner: Player", 1 if game.completed_boxes[1] > game.completed_boxes[2] else 2) if __name__ == "__main__": main() Output: References: https://blog.devgenius.io/dots-and-boxes-game-in-python-22058a187a84 www.github.com www.stackoverflow.com