Show HN: Porting a Classic 1970s Chess Program to Modern Hardware


The book “Sargon, a computer chess program”, by Dan and Kathe Spracklen
printed by Hayden in 1978 presents the provision code to the conventional
early chess program Sargon in Z80 assembly language. That is a mission
to affirm the code offered in the book abet to existence in the smartly-liked generation.

Why no longer? It turn into a stress-free distress for a originate. I truly delight in chess, I truly delight in chess
utility in standard and retro chess utility in dispute. No longer many
folk at the present time absorb familiarity and facility with Z80 assembly
language, and it be nice to practise these skills and endure in suggestions the honest
weak days. The ‘s stress-free to play with, it celebrates the
pioneers and adds some twists and curiosity I did now not search knowledge from when I
started (more on that later). Plus it be a pleasure to work on some
utility from a time when utility will be crucial and most important
without sprawling and metastasizing previous the draw of a single particular person
to grasp it huge in an cheap amount of time.

It’s miles straight forward on House windows, even whenever you occur to might maybe also very successfully be no longer a developer. First gain
Sargon as a House windows executable
then flee it below your authorized Chess GUI. If you occur to would no longer absorb a chess
GUI (or know what one is), I might respectfully recommend my like
Tarrasch Chess GUI. When you’ve got attach in
Tarrasch, employ the Alternatives > Engine menu to point Tarrasch at the Sargon
engine executable and you can also very successfully be off to the races.

On Linux or Mac it be presumably doubtless to get the code running, but
you can also very successfully be going to need some developer skills. One danger is that the
mission works by transforming the Z80 fashioned assembly language to
Intel x86 32 bit assembly language, and 32 bit (in preference to 64 bit) is
turning into problematic on Linux and Mac. Sorry. Sooner or later I might maybe assemble a 64
bit version.

I estimate this very early version of Sargon to absorb chess energy
of about 1200 Elo. Aggressive gamers might maybe luxuriate in beating up a computer
engine, for stress-free and a dose of nostalgia (whenever you occur to don’t know mighty about
chess – computer systems overtook folk in the 1990s and are now vastly stronger).
If you occur to might maybe also very successfully be correct starting out in your chess travel, Sargon will presumably
beat you but beating it is a reasonable distress. You will doubtless must
attach no lower than a little severe effort into bettering your game though.

The Zilog Z80 is a legendary microprocessor and there is a predicament net
neighborhood that celebrates it. One amongst the obedient issues about this mission
is that a byproduct of my pattern pipeline is a version of the fashioned
assembly language transformed into standard Z80 mnemonics. The orginal
Sargon Z80 code turn into considerably depraved (I assume) by a reasonably puzzling
resolution to make employ of a kind of hybrid 8080 assembly language as a replacement of precise
Z80 assembly language. (Extra about that later). It isn’t not doubtless
that there might maybe also very successfully be any individual on the market that must hack on the
Z80 code and flee it on a Z80 or a Z80 emulator, and if that’s the case
sargon-z80.asm will be of curiosity to you.

It’s a little more doubtless that there might maybe also very successfully be any individual who is
in working on the contemporary Intel x86 version of the Sargon code. The file
sargon-x86.asm (and linked sargon-asm-interface.h) is for you. I
absorb added a C language callable interface to Sargon. The interface
ideas a kind of API (for calling into Sargon), facilities for
atmosphere and inspecting registers and reminiscence old to and after Sargon
runs, and a flexible mechanism for Sargon to callback into your code
because it runs (all another time with stout get entry to to registers and reminiscence). To appear at
these issues out, there might be no other near rather than digging in to the
code. I assume it be successfully commented and I am hoping you to make your mind up.

I’ve also implemented a kind of “window into Sargon” that animates
(the utilization of the be conscious loosely) Sargon’s chess calculations. People which might maybe be
in chess programming might maybe also very successfully be in watching
Sargon make the customary minimax and alpha-beta algorithms, in the
context of a easy model that eliminates the same old distress of being
being overwhelmed by the scale and complexity of the tree of prognosis.
That is one of many unexpected twists and benefits I spoke of earlier.
(The opposite one turn into without warning discovering that I might maybe tease the PV [principle
variation] out of Sargon – enabling it to latest its prognosis delight in
a latest chess engine).

