Khianat

My self-made chess engine. It runs entirely in your browser: no engine server, no cloud. This page explains how it works, in the order the engine itself thinks, and matches the code actually running here.

The name. I was learning Indonesian when I started, and wanted something no other chess site would have. Khianat means betrayal — an Arabic loanword (خِيَانَة, khiyāna) that reached Indonesian through Malay. It fits an engine meant to win with tactics, traps and moves you did not see coming. The logo says the same: a pawn casting the shadow of a queen. It looks harmless. It is not.

Architecture

Four parts, each with one job:

chess.js (Jeff Hlywa) knows the rules and generates the legal moves. Khianat only ever picks from that list, so illegal moves are impossible by construction.
chessboard.js (Chris Oakman) draws the board and handles dragging. Pure presentation.
evaluation.js answers one question about a position: who is better, and by how much?
engine.js is the brain — opening book and search.

Player plays a move (White)
↓
Is the position in the opening book?
yes ↓     no ↓↓
Play the book reply (weighted random choice, checked against the legal moves)
↓↓
Iterative deepening: search to depth 1, then 2, then 3 … until the time budget of the chosen difficulty is spent. Each search is a negamax tree walk with alpha-beta pruning, move ordering and quiescence search at the leaves.
↓
Play the best move of the last fully finished depth, update board, sound and status
The decision path of a single Khianat move.

The evaluation function

Is this position good or bad? Khianat answers in centipawns (100 = one pawn), from White's point of view, using two ingredients.

Material. A knight is worth roughly three pawns, a queen roughly nine. The exact numbers are adapted from the Sunfish engine.

Piece square tables. The same piece is worth more on a good square. Every piece type has an 8×8 table of bonuses and penalties — a knight in the centre gets a bonus, one in the corner a hefty penalty. Black uses the same tables, mirrored.

-66
-53
-75
-75
-10
-55
-58
-70
-3
-6
100
-36
4
62
-4
-14
10
67
1
74
73
27
62
-2
24
24
45
37
33
41
25
17
-1
5
31
21
22
35
2
0
-18
10
13
22
18
15
11
-14
-23
-15
2
0
2
0
-23
-20
-74
-23
-26
-24
-19
-35
-22
-69
The knight table from White's point of view (rank 8 at the top). Light squares are good, dark squares are bad: knights belong in the center, not on the rim.

All 64 squares are added up, White positive, Black negative. Deliberately missing so far: pawn structure, king safety and mobility.

The search: Minimax

Judging the current position is not enough, because chess is about what happens next. So Khianat builds a tree: its moves, your answers, its answers to those. The evaluation runs at the leaves.

The values flow back up by the Minimax rule: on its own turns it takes the maximum, on yours it assumes you take the minimum. The move whose subtree survives that pessimism best gets played. (In the code it is the negamax form: the same thing with the sign flipped each level, so one function serves both colours.)

max min min +3 +5 +2 +9 move a move b min(3,5) = 3 min(2,9) = 2 max(3,2) = 3 → play move a
A tiny two-ply tree. Move b looks tempting (+9), but the opponent would answer with the +2 line, so move a with a safe +3 is better.

Iterative deepening. Rather than one fixed depth, Khianat searches depth 1, then 2, then 3, until its time is up, and plays the best move of the last completed depth. The thinking time stays predictable, and in simple positions the search reaches much deeper by itself. With only one legal move, it plays instantly.

Difficulty levels. The difficulty levels on the Play page simply control this search: lower levels cap the search depth and thinking time, the highest level is the unrestricted engine. Same brain, shorter or longer leash.

Alpha-beta pruning

The tree grows brutally fast: at roughly 35 legal moves per position, four half-moves already mean over a million leaves. Alpha-beta pruning cuts that down without changing the result. While searching, it remembers the best each side can already force. Once a branch is proven worse than something already in hand, the rest of it cannot change the decision and is skipped.

