[go: up one dir, main page]

0% found this document useful (0 votes)
17 views23 pages

PROLOG Project

The document is a project report on the development of a Prolog Chess Engine submitted by P. Jahnavi for a Bachelor's degree in Computer Science and Engineering (AI & ML). It details the project's objectives, system analysis, requirements, algorithms, implementation, and testing procedures. The report emphasizes the use of Prolog's logical programming capabilities to create an AI that can play chess effectively.

Uploaded by

penmethsajahnavi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views23 pages

PROLOG Project

The document is a project report on the development of a Prolog Chess Engine submitted by P. Jahnavi for a Bachelor's degree in Computer Science and Engineering (AI & ML). It details the project's objectives, system analysis, requirements, algorithms, implementation, and testing procedures. The report emphasizes the use of Prolog's logical programming capabilities to create an AI that can play chess effectively.

Uploaded by

penmethsajahnavi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 23

A

Project Report on
PROLOG CHESS ENGINE

Submitted for partial fulfilment of the requirements for the award of the degree of

BACHELOR OF TECHNOLOGY
IN
COMPUTER SCIENCE AND ENGINEERING ( AI & ML )

By
P.JAHNAVI – 22K81A6649

Under The Guidance Of


Mr. S. Chandra Prakash
Assistant Professor

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING(AI&ML)


St. MARTIN'S ENGINEERING COLLEGE
UGC Autonomous
Affiliated to JNTUH, Approved by AICTE
Accredited by NBA & NAAC A+ , ISO 9001-2008 Certified
Dhulapally, Secunderabad-500 100
www.smec.ac.in
St. MARTIN'S ENGINEERING COLLEGE
UGC Autonomous
NBA & NAAC A+ Accredited
Dhulapally, Secunderabad-500 100

CERTIFICATE

This is to certify that the project entitled “PROLOG CHESS ENGINE” is being
submitted by P.Jahnavi(22K81A6649) in fulfilment of the requirement for the
award of degree of BACHELOR OF TECHNOLOGY IN COMPUTER SCIENCE AND
ENGINEERING(AI&ML) is recorded of bonafide work carried out by them. The
result embodied in this report have been verified and found satisfactory.

Project Internal Examiner Signature of HOD


Mr. S.Chandra Prakash Dr. K . Srinivas
Assistant Professor Head of Department
Department of CSE(AI&ML) Department of CSE(AI&ML)
St. MARTIN'S ENGINEERING COLLEGE
UGC Autonomous
Accredited by NBA & NAAC A+
Dhulapally, Secunderabad-500 100
www.smec.ac.in

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING(AI&ML)

DECLARATION

We, the students of “Bachelor of Technology in Deparatment of COMPUTER


SCIENCE AND ENGINEERING(AI&ML)”, session: 2022 - 2026, St. Martin’s
Engineering College, Dhulapally, Kompally, Secunderabad, hereby declare that
the work presented in this project work entitled PROLOG CHESS ENGINE is the
outcome of our own bonafide work and is correct to the best of our knowledge
and this work has been undertaken taking care of Engineering Ethics. This result
embodied in this project report has not been submitted in any university for
award of any degree.

P.Jahnavi – 22K81A6649
ACKNOWLEDGEMENT

The satisfaction and euphoria that accompanies the successful completion of any
task would be incomplete without the mention of the people who made it
possible and whose encouragement and guidance have crowded our efforts
with success. First and foremost, we would like to express our deep sense of
gratitude and indebtedness to our College Management for their kind support
and permission to use the facilities available in the Institute.

We especially would like to express our deep sense of gratitude and indebtedness
to Dr. P. SANTOSH KUMAR PATRA, Group Director, St. Martin’s Engineering
College Dhulapally, for permitting us to undertake this project.

We wish to record our profound gratitude to Dr. M. SREENIVAS RAO, Principal,


St. Martin’s Engineering College, for his motivation and encouragement.

We are also thankful to Dr. K. SRINIVAS, Head of the Department, Computer


Science and Engineering ( AI & ML ), St. Martin’s Engineering College, Dhulapally,
Secunderabad, for his support and guidance throughout our project.