Doable customers/tinkerers must absorb reasonable expectations, the
program dates from an generation when the humblest club participant might maybe beat chess
functions running on particular person grade hardware. This turn into the very first
version of Sargon, a mission that went by many more versions,
turning into mighty stronger in the midst of the product’s lifecycle. Sargon turn into an
crucial product in computer chess historical previous, and I easy assume the
elegant resolution the Spracklen’s made to form the provision code of
their nascent commercial product on the market is well-known and sign
celebrating (by bringing that code abet to existence).

This version of Sargon veteran fastened depth, stout width search. In other
phrases it did no longer prune its search tree, obsessed with every single pass
out to a fastened depth. The depth turn into a user selectable option, with 6
(ply) being essentially the most atmosphere. On my (low-cost, aging) commodity pc,
sargon-engine.exe might maybe purchase one thing delight in 30 seconds to compose the 6
ply search in a common middlegame feature. I search knowledge from this to be between
two and three orders of magnitude sooner than the fashioned Z80 machine,
so I make no longer imagine many customers whisper the quest depth to most!

One improvement I even absorb been ready to form without changing any of
Sargon’s core code is to lengthen essentially the most search depth from 6 to 20
(because I’m no longer little to a pair K of reminiscence) and to form the quest
depth dynamic in location of fastened. I employ an iterative near. When the
GUI asks the engine to analyse a feature I originate with depth=3 (which is
truly instantaneous), latest the consequences, then pass to depth=4,
and so forth. If the GUI wants the engine to analyse indefinitely
(kibitzing) I correct continue iterating all the near up to depth=20. It’s
crucial to attain though that the time required will increase
exponentially. Seconds for depth 4, minutes by depth 7, hours by depth
9, days (10), weeks (11), years presumably (13 or so). Generally it would
never get to 20. Theoretically the minimax algorithm (which Sargon
implements successfully – no longer pretty completely since it would now not purchase into story
below-promotion) can ‘clear up chess completely’. But truly chess will
never be completely solved until we are able to in some draw flip every atom in the
universe accurate into a computer co-running on fixing the distress (and no longer
even then). Due to this we are able to no longer absorb nice issues.

Sooner or later of human v engine or engine v engine operation the GUI tells
sargon-engine the time left for the sport and I employ a easy adaptive algorithm
to imagine when to discontinue iterating and latest the handiest pass learned to

I even absorb implemented a FixedDepth engine parameter which enables
emulation of the fashioned Sargon program’s behaviour. If FixedDepth is
whisper to a non-zero number then sargon-engine would now not iterate in any respect when
playing a game, it correct goes straight to the assigned depth. This
truly has some effectivity advantages, since iterating from depth 5
(whisper) to depth 6 turn into no longer contemplated in the fashioned Sargon code at
all, so when I assemble that I’m in produce discarding all the depth 5
knowledge and starting all another time. That sounds horrifying, but endure in suggestions the
exponential growth manner that the depth 6 required time will some distance exceed
the sum of depth 3,4 and 5 required time, so barely speaking it be
no longer losing that mighty time. Iteration works successfully and is terribly pragmatic
and efficient on this Sargon implementation.

