0% found this document useful (0 votes)
34 views110 pages

NEA Analysis (First Draft) - 1

The document outlines Jack Cooke's A Level Computer Science project focused on developing an online chess application aimed at enhancing accessibility and user experience. It includes an analysis of existing chess platforms, design objectives, technical solutions, and testing strategies to ensure a robust system. Key features proposed include user registration, customizable gameplay, AI adaptability, and comprehensive post-game analysis.

Uploaded by

wiyola4140
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)
34 views110 pages

NEA Analysis (First Draft) - 1

The document outlines Jack Cooke's A Level Computer Science project focused on developing an online chess application aimed at enhancing accessibility and user experience. It includes an analysis of existing chess platforms, design objectives, technical solutions, and testing strategies to ensure a robust system. Key features proposed include user registration, customizable gameplay, AI adaptability, and comprehensive post-game analysis.

Uploaded by

wiyola4140
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/ 110

Jack Cooke A Level Computer Science Project

Contents
Contents 1
Analysis 4
Interview 4
Background to the Problem 5
Observing existing systems 6
Lichess (lichess.org) 6
Chess.com (chess.com) 9
ChessBase (chessbase.com) 11
Flowcharts 13
Move Validation Flowchart 13
Usability for a chess application 14
Tasks to be Computerised and the Benefits of Computerising 15
Tasks: 15
Qualitative Benefits: 15
Quantitative Benefits: 15
Objectives for the Proposed System 16
Possible SQL Queries 18
Design 20
Generic App Workflow 21
IOPS Chart 22
Hierarchy chart 23
System Flowchart 24
Data Flow Diagram (DFD) 25
Database Schema 26
Entity Relationship Diagram (ERD) 27
Object-Oriented Programming Class Design 28
Class: ChessBoard(QWidget) 29
Class: PromotionWindow(QWidget) 31
Class: Piece 32
Class: Rook (Child of Piece) 32
Class: Bishop (Child of Piece) 33
Class: Knight (Child of Piece) 34
Class: Queen (Child of Piece) 34
Class: Pawn (Child of Piece) 35
Class: ChessPiece(QLabel) 35
Class: ChessBoardUI(QWidget) 36
Algorithms 39
Monte-Carlo (chess engine) 39
Password-Based Key Derivation Function 2 (pbkdf2) 40

1
Jack Cooke A Level Computer Science Project

Negamax evaluation framework 41


User Interface Design Concepts 42
System Architecture 45
Technical Solution 46
Object-Oriented Programming (OOP) 46
Graphical User Interface (GUI) Development 48
Algorithm Implementation 49
Board Evaluation Function 51
Database Interaction and Security 53
Unit Testing and Test-Driven Development 54
Concurrency and Performance Optimization 56
Integration with External Data Sources 57
Version Control and Continuous Integration 58
Code Style and Linting 59
Error Handling and Logging 60
Use of Advanced Python Features 61
Networking 62
Client 62
Server 63
Deployment of Chess application 64
Testing 65
Overview 65
Test Plan 65
Database Connector Tests 65
Evaluation Board Tests 72
Monte Carlo Tree Search (MCTS) Tests 78
GUI Tests 84
Chess Board Tests 88
Networking Tests 93
Execution Plan: 97
Evaluation 98
Comparison against Objectives 98
Potential for Future Developments (TBD) 100
Registration and Login 102
Rules & Game 103
Data & Statistics 105
Customisation 105
AI Player 105
Key Resources 106
Build Log 107
Features 107
Bug Fixes 109

2
Jack Cooke A Level Computer Science Project

More Features 109


References 111

3
Jack Cooke A Level Computer Science Project

Analysis

Interview
Interviewer (Developer): What should the main focus of this chess app be?

Client: The main goal is to make chess as convenient as possible for everyone
to play, anywhere, online, without needing a board or another person.

Interviewer: What about user accounts? Are there any specific requirements?

Client: Definitely. People should be able to create accounts and log in easily.
However, the app needs a robust security system—the app should store user
passwords safely, and robust mitigations are required to block attackers from
gaining access to user accounts.

Interviewer: And for the game itself, what features should we include?

Client: The app should track everything on the board, including where the
pieces are, their type, and even special moves like castling or en passant.
Also, it’d be great if the app could recognise standard openings and suggest
counters.

Interviewer: Do you want to implement a rating system?

Client: An Elo rating system similar to chess sites like lichess or chess.com
would be great.

Interviewer: Should players get any feedback after their games?

Client: It would be awesome if players could also save or upload games so they
can view them later.

Interviewer: What kind of experience should the AI give players?

Client: The AI should adapt to the player’s level. It must be tough enough to
keep things fun but not so hard that it is frustrating.

4
Jack Cooke A Level Computer Science Project

Background to the Problem

For centuries, chess has been a beloved game enjoyed by millions worldwide.
Nevertheless, only some have had the opportunity to participate in this popular
pastime. This initiative strives to enhance chess's accessibility. By evaluating
technological innovations, promoting inclusive chess experiences, and engaging
the chess community, this effort seeks to widen the scope of the chess player
base, making the game more inclusive for all; removing the requirement for a
physical board makes the game more accessible. By making the game online, the
requirement of a similarly skilled human is removed, and the user can play
against a computer with a similar skill.

5
Jack Cooke A Level Computer Science Project

Observing existing systems

Several students were using chess-playing systems to identify valued features and
usage patterns.

Lichess (lichess.org)

1. User Registration:

1.1. Users can sign up by providing essential


details such as a unique username, email, and
password.

1.2. Users can enhance their profiles by adding


additional information, like profile pictures.

2. User Profile:

2.1. Profile Information:

2.1.1. Allow users to manage and update personal details within their
profiles.

2.1.2. Display comprehensive user statistics, including win/loss ratios


and ratings.

2.2. Preferences:

2.2.1. Empower users to customise their gaming experience by


setting preferences, such as time controls and themes.

3. Game Creation:

3.1. Create Game Interface:

3.1.1. Allow users to choose opponents,


including the computer, friends, or random
opponents.

3.1.2. Allow customisation of game


parameters, such as time controls and
variants.

6
Jack Cooke A Level Computer Science Project

4. Matchmaking:

4.1. Implement an intelligent matchmaking system based on user


preferences and skill levels.

4.2. Connect players with similar ratings to ensure fair and competitive
gameplay.

5. Gameplay:

5.1. Game Board Display:

5.1.1. Craft an engaging and visually pleasing chessboard interface.

5.1.2. Enhance the user experience by highlighting legal moves for


the selected chess piece.

5.2. Move Validation:

5.2.1. Implement rules


based on chess
regulations to validate
moves.

5.2.2. Check for critical


game conditions,
including check,
checkmate, stalemate,
and draw scenarios.

6. Time Controls and Clocks:

6.1. Time Management:

6.1.1. Implement multiple time controls, such as blitz, rapid, and


classical, to cater to different playing styles.

6.1.2. Integrate chess clocks to track each player's time during the
game accurately.

6.2. Timeout Handling:

6.2.1. Gracefully handle disconnections and


timeouts to ensure a seamless gaming
experience.

7
Jack Cooke A Level Computer Science Project

6.2.2. Implementation of auto-resignation and time forfeiture


mechanisms to maintain fair play.

8
Jack Cooke A Level Computer Science Project

Chess.com (chess.com)

1. User Registration:
1.1. Users are first asked for their skill level: New to Chess,
Beginner, Intermediate, or Advanced.
1.2. Users then enter an email address and password.
1.3. Users then log in with their details.