We would like to express our sincere gratitude and indebtedness to our project
supervisor Mr. S.Chandra Prakash, Assistant Professor, Department of
Computer Science and Engineering(AI&ML), St. Martins Engineering College,
Dhulapally, for his support and guidance throughout our project.

Finally, we express thanks to all those who have helped us successfully


completing this project. Furthermore, we would like to thank our family and
friends for their moral support and encouragement. We express thanks to all
those who have helped us in successfully completing the project.

P.Jahnavi – 22K81A6649
CONTENTS

CHAPTER 1-ABSTRACT 1

CHAPTER 2- INTRODUCTION 2

CHAPTER 3-SYSTEM ANALYSIS 3

3.1 Existing System 3

3.2 Proposed System 3

CHAPTER 4-SYSTEM REQUIREMENT 4

4.1 Hardware Requirement 4

4.2 Software Requirement 4

CHAPTER 5- ALGORITHM 5

CHAPTER 6- SYSTEM IMPLEMENTATION 6

CHAPTER 7-SYSTEM TESTING 12

CHAPTER 8-OUTPUT SCREENS 14

CHAPTER 9-CONCLUSION 16

CHAPTER 10-FUTURE ENHANCEMENT 17

CHAPTER 11-REFERENCES 18
1. ABSTRACT

A Prolog chess engine leverages the logical programming capabilities of Prolog to


create an artificial intelligence capable of playing chess. Prolog, known for its
strengths in symbolic reasoning and pattern matching, provides an ideal framework
for representing the rules and strategies of chess. The engine typically consists of a
knowledge base that encodes chess rules, including piece movements, legal moves,
and game conditions, alongside a search algorithm to explore possible moves and
outcomes. The use of recursive backtracking allows the engine to simulate multiple
moves ahead, evaluating each possible board state to make optimal decisions.
Additionally, heuristic evaluation functions can be incorporated to assess non-
terminal positions, improving the engine's practical performance. The declarative
nature of Prolog facilitates the development of such complex logical systems,
making it a powerful tool for constructing chess engines that can challenge human
players.

1
2. INTRODUCTION

A Prolog chess engine is a computer program built using the Prolog


programming language, designed to play the game of chess by applying logical
reasoning and rule-based processing, which are Prolog’s core strengths.

At its core, the Prolog chess engine involves several key components. Firstly,
it includes an efficient representation of the chessboard and pieces, typically
using lists or other structured data forms that facilitate quick access and
manipulation. This allows the engine to maintain an accurate and up-to-date
model of the game state.

The engine must generate legal moves according to the rules of chess, including
special moves like castling, en passant, and pawn promotion. This is achieved
by defining predicates that encapsulate the rules and constraints of chess,
ensuring that all generated moves are valid.

To determine the best move, the engine employs search algorithms such as
minimax, which explores possible future moves to identify the most
advantageous ones. This process is often optimized using alpha-beta pruning,
which reduces the number of moves that need to be considered by eliminating
branches of the search tree that are not promising.

Overall, a Prolog chess engine combines the principles of logical programming


with the complexities of chess, providing a rich platform for exploring artificial
intelligence techniques and gaining a deeper understanding of both Prolog and
strategic game development.

2
3. SYSTEM ANALYSIS

3.1 EXISTING SYSTEM

The board representation typically uses lists, arrays, or other data structures to
model the chessboard and piece positions. It uses algorithms such as minimax and
alpha-beta pruning to explore possible moves and evaluate their outcomes.
Develops heuristics to assess board positions based on material count, control of
the board, piece activity, and other factors.

Prolog’s logical and declarative nature can lead to inefficiencies compared to


imperative languages. Optimization is crucial for handling the complexity of
chess. Managing the vast number of possible moves and game states requires
careful design and efficient algorithms. Developing sophisticated evaluation
functions and search strategies to compete with engines written in more
performance-optimized languages.

3.2 PROPOSED SYSTEM

The proposed Prolog Chess Engine aims to leverage the strengths of Prolog's
logical reasoning and rule-based processing to create a competitive and
efficient chess-playing program. The system will focus on efficient board
representation, advanced move generation, robust search algorithms, and
effective evaluation functions.
- Implement predicates that define the legal moves for each type of piece,
considering constraints like check, checkmate, and special moves
(castling, en passant, pawn promotion).
- Use optimized data structures for board representation and move
generation to enhance performance.

