Chess PGN Player

[Home]   [Puzzles & Projects]    [Delphi Techniques]   [Math topics]   [Library]   [Utilities]




Search WWW


As of October, 2016, Embarcadero is offering a free release of Delphi (Delphi 10.1 Berlin Starter Edition ).     There are a few restrictions, but it is a welcome step toward making more programmers aware of the joys of Delphi.  They do say "Offer may be withdrawn at any time", so don't delay if you want to check it out.  Please use the feedback link to let me know if the link stops working.


Support DFF - Shop

 If you shop at Amazon anyway,  consider using this link. 


We receive a few cents from each purchase.  Thanks


Support DFF - Donate

 If you benefit from the website,  in terms of knowledge, entertainment value, or something otherwise useful, consider making a donation via PayPal  to help defray the costs.  (No PayPal account necessary to donate via credit card.)  Transaction is secure.

Mensa Daily Puzzlers

For over 15 years Mensa Page-A-Day calendars have provided several puzzles a year for my programming pleasure.  Coding "solvers" is most fun, but many programs also allow user solving, convenient for "fill in the blanks" type.  Below are Amazon  links to the two most recent years.

Mensa 365 Puzzlers  Calendar 2017

Mensa 365 Puzzlers Calendar 2018

(Hint: If you can wait, current year calendars are usually on sale in January.)


Feedback:  Send an e-mail with your comments about this program (or anything else).

Search only




Problem Description

This program enables the visual replay of PGN files recording the moves of chess games.

Background & Techniques

PGN (Portable Game Notation) is a widely used format for recording chess games for historical or study purposes.  There are many playback programs available and the world does not need another.  However a DFF viewer requested it, I could not locate an existing one written in Delphi, and it sounded like  (and was) an interesting project.  So here it is.

This version allows files of games to be loaded and individual games select for replay.  Moves are displayed sequentially by clicking the "Move" button and may be undone by clicking the "Undo" button.  Double clicking on any move in the move list will rapidly move the board forward or backward to  the position immediately prior to that move. 

There appears to be a life time's worth of games available for free download.  I have included a couple of files with 100 or so games in the downloads.  The default initial file when the program is started is "Kasparov - OK.pgn"  downloaded from   Another site with thousands of PGN games is  

Non-programmers are welcome to read on, but may want to jump to bottom of this page to download the executable program now.

Programmer's Notes:

As an real life example of "Divide and Conquer" problem solving, I have included all 5 "running versions"  of the program in the source download, each correcting errors in the existing code as they are uncovered and adding at least one major step toward the final version.  Briefly:

bulletNote: Versions 2 though 4 will not run with the Kasparov PGN file games because of slight format differences in that file which were correctly handled in Version 5.   Use file 2000WSIM.pgn for checking Versions 2, 3, or 4.
bulletVersion 1 (223 lines of code):  Implemented the Chess board image with pieces in their initial position.  Piece images are cut from a picture found online which contains 12 piece images each 64x64 bits and arranged in two rows with 6 white pieces above the 6 black pieces. Pieces are copied to the board image created in canvas panel of  Panel1.  
bulletVersion 2  (415 lines): Adds labels to the ranks (rows) and files (columns) of the Chess board.  A new panel,  BoardPanel, contains the Panel1 board image and also the rank and file labels.  This version also supports reading PGN files, allowing game selection  and  extracting moves for replay. The file selected is read into a temporary string list, TempList,  because loading and retrieving line is simpler than the alternative of using file retrieval routines.  Lines are retrieved from Templist with each new game identified by a line that begins with the text "[Entry ".  Each game is saved as an entry in in an array of  TGamerec records.  Each record has an Id string built from  concatenated player names,  match name, date and , round number fields - hopefully enough to make it unique.  The TGame rec also has a string list  (Namelist) of all of the identifying fields (lines enclosed by square brackets), an a string, (Movestr), containing a unparsed string of the moves rcelistst of the moves, defined by a number ending with a dot and two half moves (white's move followed by blac.   Id fields are also placed in TComboBox, GameBox,  where each entry selected by the user will be the game made available for playing.   The moves of the selected are displayed on the here and on the  "Replay PGN" page where the chess board resides.            
bulletVersion 3 (802 lines): Implements PGN replay of most of the extracted moves.  This was  the version with the largest code increase  as the basic moves and captures were implemented for the 6 piece shapes ( Pawn, Knight,, Bishop, Knight, Rook, Queen and King).  In Version 1, arrays WPiece and BPiece were created for the 6 White pieces and the 6 Black pieces  as TPiece objects.  TPiece is a descendent of TImage to hold the piece image with additional color, PColor, and Kind fields.  There is an additional Emptypiece piece used to erase an image on the board when a piece  moves away from it.  The chess board is initialized with 64 TPiece objects which are assigned EmptyPiece or one of the other 12 piece objects when moves are made.   The TPiece.Assign method uses Floodfill to color the background around the image to the appropriate color.   The trickiest part of checking and making moves is the indexing since PGN numbers columns from left to right as "a" to "h" and rows from top to bottom as 8 down to 1  and my board array indices run from 0 to 7 both ways.  I should have made all board  references via function calls but by the time I realized that, it was simpler to carry on by subtracting 1 from the row number, ord('a') from the ordinal value of the column letter and make all board square references as b[col, 7-row].         
bulletVersion 4 (942 lines):  Adds "Undo" feature  and support for non-standard moves:  Kingside and Queenside Castling, piece promotion,  and "en passant" Pawn capture.  "Undo" required adding moves to a string list with enough information that the pre-move status can be restored.  (the original "from"  location and the piece removed in case of a capture move, for example).. The special moves require identification about the type of move both for moving and "unmoving".  That and just  a lot more index checking to get pieces moving from and to the right locations.
bulletVersion 5 (1176 lines): Adding rapid play forward or backward by double clicking on a move in the list was fairly easy - in response to a double click, calculate the difference between the current move location and the clicked location and loop to call the "MoveBtnClick" or "UndoBtnClick handler depending on whether we need to move forward or backward. Stop when the  movelocation and clicked location coincide.  This version also implements the results of more extensive testing which uncovered a few more errors to find and fix.   E.g.:
bulletSelecting the last game in a file caused hang.
bulletThe game selection list box was not cleared before loading a different PGN file after the initial load so the game selection names did not match the games actually available. 
bulletBlack Queenside Castle did not remove piece images after undoing the move.
bulletError handling  moves like "R3b6" meaning "there are two Rooks in column b which could move to b6;  the one in row 3 was moved".  
bulletetc. etc. etc.

A logical extension for Version 6 would be to allow users to create PGN file by entering moves as board clicks.  The current playback version does some minimal error checking usually more to catch programming errors than PGN move errors. Stricter validation would be required for moves entered  by users.  Checking correctness of the target square and  availability of the path and distance for the straight line movers  would be straightforward.  More complex would be recognizing when more than one piece of the same type could have accomplished a capture.  Also recognizing when a castling move is desired, when "en passant" capture is made,  etc.

I have no doubt that there are bugs yet to be found in the current version, so when you find one, please report it using this email feedback link

September 11, 2012:  The first bug fix was posted today.  Version 5.1 (5B in to source code files) fixes two significant errors:

bulletComments in curly brackets were not handled properly  (not at all actually).  The sample PGNs I had tested with did not include any comments.
bulletThe "Save as default" check box was not working.  The file name and game index value are saved in a file named "ChessPGN.ini".  If you had previouslt tried the "Set default" option, please delete the existing ChessPGN.ini" file and try again.

July 8, 2015:  A one line change to the source code fixed a problem that only showed up (with a "Range Check" error) when running after being recompiled with "Range Checking" turned on.  Version 5.2 posted today has the fix.       

 Running/Exploring the Program 

bulletDownload  executable
bulletDownload source    

Suggestions for Further Explorations

 Allow  moves to be made by clicking on the board to create a new PGN file or truncate an existing file and create a new ending. Or finish playing a game after the loser resigns and I cannot see that the situation was hopeless J


Original:  September 03, 2012

Modified:  May 15, 2018

  [Feedback]   [Newsletters (subscribe/view)] [About me]
Copyright 2000-2018, Gary Darby    All rights reserved.