It might maybe truly sound that extending Sargon’s search depth successfully previous 6 hasn’t
been very favorable for the rationale that exponential growth makes phases previous 8 or
so inaccessible in apply. This might maybe be staunch if chess stopped in the
middlegame, but as an increasing form of pieces near off the board, there are
less strikes to search at in every feature, and Sargon can witness deeper in a
reasonable time. That is the precise fantastic thing about adaptive in location of fastened
depth. As a easy instance purchase into story the feature with White (to play)
king on e4, pawn on d4, Murky king on d7. A severe human participant will
instantaneously play Kd5 here, knowing that this is the handiest in relation to
at closing drive pawn promotion. Sargon, with completely no chess
knowledge, correct the skill to calculate diversifications searching for extra
cloth or board withhold an eye on, plays Kd5 at depth 13 (or more). The PV
linked with this pass parts the pawn queening triumphantly staunch
at the live of the line. It takes 3 minutes and 30 seconds to form the
calculation on my computer. It’s rarely world shattering but it be vastly
previous the skill of the fashioned Z80 implementation, and exhibits what a
sooner CPU and more reminiscence can assemble to an in every other case fastened chess
calculation algorithm.

Alternatively there might be no question that in standard the horizon produce, because it’s
known as, is a huge limitation on the energy of an engine that does a
stout width, fastened depth search without a pruning. Sargon runs successfully ample.
It plays gruesome anti-positional chess, but it does strive and mobilise it be
pieces and it be barely decent at ways and will on occasion slouch you
aside in a posh middlegame whenever you occur to don’t pay attention. But then it
will no longer be ready to total you off. Despite being ready to search deeper
it easy would now not realize endgames because promoting pawns takes so
many ply. And even winning with whisper K+Q v K is previous its horizon until
the opponent’s king is already corralled with Sargon’s king close by. I’m
tempted to add a easy “king in a lowering sized box” form heuristic
to the scoring feature to repair that – but that’s no longer truly utility
archaeology is it? A same distress, presumably fixable in the same near
is that Sargon will on occasion drift and concede a design by repeating
strikes even in an overwhelming feature. That is a reflection of Sargon’s
scoring feature, which would now not absorb any positional knowledge. Sargon
correct tries to bewitch cloth, and if that’s no longer doubtless withhold an eye on more
squares than the opponent. This turn into standard of the generation, in the early
days of chess programming the pioneers had been overjoyed to net that
minimax plus alpha beta and a easy cloth plus board withhold an eye on scoring
feature turn into ample to play no lower than reasonable chess. But it truly turn into
handiest a place to starting up for precise progress.

This mission contains four subprojects, two of which assemble supply code
transformation to in the terminate originate the x86 assembly language version of
Sargon, and two of which flee the following Sargon code. Let’s originate
with running the Sargon code.

Mission sargon-engine is an customary UCI chess engine. UCI is a
standardised chess engine interface. Mission sargon-engine enables any
smartly-liked chess GUI to flee Sargon to analyse positions, or play in opposition to
other engines or human gamers. A engrossing characteristic of sargon-engine
is that the fashioned Sargon code turn into handiest supposed to originate a honest
pass, however the smartly-liked translation peers into the Sargon implementation
and extracts the PV (Precept Variation – the apply up Sargon expects
to its calculated handiest pass), and Sargon’s numerical overview of the
feature. These latter procedure weren’t required by Sargon’s fashioned
user interface, but form for a mighty more fascinating user experience
when the utilization of a latest chess GUI.

Mission sargon-exams ideas a series of regression exams which
at the origin helped me get the Sargon port working, and then stored the
pattern firmly heading in the accurate direction. Extra fascinating in all likelihood is some
‘executable documentation’ constructed into the sargon-exams.exe program. This
is an strive and starting up a window into Sargon’s implementation of minimax
and alpha-beta, the elementary chess algorithms. At first this turn into
all about validating that the Sargon code turn into truly running precisely
on the smartly-liked platform, but I sophisticated it with the foundation that a developer
starting out in chess programming might maybe net it very fascinating to witness
a easy working model of these algorithms in action. The executable
documentation might maybe also also be completed by running sargon-exams.exe with a -doc
affirm line flag. The ensuing output is supplied in the repository
as sargon-exams-doc-output.txt