3
4. SYSTEM REQUIREMENTS

4.1 HARDWARE REQUIREMENTS


1. Processor (CPU): Quad-core processor (e.g., Intel Core i5 or AMD Ryzen 5)

Speed: 2.5 GHz or higher


2. Memory (RAM): Capacity: 8 GB or higher & Type: DDR4

3. Operating System

Supported OS: Windows 10/11, macOS, Linux (Ubuntu or other distributions)

Compatibility: Ensure Prolog environment is compatible with the OS

4. Prolog Environment

SWI-Prolog : Recommended due to its extensive documentation

GNU Prolog / YAP: Alternatives based on specific requirements and preferences

4.2 SOFTWARE REQUIREMENTS


1. Prolog Compiler/Interpreter : SWI-Prolog: Highly recommended due to its
extensive libraries, active community, and robust development environment.

Alternative Options: GNU Prolog, YAP (Yet Another Prolog), etc.

2. Integrated Development Environment (IDE): Tools like SWI-Prolog IDE,


which provides debugging, code analysis, and other features to facilitate
development.

3. Version Control System (VCS)

Git: Essential for source code management, collaboration, and version tracking.

4. Command-Line Interface (CLI): Ensure a robust command-line interface for


inputting moves and displaying the board state.

4
5. ALGORITHM
This algorithm outline provides a foundational structure for implementing a basic
Prolog chess engine. Each component (board representation, move generation,
search algorithms, evaluation function, game control, and user interface) can be
expanded and refined to improve the engine's performance and capabilities.
Step-1: Board Representation

Represent the chessboard using a suitable data structure. Initialize the board with
pieces in their starting positions.

Step-2: Legal Move Generation


Implement predicates to generate legal moves for each type of piece considering
the current board state and game rules.
Step-3: Move Application
Implement predicates to apply moves to the board representation, updating the
board state.
Step-4: Evaluation Fuction
Develop an evaluation function to assess the strength of a board position based on
material balance and positional factors.
Step-5: Search Algorithm (Minmax with Alpha-Beta Pruning)
Implement the minimax algorithm with alpha-beta pruning to search through
possible moves and evaluate their outcomes.
Step-6: Iterative Deepening
Optionally, implement iterative deepening to gradually increase search depth until
a time limit or maximum depth is reached.
Step-7: User Interface
Provide a basic command-line interface (CLI) or integrate with a graphical user
interface (GUI) for user interaction and visualization.

5
6. SYSTEM IMPLEMENTATION

SOURCE CODE

% Initial board setup (example)

initial_board([

[r, n, b, q, k, b, n, r],

[p, p, p, p, p, p, p, p],

[-, -, -, -, -, -, -, -],

[-, -, -, -, -, -, -, -],

[-, -, -, -, -, -, -, -],

[-, -, -, -, -, -, -, -],

[P, P, P, P, P, P, P, P],

[R, N, B, Q, K, B, N, R]

]).

% Displaying the board

display_board(Board) :-

nl,

write(' a b c d e f g h'), nl,

write(' -----------------'), nl,

display_rows(Board, 8).

6
display_rows([], _).

display_rows([Row | Rows], N) :-

write(N), write(' |'),

display_row(Row), nl,

NewN is N - 1,

display_rows(Rows, NewN).

display_row([]).

display_row([Cell | Cells]) :-

(Cell = '-' -> write(' -'); write(' '), write(Cell)),

write(' |'),

display_row(Cells).

% Validating moves

valid_move(Board, (X1, Y1, X2, Y2)) :-

% Implement logic to validate if the move is legal

% Example: checking if the move is within board boundaries

within_bounds(X1, Y1), within_bounds(X2, Y2),

% Add more conditions as per specific game rules

true.

% Example predicate to check if coordinates are within bounds

within_bounds(X, Y) :-
7
between(1, 8, X), between(1, 8, Y).

% Generate legal moves for a piece

legal_moves(Board, X, Y, Moves) :-

piece_at(Board, X, Y, Piece),

% Implement rules for each piece type