max min min +3 +5 +2 ? first branch: 3 2 ≤ 3: cutoff! never evaluated move a already guarantees +3
Same tree as above. After move a guarantees +3, the +2 reply to move b already proves move b is worse. The last leaf is never looked at.

Move ordering. Pruning works best when the strongest moves are searched first. Khianat therefore sorts moves before searching them: promotions and captures come first (preferring "small piece takes big piece"), and at the root the best move of the previous, shallower iteration is always tried first. The effect is dramatic:

plain Minimax: ~1,500,000 positions
with alpha-beta pruning: ~100,000 positions
alpha-beta + move ordering: ~10,000 positions
Typical order of magnitude for a depth 4 search with ~35 moves per position. Note: the bars use a logarithmic scale, the real difference is a factor of about 150.

Quiescence search

A fixed depth has a famous blind spot, the horizon effect: stop right after "queen takes pawn" and the position looks wonderful, even though the queen falls on the very next move.

So the search does not simply stop at the leaves. It keeps playing captures and promotions until the position is quiet, then evaluates. The side to move may also decline everything, which keeps quiet positions cheap. That is why Khianat does not fall for "grab a pawn, lose the queen".

Opening, middlegame, endgame

Opening. A personal, hand-written book of weighted replies, one repertoire for each colour. As White it keeps things sound but varied; as Black it deliberately avoids the well-trodden main lines in favour of the Alekhine, the Scandinavian, the Modern, the Dutch and the occasional Englund gambit. Every book move is checked for legality first. It is deliberately small: the engine's personality, not a database.

When the book runs out, Khianat keeps varying for a few moves by picking at random among the moves it rates as equally good, preferring the better ones. Anything that loses material is far outside that range. Weaker levels improvise more, which stops every game from following the same script.

Middlegame. Search and piece square tables do the work: pieces towards active squares, king behind its pawns, captures calculated to the end.

Endgame. With little material left, the king switches to a separate table and walks to the centre instead of hiding — exactly what you should do yourself. Mate is scored by distance, so Khianat goes for the quickest one and, when lost, drags things out. Stalemate and draws count as zero, so it will not stalemate you by accident, and it will happily steer into a draw when losing.

Performance and stability

The search runs in a Web Worker, so the page stays responsive while Khianat thinks. Everything inside that search has to be cheap.

Draws. Asking the chess library whether a position has occurred before means taking the whole game apart and rebuilding it — fine once per move, ruinous thousands of times per second. The engine keeps its own short list of positions instead.

The clock is only read every so often, because that is surprisingly expensive. When time runs out the search sets a flag and unwinds level by level rather than throwing, so every trial move is guaranteed to be taken back (a lesson learned the hard way, see blog entry #8). As a safety net the game history is restored afterwards, so the search can never corrupt the real game.

Playing strength

My estimate for the highest difficulty: around 1600 to 1800 Elo against casual players. It comes from what the engine can do, not from games it has played — the benchmark page shows what can actually be measured.

Good at: short tactics, not hanging pieces, converting won positions. Lower levels scale that down to something a beginner can beat.

Weak at: pawn structure, king safety and mobility are missing from the evaluation, there is no transposition table, and quiet positional play beyond its search depth escapes it. Patient, solid play is the best recipe against it.

0 500 1000 1500 2000 random moves greedy, depth 1 alpha-beta search faster search 1.3.0 (benchmarked) ~250 ~450 ~1500–1700 ~1600–1800 ≈1760
Strength of the engine generations so far. The first four are guesses from what the engine can do. Tactics puzzles and games against Stockfish, on the benchmark page.

Next up: a transposition table, pawn structure and king safety in the evaluation, check evasions in the quiescence search. Each a realistic future blog entry.

Credits

Board rendering by chessboard.js (Chris Oakman), chess rules by chess.js (Jeff Hlywa), piece values and square tables adapted from Sunfish (Thomas Ahle). Search, evaluation, opening book and the rest: my own work, source on GitHub. Hopefully not the last version — the blog has the rest of the story.