2. User Profile:
2.1. Profile Information:
2.1.1. Allow users to manage and update personal details within
their profiles and competitive ratings from OTB.
2.2. Preferences:
2.2.1. Users can change them for their game, the colours
for the pieces, and the board.
3. Game Creation:
3.1. Create Game Interface:
3.1.1. Allow users to choose opponents, including the
computer, friends, random opponents,
tournaments or chess variants.

4. Matchmaking:
4.1. Chess.com matches users with similar ELO ratings, where the
amount gained per game is proportional to the difference in rating.

5. Gameplay:

9
Jack Cooke A Level Computer Science Project

5.1. Game Board Display:


5.1.1. Displayed a standard board to the user; white is always on the
bottom
5.1.2. Highlights legal moves when a user clicks a piece

5.2. Move Validation:


5.2.1. Chess.com implements rules to validate moves.
5.2.2. Chess.com checks for check, checkmate, stalemate, and draw
scenarios.

6. Time Controls and Clocks:


6.1. Time Management:
6.1.1. Implements multiple time controls, such as blitz, rapid, and
classical.
6.1.2. Integrate chess clocks to track each player's time.
6.2. Timeout Handling:
6.2.1. Chess.com Gracefully handles disconnections and timeouts.

10
Jack Cooke A Level Computer Science Project

ChessBase (chessbase.com)

1. User Registration:
1.1. Users enter an email address,
password and username.
1.2. Users log in with their credentials.

2. User Profile:
2.1. Profile Information:
2.1.1. Allow users to manage and update personal details within
their profiles.
3. Game Creation:
3.1. Create Game Interface:
3.1.1. Allow users to choose opponents, including the computer,
friends, random opponents, tournaments or chess variants.

4. Matchmaking:
4.1. ChessBase matchmakes users with similar ELO ratings where the
amount gained per game is proportional to the difference in rating
5. Gameplay:
5.1. Game Board Display:
5.1.1. Displayed a standard board to the user;
white is always on the bottom
5.1.2. Highlights legal moves

6.
6.1. Move Validation:
6.1.1. ChessBase implements rules to validate moves.

11
Jack Cooke A Level Computer Science Project

6.1.2. ChessBase checks for check, checkmate, stalemate, and draw


scenarios.
7. Time Controls and Clocks:
7.1. Time Management:
7.1.1. Implements multiple time controls, such as blitz, rapid, and
classical.
7.1.2. Integrate chess clocks to track each player's time.
7.2. Timeout Handling:
7.2.1. ChessBase Handles disconnections and timeouts (Not well)

12
Jack Cooke A Level Computer Science Project

Flowcharts
See Appendix A for observations of existing applications.

Move Validation Flowchart


This flowchart abstracts the calls required to evaluate a move and the chess
application's flow.

13
Jack Cooke A Level Computer Science Project

Usability for a chess application


The following illustration outlines the process the application will go through on
startup.

14
Jack Cooke A Level Computer Science Project

Tasks to be Computerised and the Benefits of


Computerising

Based on my analysis of the currently available chess applications, I have


developed a selection of features to enhance the chess-playing experience.

Tasks:
- Board customisation
- Variable difficulty AI
- The post-game analysis allows users to see mistakes
- Detection of standard openings and variations
- Custom themes

Qualitative Benefits:
- Improves the User Interface/user experience and playability
- Facilitates user customisation and improves experience
- Adaptive difficulty, which supports player advancements and prevents
boredom

Quantitative Benefits:
- Ability to cater to any skill level.

15
Jack Cooke A Level Computer Science Project

Objectives for the Proposed System

From testing and researching existing solutions, I have gathered information


regarding the most valuable features in a chess application and routes to
implement the proposed changes to provide superior playability and user
experience.

1. Registration and login


1.1. The user should be able to store a username and password
1.2. Only password hashes should be stored
1.3. The application should mitigate basic attacks such as dictionary
attacks.
2. Rules & Game
2.1. The system must be able to store relevant details about the current
board position.
2.1.1. The type of piece, colour, and x and y coordinates should be
properties of each piece.
2.1.2. For pawns, the piece must have an attribute to check if it is on
its first move.
2.1.3. The system must detect Check, Checkmate, and Stalemate
2.2. The application should recognise textbook openings and variations
of such openings
2.2.1. The AI should know what openings act as a counter for any
opening
2.3. When a piece is selected, the board should display legal moves
2.4. The user interface must be simple so that users can easily navigate
the UI
2.5. The application should be able to assign the user a fair elo-rating,
which will determine their skill level
2.5.1. An algorithm should control the rating of a user
2.5.2. The user's rating needs to be adjusted after every game to
reflect the user's performance in that game.
3. Data & statistics
3.1. Post-game statistics should be included, such as accuracy
3.2. The user must be able to view previous games and the move order
3.3. Users should be able to import their earlier games from other
supported applications
3.4. Previous games should be exportable
4. Customisation
4.1. The user must be able to use custom themes
4.1.1. There must be a standardised format for all themes
4.1.2. Themes should be drag and drop (require no technical skill to
change)
4.1.3. The user should be able to change piece icons, board colours

16
Jack Cooke A Level Computer Science Project

5. AI Player
5.1. The user should be able to play against a chess bot with adaptive
difficulty.
5.2. The bot should be able to challenge the player enough to make the
game fun but not sufficient to make the game too difficult.

17
Jack Cooke A Level Computer Science Project

Possible SQL Queries

Display all previously played games:

SELECT * FROM Game

Fetch moves history for a given game:

SELECT notation FROM Move


WHERE game_id = ?

Deleting old games:

DELETE FROM Game


WHERE game_id = ?

Display player's rating (From a previous game):

SELECT rating, player1_rating FROM Game


WHERE game_id = ?

Display player's rating:

SELECT rating FROM Player


WHERE player_id = ?

Display players above a specified rating:

SELECT player_id, username, email, rating


FROM Player
WHERE rating > ?
LIMIT 20;

18
Jack Cooke A Level Computer Science Project

Insert a new game:

INSERT INTO Game (date_played, result)


VALUES (?, ?);

Count the Number of Games Played by Each Player:

SELECT Player.username, COUNT(Game.game_id) AS games_played


FROM Player
LEFT JOIN Move ON Player.player_id = Move.player_id
LEFT JOIN Game ON Move.game_id = Game.game_id
GROUP BY Player.player_id, Player.username;

Calculate Win-Loss Ratio for Each Player:

SELECT Player.username,
SUM(CASE WHEN Game.result = 'win' THEN 1 ELSE 0 END) AS wins,
SUM(CASE WHEN Game.result = 'lose' THEN 1 ELSE 0 END) AS losses
FROM Player
LEFT JOIN Move ON Player.player_id = Move.player_id
LEFT JOIN Game ON Move.game_id = Game.game_id
GROUP BY Player.player_id, Player.username;

Find the Longest Game (in terms of move count):

SELECT Game.game_id, COUNT(Move.move_id) AS move_count


FROM Game
JOIN Move ON Game.game_id = Move.game_id
GROUP BY Game.game_id
ORDER BY move_count DESC
LIMIT 1;

Number of moves in a game:

SELECT COUNT(move_id) FROM Move;

19
Jack Cooke A Level Computer Science Project

Design
Generic App Workflow

20
Jack Cooke A Level Computer Science Project

IOPS Chart

This chart displays how data flows in input/output, processing, and storage at the
most basic level.

