less_retarded_wiki/chess.md
2023-01-01 14:58:49 +01:00

175 lines
23 KiB
Markdown
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# Chess
Chess is an old two-player board [game](game.md), perhaps most famous and popular among all board games in [history](history.md). It is a [complete information](complete_information.md) game that simulates a battle of two armies on a 64x64 board with different battle pieces. Chess has a world-wide competitive community and is considered an intellectual sport but is also a topic of active research (as the estimated number of chess games is bigger than [googol](googol.md), it is unlikely to ever be solved) and [programming](programming.md) (many chess engines, [AI](ai.md)s and frontends are being actively developed).
{ There is a nice black and white indie movie called *Computer Chess* about chess programmers of the 1980s, it's pretty good, very oldschool, starring real programmers and chess players, check it out. ~drummyfish }
[Drummyfish](drummyfish.md) has created a suckless/[LRS](lrs.md) chess library [smallchesslib](smallchesslib.md) which includes a simple engine called *smolchess*.
**At [LRS](lrs.md) we consider chess to be one of the best games** for the following reasons:
- It is just a greatly interesting and deep game in which luck plays minimal role.
- **It is greatly [suckless](suckless.md)**, the rules are very simple, it can be implemented on simple 8bit computers. Of course the game doesn't even require a computer, just a board and a few pieces -- chess masters don't even need a board to play (they can completely visualize the games in memory). In the end one can in theory just play against himself in his head, achieving the ultimate freedom: the only dependency of the game is one's brain, i.e. it becomes a [brain software](brain_software.md). Chess is extremely inexpensive, doesn't discriminate against poor people and will survive even the most extreme technological [collapse](collapse.md).
- **No one owns chess**, the game is hundreds of years old and many books about it are also already in the [public domain](public_domain.md). It is extremely free.
- It is a basis for other derived games, for example many different chess variants or chess puzzles which can be considered a "singleplayer chess game".
- It is a source of many interesting [mathematical](math.md) and programming challenges.
- It seems to strike the right balance of simplicity and complexity, it is very simple but not so trivial as to be ever solved in a foreseeable future.
Chess as a game is not and cannot be copyrighted, but **can chess games (moves played in a match) be copyrighted?** Thankfully there is a pretty strong consensus and precedence that say this is not the case, even though capitalists try to play the intellectual property card from time to time (e.g. 2016 tournament organizers tried to stop chess websites from broadcasting the match moves under "trade secret protection", unsuccessfully).
## Chess In General
Chess evolved from ancient board games in India in about 6th century. Nowadays the game is internationally governed by **FIDE** which has taken the on role of an authority that defines the official rules: FIDE rules are considered to be the standard chess rules. FIDE also organizes tournaments, promotes the game and keeps a list of registered players whose performance it rates with so called Elo system based on the performance it also grants titles such as **Grandmaster** (GM, strongest), **Internation Master** (IM, second strongest) or **Candidate Master** (CM).
**[Elo](elo.md) rating** is a mathematical system of numerically rating the performance of players (it is used in many sports, not just chess). Given two players with Elo rating it is possible to compute the probability of the game's outcome (e.g. white has 70% chance of winning etc.). The FIDE set the parameters so that the rating is roughly this: < 1000: beginner, 1000-2000: intermediate, 2000-3000: master. More advanced systems have also been created, namely the Glicko system.
The rules of chess are quite simple ([easy to learn, hard to master](easy_to_learn_hard_to_master.md)) and can be found anywhere on the Internet. In short, the game is played on a 64x64 board by two players: one with **white** pieces, one with **black**. Each piece has a way of moving and capturing (eliminating) enemy pieces, for example bishops move diagonally while pawns move one square forward and take diagonally. The goal is to **checkmate** the opponent's king, i.e. make the king attacked by a piece while giving him no way to escape this attack. There are also lesser known rules that noobs often miss and ignore, e.g. so called en-passant or the 50 move rule that declares a draw if there has been no significant move for 50 moves.
At the competitive level **clock** (so called *time control*) is used to give each player a limited time for making moves: with unlimited move time games would be painfully long and more a test of patience than skill. Clock can also nicely help balance unequal opponent by giving the stronger player less time to move. Based on the amount of time to move there exist several formats, most notably **correspondence** (slowest, days for a move), **classical** (slow, hours per game), **rapid** (faster, tens of minutes per game), **blitz** (fast, a few seconds per move) and **bullet** (fastest, units of seconds per move).
Currently the best player in the world is pretty clearly Magnus Carlsen from Norway with Elo rating 2800+.
During [covid](covid.md) chess has experienced a small boom among normies and [YouTube](youtube.md) chess channels have gained considerable popularity. This gave rise to [memes](meme.md) such as the bong cloud opening popularized by a top player and streamer Hikaru Nakamura; the bong cloud is an intentionally shitty opening that's supposed to taunt the opponent (it's been even played in serious tournaments lol).
## Chess And Computers
{[This](https://www.youtube.com/watch?v=DpXy041BIlA) is an absolutely amazing video about weird chess algorithms :) ~drummyfish}
Chess are a big topic in computer science and programming, computers not only help people play chess, train their skills, analyze positions and perform research of games, but they also allow mathematical analysis of chess and provide a platform for things such as [artificial intelligence](ai.md).
There is a great online Wiki focused on programming chess engines: https://www.chessprogramming.org.
Chess software is usually separated to **libraries**, **chess engines** and **frontends** (or boards). Chess engine is typically a [CLI](cli.md) program capable of playing chess but also doing other things such as evaluating arbitrary position, hinting best moves, saving and loading games etc. Frontends on the other hand are [GUI](gui.md) programs that help people interact with the underlying engine.
For communication between different engines and frontends there exist standards such as XBoard (engine [protocol](protocol.md)), UCI (another engine protocol), FEN (way of encoding a position as a string), PGN (way of encoding games as strings) etc.
Computers have already surpassed the best humans in their playing strength (we can't exactly compute an engine's Elo as it depends on hardware used, but generally the strongest would rate high above 3000 FIDE). As of 2021 the strongest chess engine is considered to be the [FOSS](foss.md) engine [Stockfish](stockfish.md), with other strong engines being e.g. Leela Chess Zero (also FOSS) or AlphaZero ([proprietary](proprietary.md), by [Google](google.md)). [GNU Chess](gnu_chess.md) is a pretty strong [free software](free_software.md) engine by [GNU](gnu.md). There are world championships for chess engines such as the *Top Chess Engine Championship* or *World Computer Chess Championship*. [CCRL](https://ccrl.chessdom.com/ccrl/4040/) is a list of chess engines along with their Elo ratings. Despite the immense strength of modern engines, there are still very specific situation in which humans beat the computer (shown e.g. in [this](https://www.youtube.com/watch?v=R9IZWgArWUE) video).
The first chess computer that beat the world champion (at the time Gary Kasparov) was famously [Deep Blue](deep_blue.md) in 1997. [Alan Turing](turing.md) himself has written a chess playing algorithm but at his time there were no computers to run it, so he executed it by hand -- nowadays the algorithm has been implemented on computers (there are bots playing this algorithm e.g. on lichess).
For online chess there exist many servers such as https://chess.com or https://chess24.com, but for us the most important is https://lichess.org which is gratis and uses [FOSS](foss.md) (it also allows users to run bots under special accounts which is an amazing way of testing engines against people and other engines). These servers rate players with Elo/Glicko, allow them to play with each other or against computer, solve puzzles, analyze games, play chess variants, explore opening databases etc.
Playing strength is not the only possible measure of chess engine quality, of course -- for example there are people who try to make the **smallest chess programs** (see [countercomplex](countercomplex.md) and [golfing](golf.md)). As of 2022 the leading programmer of smallest chess programs seems to be Óscar Toledo G. (https://nanochess.org/chess.html). Unfortunately his programs are [proprietary](proprietary.md), even though their source code is public. The programs include Toledo Atomchess (392 [x86](x86.md) instructions), Toledo Nanochess (world's smallest [C](c.md) chess program, 1257 non-blank C characters) and Toledo Javascript chess (world's smallest [Javascript](javascript.md) chess program). He won the [IOCCC](ioccc.md). Another small chess program is micro-Max by H. G. Muller (https://home.hccnet.nl/h.g.muller/max-src2.html, 1433 C characters, Toledo claims it is weaker than his program).
{ Nanochess is actually pretty strong, in my testing it easily beat [smallchesslib](smallchesslib.md) Q_Q ~drummyfish }
## Stats
Chess stats are pretty [interesting](interesting.md).
**Number of possible games** is not known exactly, Shannon estimated it at 10^120 (lower bound, known as *Shannon number*). Number of possible games by plies played is 20 after 1, 400 after 2, 8902 after 3, 197281 after 4, 4865609 after 5, and 2015099950053364471960 after 15.
Similarly the number of possibly reachable positions (position for which so called *proof game* exists) is not known exactly, it is estimated to at least 10^40 and 10^50 at most. Numbers of possible positions by plies is 20 after 1, 400 after 2, 5362 after 3, 72078 after 4, 822518 after 5, and 726155461002 after 11.
Shortest possible checkmate is by black on ply number 4 (so called *fool's mate*). As of 2022 the longest known forced checkmate is in 549 moves -- it has been discovered when computing the Lomonosov Tablebases.
Average game of chess lasts 40 moves. Average [branching factor](branching_factor.md) (number of possible moves at a time) is around 33.
White wins about 38% of games, black wins about 34%, the remaining 28% are draws.
What is the **longest possible game**? It depends on the exact rules and details we set, for example if a 50 move rule applies, a player MAY claim a draw but also doesn't have to -- but if neither player ever claims a draw, a game can be played infinitely -- so we have to address details such as this. Nevertheless the longest possible chess game upon certain rules has been computed by [Tom7](tom7.md) at 17697 half moves in a paper for [SIGBOVIK](sigbovik.md) 2020.
What's the most typical game? We can try to construct such a game from a game database by always picking the most common move in given position. Using the lichess database at the time of writing, we get the following incomplete game (the remainder of the game is split between four games, 2 won by white, 1 by black, 1 drawn):
```
1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. c3 Nf6 5. d4 exd4 6. cxd4 Bb4+ 7. Nc3 Nxe4 8. O-O Bxc3 9. d5 Bf6 10. Re1 Ne7 11. Rxe4 d6 12. Bg5 Bxg5 13. Nxg5 h6 14. Qe2 hxg5 15. Re1 Be6 16. dxe6 f6 17. Re3 c6 18. Rh3 Rxh3 19. gxh3 g6 20. Qf3 Qa5 21. Rd1 Qf5 22. Qb3 O-O-O 23. Qa3 Qc5 24. Qb3 d5 25. Bf1
```
You can try to derive your own stats, there are huge free game databases such as the Lichess [CC0](cc0.md) database of billions of games from their server.
## Variants
Besides similar games such as [shogi](shogi.md) there are many variants of chess, i.e. slight modifications of rules, foremost worth mentioning is for example chess 960. The following is a list of some variants:
- **antichess** ([suicide](suicide.md), ...): The goal is to lose all pieces or get stalemated, rules are a bit changed, e.g. castling and checks are removed and taking is forced.
- **chess 960** aka **Fisher's random**: Starting position is randomly modified by shuffling the non-pawn rows (with these rules: king must be between rooks, bishops on opposite colors and black/white's positions are mirrored). The rules are the same with a slight modification to castling. This was invented by Bobby Fisher to emphasize pure chess skill as opposed to memorizing the best opening moves, he saw the opening theory as harmful to chess. Chess 960 is nowadays even advocated by some to become the "main" version of chess.
- **[chess boxing](chess_boxing.md)**: Chess combined with box, players switch between the two games, one wins either by checkmate or knockout.
- **different pieces**: Some variants use different pieces, e.g. empress (moves like rook and knight) or amazon (queen/knight).
- **duck chess**: After each move players place a duck on an empty square, the duck blocks the square. The duck cannot be left on the same square, it has to be moved. There are no checks, players win by capturing the king.
- **fog of war**: Makes chess an incomplete-information game by allowing players to only see squares they can immediately move to (this is similarly to some strategy video games).
- **horde chess**: Asymmetric starting position: large number of black pawns vs a white army of traditional pieces. Rules are slightly modified, e.g. black can only be defeated by having all pawns captured (there is no black king).
- **infinite chess**: Infinite chessboard.
- **minichess**: Smaller chessboard, e.g. 4x4, 4x8 etc. Some are already solved (e.g. 3x3).
- **more players**: E.g. 3 man chess or 4 player chess allow more than two players to play, some use different boards.
- **old chess**: The rules of chess itself have been changing over time (e.g. adding the 50 move rule etc.). The older rule sets can be seen as variants as well.
- **puzzle**: For single player, chess positions are presented and the player has to find the best move or sequence of moves.
- **racing kings**: The starting position has both players on the same side, the goal is to get one's king to the other side first.
- **3D chess**: [3D](3d.md) generalization of chess.
## Programming Chess
Programming chess is a [fun](fun.md) and enriching experience and is therefore recommended as a good exercise. There is nothing more satisfying than writing a custom chess engine and then watching it play on its own.
The core of chess programming is writing the [AI](ai.md), everything else, i.e. implementing the rules, communication protocols etc., is pretty straightforward (but still a good programming exercise). Nevertheless one has to pay a great attention to eliminating as many bugs as possible; really, the importance of writing automatic tests can't be stressed enough as debugging the AI will be hard enough and can become unmanageable with small bugs creeping in.
The AI itself works in almost all cases on the same principle: firstly we implement so called static **evaluation function** -- a function that takes a chess position and outputs its evaluation number which say how good the position is for white vs black (positive number favoring white, negative black). This function considers a number of factors such as total material of both players, pawn structure, king safety, piece mobility and so on (in new engines this function is often a learned [neural network](neural_network.md), but it may very well be written by hand). Secondly we implement a **search** algorithm -- typically some modification of [minimax](minimax.md) algorithm -- that recursively searches the game tree and looks for a move that will lead to the best result, i.e. to position for which the evaluation function gives the best value. This basic principle, especially the search part, gets very complex as there are many possible weaknesses and optimizations.
Exhaustively searching the tree to great depths is not possible due to astronomical numbers of possible move combinations, so the engine has to limit the depth quite greatly. Normally it will search all moves to a small depth (e.g. 2 or 3 half moves or *plys*) and then extend the search for interesting moves such as exchanges or checks. Maybe the greatest danger of searching algorithms is so called **horizon effect** which has to be addressed somehow (e.g. by detecting quiet positions, so called *quiescence*). If not addressed, the horizon effect will make an engine misevaluate certain moves by stopping the evaluation at certain depth even if the played out situation would continue and lead to a vastly different result (imagine e.g. a queen taking a pawn which is guarded by another pawn; if the engine stops evaluating after the pawn take, it will think it's a won pawn, when in fact it's a lost queen). There are also many techniques for reducing the number of searched tree nodes and speeding up the search, for example pruning methods such as **alpha-beta** (which subsequently works best with correctly ordering moves to search), or **transposition tables** (remembering already evaluated position so that they don't have to be evaluated again when encountered by a different path in the tree).
Many other aspects come into the AI design such as opening books (databases of best opening moves), endgame tablebases (databases of winning moves in simple endgames), heuristics in search, clock management, pondering (thinking on opponent's move), learning from played games etc. For details see the above linked chess programming wiki.
## Rules
The exact rules of chess and their scope may depend on situation, this is just a sum up of rules generally used nowadays.
The start setup of a chessboard is following (lowercase letters are for black pieces, uppercase for white pieces, on a board with colored squares A1 is black):
```
_______________
/8 |r n b q k b n r|
r | 7 |p p p p p p p p|
a | 6 |. . . . . . . .|
n | 5 |. . . . . . . .|
k | 4 |. . . . . . . .|
s | 3 |. . . . . . . .|
| 2 |P P P P P P P P|
\1 |R N B Q K B N R|
"""""""""""""""
A B C D E F G H
\_____________/
files
```
Players take turns in making moves, white always starts. A move consists of moving one (or in special cases two) of own pieces from one square to another, possibly capturing (removing from the board) one opponent's piece -- except for a special en passant move capturing always happens by moving one piece to the square occupied by the opposite color piece (which gets removed). Of course no piece can move to a square occupied by another piece of the same color. A move can NOT be skipped. A player wins by giving a **checkmate** to the opponent (making his king unable to escape attack) or if the opponent resigns. If a player is to move but has no valid moves, the game is a draw, so called **stalemate**. If neither player has enough pieces to give a checkmate, the game is a draw, so called **dead position**. There are additional situation in which game can be drawn (threefold repetition of position, 50 move rule). Players can also agree to a draw. A player may also be declared a loser if he cheated, if he lost on time in a game with clock etc.
The individual pieces and their movement rules are:
- **pawn** (`P`): Moves 1 square forward (white towards 8th rank, black towards 1st rank), unless that square is occupied by any piece (even enemy piece, pawns cannot capture going forward). From its start position a pawn can optionally move 2 squares if neither of the 2 forward squares are occupied. Pawn can capture enemy pieces 1 square diagonally forward (i.e. 1 square forward right or 1 square forward left).
- **rook** (`R`): Moves any number of squares either horizontally or vertically, but cannot jump over any pieces, however can capture (i.e. land) on a square occupied by enemy piece and capture it.
- **knight** (`N`): Can jump over pieces (both friendly and enemy), moves in "L" shapes, i.e. from its square a knight can jump to (with a possible capture) a square 2 squares in one direction and 1 square in the perpendicular direction (e.g. 2 squares down and 1 square right, or 2 squares right and 1 square up etc.).
- **bishop** (`B`): Moves like rook but diagonally, i.e. a bishop will only ever be able to move on squares of one color (the one it starts on).
- **queen** (`Q`): Can move both like bishop and rook.
- **king** (`K`): Can move (and capture) to any of the 8 immediately neighboring squares.
**Check**: If the player's king is attacked, i.e. it is immediately possible for an enemy piece to capture the king, the player is said to be in check. A player in check has to make such a move as to not be in check after that move.
A player cannot make a move that would leave him in check!
**Castling**: If a player hasn't castled yet and his king hasn't been moved yet and his kingside (queenside) rook hasn't been moved yet and there are no pieced between the king and the kingside (queenside) and the king isn't and wouldn't be in check on his square or any square he will pass through or land on during castling, short (long) castling can be performed. In short (long) castling the king moves two squares towards the kingside (queenside) rook and the rook jumps over the king to the square immediately on the other side of the king.
**Promotion**: If a pawn reaches the 1st or 8th rank, it is promoted, i.e. it has to be switched for either queen, rook, bishop or knight of the same color.
**Checkmate**: If a player is in check but cannot make any move to get out of it, he is checkmated and lost.
**En passant**: If a pawn moves 2 squares forward (from the start position), in the immediate next move the opponent can take it with a pawn in the same way as if it only moved 1 square forward (the only case in which a piece captures a piece by landing on an empty square).
Threefold repetition is a rule allowing a player to claim a draw if the same position (piece positions, player's turn, castling rights, en passant state) occurs three times (not necessarily consecutively). The 50 move rule allows a player to claim a draw if no pawn has moved and no piece has been captured in last 50 moves (both players making their move counts as a single move here).
## LRS Chess
Chess is only mildly [bloated](bloat.md) but what if we try to unbloat it completely? Here we propose the LRS version of chess. The rule changes against normal chess are:
- No castling.
- No en passant.
- Promotion is always to queen.
- No checks or checkmates, king is just another piece.
- Whoever takes the opponent's king first wins.
- If a player has no available moves, he loses.
- Only a single draw rule: if game doesn't end in 1024 half moves or fewer, it is a draw. I.e. there are no weird draw rules (50 move, repetition, ...). Of course players may still agree on draw anytime.
- Random: optionally random variant of LRS chess can be played. Here we randomly shuffle the white player's back row pieces in the starting position and mirror it for black (no weird conditions on piece positions like in chess 960).
## See Also
- [hexapawn](hexapawn.md)
- [checkers](checkers.md)
- [backgammon](backgammon.md)