(Piece = p -> pawn_moves(Board, X, Y, Moves); Moves = []).

pawn_moves(Board, X, Y, Moves) :-

% Implement rules for pawn moves (e.g., one square forward, capture)

% Example:

(valid_move(Board, (X, Y, X, Y+1)) -> Moves = [(X, Y, X, Y+1)]; Moves =


[]).

% Example predicate to get the piece at a given position

piece_at(Board, X, Y, Piece) :-

nth1(Y, Board, Row),

nth1(X, Row, Piece).

% Evaluate material balance

evaluate_material(Board, Score) :-

count_pieces(Board, 'w', TotalWhite),

count_pieces(Board, 'b', TotalBlack),

8
Score is TotalWhite - TotalBlack.

% Example predicate to count pieces of a specific color

count_pieces(Board, Color, Total) :-

aggregate_all(count, (

member(Row, Board),

member(Piece, Row),

piece_color(Piece, Color)

), Total).

% Example predicate to determine piece color

piece_color(Piece, 'w') :- member(Piece, ['K', 'Q', 'R', 'B', 'N', 'P']).

piece_color(Piece, 'b') :- member(Piece, ['k', 'q', 'r', 'b', 'n', 'p']).

% Main predicate to start the game

play :-

initial_board(Board),

display_board(Board),

play(Board, 'w').

% Example game loop (simplified)

play(Board, Player) :-

write('Player '), write(Player), write(' turn.'), nl,


9
write('Enter move (e.g., e2e4): '), read(Move),

(valid_move(Board, Move) ->

apply_move(Board, Move, NewBoard),

display_board(NewBoard),

switch_player(Player, NextPlayer),

play(NewBoard, NextPlayer) ;

write('Invalid move. Try again.'), nl,

play(Board, Player)

).

% Predicate to apply a move to the board

apply_move(Board, (X1, Y1, X2, Y2), NewBoard) :-

piece_at(Board, X1, Y1, Piece),

replace(Board, X1, Y1, '-', TempBoard),

replace(TempBoard, X2, Y2, Piece, NewBoard).

% Utility predicate to replace an element in a list at given index

replace([Row|Rows], 1, Column, Value, [NewRow|Rows]) :-

replace_element(Row, Column, Value, NewRow).

replace([Row|Rows], RowNum, Column, Value, [Row|NewRows]) :-

RowNum > 1,

NextRowNum is RowNum - 1,
10
replace(Rows, NextRowNum, Column, Value, NewRows).

replace_element([_|Columns], 1, Value, [Value|Columns]).

replace_element([Column|Columns], ColumnNum, Value,


[Column|NewColumns]) :-

ColumnNum > 1,

NextColumnNum is ColumnNum - 1,

replace_element(Columns, NextColumnNum, Value, NewColumns).

% Predicate to switch players

switch_player('w', 'b').

switch_player('b', 'w').

11
7. SYSTEM TESTING

1. Initialization and Setup Testing:


Objective: Ensure that the initial setup of the chessboard and game
parameters is correct.
Test Cases:
- Verify that the initial board setup matches the standard chess starting
position.
- Check that all pieces are correctly placed on the board according to chess
rules.
- Test initialization of game parameters such as turn order (white starts
first).

2. Move Generation and Validation Testing:


Objective: Verify that legal moves are generated correctly for each piece
and that invalid moves are rejected.
Test Cases:
- Test legal moves for different pieces (pawns, knights, bishops, etc.) in
various positions.
- Verify handling of special moves like castling, en passant, and pawn
promotion.
- Check that invalid moves (e.g., moving into check, moving opponent's
pieces) are correctly identified as illegal.

3. Applying Moves and Board State Updates:


Objective: Ensure that applying moves updates the board state accurately
and reflects the game's progression.
Test Cases:
- Apply a series of valid moves and verify that the board state after each
move is correct.
- Test capturing opponent's pieces and verify correct removal and
placement of pieces on the board.
- Check for correct promotion of pawns to queens or other pieces upon
reaching the opposite end of the board.

4. Evaluation Function Testing:


Objective: Validate that the evaluation function accurately assesses the
board position based on material balance and positional factors.
12
Test Cases:
- Test evaluation of material balance (counting pieces and calculating
material advantage).
- Verify evaluation of positional factors such as king safety, pawn
structure, and piece activity.
- Ensure that the evaluation function produces reasonable scores that
reflect the actual board position.

5. Game Control and User Interaction Testing:


Objective: Verify that the game flow, player turns, and user interface
interactions work correctly.
Test Cases:
- Simulate a complete game from start to finish, including opening,
middlegame, and endgame phases.
- Test switching turns between players and verify that the correct player is
prompted for their move.
- Validate user input handling for moves and ensure that moves are
processed accurately by the engine.

6. Integration Testing:
Objective: Test the integration of all components to ensure they work
together seamlessly.
Test Cases:
- Perform end-to-end testing of the entire chess engine functionality.
- Check for proper interaction between move generation, move application,
evaluation function, and game control.
- Validate that the system behaves as expected under various scenarios and
edge cases (e.g., checkmate, stalemate, draws).

7. Performance Testing (Optional):


Objective: Assess the chess engine's performance in terms of speed and
efficiency.
Test Cases:
- Measure the time taken to generate moves, apply moves, and evaluate
board positions for various depths of search.
- Check memory usage during prolonged gameplay to ensure there are no
memory leaks or performance issues.

13
8. OUTPUT SCREENS

8.1: Initial Board Setup

Fig 8.1: Initial board setup, when the game starts.

8.2: Displaying the board after a move

Fig 8.2: White pawn moves from e2 to e4.

14
8.3: Applying a capture move

Fig 8.3: When black knight captures white pawn at e4

8.4: Check and Checkmate

Fig 8.4: White has delivered checkmate to black’s king.

15
9. CONCLUSION

In conclusion, creating a Prolog chess engine requires meticulous integration


of several key components, including board representation, move generation
and validation, evaluation functions, game control, and user interaction. Each
component must adhere to chess rules and work harmoniously to ensure
accurate game play. The development process involves implementing
complex algorithms for move generation, legal move validation, and game
state evaluation. System testing is crucial in this context, as it verifies that the
engine operates correctly under various scenarios, from the initial setup to
end-game checkmates. Thorough testing ensures that moves are accurately
processed, the board state is updated correctly, and special moves and game-
ending conditions are handled properly. By systematically addressing each
aspect of the engine and rigorously testing its functionality, developers can
create a reliable and efficient chess engine. This engine not only provides a
challenging and enjoyable playing experience but also serves as a testament
to the capabilities of Prolog in handling complex logical problems.

16
10. FUTURE ENHANCEMENTS

1. Performance Optimization
- Parallel Processing: Implement parallel processing techniques to speed up move
generation and evaluation.
- Transposition Tables: Use transposition tables to store previously evaluated
positions and avoid redundant calculations.

2. Improved Evaluation Function


- Positional Evaluation: Enhance the evaluation function to better assess
positional advantages, including factors like pawn structure, king safety, and
control of key squares.
- Learning-Based Evaluation: Incorporate machine learning techniques to develop
an evaluation function that learns from large datasets of chess games.

3. Enhanced AI
- Adaptive AI: Develop an AI that adapts to the player's skill level over time,
providing a more tailored and challenging experience.
- Human-Like Play: Implement techniques to make the AI play in a more human-
like manner, avoiding moves that are too perfect and thus more predictable.

4. Educational Features
- Hints and Tips: Provide hints and tips to help players learn and improve their
chess skills.
- Analysis Mode: Include an analysis mode where the engine can analyze games,
suggest improvements, and explain the reasoning behind moves.

5. Multiplayer and Online Features


- Online Play: Enable online multiplayer functionality so users can play against
others over the internet.
- Tournaments: Organize online tournaments where players can compete against
each other using the Prolog chess engine.

17
11.REFERENCES

o https://github.com/zebreus/prolog-chess

o https://boxbase.org/entries/2018/nov/19/modeling-chess-in-prolog/

o https://swi-prolog.discourse.group/t/a-chess-player-i-wrote/6901

o http://www.fam-petzke.de/cp_getstarted_en.shtml

o https://electricajournal.org/en/a-new-rule-based-approach-for-computer-

chess-programming-u-gp-artificial-techniques-pecp-13926

18

You might also like