Input Process

● Players Move ● Retrieve and display previous


● Move_id games/moves from the
● Game_id database
● player1_rating ● Save moves to the database
● player2_rating ● Export moves in PGN format
● game_file (when loading from ● Convert a move on the board to
file) algebraic chess notation.

Storage Output

● Database with a table of Moves ● PGN file


● Database with a Table of Games ● Results of the game
● Database with a Table of Players

21
Jack Cooke A Level Computer Science Project

Hierarchy chart

A representation of the system structure organised by level of importance, top


down. The following diagram outlines the core programs that make up a chess
application.

22
Jack Cooke A Level Computer Science Project

System Flowchart

The flowchart illustrated below shows the process from user login to gameplay,
including storage of moves and promotions.

23
Jack Cooke A Level Computer Science Project

Data Flow Diagram (DFD)

The following diagram, written in UML format, displays the interactions and data
passed between the chess application's components.

24
Jack Cooke A Level Computer Science Project

Database Schema

Table Name Column Name Data Type Description

users id INTEGER Primary key,


unique user ID.

username TEXT Username of the


user.

password_hash TEXT Hashed password


of the user.

salt TEXT Unique salt is


used for password
hashing.

logins id INTEGER Primary key,


unique login ID.

username TEXT Username is


associated with
the login attempt.

time REAL Time of login


attempt (in
seconds).

games id INTEGER Primary key,


unique game ID.

player1 TEXT Username of the


first player.

player2 TEXT Username of the


second player.

fen TEXT Game position in


FEN format.

25
Jack Cooke A Level Computer Science Project

Entity Relationship Diagram (ERD)

26
Jack Cooke A Level Computer Science Project

Object-Oriented Programming Class Design

class: Piece

colour String (“white” or “black”)

x Integer

y Integer

class: Rook
Inherits from Piece
super().__init__(colour)

class: Knight
Inherits from Piece
super().__init__(colour)

class: Bishop
Inherits from Piece
super().__init__(colour)

class: Queen
Inherits from Piece
super().__init__(colour)

class: King
Inherits from Piece
super().__init__(colour)

class: Pawn
Inherits from Piece
super().__init__(colour)
first_move = BOOLEAN (defaults to True)

27
Jack Cooke A Level Computer Science Project

Class: ChessBoard(QWidget)
Identifier / Data Description

__init__

Parameters self - Instalises the player_turn, board


- Sets the default locations of
pieces

Returns N/A

draw_board (public)

Parameters self, layout - Called at the program start


- Adds Qt Buttons to a grid
- Calls the drawPiece function,
where a piece is present on the
board

Returns An array of Qt buttons

draw_piece

Parameters self, button, piece - Check that the piece is not


None
- Sets the piece icon from an SVG
- Sets the object name to the
location in the board List

Returns N/A

get_valid_moves

Parameters self, board, x, y - Calls the function inside the


piece’s class

Returns Array of Tuples

28
Jack Cooke A Level Computer Science Project

calculate_material_score

Parameters self - Loops through the board and


finds the sum of the
“piece.weights”

Returns Integer: score

are_you_in_check

Parameters self, player_colour - Check if any piece on the board


can attack the king

Returns Integer:
0 = No check
1 = Check
2 = Checkmate

move_piece

Parameters self, piece, - Check if the piece selected is


current_x, the same colour as the
current_y, new_x, player_turn
new_y - If a pawn is selected, check if it
is on its first move
- Call areYouInCheck; if True, only
allow moves that block check
- Removes the piece from the
current position
- Check if the piece can be
promoted, If True then open
promotionWindow
- Calls drawPiece

Returns N/A

29
Jack Cooke A Level Computer Science Project

highlight_squares

Parameters self, piece, - Highlights squares


squares - Called when a piece is selected
- Contains the button connectors
that allow for piece selection
and movement

Returns N/A

Class: PromotionWindow(QWidget)
Identifier / Data Description

__init__

Parameters self - Sets Grid layout


- Adds required buttons for pawn
promotion
- Adds connectors for when a
user clicks a piece

Returns N/A

piece_selected

Parameters self, piece - Emits a signal when a piece


selected by the user

Returns self.selected_piece

30
Jack Cooke A Level Computer Science Project

Class: Piece
Identifier / Data Description

__init__

Parameters self, colour - Initialises values


- x
- y
- selected
- colour

Returns N/A

select

Parameters self - Selects a piece

Returns self.selected = True

deselect

Parameters self - Deselects a piece

Returns self.selected = False

Class: Rook (Child of Piece)


Identifier / Data Description

__init__

Parameters self, colour - Initialises values from parent


and:
- self.weight = 5

Returns N/A

31
Jack Cooke A Level Computer Science Project

get_valid_moves

Parameters self, board, x, y - Check what squares the rook


can move to in the forward
direction
- Check what squares the rook
can move to in the backward
direction
- Check what squares the rook
can move to in the left direction
- Check what squares the rook
can move to in the right
direction

Returns An array of Tuples:


valid_moves

Class: Bishop (Child of Piece)


Identifier / Data Description

__init__

Parameters self, colour - Initialises values from parent


and:
- self.weight = 3

Returns N/A

get_valid_moves

Parameters self, board, x, y - Check diagonal up-right


- Check diagonal up-left
- Check diagonal down-right
- Check diagonal down-left

Returns An array of Tuples:


valid_moves

32
Jack Cooke A Level Computer Science Project

Class: Knight (Child of Piece)


Identifier / Data Description

__init__

Parameters self, colour - Initialises values from parent


and:
- self.weight = 3

Returns N/A

get_valid_moves

Parameters self, board, x, y - Define movement vectors, e.g.


(2,1)
- Iterate through possible
changes in coordinate

Returns An array of Tuples:


valid_moves

Class: Queen (Child of Piece)


Identifier / Data Description

__init__

Parameters self, colour - Initialises values from parent


and:
- self.weight = 9

Returns N/A

get_valid_moves

Parameters self, board, x, y - Defines the movement


directions
- Loop through all directions
- Check if there is a piece
of the same colour on
the square

Returns An array of Tuples:


valid_moves

33
Jack Cooke A Level Computer Science Project

Class: Pawn (Child of Piece)


Identifier / Data Description

__init__

Parameters self, colour - Initialises values from parent


and:
- self.weight = 1
- self.first_move = True

Returns N/A

get_valid_moves

Parameters self, board, x, y - Checks if the pawn is on the


first move
- Check if a piece is in the
way
- Check for diagonal capture
- Check for en passant

Returns An array of Tuples:


valid_moves

Class: ChessPiece(QLabel)
Identifier / Data Description

__init__

Parameters self, parent, piece - Initialises values from parent


and:
- Sets alignment
- Sets stylesheet
- Generate pixmaps
- Set fixed size for squares

Returns N/A

34
Jack Cooke A Level Computer Science Project

Class: ChessBoardUI(QWidget)
Identifier / Data Description

__init__

Parameters self - Initialises values from parent


and:
- Connects to the DB
- Creates tables if they do
not exist
- Loads the login UI

Returns N/A

init_login_ui

Parameters self - Creates widgets for username,


password, and login button

Returns N/A

handle_login

Parameters self - Reads username and password


- Inserts a login attempt
- Hides the login window
- Opens the main UI

Returns N/A

show_main_ui

Parameters self - Sets the layout to the grid


- Adds material count, clock, and
move count

Returns N/A

35
Jack Cooke A Level Computer Science Project