Mission convert-8080-to-z80-or-x86 is the elementary supply code
translation instrument that converts Sargon into one thing we are able to flee at the present time.
The reference to the older Intel 8080 processor might maybe also very successfully be confusing. The
Zilog Z80 microprocessor that Sargon 1978 ran on turn into upwardly successfully excellent
with the older Intel 8080 microprocessor. The Z80 implemented all the
8080’s directions, plus tons of of latest ones. In a utility
engineering masterstroke, Zilog made existence easy for programmers by
designing a mighty greater, more consistent and orthogonal assembly
language than the Intel fashioned for the contemporary, more nice machine. The
Zilog version accommodated all the Intel directions (obviously), and
all the Z80 extensions too in a soft and consistent near. As an
instance, the fashioned 8080 assembly language has different directions
for all of more than just a few styles of ADD operations it’ll assemble, reckoning on
the attach the operands near from. In difference the Z80 assembly language
replaces them all with correct a single ADD mnemonic. The assembler program
itself infers which precise machine code ADD instruction (including contemporary ADD
directions launched with the Z80) is required from the parameters to
the mnemonic, which might maybe be organised in a scientific and consistent near.

That’s pretty a diversion. The point is though, that Sargon 1978 turn into no longer
programmed in Zilog’s assembly language. For no matter motive, Sargon’s
programmers decided to make employ of the third celebration TDL assembler which uses
Intel’s assembler mnemonics and helps the Z80 extensions with
invented arcane Intel style mnemonics. Within the rear vision assume from
2020 this turn into a disappointing resolution, to whisper the least. By no manner suggestions, it
turned out no longer to be too mighty of a facet road block. In spite of all the pieces the Intel style
assembler is more interesting for the programmer but more straightforward on the provision code
translator because there might be a decided mnemonic for every instruction. So
it wasn’t exhausting to rework the fashioned code accurate into a more forward searching

In actuality because the name implies, convert-8080-to-z80-or-x86 can assemble two forms
of conversion, It’s miles going to convert to conventional Z80 mnemonics, or translate to
Intel x86 assembly language to flee on smartly-liked machines. The Z80
conversion is no longer strictly well-known, but I assume it be worthwhile to
successfully purchase away the unfamiliar TDL assembler conventions from the equation
for anyone else who need explore the fashioned Z80 code.

In a similar vogue, mission convert-z80-to-x86 turn into created to streamline the
workflow of anyone who needs to tinker with the Sargon code in the
future. The principle that is that a honest near in due course would be to make employ of
convert-8080-to-z80-or-x86 once to rework the fashioned Sargon code to
Z80 mnemonics. Then successfully the fashioned code might maybe also also be thrown away and
tinkering in Z80 world can continue with the customary Z80 mnemonics
version of the code. Mission convert-z80-to-x86 then exists to rework
the modified Z80 code to X86.

For the moment I even absorb no longer abandoned the fashioned 8080 code on this near.
The House windows script rebuild-and-compare.bat converts the fashioned Sargon
code straight to X86 code (8080 -> X86) and by project of the 2 step project
(8080 -> Z80 -> X86) and exams that the staunch same sargon-x86.asm
file is created by both routes.

Intel selected no longer to provide an 8080 machine code stage compatibility mode
for his or her fashioned 16 bit 8086. (Spirited diversion: One amongst the
suppliers of 8086 successfully excellent 16 bit microprocessors at the time did
provide a machine stage 8080 compatibility mode – the NEC V20). Intel
elated themselves with a extremely weak stage of compatibility, they
merely made one to 1 translation of assembly language directions
reasonably easy. A honest pragmatic resolution, but it stands out
as one of essentially the most backward compatibility antagonistic decisions in the
firm’s historical previous. Their vastly a success X86 household has supplied
narrate machine stage compatibility all the near abet to unhurried 1970s 8086
processor ever since.

No longer handiest turn into machine code compatibility no longer supplied, even supply code
stage compatibiliy turn into denied and as a replacement Intel urged translating
8080 code to 8086 code. Amusingly translation turn into required no longer handiest
as a result of a pair instruction quirks (eg 8086
directions affecting flags in every other case to the 8080 equivalents), but
because Intel pulled a Zilog and made the assembly language for the contemporary
chip more consistent and orthogonal. In spite of all the pieces even machine code
compatibility wouldn’t serve us, as Intel had been never going to provide
compatibility to the Z80 extensions.

