Ai Chess Documentation
Ai Chess Documentation
INDEX
1. INDRODUCTION ……………………………………………………………………………….3
1.1 About the project ………………………………………………………………………..5
2. SYSTEM ANALYSIS ……………………………………………………………………………..7
2.1 Requirements Analysis ………………………………………………………………..8
2.2 Existing System ……………………………………………………………………………9
2.3 Limitation of the Existing System …………………………………………………9
2.4 Proposed System ………………………………………………………………………..11
2.5 Need for the Proposed System ……………………………………………………11
2.6 Feasibility Study ………………………………………………………………………….12
2.6.1 Technical Feasibility ………………………………………………………13
2.6.2 Economical Feasibility ………………………………………………….14
2.6.3 Operational Feasibility …………………………………………………14
2.7 Data flow diagram ……………………………………………………………………….21
2.8 Flow Chart ………………………………………………………………………………….23
2.9 System Specification …………………………………………………………………..23
2.9.1 Hardware Specification ……………………………………………….23
2.9.2 Software Specification ………………………………………………...23
2.10 Software Requirements ……………………………………………………………..23
1
S6 BCA UIT MANNADY
5. SYSTEM TESTING ………………………………………………………………………………….47
5.1 Unit Testing ………………………………………………………………………………....48
5.2 Integration Testing ………………………………………………………………………..48
5.3 Validation Testing …………………………………………………………………………..49
5.4 Security Method ……………………………………………………………………………49
6. SYSTEM IMPLEMENTATION …………………………………………………………………50
6.1 System Implementation and Maintenance ……………………………………..51
7. CONCLUSION ……………………………………………………………………………………….54
7.1 Conclusion ………………………………………………………………………………………55
7.2 Future Enhancement ………………………………………………………………………..55
8. APPENDIX …………………………………………………………………………………………….57
8.1 meeting minutes …………………………………………………………………………….57
8.2 Gantt chart ……………………………………………………………………………………..62
8.3 Screen Layout ………………………………………………………………………………..64
9. BIBILOGRAPHY ……………………………………………………………………………………67
2
S6 BCA UIT MANNADY
1.INTRODUCTION
AI chess Game
3
S6 BCA UIT MANNADY
This a very basic chess game with an AI implementation using the mini max algorithm; built
in python and pygame.
To begin the game, a player has to run the main.py file providing the game mode and the
depth. The game mode must be equal to 0 or 1 and it’s the color of chosen piece (zero for
whites and one for blacks). The depth is the number of times that the computer “runs a
simulation of the games”. For example, if the depth is 2 and it is the computer turn, the
computer will simulate every possible move it has available, and for every one of those
moves, its will also play every possible move their opponent. To run the simulation the
computer always assumes that the player plays the move in their best interest. The return
value is a list containing(piece, move) tuples with the highest score.
4
S6 BCA UIT MANNADY
Project modules:
Board:-
The Board class consist of a simple 2D list to store the chess pieces and a number of
required methods like make_move(), unmake_move() (which is necessary for the mini max
algorithm), methods to check if the game is finished, and a evaluation method which returns
the total score of the caller’s piece minus the total score of the opponent’s piece (also
required for AI).
Chess Piece:-
The Chess Piece class is an abstract class and its is used as a parent for every piece. It
consists of a method for moves filtering (prevent illegal moves like exposing the king) and
some methods to keep the previous state of the chess piece intact (required by the AI when
calling unmake_move()). Every chess piece is equipped with a get_score() function that is
used when evaluating the board. The scores are 10 points for bishops and rooks,240 for the
queen and 1000 for the king.
Computer:-
The Computer class is a static class and it is used to get a move from the computer. There is
a method that returns an AI move using the minimax algorithm.
AI:-
The mini max algorithm starts by making every possible (valid) move, and for each one of
those moves, it simulates the opponents move that it’s in their best interest. Note that since
the goal of the game is not to “eat” the king, but instead “trap” him, the computer assumes
that the player can make illegal moves. This is a recursive algorithm that stops when there
are no more moves available, or the board is terminal.
Logging:-
By setting log=True in the board constructor parameters, the logger.py script will produce
a .txt file that contains the minimax tree of the current AI move decision
5
S6 BCA UIT MANNADY
2.SYSTEM ANALYSIS
6
S6 BCA UIT MANNADY
System analysis is a general terms that refers to an orderly, structured
process for identifying and solving problems. We call system analysis process lifecycle
methodology, since its relates to four significant phases in the life cycle of all business
information system. The life cycle is divided into four phases.
There are,
Study Phase
Design Phase
Development Phase
Implemented Phase
Analysis implies the process of breaking something into parts so that the whole may be
understood. The definition of the system analysis includes not only the process of analysis
but also of synthesis, which implies the process of putting together to form a new whole.
All activities associated with each life cycle phase must be performed, managed and
documented. Hence, we define system analysis as the performance, management,
documentation of activities related to the life cycle phases of a computer-based business
system. In the study of phase a detailed study of the project is made and clear picture of
the project is in mind. In the design phase the designing of the input, output and table
designs are made. Development phase is where the physical designing of the input-output
screens and coding of the system is done. System implementation actually implements the
system by the making necessary testing.
2.2Existing System
7
S6 BCA UIT MANNADY
1. Board: This module defines the chess board and its properties. It
contains the logic for placing pieces, checking for legal moves, and
determining the game’s outcome.
2. Minimax: This module implements the minimax algorithm with alpha-
beta pruning for evaluating the best move for the AI player.
3. Graphics: This module is responsible for displaying the chess board and
accepting user input. It also handles the game loop and update the
board and accepting user input. It also handles the game loop and
updates the board state based on user input.
4. Logger: This module logs the Minimax algorithm’s search tree and writes
it to a file for later analysis.
5. Main: This is the entry point of the program, which initialize the chess
board and starts the game loop. The user can choose the game mode, AI
difficulty, and whether to enable logging.
The AI chess game uses object-oriented programming concepts to model the
chess piece and the chess board. The Minimax algorithm is implemented to
evaluate the best move for the AI player. The graphics module uses the
Pygame library to display the chess board and accept user input. The game
loop updates the board state based on user input and AI’s move. The logger
module logs the Minimax algorithm’s search tree and writes it to file for later
analysis.
2.3Limitation of the Existing System
(1) Computational complexity: The game of chess has an enormous number
of possible moves, making it computationally expensive to explore all
possible moves and their outcomes.
(2) Knowledge representation:Representing knowledge of chess strategies
and tactics can be difficult, and current systems often rely on rule-based
system or large database of past games.
(3) Difficulty in evaluating positions: Evaluating a chess position can be
challenging, as it often requires knowledge of chess strategy and tactics,
and it can be difficult to assign a numerical value to a position.
(4) Limited ability to learn: While AI chess systems can improve through
self-play or by learning from human games, they still have limited ability
to learn from experience and adapt to new situations.
(5) Limited ability to understand the game: AI chess system have limited
ability to understand the game, the motivations of the players, and the
subtle nuances of the game.
8
S6 BCA UIT MANNADY
2.4 Proposed System
The proposed system will be flexible, user-friendly, and efficient. It will provide a
challenging experience for the user while playing against the AI. The logging features will
provide insight into the workings of the AI, which will be helpful for researchers and
developers who are intrested in AI and chess.
1. Chess Board: This component will represent the chess board, its squares and pieces. The
board will have a matrix representation and will be able to determine the legal moves for a
piece.
2. AI Engine: This component will implement the Minimax algorithm along with Alpha-Beta
pruning to determine the best move for the AI player. The depth of the search tree can be
adjusted to control the difficulty level of the game.
3. User Interface: This component will provide an interactive interface for the user to play the
game. The user will be able to move the pieces and the AI will respond with its move.
4. Logging: A logging component will be added to record the moves made by both the user and
the AI. This will be helpful in understanding the thought process of the AI and in debugging
the code.
9
S6 BCA UIT MANNADY
1. Minimax algorithm: The system uses the Minimax algorithm to determine the best
move for the AI player. The algorithm is a decision-making algorithm that considers
all possible moves and their consequences to determine the best move for the AI
player.
3. Graphical User Interface (GUI): The system uses the graphics module to provide a
GUI for the players. The GUI allows players to interact with the chessboard and make
moves.
4. Game modes: The system provides two game modes, where one player can play as
whites and the other as blacks.
5. Logging: The system provides logging functionality, which allows players to keep
track of the moves made in a game. The logging feature can be turned on and off.
6. Depth: The system allows players to set the depth of the Minimax algorithm, which
determines how many moves ahead the AI player considers.
7. Piece placement: The system allows players to place pieces on the chessboard at the
start of the game.
In conclusion, the proposed system is designed to play chess and provide a challenging and
fun experience for players. The system combines the Minimax algorithm with Alpha-Beta
pruning, a GUI, game modes, logging, depth setting, and piece placement to provide a
complete chess playing experience.
2.5Feasibility study
A feasibility study is made to see if the project on completion will serve the purpose of
the organization for the amount of work time and effort spent on it Feasibility study lets
the developer to foresee the future of the project and its usefulness.There are three
aspects in the feasibility study portion of the preliminary investigation:
Technical Feasibility
Economic Feasibility
Operational Feasibility
10
S6 BCA UIT MANNADY
The proposed system must be evaluated from the technical point of view first,and if
technically feasible their impact on the organization must be devised.Then they must be
tested for economic feasibility.
graphics: A library used to display the chess board and pieces on a graphical user
interface.
11
S6 BCA UIT MANNADY
Board: A custom library that implements the chess board and game rules.
However, the graphics library used in the code is not a standard library in Python, and its
installation and setup may require additional steps. Additionally, the code may require
further optimization and fine-tuning to improve the performance and decision-making of
the AI.
12
S6 BCA UIT MANNADY
available, giving an indication that the system is economically possible for development. The
analysis raises financial and economic questions during the preliminary investigation to
estimate the following:
To be judged feasible, a proposal for the specific project must pass all these tests,
otherwise it is not considered as a feasible project.
13
S6 BCA UIT MANNADY
2. Availability of Required Libraries: The code requires the following libraries to run:
‘graphics’, ’itertools’, ’numpy’, ‘logging’, and ‘Board’. These libraries must be
installed on the system and accessible to the code in order to run the game.
3. User Familiarity with the Code: The proposed system requires users to be familiar
with the code and the logic behind the AI's decision-making process in order to play
the game effectively.
4. Game Mode: The code allows for two game modes: whites down and blacks down.
This choice affects the starting configuration of the board and the order of moves
made by the AI and human players.
5. Depth of AI Minimax Algorithm: The code allows users to set the depth of the AI's
minimax algorithm, which determines the level of difficulty of the game. A deeper
minimax algorithm leads to a more challenging game, but also requires more
computing resources.
6. Logging: The code includes a logging feature that can be enabled or disabled.
Enabling logging will create a text file that logs the movements of the pieces during
the game, which can be useful for debugging or analyzing the game. However, the
logging feature will also take up additional disk space and increase the processing
time of the code.
In conclusion, the operational feasibility of the AI chess project depends on the availability
of the required resources, the user's familiarity with the code, and the chosen game
settings.
14
S6 BCA UIT MANNADY
RAM 2GB for developer or evaluation use
Software Version
pycharm 3.1
python 3.11
15
S6 BCA UIT MANNADY
For the proposed AI chess game, the following development environment is recommended:
Python version 3.7 or later: The code is written in Python, and a version of 3.7 or later is
required for proper functioning of the code. Graphics library: The code makes use of the
graphics library to display the chess board and pieces. This library can be installed by
running pip install graphics in the terminal or command prompt. Operating system: The
code has been tested on Windows 10 and MacOS and is expected to work on other
operating systems as well. Text editor: Any text editor with Python syntax highlighting and
support for project management can be used to work with the code. Examples include
PyCharm, Visual Studio Code, and Sublime Text. It is also recommended that the
development environment includes an interactive debugger and an environment for testing
and debugging the code. The development environment should be able to manage
dependencies and allow for version control through Git.
16
S6 BCA UIT MANNADY
3.SYSTEM DESIGN
17
S6 BCA UIT MANNADY
designing input data is to make data entry as easy,logical and free from errors as
possible.Input design is a apart of overall system design,which requires carefully
attention.If the data going into system is incorrect,them the processing and output will
magnify these errors
Initialization of the game: The game can be initialized in two modes, i.e., white pieces
first or black pieces first. The game mode can be selected by passing the argument
"game_mode" to the class "Board" and setting it to either 0 for white pieces first or 1
for black pieces first.
Placing pieces on the board: The pieces can be placed on the board by calling the
method "place_pieces()" on the board object. The method will initialize the starting
positions of all the pieces on the board.
Input from the user: During the game, the user can select the piece they want to move
and the desired position to move it to. This input can be given through the graphics
interface.
The input design is designed in such a way that the user can easily interact with the game
and make moves. The input is also validated to ensure that only valid moves are allowed,
and invalid moves are rejected.
18
S6 BCA UIT MANNADY
3.2 Output Design
The outputs of the proposed AI chess game system would be the graphical representation of
the chess board, moves made by the players or AI, and the end result of the game
(checkmate, draw, or resign). The graphical representation of the chess board would be
created using the graphics library. The moves made by the players or AI would be displayed
on the chess board and updated in real-time. The end result of the game would be displayed
in a message box or through some other means of notification.
19
S6 BCA UIT MANNADY
20
S6 BCA UIT MANNADY
4 SYSTEM CODING
1. Code optimization
21
S6 BCA UIT MANNADY
Optimization aims at improving optimization efficiency of a program.This is achieved in two
ways:
2. Validation
Validation is an important aspect of software development and it ensures that the code
meets the specified requirements and works as intended. For this AI chess game, the
following validations should be considered:
Input Validation: Ensure that the input provided by the user is in the correct format. For
example, the move provided by the user should be a valid chess move.
Boundary Validation: Validate the inputs that are at the edge of the system's capacity.
For example, check if the depth of the AI's move is within the acceptable range.
Logic Validation: Ensure that the logic of the code is correct and does not produce
unexpected results. For example, ensure that the AI's move is valid and does not break
any chess rules.
Exception Handling: Handle exceptions and unexpected events gracefully. For example,
handle the situation when the user tries to make an illegal move.
Performance Validation: Ensure that the code performs well under different scenarios
and with different inputs. For example, measure the time taken by the AI to make a
move with different depths.
It's important to test the code thoroughly and validate it before releasing it to the users. A
well-validated code not only ensures the reliability of the system but also provides a good
user experience.
3. Code
//Implementing ChessPieces
def place_pieces(self):
self.board.clear()
self.whites.clear()
self.blacks.clear()
self.initialize_board()
22
S6 BCA UIT MANNADY
self.whiteKing = King('white', 0, 4, '\u265A')
self.blackKing = King('black', 7, 4, '\u2654')
for j in range(8):
self[1][j] = Pawn('white', 1, j, '\u265F')
self[6][j] = Pawn('black', 6, j, '\u2659')
self[0][0] = Rook('white', 0, 0, '\u265C')
self[0][7] = Rook('white', 0, 7, '\u265C')
self[0][1] = Knight('white', 0, 1, '\u265E')
self[0][6] = Knight('white', 0, 6, '\u265E')
self[0][2] = Bishop('white', 0, 2, '\u265D')
self[0][5] = Bishop('white', 0, 5, '\u265D')
self[0][3] = Queen('white', 0, 3, '\u265B')
self[0][4] = self.whiteKing
self[7][0] = Rook('black', 7, 0, '\u2656')
self[7][7] = Rook('black', 7, 7, '\u2656')
self[7][1] = Knight('black', 7, 1, '\u2658')
self[7][6] = Knight('black', 7, 6, '\u2658')
self[7][2] = Bishop('black', 7, 2, '\u2657')
self[7][5] = Bishop('black', 7, 5, '\u2657')
self[7][3] = Queen('black', 7, 3, '\u2655')
self[7][4] = self.blackKing
if depth == 0 or board.is_terminal():
data[1] = board.evaluate()
return data
if max_player:
max_eval = -math.inf
for i in range(8):
for j in range(8):
if isinstance(board[i][j], ChessPiece) and board[i][j].color !=
board.get_player_color():
piece = board[i][j]
moves = piece.filter_moves(piece.get_moves(board), board)
for move in moves:
board.make_move(piece, move[0], move[1], keep_history=True)
evaluation = minimax(board, depth - 1, alpha, beta, False, False, data)[1]
if save_move:
if evaluation >= max_eval:
if evaluation > data[1]:
data.clear()
data[1] = evaluation
data[0] = [piece, move, evaluation]
23
S6 BCA UIT MANNADY
elif evaluation == data[1]:
data[0].append([piece, move, evaluation])
board.unmake_move(piece)
max_eval = max(max_eval, evaluation)
alpha = max(alpha, evaluation)
if beta <= alpha:
break
return data
else:
min_eval = math.inf
for i in range(8):
for j in range(8):
if isinstance(board[i][j], ChessPiece) and board[i][j].color ==
board.get_player_color():
piece = board[i][j]
moves = piece.get_moves(board)
for move in moves:
board.make_move(piece, move[0], move[1], keep_history=True)
evaluation = minimax(board, depth - 1, alpha, beta, True, False, data)[1]
board.unmake_move(piece)
min_eval = min(min_eval, evaluation)
beta = min(beta, evaluation)
if beta <= alpha:
break
return data
def get_ai_move(board):
moves = minimax(board, board.depth, -math.inf, math.inf, True, True, [[], 0])
if board.log:
logger.write()
# moves = [[pawn, move, move_score], [..], [..],[..], total_score]
if len(moves[0]) == 0:
return False
best_score = max(moves[0], key=lambda x: x[2])[2]
piece_and_move = random.choice([move for move in moves[0] if move[2] == best_score])
piece = piece_and_move[0]
move = piece_and_move[1]
if isinstance(piece, ChessPiece) and len(move) > 0 and isinstance(move, tuple):
board.make_move(piece, move[0], move[1])
return True
//Implementing AI to move
def get_ai_move(board):
moves = minimax(board, board.depth, -math.inf, math.inf, True, True, [[], 0])
if board.log:
24
S6 BCA UIT MANNADY
logger.write()
# moves = [[pawn, move, move_score], [..], [..],[..], total_score]
if len(moves[0]) == 0:
return False
best_score = max(moves[0], key=lambda x: x[2])[2]
piece_and_move = random.choice([move for move in moves[0] if move[2] ==
best_score])
piece = piece_and_move[0]
move = piece_and_move[1]
if isinstance(piece, ChessPiece) and len(move) > 0 and isinstance(move, tuple):
board.make_move(piece, move[0], move[1])
return True
def get_random_move(board):
pieces = []
moves = []
for i in range(8):
for j in range(8):
if isinstance(board[i][j], ChessPiece) and board[i][j].color !=
board.get_player_color():
pieces.append(board[i][j])
for piece in pieces[:]:
piece_moves = piece.filter_moves(piece.get_moves(board), board)
if len(piece_moves) == 0:
pieces.remove(piece)
else:
moves.append(piece_moves)
if len(pieces) == 0:
return
piece = random.choice(pieces)
move = random.choice(moves[pieces.index(piece)])
if isinstance(piece, ChessPiece) and len(move) > 0:
board.make_move(piece, move[0], move[1])
class BoardRepr:
def __iter__(self):
25
S6 BCA UIT MANNADY
return self.array_repr
def __str__(self):
return str(self.array_repr)
def __repr__(self):
return str(self.depth)
class Logger(metaclass=Singleton):
log_file = 'minimax_tree.txt'
def __init__(self):
self.arr = []
def clear(self):
open(self.log_file, 'w').close()
self.arr.clear()
def write(self):
// main.py
import graphics
from Board import *
26
S6 BCA UIT MANNADY
if __name__ == '__main__':
keep_playing = True
while keep_playing:
graphics.initialize()
board.place_pieces()
graphics.draw_background(board)
keep_playing = graphics.start(board)
27
S6 BCA UIT MANNADY
4. SYSTEM TESTING
Software Testing is critical element of software quality assurance and represents the
ultimate review of specification design and coding.Testing begins by testing program
modules separately,followed by testing”bundled”modules as a unit.A program module may
function perfectly in isolation but fail when interfaced with successively larger up to the
system test level.The following methods of testing were carried out to assure the
correctness and reliability.
28
S6 BCA UIT MANNADY
All during the system design activity,basic program module are tested .At this stage program
modules are tested .At this stage programmers usually makeup their own data.Unit testing
with test data is necessary,of course,but it is not sufficient.Although it is important know if
the logic included in a program works properly,conditions that are not included in the
program are also considered.In this mainly syntax and logical arrays of the programs are
tested.
As module pass unit test,they are integrated for testing programs are invariability related to
one another and interact in a total system.Each program is tested to see whether it confirms
to related programs in the system.Each portion of the system is tested against the entire
module with both tested data and live data before the entire system is ready to be tested.
Validation succeeds when the software function in a manner the user wishes validation
refers to the process of using software to live environment in order to find errors. During
the course of validation system failure may occur and sometimes coding has to be changed
according to the requirement.Thus the feedback from the validation phase generally
produces changes in the software.
When it comes to security in AI chess games, the following methods can be employed to
ensure that the system is secure and protected:
1. Data Encryption: Encrypting sensitive information such as player data and game logs can
help protect the information from unauthorized access.
2. Access Control: Implementing an access control system that requires users to provide
credentials such as usernames and passwords can prevent unauthorized
access to the game and its data.
29
S6 BCA UIT MANNADY
3. Firewalls: A firewall can be implemented to protect the AI chess game from external
threats such as hacking and cyber attacks.
4. Security Updates: Regularly updating the security features of the AI chess game, such as
software patches and bug fixes, can help prevent vulnerabilities from
being exploited.
5. Monitoring and Logging: Implementing a monitoring and logging system that keeps track
of all activity within the AI chess game can help identify and
respond to security incidents quickly.
Note that different AI chess games may have different levels of security and may implement
different security methods depending on their specific needs and requirements.
30
S6 BCA UIT MANNADY
5. SYSTEM IMPLEMENTATION
窗体底端
窗体顶端
窗体底端
31
S6 BCA UIT MANNADY
users and testing of the system. Education of users should really take place much earlier in
the project i.e., When they are involved in the investigation and design work.
Training has to be given to the staff regarding the new system .Once staff has been
trained,the system can be tested.Implementation is the stage of the project where the
theoretical design is turned into working system or it is the key stage in achieving a
successful new system,because usually it involves a lot of up heal in the user
department.Therefore,it must be carefully planned and controlled. It can also be considered
to be the most crucial stage in achieving a successful new system and in giving the user
confidence that the new system will work and be effective.
Implementation is the final and important phase it is the phase where theoretical design is
turned into working system,which works for the user in the most effective manner .It
involves careful planning,investigation of the present system and the constraints
involved,user training,system testing and successful running of developed proposed system.
The implementation process begins with preparing a plan for the implementation of the
system.According to this plan,the activities are to be carried out,discussions made regarding
the equipment and resources and the additional equipment's has to be implemented the
new system.The user tests the developed system and changes are made according to their
needs.the testing phase involves the testing of a system using various kinds of data.This
method also offers the greatest security since old system can take over if the errors are
found or inability to handle certain type of transactions while using the new system
SYSTEM MAINTENANCE
Software maintenance denotes any changes made to software after it has been delivered to
customer.Maintenance is inevitable to almost any kind of product.Most products need
maintenance due to wear and tear or damage caused due to use.Although software does
not wear out like a hardware,it ‘ages’ and eventually fails perform.So,maintenance becomes
a necessity.
32
S6 BCA UIT MANNADY
2. Adaptive:A software product might need maintenance when the customer need the
product to run on new platform,on new operating system,or when they need the product to
be interfaced with new hardware or software.
33
S6 BCA UIT MANNADY