init_ui

Parameters self - Creates buttons for all the


pieces
- Connects the buttons to the
handle_click function
- Adds the buttons as widgets

Returns N/A

start_timer

Parameters self - Updates clock every 10ms

Returns N/A

get_valid_moves

Parameters self - Adds the clock label to the


board

Returns N/A

handle_click

Parameters self - Adds the clock label to the


board

Returns N/A

move_piece

Parameters self, source_row, - Implements checks for move


source_col, validity
target_row, - Updates the GUI as necessary
target_col,
is_ai_move

Returns N/A

36
Jack Cooke A Level Computer Science Project

ai_move

Parameters self - Instalises MCTS


- Runs an iteration to get the
best move

Returns N/A

update_material_count

Parameters self - Updates the material count


widget

Returns N/A

37
Jack Cooke A Level Computer Science Project

Algorithms

Monte-Carlo (chess engine)


Monte Carlo Algorithms generate a tree data structure and simulate how an
outcome values when a value changes.

Monte-Carlo Tree Search (MCTS) is a Best-First Search (BFS) that generates


random outcomes, building a traversable game tree. When paired with Upper
Confidence bounds applied to Trees (UCT), the tree can be easily traversed, and
nodes that do not produce favourable results are pruned from the tree.

MCTS consists of four stages: 1. Selection: The tree is traversed from the root node
until it selects a new leaf node
1. Expansion: Adds a leaf to the tree
2. Simulation: Evaluate the move. The result is either 1, 0, -1
3. Backpropagation: Propagates results through the tree

Steps of MCTS (Monte Carlo Tree Search.)

The most significant issue with the bare implantation of MCTS is the flaw whereby
the program may favour a move that loses due to a statistically unlikely playout
caused by the random nature of MCTS; the usage of UCT mitigates this.

Other limitations of MCTS include the reliance on external models to evaluate the
position, such as Neural Networks or other algorithmic evaluation methods, such
as assigning piece-specific weights to squares. Furthermore, to parse the vast
number of positions in a reasonable time, Alpha-beta pruning and a cap on max
iterations can be introduced since, after ten moves, there are already
~70,000,000,000,0002 possible unique positions. The time complexity of
computing all positions increases exponentially as more moves occur. Alpha-beta
pruning works by defining alpha as beta as the lower bound and alpha as the
upper bound; as the algorithm explores the tree, if a move results in a value worse

38
Jack Cooke A Level Computer Science Project

than the current alpha or beta value, all subtrees from the node are removed,
therefore decreasing the number of nodes to parse and the time to find the best
move.

Password-Based Key Derivation Function 2 (pbkdf2)


Hashes store passwords securely since they are one-way functions and are
difficult to reverse engineer when appropriately utilised.

Pbkdf2 is a cryptographic hashing algorithm defined in the IEEE rfc2898 (Internet


Engineering Task Force)
standard for deriving cryptographic keys from an input. The
algorithm can generate computationally complex keys from the following inputs:
password, salt, iteration count, and intended length, where a salt represents a
random alphanumeric value.

(National Institute of Standards and Technology)

To properly implement pbkdf2, different salts should be used for each user to
thwart attackers using rainbow tables. Furthermore, adding a pepper to the
opposite end as the salt when hashing a password can prevent an attack that
gained access to the database from being able to decrypt it, providing the pepper
is stored in a secure place such as an HSM.

https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-132.pdf
https://www.ietf.org/rfc/rfc2898.txt
ISSUES: SEE https://pycryptodome.readthedocs.io/en/latest/src/protocol/kdf.html

39
Jack Cooke A Level Computer Science Project

Negamax evaluation framework


Negamax is an implementation of a minimax algorithm. To implement a
Negamax algorithm, search depth, a root node to start from, and a static
evaluation that returns a score relative to the evaluated side are requirements.
The simplest definition of Negamax is as follows:

Python
score = materialWeight * (numWhitePieces - numBlackPieces) * who2move

Negamax requires an evaluation function to return the correct result; I


implemented my evaluation function using Python using the following
mathematical algorithm.