The base line though is that changing both 8080 or Z80 assembly
code to Intel X86 in all fairness easy. I selected to pass with x86
32 bit mode in location of x64 64 bit mode. Translating to x64 ought to easy be
same and is left as an bid for the reader 🙂 Or for me in the

The conversion model veteran for this mission establishes a 64K block of
reminiscence to emulate the Z80’s total reminiscence dwelling for the duration of the 32 bit reminiscence
model. In spite of all the pieces 64K is a ludicrously miniature amount of reminiscence at the present time.
By no manner-the-less it be more than ample for Sargon. Sargon’s largest
reminiscence requirement by some distance is a two stage pass buffer. Two stage because
at any given time Sargon is evaluating correct one sequence of strikes from
the originate feature, but every pass in that sequence is identified in a
separate record of all correct strikes from a feature in the total tree of
strikes. Z80 Sargon has a max ply depth of 6. It navigates round the stout
width pass tree (no pruning) without recursion the utilization of the easy two
stage pass buffer. It stores 6 bytes per pass node. So its two stage
pass buffer requires 6 x 6 x MAX bytes of reminiscence the attach MAX is the
knowing most series of correct strikes ready. Z80 Sargon
allocates 2K for this, which implies MAX equals about 60. X86 Sargon
extends the max ply depth to 20 and splurges successfully your total of
the emulated Z80’s 64K to the duty (linked to MAX=500). That renders
the single point the attach Sargon exams whether it has flee out of reminiscence as
fully redundant (correct to boot to I make no longer assume Sargon would
truly gracefully get successfully from the reminiscence stout situation).

The greatest conversion danger is that the Z80 uses 16 bit pointers,
but x86 32 bit mode uses 32 bit pointers My resolution to this distress turn into
to whisper one x86 register ebp to continuously point at the 64K block of
emulation reminiscence and to compose all reminiscence accesses relative to the ebp
register. That is all very stunning and convenient, because the ebp register is
left over after allocating the choice x86 pointer registers to emulate
z80 pointer registers (ebx = hl, ecx=bc, edx=de, esi=ix, edi=iy). The
top 16 bits of every of the x86 registers is cleared old to entering the
Sargon code and no x86 code is generated that can exchange the head 16
bits. So we are able to confidently emulate a (ix+offset) Z80 reminiscence get entry to whisper
with a (ebp+esi+offset) x86 reminiscence get entry to. This near ought to easy easy be
on the market if an x64 version is made later.

Stack accesses would be more complex to emulate because even supposing x86
fortunately accomodates 8 and 16 bit reminiscence accesses in standard, all stack
operations in x86 mode are 32 bit. Fortuitously Sargon itself would now not assemble
any ‘tricks’ with the stack. It correct uses it for straightforward pushes,
pops, calls and returns, and we are able to emulate that with a customary stack
maintained by our runtime in a different part of reminiscence to
our 64K emulation buffer. This speaks to a mighty broader point; the 2
conversion functions on this suite absorb been expressly constructed to
compose the Sargon conversion. They will presumably require work to
convert every other 8080 or Z80 program accurate into a working x86 program. Apart
from the leisure, directions that Sargon never uses are no longer
essentially transformed.

I even absorb veteran Visible Studio 2017, even supposing any gadget that can develop C++
functions with a single X86 assembly module ought to easy be incandescent. I even absorb
integrated a VS2017 resolution and four mission files in the repository, but
there might be no magic concerned wherever. By some distance the greatest
knowledge in the resolution and mission files is that the person
procedure are constructed as follows;

  • sargon-engine = sargon-engine.cpp + sargon-x86.asm + sargon-interface.cpp + sargon-pv.cpp + thc.cpp + util.cpp
  • sargon-exams = sargon-exams.cpp + sargon-x86.asm + sargon-interface.cpp + sargon-minimax.cpp + sargon-pv.cpp + thc.cpp + util.cpp
  • convert-8080-to-z80-or-x86 = convert-8080-to-z80-or-x86.cpp + convert-8080-to-z80-or-x86-predominant.cpp + util.cpp
  • convert-z80-to-x86 = convert-z80-to-x86.cpp + util.cpp

I ought to easy mention a pair of miniature roadblocks I overcame in creating the
mission files;

To flip on assembly programming in Visible C++ 2017

Menu > Mission > develop customizations, flip on MASM (Handiest add asm files after doing this)

We also need linker option SAFESEH:NO (Properties / Linker / All Alternatives
/ Image has protected exception handlers) or correct employ option search facility
on “SAFESEH”. It’s wished because we assemble long jumps to cleave quick Sargon’s
pass calculation if it takes too long, or if the GUI calls on it to

  • Background knowledge
    There might be an total bunch background knowledge on Sargon here. I am hoping this page
    will soon absorb a hyperlink abet to this mission.

  • Scan of fashioned book
    I truly absorb a paper replica of the book I picked up from, but I’m
    gratified to absorb get entry to to this digital replica as successfully, particularly since
    my paper replica of the book turned out to absorb had the TDL assembler reference cloth
    at the live ripped out!

  • Stack Overflow Discussion with Andre Adrian
    I first contemplated this mission round 2010, and asked for advice on
    Z80 conversion tools on this Stackoverflow post. The page contains pretty
    a wonderful deal of background knowledge about the mission. I mention Andre
    Adrian, a German programmer who gave me the foundation for the mission and who
    the arrives to make a contribution to the discussion. Inevitably and sadly, the discussion turn into
    closed as no longer assembly Stackoverflow guidelines. It makes me gratified to
    watch that I even absorb finally written my like conversion tools and got
    this mission executed after placing it on the abet burner for so many years.

  • Andre Adrian’s Z80 port
    I veteran this, plus the scan of the book above and my like paper replica to
    get to phases/sargon1.asm which is the place to starting up of my conversion
    pipeline, being as shut to the precise text of the Sargon program in the
    book as I’m able to form it.

Andre Adrian’s work first got here to my attention when I realized he had
added a chess engine interface to my port of Microchess by Peter
Jennings, an perfect older 1970s chess program which I ported to House windows
round 2006. It’s fascinating that in that earlier mission I ported the
fashioned user interface of the program and Andre Adrian improved on my
work by adding a chess engine interface. Andre Adrian ported Sargon
including its fashioned user interface to CP/M in whisper that it would be veteran
with a CP/M emulator. Now I even absorb in flip improved his mission (I assume)
in the same near he improved mine by replacing the fashioned user
interface with a latest chess engine interface.

There might be more knowledge on my earlier 6502 Microchess mission on Peter
Jennings Microchess historical previous page. I
ought to easy truly affirm my supply code conversion over to Github.

The directory phases/ contains the conversion project, starting with the
unmodified program text from the book, progressing by e-book and
mechanical modification by to the final sargon-x86.asm file (and
its accomplice sargon-asm-interface.h). The directory contains its like
readme.txt file to characterize them. There might be also rebuild-and-compare.bat
script in the mission root directory to repeat and test the conversion

I acknowledge the possession of legendary programmers Dan and Kathe
Spracklen. When I started on the mission I added that in the occasion that they contact me
in respect of this mission, I might honour their wishes, no matter they
would be. Since then though I even absorb attach a tall amount of effort into
polishing this accurate into a model mission. I’ve opened up a window into the
program, and introduced it abet to existence. I assume I might maybe absorb a gargantuan deal
of danger deleting this mission now, if I turn into asked to assemble that.
Hopefully a purely hypothetical ask. There might be clearly no commercial
motive of incentive for anyone on this mission. As I wrote on Twitter “I
am porting a 70s chess program written in Z80 assembly to flee on smartly-liked
machines with an customary chess engine interface. By no manner has a mission
been more guaranteed no longer to generate a single cent of earnings.”


Please enter your comment!
Please enter your name here