Skip to content

Latest commit

 

History

History
349 lines (284 loc) · 15.9 KB

ChessAI.md

File metadata and controls

349 lines (284 loc) · 15.9 KB

ChessAI

animated

Index

  • Demo
  • About the Project
  • Tech Stack
  • File Structure
  • Getting Started
  • Features
  • Usage
  • Theory and Approach
  • Future Scope
  • Acknowledgements
  • Contributors
  • Demo

    Demo Video Link:

    https://drive.google.com/file/d/1-EqixFDe9Iy7AqRsp5VVrwxX8uG5FjgJ/view?usp=sharing

    Demo GIF

    animated

    AI Move

    animated

    Home Screen

    Our Chess Board

    Chess Board With Pieces

    animated

    Undo Move

    animated

    Castling Move

    animated

    Checkmate

    animated

    Stalemate

    animated

    Enpassant Capture

    animated

    Reset Game

    About the Project

    Aim:

    To create a highly intelligent AI opponent for players to play using the NegMax algorithm for evaluation of different possible moves and then choosing the best on the basis of evaluation score.

    Description:

    The project is a chess AI that can play against a human player. The AI uses the NegMax algorithm with alpha-beta pruning to determine the best move at each gamestate.

    The project is written in Python and uses the pygame library for the GUI. The AI uses the NegMax algorithm with alpha-beta pruning to determine the best move at each gamestate. The AI is also able to play against itself. The AI understands each game state by assigining an evaluation score to each possible gamestate. The AI considers the following factors when assigning an evaluation score to a gamestate:
    • Material
    • Positional Advantage
      • Control of the center
      • Control of the center files
      • Control of the center ranks
      • Control of the center diagonals
      • Control of the center squares
      • Control of the center squares
    • King Safety
    • Castling
    • King's
      • Position
      • Number of pieces attacking it
      • Number of pieces defending it
    • Number of pieces defending the King
    • Double Pawns
    • Queen Mobility
    • King Mobility
    • Freedom of Movement
    • Knight Support
    • Based on these factors, the AI assigns an evaluation score to each gamestate. Then the AI uses the NegMax algorithm with alpha-beta pruning to determine the best move at each gamestate.

      Tech Stack

      This project is built using the following technologies:

      • Python
      • Pygame

          • Pygame is a Python library that is commonly used for developing 2D games. It provides a set of modules that allow developers to create games and multimedia applications. Pygame is built on top of the Simple DirectMedia Layer (SDL) library, which provides low-level access to audio, keyboard, mouse, joystick, and graphics hardware.
          • Pygame is a popular choice for game development because it is easy to learn and use, and it provides a lot of functionality out of the box. It includes modules for handling graphics, sound, input, and networking, among other things.
          • In the context of the provided code excerpt, Pygame is being used to build a chess game.Pygame is a Python library that is commonly used for developing 2D games. It provides a set of modules that allow developers to create games and multimedia applications. Pygame is built on top of the Simple DirectMedia Layer (SDL) library, which provides low-level access to audio, keyboard, mouse, joystick, and graphics hardware.
          • Pygame is a popular choice for game development because it is easy to learn and use, and it provides a lot of functionality out of the box. It includes modules for handling graphics, sound, input, and networking, among other things.
          • Pygame is being used to build a chess game.
        • Numpy

          • NumPy, short for Numerical Python, is a fundamental package for scientific computing in Python.
          • It provides support for arrays, matrices and a large library of high-level mathematical functions to operate on these arrays.
          • NumPy's array object is more efficient and faster than Python's native list.
          • It is an open-source module and is used in a wide range of applications including linear algebra, Fourier transform, and matrix computations.
          • NumPy is also interoperable and can seamlessly and speedily integrate with a wide variety of databases.
          • It is a key package in the field of machine learning, data analysis, and complex visualizations.

        File Structure

        .
        ├── Notes
            |── RohanC1.pdf
            ├── AdityaC1P1.pdf
            ├── AdityaC1P2.pdf
        |── MiniProjects
            |── Aditya
                |── NatureOrientedGeneticAlgorithm
                    |──code
                       ├── main.py
                       |──...
                |── Flappy Bird
                    |──... 
            |── Rohan
                |── Genetic_Monkey_Shakespeare_Simulation
                    |──...
                |── Snake Game
                    |──...
        |── README.md
        ├── CHESS_AI-PROJECT_REPORT.pdf
        ├── ChessAI
            ├── images
               ├── ...
            ├── AI.py
            ├── engine.py
            ├── main.py
        
        .
        

        Getting Started

        Prerequisites

        • Python 3
        • Pygame
        • Numpy

        Installation

        1. Clone the repository
        2. Select whether you want to play versus computer, against another player locally, or watch the game of two computers From the Appropriate flag in the main.py file ''' playerone = True playertwo = False Indicates that the player is playing against the computer True indicates that the player is a human player False indicates that the player is a computer player '''
        3. Install pygame
          • On the Terminal, run:
          • pip install pygame
          • Pygame should get installed
        4. Run main.py
        5. python main.py
        6. The Home Screen of the Game should appear on your screen

      Features

      • Play against the computer
      • Play against another player locally
      • Watch the game of two computers
      • Live Valid Move Checking
      • Castling
      • En Passant
      • Promotion with its own menu
      • Checkmate
      • Stalemate
      • Undo Moves
      • Reset Game

      Usage

      • Run main.py
      • The Home Screen of the Game should appear on your screen
      • Follow the message on the screen
          Press any key to start the game
      • The Game Screen should appear on your screen
      • Click a Chess piece to highlight it Valid Landing Squares
      • Click a Valid Landing Square to move the Chess piece to that square
      • UseCtrl + Z Button to undo a move
      • UseCtrl + R Button to reset the game
      • If Pawn Promotion occurs for the pawn of the human player, follow the instructions on the on-screen menu to do pawn promotion to your chosen piece
      • Play the game until Checkmate or Stalemate occurs

      Theory And Approach

      Negamax Algorithm

      Game Tree: The algorithm starts by generating a game tree, which is a representation of all possible moves from the current position. Each node in the tree represents a possible game state, and each edge represents a move.

      Evaluation Function: For each leaf node (end game state), the algorithm uses an evaluation function to assign a numerical value. This value represents the "goodness" of the game state for the AI. In chess, the evaluation function might consider factors like material balance, king safety, pawn structure, etc.

      Negation Principle: The Negamax algorithm is based on the principle that the value of a position to a player is the negation of the value of that position to the other player. This simplifies the implementation of the algorithm, as it only needs to consider the perspective of the AI, not the opponent.

      Search: The algorithm performs a depth-first search of the game tree. When it reaches a leaf node, it propagates the score back up to the parent node, negating the score at each level. This is based on the assumption that each player will choose the move that maximizes their minimum score (hence "minimax").

      The Best Move: Once all scores are propagated, the AI chooses the move that leads to the highest score.

      Alpha Beta Pruning

      Alpha-beta pruning is an optimization technique for the Negmax algorithm. It reduces the number of nodes that need to be evaluated in the game tree by eliminating branches that don't need to be searched because they can't possibly influence the final decision.

      Here's how it works in the context of the provided code:

      Alpha and Beta: Alpha is the best value that the maximizer currently can guarantee at that level or above. Beta is the best value that the minimizer currently can guarantee at that level or above.

      Pruning:: During the search, the algorithm keeps track of the best scoring option found so far. If it finds a move that scores higher than what the opponent could potentially achieve (beta), it stops evaluating the remaining moves (break), as the opponent would never allow this situation to occur.

      Updating Alpha: If the score of the current move (maxScore) is greater than the current best (alpha), the best score is updated. This is because the maximizer has found a better move.

      Score Negation: The score is negated when passed to the recursive call because the perspective changes from maximizer to minimizer or vice versa.

      Alpha Beta Inversion: Alpha and beta values are inverted when passed to the recursive call because the roles of the maximizer and minimizer are swapped.

      In summary, alpha-beta pruning allows the algorithm to ignore parts of the search tree that are irrelevant to the final decision, which can greatly improve efficiency in games with large search trees, like chess.

      Pygame

      1. Initialization: Pygame is first initialized using pygame.init(). This function initializes all the modules required for Pygame.
      2. Creating a Game Window: Pygame creates a game window or screen using pygame.display.set_mode(). This is where all the game objects, animations, and text will be displayed.
      3. Game Loop: Pygame runs a game loop where the game events are continuously checked and game objects are updated and drawn on the game window.
      4. Event Handling: Pygame handles different types of events like keyboard input, mouse movement, button clicks, etc. These events are used to control the game characters or to trigger certain game actions.
      5. Drawing and Updating Game Objects: Pygame provides functions to draw game objects on the game window. It also provides functions to update the game window so that the changes become visible.
      6. Sound and Music: Pygame has modules to play sound effects and music. This adds to the overall game experience.
      7. Timing: Pygame provides a way to track and control time. This is used to control the speed of game characters or to introduce delay in certain game actions.
      8. Collision Detection: Pygame provides simple collision detection. This is used to detect when game characters or objects collide with each other.
      9. Game Over: Pygame provides functions to end the game and quit the game window.

      Future Scope

      • More Use of Genetic Algorithm in The AI part
      • Better tuning of Parameter weights
      • A database to store player information
      • More Game Modes

      Acknowledgements

      Project Mentor Siddeshsingh Tanwar for his support and guidance throughout the duration of the project.

      Community of Coders(COC) for providing us with the opportunity to work on this project.

      Contributors