f(p) = 200(K-K')
+ 9(Q-Q')
+ 5(R-R')
+ 3(B-B' + N-N')
+ 1(P-P')
- 0.5(D-D' + S-S' + I-I')
+ 0.1(M-M')

KQRBNP = number of kings, queens, rooks, bishops, knights and pawns


D,S,I = doubled, blocked and isolated pawns
M = Mobility (the number of legal moves)

40
Jack Cooke A Level Computer Science Project

User Interface Design Concepts

Initial Concepts:

Strengths:

● Readability: The high-contrast colours make the board and pieces easy to
see and understand.
● Aesthetic Appeal: The green squares add a modern twist to the traditional
chessboard design, making it visually appealing.
● Standard Compliance: The setup adheres to standard chess rules.

Potential Improvements:

● Highlighting: Add move highlighting or the ability to show valid moves for
selected pieces to improve interactivity.
● Coordinates: Include board coordinates (e.g., a1, h8) for easier reference
● Colour Customization: Allow users to change the board and piece colours
to suit their preferences.

41
Jack Cooke A Level Computer Science Project

Strengths:

● Functionality: Timers and move history support competitive play and


enhance usability for experienced players.
● Clarity: The minimalist style ensures the board, pieces, and UI elements are
not cluttered, keeping the interface clean.
● Chess Notation: Standard notation in the move list is an excellent feature
for players who study chess and review their games.

Potential Improvements:

● Aesthetic Enhancements: Introduce colour customisation for the board


and pieces to cater to diverse user preferences.
● Interactive Features: Highlight the last move made and valid moves for
selected pieces.

42
Jack Cooke A Level Computer Science Project

Strengths:

● Functionality: Timers and move history support competitive play and


enhance usability for experienced players.
● Chess Notation: Standard notation in the move list is an excellent feature
for players who study chess and review their games.

Potential Improvements:

● Aesthetic Enhancements: Introduce colour customisation for the board


and pieces to cater to diverse user preferences. Modifying the colour
scheme to look less like something out of the 1950s.

Overall:

● This design is worse than the design above due to the colour scheme and
the top bar feeling crowded.

43
Jack Cooke A Level Computer Science Project

System Architecture

The diagram below illustrates the system's components, including databases,


front-end, back-end, and middleware (connections in between).

44
Jack Cooke A Level Computer Science Project

Technical Solution

Object-Oriented Programming (OOP)

This project extensively uses OOP principles such as encapsulation, inheritance,


and polymorphism.
● Custom Classes for Chess Pieces: Each chess piece is represented by a class
(Pawn, Rook, Knight, Bishop, Queen, King) in pieces.py. These classes
encapsulate the behaviour and properties of each piece, such as
movement patterns.
● Inheritance and Method Overriding: The chess piece classes inherit from a
base class and override methods to define specific behaviours. For
example, each subclass defines the move() method differently to reflect
each piece's unique movements.

● Chess Board Management: The ChessBoard class in chess_board_1.py


manages the game's state, including the placement of pieces, move
validation, and game rules enforcement.

● GUI Components: In gui.py, the ChessBoardUI class inherits from QWidget


(a PyQt5 class) to create the main interface. Custom widgets like
ChessPiece are derived from QLabel to display pieces on the board.

45
Jack Cooke A Level Computer Science Project

46
Jack Cooke A Level Computer Science Project

Graphical User Interface (GUI) Development

● PyQt5 Framework: The application uses PyQt5 to build a responsive and


interactive GUI. This involves creating windows, dialogues, buttons, labels,
and layout management.
● Event Handling: Methods like handle_click() in ChessBoardUI respond to
user interactions, such as clicking on a chess square and updating the
game state accordingly.
● Dynamic Interface Updates: The GUI reflects real-time changes in the
game, updating the board display after each move and showing relevant
information like move count and player turn.

47
Jack Cooke A Level Computer Science Project

Algorithm Implementation

● Monte Carlo Tree Search (MCTS): The mcts.py module implements the
MCTS algorithm for AI decision-making. This involves:
○ Tree Structure: The Node class represents each state in the game
tree, holding information about the board state, parent and child
nodes, visit counts, and value evaluations.
○ Algorithm Phases: The MCTS implementation includes selection,
expansion, simulation, and backpropagation phases. Methods like
select(), expand(), simulate(), and backpropagate() manage these
processes.
○ Heuristic Evaluation: The AI uses the board evaluation function to
simulate and evaluate potential moves.

48
Jack Cooke A Level Computer Science Project

49
Jack Cooke A Level Computer Science Project

Board Evaluation Function

● Complex Evaluation Metrics: In eval_board.py, the eval_board() function


assesses the board state using a formula for material balance, pawn
structure (doubled, blocked, isolated pawns), mobility, and positional
advantages.
● Quantitative Scoring: The evaluation function calculates a numerical score
that represents the favorability of the board state for a given player.
● Normalisation of Scores: Incorporates score normalisation to scale
evaluation results between 0 and 1, enhancing the consistency of AI
decisions.

50
Jack Cooke A Level Computer Science Project

51
Jack Cooke A Level Computer Science Project

Database Interaction and Security

● SQLite Integration: The application connects to a SQLite database using the


DBConnector class in db_connector.py.
● User Authentication:
○ Secure Password Storage: SHA-256 is used to hash user passwords
and a unique salt for each user, enhancing security against password
attacks by exponentially increasing the time complexity of a brute
force attack where the attacker has database access.
○ Verification Mechanism: The verify_user() method checks user
credentials securely by comparing the hashed password inputs.

● Data Management:
○ CRUD Operations: The application performs Create, Read, Update,
and Delete operations on the database for managing users, login
attempts, and game records.
○ Prepared Statements: Parameterised queries to prevent SQL
injection attacks.

52
Jack Cooke A Level Computer Science Project

Unit Testing and Test-Driven Development

● Testing Frameworks: Utilizes unittest and pytest for writing and executing
test cases.

● Comprehensive Test Coverage:


○ Database Tests: test_db_connector.py verifies database operations,
including user insertion and authentication.
○ Algorithm Tests: test_mcts.py tests the MCTS implementation to
ensure correct AI behaviour.
○ Evaluation Function Tests: test_eval_board.py checks the accuracy of
board evaluations under different scenarios.
○ GUI Tests: test_gui.py validates the GUI components, such as the
login interface and game display updates.

53
Jack Cooke A Level Computer Science Project

● Continuous Integration: Integration with GitHub Actions automates the


testing process on code pushes and pull requests.

54
Jack Cooke A Level Computer Science Project

Concurrency and Performance Optimization

● Multithreading and Multiprocessing:


○ In pgn_to_db.py, concurrent processing speeds up the parsing of
large PGN files by running the operations in parallel.
○ Uses concurrent.futures and the ProcessPoolExecutor to distribute
tasks across multiple CPU cores.

55
Jack Cooke A Level Computer Science Project

Integration with External Data Sources

● PGN File Parsing:


○ The pgn_to_db.py script reads and processes PGN files, which are
standard formats for recording chess games.
○ Extracts game data and stores it in the database for use in training or
analysis.

● Data Handling:
○ Uses the chess.pgn module to parse PGN files efficiently.
○ Manages large datasets by splitting files and processing chunks
asynchronously.

56
Jack Cooke A Level Computer Science Project

Version Control and Continuous Integration

● GitHub as a VCS system:


○ The project is managed using Git and hosted on GitHub, enabling
version tracking and collaboration.
● Continuous Integration Pipeline:
○ The workflow defined in python-app.yml sets up automated testing
(using pytest) and code linting (using ruff).
○ Ensures code quality and stability through automated checks on
every commit.

57
Jack Cooke A Level Computer Science Project

Code Style and Linting

● PEP 8 Compliance:
○ The codebase adheres to Python's PEP 8 style guidelines, enhancing
readability and maintainability.
● Linting Tools:
○ A fast Python linter, Ruff detects and fixes coding errors and style
issues.
○ Automated linting is integrated into the CI pipeline to enforce code
standards.

58
Jack Cooke A Level Computer Science Project

Error Handling and Logging

● Exception Handling:
○ The application includes try-except blocks to handle potential
runtime errors gracefully.
○ Provides informative error messages to assist in debugging.
● Logging:
○ Utilises the logging module to record events, errors, and significant
actions within the application.
○ Log files help in monitoring the application's behaviour over time.

59
Jack Cooke A Level Computer Science Project

Use of Advanced Python Features

● Decorators and Context Managers: Implemented custom decorators for


profiling or timing functions
● Type Hinting: The code includes type hints to improve code clarity and
assist with static analysis tools.

60
Jack Cooke A Level Computer Science Project

Networking

The application consists of a client and a server, with the server running on a
remote machine or locally.

Client
The client connects to the server or port 5556 and communicates with the server
using SOCK_STREAM, which uses the Transmission Control Protocol to prevent
data loss between the client and server.

61
Jack Cooke A Level Computer Science Project

Server
The server listens to port 5556 for incoming connections from the client and can
support multiple clients. The server binds to a port and listens for connections.
The server then makes all the moves locally and uses Pickle, a Python serialisation
library, to send Python Objects to the client.

62
Jack Cooke A Level Computer Science Project

Deployment of Chess application

The application uses docker-compose to build containers and provide an isolated


network for the server to communicate with the database.

● A custom container is built from the following file to run the Python part of
the application.

63
Jack Cooke A Level Computer Science Project

Testing

Overview

This test plan outlines the testing strategy for the chess application. The tests
ensure the system works as expected and meets the specified objectives. The
tests will be automated using pytest and unittest, and the results will be analysed
using SonarQube.

Test Plan

Database Connector Tests


See 3:54 - 4:10 in the attached video and 4:41 - 5:12 for demonstration.

Purpose: Verify the functionality of the database connector. Test Data: Temporary
SQLite database. Expected Outcome: The database tables are created, and data
can be inserted, retrieved, and verified.

64
Jack Cooke A Level Computer Science Project

65
Jack Cooke A Level Computer Science Project

Test Cases:

test_create_users_table:
Description: Verify that the users table is created successfully.
Expected outcome: A table is created with the columns and restrictions specified
in the image below

66
Jack Cooke A Level Computer Science Project

test_insert_user:
Description: Verify that a user can be inserted into the users table.
Expected outcome: A user with the username “test_user” is inserted into the test
table, where a random 16-bit value is the salt and the password is stored as a hash.

test_verify_user:
Description: Verify that user verification works correctly.
Expected outcome: When entering the correct credential, a user can access their
account.

67
Jack Cooke A Level Computer Science Project

test_create_logins_table:
Description: Verify that the logins table is created successfully.
Expected outcome: A table is created with the columns and restrictions specified
in the image below

68
Jack Cooke A Level Computer Science Project

test_insert_login_attempt:
Description: Verify that a login attempt can be inserted into the logins table.
Expected outcome: A table is created with the columns and restrictions specified
in the image below

test_get_login_attempts:
Description: Verify that login attempts can be retrieved from the logins table.
Expected outcome: When a user is inserted into the login attempts table, the
timestamp associated with the login is correct.

69
Jack Cooke A Level Computer Science Project

test_create_games_table:
Description: Verify that the games table is created successfully.
Expected outcome: A table is created with the columns and restrictions specified
in the image below

test_insert_game:
Description: Verify that a game can be inserted into the games table.
Expected outcome: When a game is complete, check that the match inserted into
the table exists and is formatted correctly.

70
Jack Cooke A Level Computer Science Project

Evaluation Board Tests


Purpose: Verify the functionality of the board evaluation. Test Data: Various board
configurations. Expected Outcome: The board evaluation function returns the
correct score.

See 2:47 - 3:16 in the attached video and 4:41 - 5:12 for demonstration.

Test Cases:

71
Jack Cooke A Level Computer Science Project

test_eval_board_empty:
Description: Verify that an empty board returns a score of 0.
Expected outcome: An empty board should have a score of 0.

72
Jack Cooke A Level Computer Science Project

test_eval_board_standard:
Description: Verify that the standard starting position returns a score of 0.
Expected outcome: A symmetrical board should return a score of 0.

73
Jack Cooke A Level Computer Science Project

test_eval_board_all_white:
Description: Verify that a board with all white pieces returns the correct score.
Expected outcome: An all-white board with a default setup should have a score of
226.0 when using the NEGAMAX evaluation framework

74
Jack Cooke A Level Computer Science Project

test_eval_board_mixed:
Description: Verify that a board with mixed pieces returns the correct score.
Expected outcome: A board with a known random mix of pieces, where the value
of each piece is the same, and the team is different, should return a value of 0
using the NEGAMAX evaluation framework.

75
Jack Cooke A Level Computer Science Project

test_eval_board_normalised:
Description: Verify that the board score is normalised correctly.
Expected outcome: All normalised scores should be the datatype float between 0
and 1.

76
Jack Cooke A Level Computer Science Project

Monte Carlo Tree Search (MCTS) Tests


Purpose: Verify the functionality of the MCTS algorithm. Test Data: Initial board
configuration. Expected Outcome: The MCTS algorithm selects the best move and
updates the tree correctly.

See 1:41 - 2:25 in the attached video and 4:41 - 5:12 for demonstration.

Test Cases:

test_node_initialization:
Description: Verify that nodes are initialised correctly.
Expected outcome: The initial node values are as expected

77
Jack Cooke A Level Computer Science Project

test_node_is_leaf:
Description: Verify that the leaf status of a node is determined correctly
Expected outcome: A node with no children should be classed as a leaf; a node
with any number of children should not be considered a leaf.

test_node_expand:
Description: Verify that nodes can be expanded with valid moves.
Expected outcome: A node with a valid move can be expanded into multiple
children, each with a different board state.

78
Jack Cooke A Level Computer Science Project

test_node_apply_move:
Description: Verify that a move can be applied to a node.
Expected outcome: A node with a move applied to it has an array where the new
move is present.

test_node_update:
Description: Verify that nodes can be updated with a value.
Expected outcome: When the update method is called on a node, the number of
visits increments and the value changes.

79
Jack Cooke A Level Computer Science Project

test_mcts_select:
Description: Verify that the MCTS algorithm selects the correct node.
Expected outcome: A root node is selected correctly.

test_mcts_expand:
Description: Verify that the MCTS algorithm expands the correct node.
Expected outcome: An expanded node has more than 0 children.

test_mcts_simulate:
Description: Verify that the MCTS algorithm simulates a game correctly.
Expected outcome: A node that has simulated called has a float value associated.

80
Jack Cooke A Level Computer Science Project

test_mcts_backpropagate:
Description: Verify that the MCTS algorithm backpropagates the value correctly.
Expected outcome: The number of visits and value changes when the
backpropagate function is called.

test_mcts_run:
Description: Verify that the MCTS algorithm runs correctly.
Expected outcome: When the run function is called, the root node has been
visited at least once.

81
Jack Cooke A Level Computer Science Project

test_mcts_best_move:
Description: Verify that the MCTS algorithm selects the best move
Expected outcome: When running MCTS the best move is always associated with
a node.

82
Jack Cooke A Level Computer Science Project

GUI Tests
Purpose: Verify the functionality of the graphical user interface. Test Data: User
inputs and board configurations. Expected Outcome: The GUI updates correctly
based on user interactions.

See 2:25 - 2:48 in the attached video and 4:41 - 5:12 for demonstration.

Test Cases:

test_initialization:
Description: Verify that the GUI components are initialised correctly.
Expected outcome: When creating a GUI, the correct widgets are present.

83
Jack Cooke A Level Computer Science Project

84
Jack Cooke A Level Computer Science Project

test_login_valid:
Description: Verify that a valid login works correctly.
Expected outcome: When logging in with the correct credentials, a user is logged
in and the window changes.

test_login_invalid:
Description: Verify that invalid logins are handled correctly.
Expected outcome: When logging in with the incorrect credentials, a user is not
logged in, and the login window does not change.

85
Jack Cooke A Level Computer Science Project

test_ui_updates_on_move:
Description: Verify that the UI updates correctly when a move is made.
Expected outcome: After a move is made, the UI move count and player to move
should change.

test_parse_ini:
Description: Check that .INI files are correctly loaded.
Expected outcome: A known dummy INI file should be loaded correctly into a
dictionary.

86
Jack Cooke A Level Computer Science Project

Chess Board Tests


Purpose: Verify the functionality of the chess board. Test Data: Various board
configurations and moves. Expected Outcome: The chess board updates correctly
based on the moves and game state.

See 3:16 - 3:55 in the attached video and 4:41 - 5:12 for demonstration.

Test Cases:

test_initial_setup:
Description: Verify that the initial setup of the chessboard is correct.
Expected outcome: The positions of each piece are correct for a standard chess
game.

87
Jack Cooke A Level Computer Science Project

test_load_openings:
Description: Verify that the openings are loaded correctly.
Expected outcome: The openings are loaded correctly into a non-empty
dictionary.

test_get_opening:
Description: Verify that the correct opening is identified.
Expected outcome: A non-standard opening is classed as unknown.

test_get_all_valid_moves:
Description: Verify that all valid moves are returned correctly.
Expected outcome: A standard chessboard should have multiple valid moves.

88
Jack Cooke A Level Computer Science Project

test_board_array_to_fen:
Description: Verify that the board array is converted to FEN correctly.
Expected outcome: Any chess board should return a valid non-0 length string in
Forth Edwards Notation.

test_get_material_count:
Description: Verify that the material count is calculated correctly.
Expected outcome: Any chessboard should have a positive integer material count.

test_move_piece:
Description: Verify that pieces can be moved correctly.
Expected outcome: Valid moves should be accepted, and invalid moves should be
rejected.

89
Jack Cooke A Level Computer Science Project

test_enpesaunt:
Description: Verify that en passant moves are handled correctly.
Expected outcome: A board not set up for en passant should return False.

test_castling:
Description: Verify that castling moves are handled correctly.
Expected outcome: A board set up for queenside castling should allow castling.

test_are_you_in_check:
Description: Verify that the check status is determined correctly.
Expected outcome: A board with position where the user is not in check returns 0.

90
Jack Cooke A Level Computer Science Project

test_game_over:
Description: Verify that the game-over status is determined correctly.
Expected outcome: A board where there is no checkmate is not over.

test_pawn_promotion:
Description: Verify that pawn promotion is handled correctly.
Expected outcome: A pawn can be promoted to a queen when on a valid square.

91
Jack Cooke A Level Computer Science Project

Networking Tests
Purpose: Verify that the client and server interact as expected. Test Data: Various
standard application operations, login, and moves. Expected Outcome: The
networked client behaves like the local GUI client.

See 0:32 - 1:41 in the attached video

Test Cases:

Client:

test_recieve_data:
Description: Verify that data can be sent from the server to the client
Expected outcome: A socket allows the client to send and receive data and
serialise Python objects using pickle.

92
Jack Cooke A Level Computer Science Project

Server:

test_chess_server_init:
Description: Checks initialisation of the server
Expected outcome: A server binds to the correct ports and creates threads to
handle each connection.

93
Jack Cooke A Level Computer Science Project

GUI:

test_ui_initialization:
Description: Check that the correct layout and labels are set.
Expected outcome: The layout of the board is set correctly.

test_login_ui_initialisation:
Description: Check that the username and password fields are present.
Expected outcome: The login UI has the correct field to authenticate.

94
Jack Cooke A Level Computer Science Project

test_handle_login_sucess:
Description: Checks that the test_user can log in.
Expected outcome: A user with the correct credentials is able to authenticate and
change the window.

test_handle_login_faliure:
Description: Checks that a user without an account is unable to log in
Expected outcome: A user with the wrong credentials is unable to log into the
system.

95
Jack Cooke A Level Computer Science Project

test_update_clock:
Description: Checks that the clock inside the UI updates relative to the current
time
Expected outcome: The clock widget updates to the correct value.

test_handle_click:
Description: Checks that pieces can be moved
Expected outcome: When a user clicks on a square for a piece to be moved to, the
correct functions are called in the background

Execution Plan:

The tests will be executed in multiple environments using tox for orchestration,
pytest, and unittest for testing. The results will be analysed using SonarQube to
ensure code quality and coverage.

96
Jack Cooke A Level Computer Science Project

Evaluation

Comparison against Objectives


The following table compares the completed system's performance to the
objectives laid out in the analysis on page 9 of the Objectives of the Proposed
System.

Objective Completed system

Registration and login Passwords are not stored. Only salt


and a hash are stored in the database.
1. The user should be able to store
Logins are rate-limited to prevent
a username and password users from being able to brute force
2. Only password hashes should using a rainbow table or dictionary
be stored attack.
3. The application should mitigate
basic attacks such as dictionary
attacks.

Rules & Game The board is represented using a


piece-centric model, where data is
1. The system must be able to
stored inside the piece class rather
store relevant details about the than on the board.
current board position. Pawns have a first_move attribute that
2. The type of piece, colour, and x determines if they can move two
and y coordinates should be squares.
properties of each piece. Check checkmate and stalemate
detection are fully implemented into
3. For pawns, the class must have
the application.
an attribute to check if it is on Opening detection is fully
its first move. implemented into the application and
4. The system must detect Check, displayed in the GUI
Checkmate, and Stalemate Legal moves are highlighted on the
5. The application should board in a separate colour.
recognise textbook openings The UI is minimal and easy to navigate
due to low complexity
and variations of such openings
6. When a piece is selected, the
board should display legal
moves
7. The user interface must be
simple so that users can easily
navigate the UI

97
Jack Cooke A Level Computer Science Project

Data & statistics The user can export their game as a


standard portable game notation
1. Post-game statistics should be
(PGN) file, a widely used format that
included, such as accuracy allows the user to use any tool to
2. The user must be able to view generate engine evaluation or replay
previous games and the move the game on other platforms. An
order export button on the main UI saves
3. Previous games should be the file to disk and displays the relative
path.
exportable

Customisation The user can change their theme in an


INI configuration file, which uses a
1. The user must be able to use
standard format and allows them to
custom themes change piece icons and board colours.
2. There must be a standardised
format for all themes
3. Themes should be drag and
drop (require no technical skill
to change)
4. The user should be able to
change piece icons, board
colours

AI Player The player can adjust the difficulty via


a value in a config file.
1. The user should be able to play
against a chess bot with
adaptive difficulty.
2. The bot should be able to
challenge the player enough to
make the game fun but not
sufficient to make the game too
difficult.

98
Jack Cooke A Level Computer Science Project

Potential for Future Developments


Enhanced AI Functionality

● Develop a more advanced AI using reinforcement learning or neural


networks to better adapt to player styles and offer dynamic challenges.
● Implement AI training pipelines that allow users to train custom AIs using
their games or datasets.

Improved User Engagement Features

● Add a gamification layer with achievements, badges, or milestones to


increase user retention.
● Introduce a social component, such as friend lists or chat functionalities
during games.

Mobile Application Development

● Develop mobile versions of the chess app to expand its accessibility and
reach a broader audience.

Expanded Game Modes and Variants

● Introduce chess variants like Fischer Random Chess, Bughouse, or Horde to


diversify gameplay.
● Add puzzles or tactical training exercises to enhance the educational
aspect of the app.

Advanced Post-Game Analysis

● Enhance post-game analysis by integrating third-party chess engines like


Stockfish for detailed move-by-move feedback.
● Include visualizations of the game's turning points and recommended
moves to improve player understanding.

Community and Competitive Features

● Introduce online tournaments or leaderboards to foster competition


among users.
● Develop a matchmaking system that pairs players based on similar ELO
ratings.

Integration with External Platforms

● Allow integration with popular chess platforms like Lichess or Chess.com


for importing and exporting games or synchronizing stats.
● Enable streaming or recording options for users who want to share their
games.

99
Jack Cooke A Level Computer Science Project

Localization and Accessibility

● Add support for multiple languages to cater to a global audience.


● Improve accessibility with features like text-to-speech, high-contrast
modes, and support for keyboard navigation.

100
Jack Cooke A Level Computer Science Project

Registration and Login

Objective: The user should be able to store a username and password.


Implementation Details:
● User Registration: The application allows users to register by providing a username
and password. This is managed through the DBConnector class in postgres_auth.py.

Objective: Only password hashes should be stored.


Implementation Details:
● Password Hashing: Passwords are hashed securely using SHA-256 before being
stored in the database. A unique salt is applied to each password to enhance
security.

Objective: The application should mitigate basic attacks such as


dictionary attacks.
Implementation Details:
● Salted Hashes: By using unique salts for password hashing, the application reduces
vulnerability to dictionary attacks.
● Secure Verification: The application correctly handles password verification during
login without exposing sensitive data.

101
Jack Cooke A Level Computer Science Project

Rules & Game

Objective: The system must be able to store relevant details about the current
board position.
Implementation Details:
● Board Representation: The ChessBoard class in chess_board_1.py maintains the
board's current state, including the position of all pieces.

Objective: The system must detect Check, Checkmate, and Stalemate.


Implementation Details:
● Check Detection: Basic check detection is implemented by evaluating if the king is
threatened after a move.

● Checkmate and Stalemate: Implemented inside the same function, returning different
values based on the status

102
Jack Cooke A Level Computer Science Project

Objective: The application should recognise textbook openings and


variations of such openings.
Implementation Details:
● Opening Database: The load_openings() method attempts to load and recognise
standard openings from a file.

Objective: The user interface must be simple so that it can be easily


navigated.
Implementation Details:
● Intuitive Design: The GUI, developed using PyQt5, features a clean layout with clear
buttons and controls for easy navigation.

103
Jack Cooke A Level Computer Science Project

Data & Statistics

Objective: Post-game statistics, such as accuracy, should be included.


Implementation Details:
● Basic Statistics: The application tracks basic metrics like the number of moves and
results of the game.

Objective: The user must be able to view previous games and the move order.
Implementation Details:
● Game Records: Game data is saved to a SQLite Database

Customisation

Objective: The user should be able to change piece icons & board
colours.
Implementation Details:
● The user can change the icons by replacing the SVG files in ./media/white or
./media/black
● The user can change the board colours by modifying them in gui.py

AI Player

Objective: The user should be able to play against a chess bot with
adaptive difficulty.
Implementation Details:
● Existing AI: The AI uses a Monte Carlo Tree Search algorithm to play against the
user.

104
Jack Cooke A Level Computer Science Project

Key Resources
https://www.chessprogramming.org/Main_Page
https://www.chess.com/terms/chess-pgn
https://www.chess.com/terms/fen-chess
https://www.pythonguis.com/tutorials/creating-multiple-windows/
https://towardsdatascience.com/train-your-own-chess-ai-66b9ca8d71e4
https://database.lichess.org/#standard_games
https://www.kaggle.com/datasets/datasnaek/chess/data
https://github.com/Lightning-AI/pytorch-lightning
https://en.wikipedia.org/wiki/Minimax
https://www.freecodecamp.org/news/create-a-self-playing-ai-chess-engine-from-s
cratch/#part-3-how-to-train-the-ai-model
https://pytorch.org/
https://docs.python.org/3/howto/logging.html
https://doc.qt.io/qtforpython-5/PySide2/QtWidgets/QPushButton.html#more

105
Jack Cooke A Level Computer Science Project

Build Log

Features

Commit 3: PyQt5 Skeleton:


- Simple UI for piece SVG containing only the board in black and white
- Basic movement and piece highlighting.

PR #1 431f327:
- SQLite wrapper allowing basic CRUD operations
- DB create containing schema
- Test coverage for non-PyQt5 functions

Commit f15973d: Split files.


- Move all Python classes from app.py to separate files to make the
workspace easier to navigate.

Commit 00c5b74: fix promotion handling.


- Pieces were unable to promote due to the missing call to the method:
self.promotion_window.piece_selected.connect(self.handle_piece_selected)

Commit 5c1edab: fix index error when no Valid Moves exist


- Issue: Crash when there are no valid moves for a given piece
- Fixed by logging an error to the console when the getter function in
ChessBoard.py calls self.getValidMoves() returns the error: index out of
range

Commit c86355e: initial chess engine


- Uses PyTorch to train a neural network from lichens public shards
(approximately one million games)

Commit 2106226: fix the issue calling PromotionWindow


- Issue: When the PromotionWindow was opened, the listener did not
receive a signal.
- Fixed by replacing the piece_selected method with piece_selected.emmit

Commit 06f713e: decrease memory use when loading data


- Issue: When loading Lichess shards to memory, RAM usage exceeds that of
the system

106
Jack Cooke A Level Computer Science Project

- Fixed by splitting the shard into multiple files and loading them
asynchronous at a rate determined by the system the program is running
on

Commit ee407f3: fix tensor structure, auto remove old logs, configure
tb logging
- Issue: The old structure did not include multithreading, causing subpar
training speeds.
- Fixed by specifying the number of workers in a pool and restructuring the
tensors to store game data more efficiently, mapping the data to 32-bit
floating point values

Commit eb9a812: Adds scaffolding for Monte-Carlo Tree Search


Algorithm
- Issue: Lack of speed when using a custom model

Commit eb9a812: adds profiling, concurrent processing, more efficient


data frames, and batch processing.
- Issue: When processing large amounts of games for conversion, only a
single thread is used, and for 1,000,000 games, the time is approximately
40 minutes
- Fixed using the concurrent library and profiling to determine a more
appropriate data structure time was reduced by 75%

Commits 2801bfc, c34746a, and e4c27fb : 📝 update / add comments


- Issue: Code comments did not clearly explain what was happening
- Fixed by expanding on what inputs and outputs a function expects and
adding some processes to comment

Commit 2eaed41: ⚡ add GPU acceleration


- Issue: System resources are not used efficiently in the training process is
constrained by CPU operations
- Fixed by adding GPU acceleration to take advantage of Nvidia CUDA cores
in the GPU

107
Jack Cooke A Level Computer Science Project

Bug Fixes

Commit 963ac2d: 🐛 fix visually duplicated pieces.


- Issue: A user was able to select a piece, then when the move took place, the
piece would appear to stay in the same position with a new instance at the
cursor
- Fixed by adding a function to redraw all the changes to the board after
every move

Commit 1fe091d and d9b4ff2: 🐛 Pawns cannot move two squares on


the first move.
- Issue: Pawns do not move two squares
- Fixed by adding a check for the isFirstMove variable inside the instance of
the Pawn class.

More Features

PR #13 4e404ea: add user controls for board colour


- Issue: Pieces are challenging to see on the board
- Fixed by shifting the board to an off-white and off-black by default and
adding user-defined RGB values for board colours

PR #14: Add encryption and decryption functionality using Tornado


- Feature: Mock Hardware Security Module (HSM)
- Uses GCM for asymmetric cyphers and pbkdf2 for data encryption

PR #15: Add SonarCloud coverage integration and improve testing


- Feature: Modifies a GitHub action to track code coverage using pytest-cov
and upload codebase as well as test results to SonarCloud for analysis

Features:

PR #16 Code refactor


- Removes duplicates, unused parameters and refactors function calls

PR #17 Database implantation changes


- Log user login times

108
Jack Cooke A Level Computer Science Project

- Store FEN strings as board representation

PR #21 Add user login to the GUI & other features


- Added move count, material count, and login window (with auth using the
DB)

PR #22 MCTS in the GUI


- Adds the bot to the GUI

PR #23 Opening Detection


- Adds detections of openings using lichess dataset

PR #24 & #25 Update testing workflow


- Move to a self-hosted SonarQube instance
- Update Tox

PR #27 Add Pawn Promotion (GUI)


- Adds promotion to the GUI

PR #28 Documentation
- Update install process and supported Python versions

PR #30 Client - Server networking for the chess application


- Migrated user logins to a PostgreSQL server
- Fixed minor code smells

Commit 119ceac - Add move history to the GUI


- Refactor layout of GUI
- Adds move history table

Commit ac026e5 - Save move history to local SQLite DB


- Adds new save_move() function
- Automatically saves the move to a DB

109
Jack Cooke A Level Computer Science Project

References

Works Cited

Shannon number - Wikipedia, https://en.wikipedia.org/wiki/Shannon_number.

Accessed 28 August 2024.

Internet Engineering Task Force. Password-Based Cryptography Specification.

2.0, The Internet Society, 2000, https://www.ietf.org/rfc/rfc2898.txt. Accessed

26 November 2024.

Monte Carlo Tree Search. “Monte Carlo tree search.” Wikipedia,

https://en.wikipedia.org/wiki/Monte_Carlo_tree_search. Accessed 26

November 2024.

National Institute of Standards and Technology. NIST SP 800-132,

Recommendation for Password-Based Key Derivation Part 1: Storage

Applications, December 2010,

https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-132.p

df. Accessed 2 September 2024.

110

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy