<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/"
    xmlns:atom="http://www.w3.org/2005/Atom" xmlns:media="http://search.yahoo.com/mrss/" version="2.0">
    <channel>
        
        <title>
            <![CDATA[ chess - freeCodeCamp.org ]]>
        </title>
        <description>
            <![CDATA[ Browse thousands of programming tutorials written by experts. Learn Web Development, Data Science, DevOps, Security, and get developer career advice. ]]>
        </description>
        <link>https://www.freecodecamp.org/news/</link>
        <image>
            <url>https://cdn.freecodecamp.org/universal/favicons/favicon.png</url>
            <title>
                <![CDATA[ chess - freeCodeCamp.org ]]>
            </title>
            <link>https://www.freecodecamp.org/news/</link>
        </image>
        <generator>Eleventy</generator>
        <lastBuildDate>Sat, 30 May 2026 11:14:39 +0000</lastBuildDate>
        <atom:link href="https://www.freecodecamp.org/news/tag/chess/rss.xml" rel="self" type="application/rss+xml" />
        <ttl>60</ttl>
        
            <item>
                <title>
                    <![CDATA[ The Chess "Italian Game" Handbook: Traps for White ]]>
                </title>
                <description>
                    <![CDATA[ A chess game is usually divided into three phases: the opening, middlegame, and endgame. In the opening phase, each player develops and sets up their pieces. In the middlegame, they plan attacks, execute different tactics and strategies to gain an ad... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/the-chess-italian-game-handbook-traps-for-white/</link>
                <guid isPermaLink="false">69932b89881a983a8060252f</guid>
                
                    <category>
                        <![CDATA[ chess ]]>
                    </category>
                
                    <category>
                        <![CDATA[ youtube ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Ihechikara Abba ]]>
                </dc:creator>
                <pubDate>Mon, 16 Feb 2026 14:36:57 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1771252596669/88710fa6-d7b3-4914-ae0c-cafa7ea244a6.jpeg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>A chess game is usually divided into three phases: the opening, middlegame, and endgame.</p>
<p>In the opening phase, each player develops and sets up their pieces. In the middlegame, they plan attacks, execute different tactics and strategies to gain an advantage and weaken their opponent. In the endgame, there are usually few pieces left on the board, and each player tries to win using certain techniques and piece coordination.</p>
<p>In this handbook, you'll learn about opening traps for the Italian Game, which is one of the most played openings in chess.</p>
<p>When learning about openings, you're usually taught some basic principles, like:</p>
<ul>
<li><p>Control and fight for the center.</p>
</li>
<li><p>Develop pieces.</p>
</li>
<li><p>Castle the king early.</p>
</li>
<li><p>Connect the rooks.</p>
</li>
<li><p>Don’t bring the queen out early.</p>
</li>
<li><p>Avoid unnecessary pawn moves, and so on.</p>
</li>
</ul>
<p>These principles are easier said than done. Many beginners focus too much on implementing them and fall for obvious traps. That’s what this handbook will help you with.</p>
<p>Learning about an opening is as important as learning the common mistakes associated with each opening. You can learn a chess opening to improve your tactics and strategy, understand how to develop your pieces, and understand how to spot certain mistakes early so you can avoid them or take advantage of them.</p>
<p>This handbook will focus on those opening mistakes and how to take advantage of them when playing as white.</p>
<p>You can watch the <a target="_blank" href="https://youtu.be/NDdCrvC79eg">video version of this handbook here</a>:</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/NDdCrvC79eg" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
<p> </p>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ul>
<li><p><a class="post-section-overview" href="#heading-how-to-use-this-handbook">How to Use this Handbook</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-what-this-handbook-will-teach-you">What this Handbook Will Teach You</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-what-this-handbook-will-not-teach-you">What this Handbook Will Not Teach You</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-traps">Traps</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-the-italian-game">The Italian Game</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-create-traps-in-the-italian-game">How to Create Traps in the Italian Game</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-game-1-giuoco-piano">Game #1 - Giuoco Piano</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-game-2">Game #2</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-game-3-legals-mate">Game #3 - Legal's Mate</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-game-4">Game #4</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-game-5-the-fried-liver-attack">Game #5 - The Fried Liver Attack</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-game-6-anti-fried-liver-defence">Game #6 - Anti-Fried Liver Defence</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-conclusion">Conclusion</a></p>
</li>
</ul>
<h2 id="heading-how-to-use-this-handbook">How to Use this Handbook</h2>
<p>This handbook makes use of notations and images. If you understand chess notations, then you can follow along without relying on the images. If you're new to notations, I'd recommend reading the What are Notations in Chess? chapter of <a target="_blank" href="https://www.freecodecamp.org/news/checkmate-patterns-in-chess-for-beginners/#heading-chapter-1-what-are-notations-in-chess-algebraic-chess-notation-explained">this handbook</a>.</p>
<p>In order to follow along, you should have a board with you. You can use either a physical board or an online chessboard. You can use <a target="_blank" href="https://lichess.org/">Lichess</a> for your online chessboard. Under the Tools section, you should see a couple of board related tools that you can make use of.</p>
<p>I would not recommend reading through without practicing. The best way to understand certain concepts is to try them out yourself.</p>
<p>And remember, improving in chess takes time and effort, so don't feel bad if you don't automatically start seeing gains. Focus on understanding and practicing first, and if you're doing that the right way, you'll gradually start progressing.</p>
<h2 id="heading-what-this-handbook-will-teach-you">What This Handbook Will Teach You</h2>
<p>This handbook will teach you some opening traps when playing the Italian Game as white. The overall purpose is for you to see common opening mistakes and how to take advantage of them. Even though you'll play as white in this case, you'll also learn why your opponents fall for these tricks, and that should help you avoid them when playing as black.</p>
<p>So, this is not an Italian Game opening handbook where we'll analyze lengthy games from start to finish. This is solely for beginners who want to understand why certain traps occur occasionally and why they always fall for them. You can learn something useful with this handbook irrespective of the color you play as.</p>
<h2 id="heading-what-this-handbook-will-not-teach-you">What This Handbook Will Not Teach You</h2>
<p>This handbook will not teach you how to follow basic opening principles to a tee. Sometimes, in order to win early and gain an advantage early in the game, you have to play unconventionally. These unconventional moves may prevent you from following certain principles.</p>
<p>You’ll not learn deeply about piece placement or pawn structure. These concepts are part of this handbook but we won’t focus much on them.</p>
<p>This guide will also not make reference to popular or model games. That is, won’t not make use of or analyze games that have been played by masters in the past. So, I won’t be explaining key moments from specific games.</p>
<h2 id="heading-traps">Traps</h2>
<p>Chess isn't scripted, so if you rely on your opponent to fall for certain tricks because you played the "right" moves from a course, then you may lose a lot of games. The traps here should not be seen as a conventional way of playing openings. It's important that you understand the concept behind the moves, as this will help you adjust your gameplay against anyone who knows how not to fall for traps.</p>
<p>In summary, don't memorize lines to use against opponents. Understand the concept and strategies first. Doing that will help you improve your tactics/strategy, and make it easier to spot similar positions in different games.</p>
<p>Let's get started!</p>
<h2 id="heading-the-italian-game">The Italian Game</h2>
<p>The Italian Game is a very popular chess opening used by players across all levels of chess. The opening allows you to quickly develop your pieces and move them to active positions, and gain control of the center.</p>
<p>The Italian Game starts with these lines:</p>
<ol>
<li><p>e4 e5</p>
</li>
<li><p>Nf3</p>
</li>
</ol>
<p>Bringing the knight to f3 attacks the pawn on e5, which leads to black playing:</p>
<ol start="2">
<li>... Nc6</li>
</ol>
<p>This defends the e5 pawn.</p>
<ol start="3">
<li>Bc4</li>
</ol>
<p>Finally, the bishop is moved the c4, and here's what the position looks like:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1769706417111/efb650a7-c1cd-4864-af48-230992b198c1.png" alt="Italian Game starting position" class="image--center mx-auto" width="702" height="703" loading="lazy"></p>
<p>When you reach the position in the image above, you've entered the Italian Game opening. Let's analyze white's position.</p>
<p>White has developed two minor pieces and a pawn, and has made way for castling and protecting the king early in the game. White is not wining yet, but that could quickly change depending on what black plays.</p>
<ol start="3">
<li>... Bc5</li>
</ol>
<p>This position leads to a variation of the Italian Game known as Giuoco Piano, and it’s played very often. In fact, it’s the most played variation of the Italian Game. We’ll start with that variation in the next section.</p>
<h2 id="heading-how-to-create-traps-in-the-italian-game">How to Create Traps in the Italian Game</h2>
<p>In this section, you'll learn some common traps for the Italian Game. We'll start with the Giuoco Piano variation.</p>
<h2 id="heading-game-1-giuoco-piano">Game #1 - Giuoco Piano</h2>
<p>Here's the starting position of the Giuoco Piano variation:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1769706451508/f783ad3e-658b-4f91-bb8e-8dbabf1b500c.png" alt="Giuoco Piano variation of the Italian Game" class="image--center mx-auto" width="702" height="703" loading="lazy"></p>
<ol start="4">
<li>c3</li>
</ol>
<p>Moving the pawn to c3 provides support for the d-file pawn, which can threaten the bishop on c5 and gain control of the center.</p>
<ol start="4">
<li>... Nf6</li>
</ol>
<p>With that, the black knight threatens to capture the pawn on e4 and clears the way for castling.</p>
<p>Here's our current position:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1769706486975/cd1132db-4174-4ceb-aca7-9365c5722e66.png" alt="black moves knight to f6 and threatens the pawn on e4" class="image--center mx-auto" width="703" height="700" loading="lazy"></p>
<p>What should you play here? Well, this section is about tricks. The safest move here would be d3 – this keeps things balanced, protects the e-pawn, and allows you to continue developing your pieces. But we're not going for a balanced or safe development.</p>
<ol start="5">
<li>d4</li>
</ol>
<p>This move forces black to capture on d4. If black chooses to move the bishop to a different square like Bb6, then we'll have something like 6. dxe5 Ng4, 7. Bxf7+ Kxf7, 8. Ng5+ Ke8. Black can't castle at the moment, as white is trying to gain more control of the center and can easily start attacking from the kingside. So retreating with the bishop isn't a good move for black. Although black can move the bishop to other squares and have a different outcome, white still gains an advantage.</p>
<ol start="5">
<li><p>... exd4</p>
</li>
<li><p>cxd4</p>
</li>
</ol>
<p>That brings us to this position:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1769706502296/692c8aad-4907-4fa3-b334-db3d55a23228.png" alt="the white c-pawn captures the black d-pawn" class="image--center mx-auto" width="705" height="702" loading="lazy"></p>
<p>Again, retreating with the bishop puts black at a disadvantage. For example, 6. ...Bb6, 6. ...Bd6, or 6. ...Be7 will simply allow white to start attacking with the pawns in the center of the board. The worst move here would be 6. ...Bf8, which both blocks black from castling and allows white to start attacking from the center.</p>
<p>The best move for black would be to check the king:</p>
<ol start="6">
<li>... Bb4+</li>
</ol>
<p>This is a crucial point for the trap. The safest move here is 7. Nd2. This protects the king and keeps the game balanced. But again, we're not playing it safe this time.</p>
<ol start="7">
<li>Nc3</li>
</ol>
<p>Let's look at the position visually:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1769706524493/c29f4a75-575a-4ce8-abbd-52140a2c2235.png" alt="white moves knight to c3 to block the check" class="image--center mx-auto" width="703" height="702" loading="lazy"></p>
<p>This position gives black a slight advantage. In order to set the perfect trap for your opponent, you may have to sacrifice some of your pieces and give them some false advantage. This doesn't mean that every trap will work – so make sure to evaluate your position well before taking chances.</p>
<p>With Nc3, white gives up the e4 pawn. This position is known as the Greco's Gambit. The main purpose of the move is to lure your opponent into capturing the e4 pawn with its knight.</p>
<ol start="7">
<li>... Nxe4</li>
</ol>
<p>This is a common response. Without getting rid of that pawn, white can start attacking with the pawns and make black's opening a bit difficult. So how do you respond? Remember, we're playing a gambit, which involves sacrificing a piece, usually a pawn, in the beginning of the game in order to gain an advantage.</p>
<p>Since black has accepted the gambit by capturing that pawn, we can continue with the plan.</p>
<ol start="8">
<li>O-O</li>
</ol>
<p>Now that the king has been safely castled, a couple of things have changed:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1769706537110/a4e3958f-4088-4b41-b102-e5e6385f9e0c.png" alt="white castle" class="image--center mx-auto" width="703" height="702" loading="lazy"></p>
<p>The knight on c3 is no longer pinned to the king, and if black castles, it'll lose the e4-knight. The best move here for black is to capture with the bishop. This is something you should always remember when playing as black in this position. White starts gaining some advantage if black captures with the knight, and that's what we'll use to learn about the trap here.</p>
<ol start="8">
<li><p>... Nxc3</p>
</li>
<li><p>bxc3 Bxc3</p>
</li>
</ol>
<p>We've managed to lure black into the trap by sacrificing more pieces. Black is threatening the a1-rook, but we're not going to try and save it. Since the purpose of a gambit is to gain advantage, we must capitalize on doing just that. If you try saving the a1-rook, then black will simply castle and you'd be in a slightly losing position.</p>
<ol start="10">
<li>Ba3</li>
</ol>
<p>This prevents black from castling the king. Here's what the current position looks like:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1769706548912/6863e580-f88a-4c5d-820b-0cbc97f302a8.png" alt="white bishop moves to c3 to block black from castling" class="image--center mx-auto" width="703" height="703" loading="lazy"></p>
<p>White already has more advantage in this position and is giving up the a1-rook. If black decides to block the a3-bishop with 10. ...d6, then black would lose its bishop after 11. Rc1 Ba5 12. Qa4 Bd7 13. d5 Nd4 14. Qxa5. This is another variation you can learn, in case black doesn't capture the bishop. But don't rely on these to always work – you're better off understanding the strategy behind these attacks than trying to replicate them all the time.</p>
<ol start="10">
<li>... Bxa1</li>
</ol>
<p>This is the moment we've been waiting for all along.</p>
<ol start="11">
<li>Re1+</li>
</ol>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1769706562361/850f0037-711a-4060-b850-1ab7c858dcc7.png" alt="rook check on the black king" class="image--center mx-auto" width="700" height="702" loading="lazy"></p>
<p>Black can only defend the king with the knight or the queen. Neither of those moves will make black's position any better. Naturally, defending with the knight would be the first option (although I would suggest resigning if you're playing as black in this position against a player who knows what they're doing).</p>
<ol start="11">
<li>... Ne7</li>
</ol>
<p>As white, you can either play 12. Bxe7 or 12. Rxe7. The former would lead to a black losing its queen after 12. ...Qxe7, 13. Rxe7+.</p>
<ol start="12">
<li>Rxe7</li>
</ol>
<p>The best option for black would be to lose the queen by capturing the e7-rook. Not that it gives black any sort of advantage, but it's better than moving the king to f8. If your opponent plays 12. ...Qxe7, then you can capture the queen with Bxe7, forcing the king to capture back on e7. At that point, your trap would have served its purpose: you've taken your opponent's queen, delayed their opening development, and their king can no longer castle. For you, your king is safe and you have enough minor pieces and your queen to win the game.</p>
<ol start="12">
<li>... Kf8</li>
</ol>
<p>Here's our current position:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1769706579275/75cbb3ac-d7a3-4a9e-8d3c-10fe86f6311c.png" alt="white continues to attack the black king with the rook" class="image--center mx-auto" width="703" height="700" loading="lazy"></p>
<p>The light squared bishop has been sitting on c4 since the game started. It's finally time for it to join and support the attack.</p>
<ol start="13">
<li>Rf7+</li>
</ol>
<p>White checks the black king, forcing it back to e8. The king cannot capture the rook because it’s protected by the bishop on c4. No matter what black plays at this point, the game will end in two moves. If black plays:</p>
<ol start="13">
<li>... Kg8</li>
</ol>
<p>Then the game ends with a double check:</p>
<ol start="14">
<li>Rf8#</li>
</ol>
<p>If black plays this instead:</p>
<ol start="13">
<li>... Ke8</li>
</ol>
<p>Then white can respond with a check, forcing the game to end:</p>
<ol start="14">
<li><p>Qe1+ Qe7</p>
</li>
<li><p>Qxe7#</p>
</li>
</ol>
<p>This game showed how placing your pieces on certain squares can help you gain an advantage later in the game. For example, white's light squared bishop seemed insignificant until it was needed to end the game. Placing the bishop on c4 is where the Italian Game starts and that bishop can become very troublesome for your opponents if they don't defend properly.</p>
<p>Here's a replay of the moves, along with the notations:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1769707180969/2558a06d-ae2f-4c63-a4c1-d51fe8364f46.gif" alt="replay of the moves from the Giuoco Piano variation of the Italian Game" class="image--center mx-auto" width="704" height="704" loading="lazy"></p>
<ol>
<li><p>e4 e5</p>
</li>
<li><p>Nf3 Nc6</p>
</li>
<li><p>Bc4 Bc5</p>
</li>
<li><p>c3 Nf6</p>
</li>
<li><p>d4 exd4</p>
</li>
<li><p>cxd4 Bb4+</p>
</li>
<li><p>Nc3 Nxe4</p>
</li>
<li><p>O-O Nxc3</p>
</li>
<li><p>bxc3 Bxc3</p>
</li>
<li><p>Ba3 Bxa1</p>
</li>
<li><p>Re1+ Ne7</p>
</li>
<li><p>Rxe7+ Kf8</p>
</li>
<li><p>Rxf7+ Ke8</p>
</li>
<li><p>Qe1+ Qe7</p>
</li>
<li><p>Qxe7#</p>
</li>
</ol>
<h2 id="heading-game-2">Game #2</h2>
<p>Here's our starting position again:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1769707790507/938b0635-36a0-4479-a351-939c7c1a97a2.png" alt="Italian Game starting position" class="image--center mx-auto" width="702" height="703" loading="lazy"></p>
<ol>
<li><p>e4 e5</p>
</li>
<li><p>Nf3 Nc6</p>
</li>
<li><p>Bc4 Bc5</p>
</li>
<li><p>Nc3 Nf6</p>
</li>
<li><p>d3 d6</p>
</li>
<li><p>Bg5</p>
</li>
</ol>
<p>Nothing much has happened here. Both sides have focused on developing their pieces so far and the game is still balanced. Here's our current position:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1769707804625/2f5803a7-3e14-412e-bc45-4312a43d4768.png" alt="white pin on black knight" class="image--center mx-auto" width="700" height="705" loading="lazy"></p>
<p>The common move here for black is usually h6, and that is probably the best move. Most players don’t want to worry about the bishop pin when they want to move the queen or the f6-knight, so it's usually a good idea for them to start pushing the bishop away.</p>
<ol start="6">
<li><p>... h6</p>
</li>
<li><p>Bf6</p>
</li>
</ol>
<p>With this move, white forces the black queen to capture on f6:</p>
<ol start="7">
<li>... Qxf6</li>
</ol>
<p>Now white can start setting a trap. Here's the current position of the board:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1769707816779/5b323bd9-83a0-4871-8039-c71bb92edf5a.png" alt="black queen captures on f6" class="image--center mx-auto" width="705" height="703" loading="lazy"></p>
<ol start="8">
<li>Nd5</li>
</ol>
<p>This forces the queen back to d8. If the queen moves to e6, it'll be forked with 9. Nc7+. If the queen moves to g6 in order to put pressure on the kingside, the knight can fork the king and rook on c7 as well. So the best move for white would be moving back to d8.</p>
<ol start="8">
<li><p>... Qd8</p>
</li>
<li><p>c3</p>
</li>
</ol>
<p>Now white is trying to take more control of the center.</p>
<ol start="9">
<li>... Be6</li>
</ol>
<p>Black attempts to add pressure in the center while developing a minor piece. But this move allows white to move on with some traps. It’s not very evident to see with the current position:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1769707831082/b7db3201-f3a7-4497-9d2e-9d3970b0a644.png" alt="black bishop to e6" class="image--center mx-auto" width="700" height="702" loading="lazy"></p>
<ol start="10">
<li><p>d4 exd4</p>
</li>
<li><p>cxd4</p>
</li>
</ol>
<p>Black can play a couple of moves here, but none of them really leads to an advantage. If black plays 11. ...Bb4+, then you'd have something like 12. Nxb4 Bxc4 13. Nxc6 bxc6 14. Qc2 Be6 15. Qxc6+ Bd7 16. Qc3. White comes out of the situation with more control of the center and a pawn up. This is the safest route for black. The alternatives, as you'll see in the following moves, will lead to black losing at least one minor piece.</p>
<p>Here's our current position (we'll revert back to this position to see other variations for the traps later):</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1769707840872/cdd115f6-6151-475c-bc4a-c45c38c7063f.png" alt="pawn trades in the center" class="image--center mx-auto" width="702" height="702" loading="lazy"></p>
<h3 id="heading-variation-1">Variation #1</h3>
<ol start="11">
<li>... Bb6</li>
</ol>
<p>The bishop retreats to avoid getting captured by the d4-pawn, but this is a blunder.</p>
<ol start="12">
<li>Nxb6</li>
</ol>
<p>Now black is down a piece. If black plays Bxc4, then the b6-knight will simply capture on c4. So black is forced to take the b6-knight. The reality is that, no matter what black plays in this position, it's going to be down by at least one minor piece.</p>
<ol start="12">
<li><p>... axb6</p>
</li>
<li><p>d5</p>
</li>
</ol>
<p>Here's our current position:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1769707853318/1c22380f-4306-45b2-8179-689eeffd18c2.png" alt="pawn fork on d5" class="image--center mx-auto" width="703" height="703" loading="lazy"></p>
<p>If black chooses to move either the knight or bishop away from the pawn fork, then it'll lose the other. But the knight can attack on a5, right? Well, let's see how that pans out for black.</p>
<ol start="13">
<li><p>... Na5</p>
</li>
<li><p>Bd3</p>
</li>
</ol>
<p>Now, can black safely move the bishop away and save both pieces that were under threat? Unfortunately, the knight is now trapped. So, right from when the pawn fork happened, one piece was "destined" to leave the board.</p>
<ol start="14">
<li><p>... Bg4</p>
</li>
<li><p>b4</p>
</li>
</ol>
<p>Now, no matter what black plays next, the a5-knight will be captured. Here's the position:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1769707864251/3b15aaeb-a9dd-458f-8a74-2dbb82a28c9b.png" alt="pawn move to trap a5-knight" class="image--center mx-auto" width="703" height="703" loading="lazy"></p>
<p>That concludes things for this variation of the trap. Here's a replay of the first variation of the trap and the notations:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1769708076475/433a2257-e556-4223-8f5d-6ed7cc964233.gif" alt="replay of moves" class="image--center mx-auto" width="702" height="700" loading="lazy"></p>
<ol>
<li><p>e4 e5</p>
</li>
<li><p>Nf3 Nc6</p>
</li>
<li><p>Bc4 Bc5</p>
</li>
<li><p>Nc3 Nf6</p>
</li>
<li><p>d3 d6</p>
</li>
<li><p>Bg5 h6</p>
</li>
<li><p>Bxf6 Qxf6</p>
</li>
<li><p>Nd5 Qd8</p>
</li>
<li><p>c3 Be6</p>
</li>
<li><p>d4 exd4</p>
</li>
<li><p>cxd4 Bb6</p>
</li>
<li><p>Nxb6 axb6</p>
</li>
<li><p>d5 Na5Bd3 Bg4</p>
</li>
<li><p>b4</p>
</li>
</ol>
<h3 id="heading-variation-2">Variation #2</h3>
<p>Now, let's go back to the position that started the first variation:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1769708094266/23380687-0b20-477c-8b42-1b5e262742a9.png" alt="variation 2 starting position " class="image--center mx-auto" width="702" height="702" loading="lazy"></p>
<p>If black decides to capture the d5-knight, here's what will happen:</p>
<ol start="11">
<li><p>... Bxd5</p>
</li>
<li><p>exd5</p>
</li>
</ol>
<p>Which brings us to this position:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1769708101452/7e73753f-d97d-4935-a5a5-a79e5748c47e.png" alt="pawn attack on black knight and bishop" class="image--center mx-auto" width="702" height="703" loading="lazy"></p>
<p>Two of white's minor pieces are now under attack and one will eventually be captured. If black plays:</p>
<ol start="12">
<li>... Bb4+</li>
</ol>
<p>Then you'll have something like this:</p>
<ol start="13">
<li><p>Kf1 Ne7</p>
</li>
<li><p>Qa4+ Qd7</p>
</li>
<li><p>Qxb4</p>
</li>
</ol>
<p>Black ends up losing the bishop. Here's a replay of the moves above, along with the notations:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1769708118695/968de982-1687-42d1-80cb-8bc11a7d4c7d.gif" alt="replay of moves" class="image--center mx-auto" width="702" height="704" loading="lazy"></p>
<ol>
<li><p>e4 e5</p>
</li>
<li><p>Nf3 Nc6</p>
</li>
<li><p>Bc4 Bc5</p>
</li>
<li><p>Nc3 Nf6</p>
</li>
<li><p>d3 d6</p>
</li>
<li><p>Bg5 h6</p>
</li>
<li><p>Bxf6 Qxf6</p>
</li>
<li><p>Nd5 Qd8</p>
</li>
<li><p>c3 Be6</p>
</li>
<li><p>d4 exd4</p>
</li>
<li><p>cxd4 Bxd5</p>
</li>
<li><p>exd5 Bb4+</p>
</li>
<li><p>Kf1 Ne7</p>
</li>
<li><p>Qa4+ Qd7</p>
</li>
<li><p>Qxb4</p>
</li>
</ol>
<h2 id="heading-game-3-legals-mate">Game #3 – Legal's Mate</h2>
<p>The Legal Trap is one that allows you to capitalize on your opponent's mistakes in the opening phase of the game. With this trap, the game ends after eight moves.</p>
<p>Note that the trap may not work against intermediate players. Most of the moves that lead up to the mate are all bad moves and you won’t often see that many bad moves in row.</p>
<p>As usual, here's the starting position of the Italian Game:</p>
<ol>
<li><p>e4 e5</p>
</li>
<li><p>Nf3 Nc6</p>
</li>
<li><p>Bc4</p>
</li>
</ol>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1769708141459/53fda81e-abb8-42a6-9950-9ea8c0d7a2f3.png" alt="Italian Game starting position" class="image--center mx-auto" width="703" height="705" loading="lazy"></p>
<ol start="3">
<li>... d6</li>
</ol>
<p>This is black's first bad move. The d6-pawn now prevents the development of the dark squared bishop. Beginners often make this mistake because they want to strengthen the support on the e-pawn and use the light squared bishop to pin white's knight.</p>
<ol start="4">
<li>Nc3 Bg4</li>
</ol>
<p>Here's the position so far:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1769708149205/b654c08e-0495-48e2-bf46-e8a69b72434d.png" alt="black bishop pin on white knight" class="image--center mx-auto" width="700" height="703" loading="lazy"></p>
<p>Black pins the white knight and can decide to put more pressure by bringing the knight to d4 next.</p>
<ol start="5">
<li>h3</li>
</ol>
<p>White attempts to push the bishop back. In this position, moving the bishop back to e6 would be best for black. But most beginners would want to maintain the pin on the knight.</p>
<ol start="5">
<li>... Bh5</li>
</ol>
<p>Black moves back but continues pinning the knight. This is where white attempts to end the game by giving up the queen.</p>
<ol start="6">
<li>Nxe5</li>
</ol>
<p>Here's the current position:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1769708162656/72298e75-4691-49d4-8b0e-88c0e5d7540c.png" alt="knight captures to trick black " class="image--center mx-auto" width="700" height="703" loading="lazy"></p>
<ol start="6">
<li>... Bxd1</li>
</ol>
<p>Black goes for the queen without seeing white's plan.</p>
<ol start="7">
<li><p>Bxf7+ Ke7</p>
</li>
<li><p>Nd5#</p>
</li>
</ol>
<p>The game ends in eight moves.</p>
<p>This is not a checkmate pattern you'll see often, but it's important to understand how it works. Positions like this can appear at any time, so you should focus more on understanding why the pieces were moved to certain squares instead of memorizing the lines.</p>
<p>I know I’ve mentioned this before, but it's crucial to repeat it here because if you try to use the Legal's Mate as your main strategy from the beginning of the game, then you'll most likely encounter difficulties.</p>
<p>Here’s a replay of the move, along with the notations:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1769708419808/d8c007c3-6f57-4346-a400-de4fe7720a34.gif" alt="replay of moves" class="image--center mx-auto" width="704" height="702" loading="lazy"></p>
<ol>
<li><p>e4 e5</p>
</li>
<li><p>Nf3 Nc6</p>
</li>
<li><p>Bc4 d6</p>
</li>
<li><p>Nc3 Bg4</p>
</li>
<li><p>h3 Bh5</p>
</li>
<li><p>Nxe5 Bxd1</p>
</li>
<li><p>Bxf7+ Ke7</p>
</li>
<li><p>Nd5#</p>
</li>
</ol>
<h2 id="heading-game-4">Game #4</h2>
<p>This particular trap is one that many beginners fall for. The aim is to allow your opponent to think they're getting a free pawn, but then they either lose the game or a minor piece.</p>
<ol>
<li><p>e4 e5</p>
</li>
<li><p>Nf3 Nc6</p>
</li>
<li><p>Bc4 Bc5</p>
</li>
<li><p>c3 Nf6</p>
</li>
<li><p>d4 Bb6</p>
</li>
</ol>
<p>In this case, black decides not to capture the d-pawn. That move gives white an advantage in the opening, because it can start attacking with the pawns in the center. Here's the current position:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1769708465419/1ef4b005-7472-4d27-805a-c8f958b03471.png" alt="black bishop moves away from center and avoids trading pawns" class="image--center mx-auto" width="703" height="700" loading="lazy"></p>
<ol start="6">
<li>dxe5</li>
</ol>
<p>This move is where most beginner players mess up. They assume that the e4-pawn is up for grabs. The moment black captures that pawn, then the knight will be trapped. But it's not just that. Here:</p>
<ol start="6">
<li><p>... Nxe4</p>
</li>
<li><p>Qd5</p>
</li>
</ol>
<p>The queen move threatens a checkmate on f7 if black tries to saves the knight. There is really nowhere for that knight to go, so you're better off saving your king with 7. ...Qe7 if you're playing as black in this position.</p>
<p>Here's a replay of the moves, along with the notations:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1769708534985/b66970f3-6280-4b70-a166-d58e17e28686.gif" alt="replay of moves" class="image--center mx-auto" width="702" height="702" loading="lazy"></p>
<ol>
<li><p>e4 e5</p>
</li>
<li><p>Nf3 Nc6</p>
</li>
<li><p>Bc4 Bc5</p>
</li>
<li><p>c3 Nf6</p>
</li>
<li><p>d4 Bb6</p>
</li>
<li><p>dxe5 Nxe4</p>
</li>
<li><p>Qd5</p>
</li>
</ol>
<h2 id="heading-game-5-the-fried-liver-attack">Game #5 - The Fried Liver Attack</h2>
<p>The Fried Liver Attack is one of the most common tricks played by beginners. Many amateur players fall for this trick because it creates tension at the beginning of the game.</p>
<p>Here's what the position of the Fried Liver Attack looks like:</p>
<ol>
<li><p>e4 e5</p>
</li>
<li><p>Nf3 Nc6</p>
</li>
<li><p>Bc4 Nf6</p>
</li>
<li><p>Ng5</p>
</li>
</ol>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1769711722677/8cb76159-5d2a-4a3e-bf11-6ca30b2ed342.png" alt="The Fried Liver Attack starting position" class="image--center mx-auto" width="703" height="703" loading="lazy"></p>
<p>The most commonly played move here is d5. If you play anything else as black, then 5. Nxf7 will fork the queen and the rook.</p>
<ol start="4">
<li>… d5</li>
</ol>
<p>And we have this position:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1769711999847/32a07dab-7592-43dd-8dd2-116fdf55fbde.png" alt="black plays d5 to block the white bishop" class="image--center mx-auto" width="703" height="706" loading="lazy"></p>
<ol start="5">
<li>exd5 Nxd5</li>
</ol>
<p>The 5. …Nxd5 play is one I wouldn’t recommend for most beginners playing as black. It can lead to some complicated situations.</p>
<ol start="6">
<li>Nxf7</li>
</ol>
<p>Now black has no option other than to capture the f7-knight, which now prevents the king from castling later in the game. If black ignores the knight, then it’ll lose either its queen or rook.</p>
<ol start="6">
<li><p>… Kxf7</p>
</li>
<li><p>Qf3+</p>
</li>
</ol>
<p>The problem now is that the king is being forced to move closer to the center of the board and protect the knight on d5. Remember, one of the opening principles in chess is to castle your king early, but black can no longer do that.</p>
<p>If black decides to move the king backwards, let’s say 7. …Kg8, then the game will end in three moves: Bxd5+ Qxd5 9. Qxd5+ Be6 10. Qxe6#. If black moves to e8 instead, then white can capture the knight on d5 and black still wouldn’t be able to castle.</p>
<ol start="7">
<li>… Ke6</li>
</ol>
<p>This is not a completely losing position for black, but it’ll be easier for white to put more pressure on the king, and if black doesn’t play very well, the game could end. With the king in the center, white can add more pieces to the attack:</p>
<ol start="8">
<li>Nc3</li>
</ol>
<p>The knight now threatens the black knight as well.</p>
<ol start="8">
<li><p>… Nb4</p>
</li>
<li><p>O-O c6</p>
</li>
</ol>
<p>Here’s the current position:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1769712632064/0ed2c8a4-14e5-4eaf-96ff-bbed68b5c0cc.png" alt="black plays c6 to add support for the d5-knight " class="image--center mx-auto" width="703" height="703" loading="lazy"></p>
<p>As you can see, white has more advantage: the black king can no longer castle and is close to the center of the board. The white king has castled and is safe, and white can focus on developing its pieces while black has to find a way to prevent a checkmate or losing the knights.</p>
<p>It’s still possible for black to win in the situation, but this can become very complicated, especially for beginners.</p>
<p>Here’s a replay of the moves, along with the notations:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1769712918353/338cc754-d89f-483f-b737-9b1799246db4.gif" alt="replay of moves" class="image--center mx-auto" width="700" height="702" loading="lazy"></p>
<ol>
<li><p>e4 e5</p>
</li>
<li><p>Nf3 Nc6</p>
</li>
<li><p>Bc4 Nf6</p>
</li>
<li><p>Ng5 d5</p>
</li>
<li><p>exd5 Nxd5</p>
</li>
<li><p>Nxf7 Kxf7</p>
</li>
<li><p>Qf3+ Ke6</p>
</li>
<li><p>Nc3 Nb4</p>
</li>
<li><p>O-O c6</p>
</li>
</ol>
<h2 id="heading-game-6-anti-fried-liver-defence">Game #6 - Anti-Fried Liver Defence</h2>
<p>From our last game, here’s the setup for the Fried Liver Attack:</p>
<ol>
<li><p>e4 e5</p>
</li>
<li><p>Nf3 Nc6</p>
</li>
<li><p>Bc4 Nf6</p>
</li>
<li><p>Ng5</p>
</li>
</ol>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1769708545356/008d3b15-a358-4a97-9821-65b8fe58f476.png" alt="Fried Liver Attack starting position" class="image--center mx-auto" width="703" height="703" loading="lazy"></p>
<p>Since many beginners struggle with the tension created from the Fried Liver Attack, they try to avoid it completely from the beginning of the game. So, some might play h6 as their third move to prevent the white knight from moving to the g5 square. That is:</p>
<ol>
<li><p>e4 e5</p>
</li>
<li><p>Nf3 Nc6</p>
</li>
<li><p>Bc4 h6</p>
</li>
</ol>
<p>Which leads to this position:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1769708558473/40a79404-2603-4971-bf91-b4d51ec6267d.png" alt="Anti-Fried Liver Defence starting position " class="image--center mx-auto" width="705" height="705" loading="lazy"></p>
<ol start="4">
<li><p>d4 exd4</p>
</li>
<li><p>Nxd4</p>
</li>
</ol>
<p>This is where white sets the trap. Black should continue developing minor pieces and castle the king. A move like 5. ...Nf6 would work for black. But some people may want to double the attack on the d4-knight in order to push it back:</p>
<ol start="5">
<li>... Bc5</li>
</ol>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1769708561048/356f3282-5210-4c20-8598-2f1ef7dfe21a.png" alt="black blunders by moving the bishop to c5" class="image--center mx-auto" width="703" height="703" loading="lazy"></p>
<ol start="6">
<li><p>Bxf7+ Kxf7</p>
</li>
<li><p>Qh5+ Kf8</p>
</li>
<li><p>Qxc5+</p>
</li>
</ol>
<p>With these moves, black no longer has the option of castling and the kingside looks weaker.</p>
<p>Here's a replay and the notations:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1769708627936/3c6f0fe1-f918-4d3d-a75a-fceaf35a26aa.gif" alt="replay of moves" class="image--center mx-auto" width="704" height="702" loading="lazy"></p>
<ol>
<li><p>e4 e5</p>
</li>
<li><p>Nf3 Nc6</p>
</li>
<li><p>Bc4 h6</p>
</li>
<li><p>d4 exd4</p>
</li>
<li><p>Nxd4 Bc5</p>
</li>
<li><p>Bxf7+ Kxf7</p>
</li>
<li><p>Qh5+ Kf8</p>
</li>
<li><p>Qxc5+</p>
</li>
</ol>
<h2 id="heading-conclusion">Conclusion</h2>
<p>This handbook showed you some of the most common beginner traps for the Italian Game. Although we saw most of the traps from the perspective of white, it can also help you defend against them when playing as black.</p>
<p>Opening moves in chess can be quite tricky. You may decide to stick with opening principles by developing your pieces, trying to control the center, and castling early. But, along the way, you may miss obvious mistakes and fall for your opponent’s traps.</p>
<p>You shouldn’t learn chess openings in order to replicate everything you see in various courses. Instead, you should try and understand why certain moves were made and their outcome. That way, you can improve your tactics and strategy and be able to recognize similar positions in other games.</p>
<p>I hope this handbook has been helpful for you on your chess journey. You can <a target="_blank" href="https://lichess.org/@/IHECHIKARA">find me on Lichess @ IHECHIKARA</a>.</p>
<p>You can watch the video version of this handbook here.</p>
<p>You can <a target="_blank" href="https://www.freecodecamp.org/news/checkmate-patterns-in-chess-for-beginners/">learn about checkmate patterns in chess here</a>.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Checkmate Patterns in Chess for Beginners ]]>
                </title>
                <description>
                    <![CDATA[ After learning the rules and basics of chess, there are various concepts that beginners should learn in order to keep improving. Some of these concepts include opening principles, middle game concepts, endgame fundamentals, and strategy. In this hand... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/checkmate-patterns-in-chess-for-beginners/</link>
                <guid isPermaLink="false">68a72ee03bbf12346853dce9</guid>
                
                    <category>
                        <![CDATA[ chess ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Tutorial ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Strategy ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Ihechikara Abba ]]>
                </dc:creator>
                <pubDate>Thu, 21 Aug 2025 14:36:16 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1755720597720/2bb80910-7697-45e2-8163-dbfb73b4998f.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>After learning the rules and basics of chess, there are various concepts that beginners should learn in order to keep improving. Some of these concepts include opening principles, middle game concepts, endgame fundamentals, and strategy.</p>
<p>In this handbook, we’ll focus on endgame fundamentals. You’ll learn about some common checkmate patterns for beginners and how you can recognize these patterns more easily to increase your chances of winning.</p>
<p>This handbook is not for absolute beginners. You should understand these concepts before proceeding:</p>
<ul>
<li><p>How to identify each chess piece.</p>
</li>
<li><p>How to set up a chess board.</p>
</li>
<li><p>How each piece moves.</p>
</li>
<li><p>Some basic chess terms like "capture", "castling", "check", "checkmate", "piece promotion", "fork", "pin", and so on.</p>
</li>
</ul>
<p>If you're new to chess, or you're not yet familiar with the prerequisites, then <a target="_blank" href="https://lichess.org/learn">this free resource</a> is a good place to start.</p>
<p>In the first chapter, you'll learn about algebraic chess notations. You’ll learn about files and ranks, how to identify and denote each square on a board, and how to record chess moves using algebraic chess notations.</p>
<p>In the second chapter, you’ll learn about some checkmate patterns like queen and king vs king, two rooks vs king, opera mate, Anastasia’s mate, and so on.</p>
<p>I've provided some exercises in different sections to help you practice. You can find the answers to each exercise at the end of the handbook.</p>
<p>I’ve also included some practice positions for each endgame pattern. To use them, click on the link provided for each exercise, then click on “CONTINUE FROM HERE” in the options at the bottom-right of the page. That is:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1755630305311/3fdcec2a-a6b2-485b-9e78-1a1620d522a0.jpeg" alt="press the &quot;CONTINUE FROM HERE&quot; button to practice the position against an engine" class="image--center mx-auto" width="971" height="816" loading="lazy"></p>
<p>This will let you practice the positions against an engine. The engine has varying levels of strength, so you should try beating each level. You can find links for all the practice positions at the end of the article. You can also use the board editor from the links to set up your own positions.</p>
<p>You can watch the video version of this handbook here:</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/1AX7_aPWmbE" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
<p> </p>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ol>
<li><p><a class="post-section-overview" href="#heading-how-to-use-this-handbook">How to Use this Handbook</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-chapter-1-what-are-notations-in-chess-algebraic-chess-notation-explained">Chapter 1: What are Notations in Chess? Algebraic Chess Notation Explained</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-what-are-chess-notations">What are Chess Notations?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-what-is-algebraic-chess-notation">What is Algebraic Chess Notation?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-what-are-chess-notations-used-for">What are Chess Notations Used For?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-write-algebraic-chess-notations">How to Write Algebraic Chess Notations</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-identify-squares-on-a-chess-board">How to Identify Squares on a Chess Board</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-chapter-2-checkmate-patterns-for-beginners">Chapter 2: Checkmate Patterns for Beginners</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-what-is-a-check-and-checkmate-in-chess">What is a Check and Checkmate in Chess?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-checkmate-patterns">Checkmate Patterns</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-checkmate-patterns-ii">Checkmate Patterns II</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-conclusion">Conclusion</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-exercise-answers">Exercise Answers</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-practice-position-urls">Practice Position URLs</a></p>
</li>
</ol>
<h2 id="heading-how-to-use-this-handbook"><strong>How to Use this Handbook</strong></h2>
<p>This handbook is not meant to be read and understood just once. If you're a beginner, then chances are high that you'll reference it multiple times in order to understand certain concepts.</p>
<p>In order to get the best out of this resource, you'll need a chess board. You can use either a physical board or an online chessboard. I recommend using <a target="_blank" href="https://lichess.org/">Lichess</a> if you're going to use the latter option.</p>
<p>You should try and replicate the moves as you read. Remember, you're not meant to understand everything the first time you read it, so it’s totally fine to go over one concept again and again.</p>
<p>Chess books can be boring, but don't let that hinder your progress. It gets interesting when you're able to understand, practice, and see improvements from what you've learned.</p>
<p>Let's get started!</p>
<h2 id="heading-chapter-1-what-are-notations-in-chess-algebraic-chess-notation-explained">Chapter 1: What are Notations in Chess? Algebraic Chess Notation Explained</h2>
<p>You can use chess notations to record chess moves, and this handbook will rely heavily on them to teach you difference concepts about chess as a beginner. The first time you learn about writing or reading notations may seem overwhelming, but don't worry – with constant practice and studying, you'll get the hang of it.</p>
<h3 id="heading-what-are-chess-notations"><strong>What are Chess Notations?</strong></h3>
<p>To put it simply, chess notation is a method of recording moves in a chess game. In a physical chess game, it usually involves two players writing down moves as they’re played.</p>
<p>While there are other forms of chess notations like descriptive, coordinate, numeric, and so on, we'll focus primarily on algebraic chess notation.</p>
<h3 id="heading-what-is-algebraic-chess-notation"><strong>What is Algebraic Chess Notation?</strong></h3>
<p>Algebraic chess notation is the standard way of recording chess. Each notation shows the move number, the piece moved, and the position of the board where the piece was moved to. In some cases, the notations also show an action being performed, like a check, a checkmate, castling, and so on.</p>
<p>For example:</p>
<ol>
<li><p>e4 d5</p>
</li>
<li><p>d4 dxe4</p>
</li>
<li><p>Nc3 e6</p>
</li>
</ol>
<p>These may look strange if it's your first time looking at notations. But don't worry, you'll understand how to write and read/interpret them as we progress.</p>
<p>In online games, they're recorded automatically:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1755278278381/25c66717-56a0-46ac-99dd-5db78c6b1a37.png" alt="chess notations on Lichess" class="image--center mx-auto" width="2510" height="1291" loading="lazy"></p>
<p>The image above shows a chess game played on <a target="_blank" href="https://lichess.org/">lichess.org</a>. On the right side of the image, you can see the notations of the game as each move was played, along with numbers corresponding with the moves. We'll talk more about the numbers later.</p>
<p>Now that you know what notations are, let's talk about why they're needed.</p>
<h3 id="heading-what-are-chess-notations-used-for"><strong>What are Chess Notations Used For?</strong></h3>
<p>Here are some of the uses of chess notations:</p>
<h4 id="heading-competitiveprofessional-chess">Competitive/Professional Chess</h4>
<p>Algebraic chess notation is the standard way of recording a chess game in tournaments. In over the board tournaments, each player is given a piece of paper with columns for writing each move played. Note that this involves recording their opponent's moves as well.</p>
<h4 id="heading-studying-and-teaching-chess">Studying and Teaching Chess</h4>
<p>You can think of chess notations as the language of chess, and to learn about something, there has to be a way to pass and communicate information.</p>
<h4 id="heading-communication">Communication</h4>
<p>With chess notations, you can communicate moves and share games with players across the world without needing a physical board.</p>
<h3 id="heading-how-to-write-algebraic-chess-notations"><strong>How to Write Algebraic Chess Notations</strong></h3>
<p>Algebraic chess notation makes use of the board coordinates and the pieces to denote moves.</p>
<p>Let's start with the coordinates:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1755278306647/e0c0d1d4-74cb-4f49-9180-42b81102f7d2.png" alt="an empty chess board" class="image--center mx-auto" width="1093" height="1096" loading="lazy"></p>
<p>The image above shows a chess board without the pieces. On the right edge of the board are numbers 1 to 8, and the bottom edge of the board has letters a to h. You can use these numbers and letters to refer to a particular position of the board.</p>
<p>Each vertical column (top to bottom) in a chess board is called a file, while each horizontal row (left to right) is called a rank. You can also associate them with the letters and numbers: the letters can be used to reference files, while the numbers can be used to reference ranks.</p>
<h4 id="heading-files-a-to-f">Files a to f</h4>
<p>There are eight files in a chess board. Another way to say this is that, from top to bottom, there are eight vertical lines (stack of squares from top to bottom) in a chess board. Each vertical line is associated with a letter, which is usually written at the bottom edge of the board. That is:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1755278341256/ee7fae5e-3a9d-4477-b036-dbcaa031b92d.png" alt="a chess board show an arrow on each file" class="image--center mx-auto" width="1098" height="1096" loading="lazy"></p>
<p>To help you understand files, let's try and identify some of them separately. The image below shows the a-file:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1755278367782/da2fab28-9cc3-47a8-ad90-cad1e55cfbb7.png" alt="a chess board with an arrow on the a-file" class="image--center mx-auto" width="1087" height="1087" loading="lazy"></p>
<p>We can tell that this is the a-file because the all the squares in that vertical column fall under the part of the board labelled "a". Remember that files go from top to bottom.</p>
<p>Here's another example:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1755278386430/f2842bda-1dee-466e-9ddb-70328001873c.png" alt="a chess board with an arrow on the f-file" class="image--center mx-auto" width="1093" height="1092" loading="lazy"></p>
<p>This arrow runs from top to bottom, but on a different part of the board. To know what file this is, simply look the the letter associated with the vertical column. Using that, we can say that the arrow is on the the f-file.</p>
<p>Here's an exercise for you (you can find the answers to each exercise at the end of the handbook):</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1755278412195/1f83d8b6-d192-4f60-9604-5a8de609ceec.png" alt="an exercise to find what file the arrow is on" class="image--center mx-auto" width="1093" height="1087" loading="lazy"></p>
<p>In the image above, using the letters on the board, what file is the arrow on?</p>
<h4 id="heading-ranks-1-to-8">Ranks 1 to 8</h4>
<p>Just like files, we have eight ranks in a chess board. These are the eight horizontal lines (stack of squares from left to right) in a chess board. That is:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1755278462326/7308dc99-8679-40f9-bd98-02a7644ba14a.png" alt="a chessboard with an arrow on each rank" class="image--center mx-auto" width="1089" height="1090" loading="lazy"></p>
<p>Let's identify some of the ranks separately.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1755278544960/1e785b64-dc0a-4770-a70c-95e9bdfd4a06.png" alt="a chessboard with an arrow on the fourth rank" class="image--center mx-auto" width="1087" height="1087" loading="lazy"></p>
<p>Using the position of the arrow, you can tell the rank. The arrow run from left to right on the part of the board with the number 4, so we can say that it is on the fourth rank.</p>
<p>Here's another example:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1755278560474/1b75018e-2197-4d7f-8614-add51e756024.png" alt="a chessboard with an arrow on the first rank" class="image--center mx-auto" width="1087" height="1080" loading="lazy"></p>
<p>You may confuse files and ranks here since you can see the letters at the bottom. Remember, we're dealing with ranks here, and they go from left to right, not top to bottom. From left to right, in the image above, we can see the letter 1. So the arrow is on the first rank.</p>
<p>Here's an exercise for you:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1755278592936/77305a72-bbc8-45f9-aff4-82a9cbb8f9de.png" alt="a chessboard with an arrow on the eighth rank" class="image--center mx-auto" width="1089" height="1086" loading="lazy"></p>
<p>In the image above, using the numbers on the board, what rank is the arrow on?</p>
<h3 id="heading-how-to-identify-squares-on-a-chess-board">How to Identify Squares on a Chess Board</h3>
<p>Now that you know what files and ranks are in chess, let's see how you can use them to identify a square. Identifying a square is important when writing notations. Each notation is made up of the move number, the piece moved, and the coordinate. In the case, a coordinate is the combination of a file and a rank.</p>
<p>Let's start with this image:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1755278624546/a25a44db-7950-462b-ac2d-24c6105743f6.png" alt="a chessboard with a circle on e5" class="image--center mx-auto" width="1093" height="1084" loading="lazy"></p>
<p>In the image above, we have a circle on a random square. The goal here is to identify that square, that is, to refer to it as "something".</p>
<p>To identify the square, you have to trace its file and the rank. Let' start with the file.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1755278670477/1e0355a5-35f7-4098-adba-0ab1b7fb5980.png" alt="a chessboard with a circle and arrow pointing to e5" class="image--center mx-auto" width="1090" height="1084" loading="lazy"></p>
<p>Using the arrow, we can see that the circle falls under the e-file. Next, let's trace the rank.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1755278713838/05fe7d3c-0902-4b85-b7f9-270b9475146b.png" alt="a chessboard with a circle and arrows pointing to e5" class="image--center mx-auto" width="1089" height="1086" loading="lazy"></p>
<p>Great! We can tell that the circle is on the fifth rank.</p>
<p>So we can say that we have a circle on the e-file and the fifth rank. Using notations, you can write it as e5.</p>
<p>In the next example, we'll identify the position of chess pieces. In order to do that, you need to know the letters that represent each piece on a board:</p>
<p>King = K</p>
<p>Queen = Q</p>
<p>Rook = R</p>
<p>Bishop = B</p>
<p>Knight = N</p>
<p>Pawn = no letter (denoted by the square they move to).</p>
<p>In our last example, we identified the square as e5. If you replace that square with a chess piece, then the the notation would start with the letter of that piece, followed by its position on the board. Here's an example:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1755278735253/f4b13367-7bbe-48f9-b7e3-f8359081cbe0.png" alt="queen on e5" class="image--center mx-auto" width="1087" height="1086" loading="lazy"></p>
<p>Now we have the queen on the e5 square. The notation will look like this: Qe5. This way of writing the letter of the piece, followed by the coordinate of the square applies to other pieces, except the pawns. For pawns, you only write the coordinate.</p>
<p>If you had a rook on e5, the notation would be Re5, Ke5 for a king, Ne5 for a knight, Be5 for a bishop, and e5 for a pawn.</p>
<h3 id="heading-how-to-write-algebraic-chess-notations-1"><strong>How to Write Algebraic Chess Notations</strong></h3>
<p>We stated earlier that algebraic chess notations show the move number, the piece moved, and the position of the board where the piece is moved to. In our examples, you've seen how to write the piece moved, and where it was moved to using coordinate (files and ranks). In the examples for this section, we'll add the move number to complete the algebraic chess notation.</p>
<p>By move number, we simply mean the turn count. Each move number is associated with one White and one Black move. For instance, the first move of the game will have a move number of 1. Let's look at some examples.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1755278762190/45bcd65e-3901-40b0-a602-494bfc696643.png" alt="chessboard starting position" class="image--center mx-auto" width="1132" height="1123" loading="lazy"></p>
<p>Each piece on the board is in its starting position. Let's make the first move for White:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1755278784164/52dc3f3b-16eb-47ef-b157-2d1bef6f0564.png" alt="first pawn move for white" class="image--center mx-auto" width="1129" height="1120" loading="lazy"></p>
<p>White has moved a pawn to e4. To record this, you'd start with the move number, followed by the piece and coordinate. That is:</p>
<ol>
<li>e4</li>
</ol>
<p>Next, Black's move.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1755278805904/2c4632a4-74cb-45df-9c4e-b7c9553c1700.png" alt="first pawn move for black" class="image--center mx-auto" width="1123" height="1122" loading="lazy"></p>
<p>Black responded by moving a pawn to e4. Since this is Black's first move, it'll also be recorded under move number 1:</p>
<ol>
<li>e4 e5</li>
</ol>
<p>If you look at the algebraic notation above, you can see that both notations are written on the same line, and are both associated with move number 1. To interpret this, the first coordinate belongs to White, while the second belongs to Black.</p>
<p>To make this even clearer, let's continue the game. It's White's turn to play.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1755278832714/22efd090-04bb-485d-b0be-8eada8d76784.png" alt="white knight to f3" class="image--center mx-auto" width="1125" height="1120" loading="lazy"></p>
<p>The white knight was moved to f3, which can be denoted by Nf3. Since this is White's second move, it'll be recorded under move number 2:</p>
<ol>
<li><p>e4 e5</p>
</li>
<li><p>Nf3</p>
</li>
</ol>
<p>Now Black has to respond with a second move.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1755278861739/d4e8e53f-6753-4ad8-ac2d-2e44c573c63c.png" alt="black knight to c6" class="image--center mx-auto" width="1119" height="1117" loading="lazy"></p>
<p>Black played Nc6 (knight to c6). Remember that this is the second move for Black, so it has to be recorded in move number 2, right after the notation for White's second move. So we'll have this:</p>
<ol>
<li><p>e4 e5</p>
</li>
<li><p>Nf3 Nc6</p>
</li>
</ol>
<p>This system of recording chess moves is known as algebraic chess notation. Here's a summary of how it works:</p>
<ul>
<li><p>You write the move number.</p>
</li>
<li><p>You write piece moved (omitted for pawns).</p>
</li>
<li><p>You write the coordinate (file and rank) that the piece moved to.</p>
</li>
</ul>
<p>With this information, you can easily read and write chess notations! But we're not done yet. How do you write checks, checkmates, castling, and pawn promotions?</p>
<h3 id="heading-how-to-write-a-check-notation-in-algebraic-chess-notations"><strong>How to Write a Check Notation in Algebraic Chess Notations</strong></h3>
<p>You can use the + symbol to denote a check. This comes after the move notation. That is, you write the notation as you would for any other move, and then add the + symbol at the end. Here's an example:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1755278891757/ecb8de32-58c3-481c-8fa2-e229cd555fab.png" alt="queen check" class="image--center mx-auto" width="1117" height="1116" loading="lazy"></p>
<p>Here, the queen moves to e7 to check the king. So the notation would be Qe7+. The + at the end denotes the check by the queen. If you write it as Qe7, without the check symbol, then you'd have an inaccurate notation of the move.</p>
<h3 id="heading-how-to-write-a-checkmate-notation-in-algebraic-chess-notations"><strong>How to Write a Checkmate Notation in Algebraic Chess Notations</strong></h3>
<p>A checkmate is denoted by the # symbol. It also comes after the move notation. That is, you write the notation as you would for any other move, and then add the # symbol at the end. Here's an example:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1755278908199/7a808ce3-25eb-419b-ac9f-ef03a4bcb4ef.png" alt="checkmate with two rooks" class="image--center mx-auto" width="1117" height="1116" loading="lazy"></p>
<p>In the image above, the rook moved to g8 to win the game. The notation would be Rg8#. The # symbol denotes the checkmate.</p>
<h3 id="heading-how-to-write-a-castling-notation-in-algebraic-chess-notations"><strong>How to Write a Castling Notation in Algebraic Chess Notations</strong></h3>
<p>In a chess game, castling can either be to the kingside or queenside. Kingside castling is denoted using O-O, while queenside castling is denoted using O-O-O. Note that the symbol is not a zero. Rather, it's an O, as in <strong>o</strong>range.</p>
<h3 id="heading-how-to-write-a-capture-move-in-algebraic-chess-notations"><strong>How to Write a Capture Move in Algebraic Chess Notations</strong></h3>
<p>Capture moves are denoted using the x symbol. Here are some different variations:</p>
<ul>
<li><p>Qxg6 means that the queen captured a piece on g6.</p>
</li>
<li><p>Qxg6+ means that the queen captured a piece on g6 and checked the king.</p>
</li>
<li><p>Qxg8# means that the queen captured a piece on g8 and checkmated the king.</p>
</li>
<li><p>dxe4 mean that a pawn captured a piece on e4.</p>
</li>
</ul>
<p>In a case where you have two pieces that can move to the same square, you have to include the file of the piece that was moved. Here's an example:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1755278931250/f8345127-37c3-4b34-aa72-67f625a7d8af.png" alt="two knights attacking a rook on g8" class="image--center mx-auto" width="1084" height="1084" loading="lazy"></p>
<p>In the board above, we have two knights: one on the f-file and another on the h-file. Both knights can capture the rook on g8, and it may be confusing for someone reading your notations if you don't specify which knight was moved.</p>
<p>To denote this, you have to add the file from where the knight was moved in your notation. So, if you capture with the knight on the f-file, you'd have Nfxg8 (knight on f-file captured a piece on g8). On the other hand, capturing with the knight on the h-file will result to a notation like this: Khxg8.</p>
<p>This is not only specific to capturing pieces. If you have two knights that can move to the same square, then you'd have to include the previous file of whichever knight that is moved. So, assuming that we didn't have a rook to capture on g8, you'd have Nfg8 to denote that the knight on f-file moved to g8, and Nhg8 to denote that the knight on the h-file moved to g8.</p>
<h3 id="heading-how-to-denote-piece-promotion-in-algebraic-chess-notations"><strong>How to Denote Piece Promotion in Algebraic Chess Notations</strong></h3>
<p>You can use the = symbol to denote the promotion of a pawn. That is:</p>
<ul>
<li><p>e8=Q means that pawn moved to e8 and got promoted to a queen.</p>
</li>
<li><p>e8=Q+ means that pawn moved to e8, got promoted to queen, and checked the king.</p>
</li>
<li><p>e8=Q# means that pawn moved to e8, got promoted to queen, and checkmated the king.</p>
</li>
<li><p>e8=N means that pawn moved to e8 and got promoted to a knight.</p>
</li>
</ul>
<p>Here are two exercises for you:</p>
<ul>
<li><p>How do you write the notation if a pawn moves to d1 and gets promoted to a rook?</p>
</li>
<li><p>How do you write the notation if a pawn moves to b8 and gets promoted to a bishop?</p>
</li>
</ul>
<p>And here's the main exercise for this chapter. Show the final board position using these notations:</p>
<ol>
<li><p>e4 e5</p>
</li>
<li><p>Nf3 Nc6</p>
</li>
<li><p>Bb5 Nf6</p>
</li>
<li><p>O-O Nxe4</p>
</li>
<li><p>Re1 Nd6</p>
</li>
<li><p>Nxe5 Be7</p>
</li>
<li><p>Bf1 Nxe5</p>
</li>
<li><p>Rxe5 O-O</p>
</li>
<li><p>d4 Bf6</p>
</li>
<li><p>Re1 Re8</p>
</li>
<li><p>c3 Rxe1</p>
</li>
<li><p>Qxe1 Nf5</p>
</li>
<li><p>Bf4 d6</p>
</li>
<li><p>a4 Qe7</p>
</li>
<li><p>Na3 g5</p>
</li>
<li><p>Bd2 Qxe1</p>
</li>
<li><p>Rxe1 Bd7</p>
</li>
<li><p>a5 Kg7</p>
</li>
</ol>
<h2 id="heading-chapter-2-checkmate-patterns-for-beginners">Chapter 2: <strong>Checkmate Patterns for Beginners</strong></h2>
<p>Before we look at the common checkmate patterns, let's talk a bit about what a check means. We'll do this using the attack pattern or capture method of the pieces.</p>
<h3 id="heading-what-is-a-check-and-checkmate-in-chess"><strong>What is a Check and Checkmate in Chess?</strong></h3>
<p>The main goal of a standard chess match is to capture your opponent's king. You can do this in multiple ways, with different combinations of pieces.</p>
<p>A check is simply an attack on a king. When the king is in check, it must move to a safe square. A safe square for a king in chess is a square where the king is not under attack.</p>
<p>This is an example of a check:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1755279141941/1374098d-5c8b-4440-8a4f-724743312b39.png" alt="queen check" class="image--center mx-auto" width="760" height="756" loading="lazy"></p>
<p>The king in the image above is being threatened by the queen. You can deliver checks based on how a piece moves and captures other pieces. A rook can deliver a check like this:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1755279158250/f0c4ce08-5c36-40ab-b4b5-7fe629b36c56.png" alt="rook check" class="image--center mx-auto" width="760" height="755" loading="lazy"></p>
<p>A bishop can deliver a check like this:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1755279174540/cd241bae-1c07-4ba8-a1b9-ecc732102ed3.png" alt="bishop check" class="image--center mx-auto" width="758" height="758" loading="lazy"></p>
<p>Same applies to the knights and pawns – they can check the king based on their movement and mode of attack.</p>
<p>So what is a checkmate? Well, a checkmate happens when the opponent's king has no safe squares to move to after a check. This can be the result of the king being trapped by its own pieces, the king being unable to move to another square because its opponent has control of all the possible squares it can move to, or not having any piece to block the attack on the king.</p>
<p>In this sections that follow, you'll learn about different checkmate patterns using a combination of different pieces.</p>
<h3 id="heading-checkmate-patterns"><strong>Checkmate Patterns</strong></h3>
<h4 id="heading-how-to-play-the-two-rooks-vs-king-checkmate-pattern">How to Play the Two Rooks vs King Checkmate Pattern</h4>
<p>This endgame pattern usually involves two rooks against a king. It is one of the easiest checkmate patterns, but it's also easy to get carried away as a beginner. Here, you'll learn how to effectively mate and end a game with two rooks.</p>
<p>Consider this position:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1755279449474/be39b6e4-7816-4717-b17a-534f36c7f9bd.png" alt="two rooks against a king endgame" class="image--center mx-auto" width="760" height="763" loading="lazy"></p>
<p>White can end this game in six moves. Here are some things to keep in mind when you have a position like this:</p>
<ul>
<li><p>Restrict the opposing king's movement by cutting off squares where it can move to.</p>
</li>
<li><p>Keep your rooks away from the opposing king or/and close to each other.</p>
</li>
</ul>
<p>Let's see how each step works using the position above.</p>
<p><strong>Restrict the King:</strong></p>
<p>Looking at the initial position above, you can see that the king is on the f-file. Our goal here is to isolate the king and restrict its movement. One common move for beginners would be to check the king with Rf2+. But this allows the king to move closer to the rook on d4. That is:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1755279474239/1a1b715c-09f0-4fc4-9cac-d1f47e48e746.png" alt="two rooks against a king endgame" class="image--center mx-auto" width="757" height="760" loading="lazy"></p>
<p>While this is still a winning position, you'll spend more moves trying to restrict the king's movement. If you're playing a timed game, you may end up with a forced draw, losing a rook, or even losing the game, depending on the pieces on the board. This makes it important to know where and when to move your rooks.</p>
<p>So, back to the starting position:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1755279507154/dfc85f37-4d5e-45fe-8246-7adb8e5cae7e.png" alt="two rooks against a king endgame" class="image--center mx-auto" width="760" height="763" loading="lazy"></p>
<ol>
<li>Re2 Kf5.</li>
</ol>
<p>Playing Re2 cuts off the e-file, meaning that the black king can no longer get on any square in that file. Since the king can not pass through or get on the e-file, it means that the a to e files have become inaccessible to it. It is now left with the f to h files.</p>
<p>The king responds with Kf5, an attempt to get closer and capture a rook. At this point, you'd want to stay away from the king.</p>
<p><strong>Move Your Rooks Away From The King:</strong></p>
<p>This is the current position:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1755279519416/6635d2ec-2781-48c7-823b-fe8ab3317c5a.png" alt="two rooks against a king endgame" class="image--center mx-auto" width="760" height="757" loading="lazy"></p>
<p>Be careful not to play Re5+, confusing the d-rook for a supporting queen. This forces you into a one rook and king checkmate endgame (you'll learn about that in the next section) after Kxe5. This is a better move:</p>
<ol start="2">
<li>Rd8</li>
</ol>
<p>Which brings us to this position:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1755279554729/5938f427-2a49-47f9-9346-9ab589e8b4b3.png" alt="two rooks against a king endgame" class="image--center mx-auto" width="760" height="760" loading="lazy"></p>
<p>This keeps your rooks far away from the black king. Since the king is limited to one square per move, it'll have a long way to go before getting close to either rook. And in the process of getting close, you can continue limiting which files it can get on.</p>
<p>The king has five possible moves here: Kf6, Kf4, Kg6, Kg5, Kg4. The only thing these moves have in common is that they lead to nowhere. But let's assume the black king has some sort of miracle to perform here.</p>
<ol start="2">
<li>... Kg6</li>
</ol>
<p>The king moving to g6 gives you the opportunity to occupy the f-file with:</p>
<ol start="3">
<li>Rf8</li>
</ol>
<p>You have the f-file, but your rook is closer to the king:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1755279573831/174f9c17-4caa-48aa-aad6-11eb83f5e13a.png" alt="two rooks against a king endgame" class="image--center mx-auto" width="760" height="757" loading="lazy"></p>
<ol start="3">
<li>... Kg7</li>
</ol>
<p>The king moves closer to challenge the rook. Unfortunately, a checkmate is still inevitable. At the point, you've not only restricted the files that the king can move to, you've also lured it all the way to the seventh rank.</p>
<p><strong>Keep Your Rooks Closer to Each Other:</strong></p>
<ol start="4">
<li>Rf1</li>
</ol>
<p>With one rook on f1 and the other on e2, you're far away from the king and have both rooks closer to each other:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1755279765163/b4dd7a02-0356-484d-be33-9ae1b0d1353d.png" alt="two rooks against a king endgame" class="image--center mx-auto" width="757" height="759" loading="lazy"></p>
<p>With this position, it will take the king at least four moves to get to your rooks.</p>
<ol start="4">
<li>... Kg6</li>
</ol>
<p>All that's left is to do now is keep pushing the king away from accessing other files:</p>
<ol start="5">
<li>Rg2+</li>
</ol>
<p>Checking the king with the g-rook forces it to the h-file. Since you have a rook occupying the e-file, the king can’t go there.</p>
<ol start="5">
<li><p>... Kh5</p>
</li>
<li><p>Rh1#</p>
</li>
</ol>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1755279786015/3ba53269-7129-44e0-b3bd-2e994a8e9ef5.png" alt="two rooks against a king checkmate" class="image--center mx-auto" width="878" height="757" loading="lazy"></p>
<p>There are multiple ways to checkmate the king from the starting position, and in some cases, you may already have enough space to bring your rooks together and trap the king, instead of trying to restrict it to a part of the board first.</p>
<p>Consider this position:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1755279798809/e3cdade1-b363-4aef-9d45-f34f6b56143f.png" alt="two rooks against a king endgame" class="image--center mx-auto" width="763" height="760" loading="lazy"></p>
<p>The black king is already in a bad position. If you move the b-rook to b6, the game ends after Ra7+ and Rb8#. This did not require you to restrict the king.</p>
<p>Another thing to keep in mind is that your rooks must not always be close to each other to win games like this. Here's another position:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1755279808479/26e2581f-b0ee-431a-8d85-ef7d86773e36.png" alt="two rooks against a king endgame" class="image--center mx-auto" width="761" height="758" loading="lazy"></p>
<p>Here, the king is already limited to only the sixth and seventh rank, and you have enough squares/space between it and the rooks to win. There’s no need to avoid the king by moving one rook to a different part of the board.</p>
<p>Playing Rh7+ forces the king into the eighth rank and Ra8# checkmates the king.</p>
<p>You'll also notice that the white king did not participate in these moves. Its contribution was staying out of the way of the rooks. In some cases, the king can be helpful in delivering a checkmate. But if it'll block your rooks from restricting an enemy king, then you should keep your king away.</p>
<p>Here's a replay of the moves, along with the notations:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1755280037181/5409f0bd-e3ca-4471-b293-8f254bc07116.gif" alt="replay of all moves in two rooks against a king endgame" class="image--center mx-auto" width="758" height="758" loading="lazy"></p>
<ol>
<li><p>Re2 Kf5</p>
</li>
<li><p>Rd8 Kg6</p>
</li>
<li><p>Rf8 Kg7</p>
</li>
<li><p>Rf1 Kg6</p>
</li>
<li><p>Rg2+ Kh5</p>
</li>
<li><p>Rh1#</p>
</li>
</ol>
<p>You can replicate them on your own if you weren't doing so already, and practice with the positions provided below.</p>
<h4 id="heading-practice-position-for-two-rooks-vs-king-endgamecheckmate-pattern">Practice Position for Two Rooks vs King Endgame/Checkmate Pattern</h4>
<p>You can practice what you've learned in the last section using this position:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1755280062216/a673f5b1-a0a6-4a90-9432-c52ce3ce9109.png" alt="practice position" class="image--center mx-auto" width="759" height="758" loading="lazy"></p>
<p>I’ve set up the position for you here: <a target="_blank" href="https://lichess.org/editor/1r4k1/8/8/5r2/8/3K4/8/8_b_-_-_0_1?color=black">https://lichess.org/editor/1r4k1/8/8/5r2/8/3K4/8/8_b_-_-_0_1?color=black</a>. Click on the link, then click on “CONTINUE FROM HERE” to practice the position against an engine.</p>
<h3 id="heading-how-to-play-the-king-and-rook-vs-king-checkmate-pattern"><strong>How to Play the King and Rook vs King Checkmate Pattern</strong></h3>
<p>Before we talk about how to win this game, you need to learn about the concept of "direct opposition". This happens when two kings are facing each other on the same file or rank, with exactly one square between them. That is:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1755280143703/c5eae79f-8e20-40a0-847b-d63f3566d361.png" alt="kings in direct opposition " class="image--center mx-auto" width="760" height="762" loading="lazy"></p>
<p>The kings in the image above are facing each other, have one square between them, and are both on the d-file. Both kings are in direct opposition.</p>
<p>Here's another example:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1755280152482/04514349-1f19-4c7b-a2be-e1fce2e74a7b.png" alt="kings in direct opposition " class="image--center mx-auto" width="757" height="758" loading="lazy"></p>
<p>The kings are still facing each other, they also have a square between them, but are now on the seventh rank. There are other forms of opposition like the diagonal and distant opposition, but we won't discuss them here.</p>
<p>So why does direct opposition matter in our current position? Well, let's look at how the king moves.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1755280163774/098b5c89-946c-4483-9ad6-efb6fe018730.png" alt="all possible king moves" class="image--center mx-auto" width="759" height="759" loading="lazy"></p>
<p>The black king, in the image above, can move to all the squares with a circle on them. Now, here's what happens when the king is in direct opposition with the other king.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1755280176802/87880756-f232-46db-a978-c415032eec8c.png" alt="all possible king moves when in direct opposition " class="image--center mx-auto" width="758" height="757" loading="lazy"></p>
<p>Now the black king has lost the ability to move to three squares in the direction of the opposition. This also implies that the black king, using the position in the image above, no longer has access to the fourth rank. So playing Ra5+ forces the black king to move to the sixth rank, restricting it, and allowing the white king to come closer and set up another direct opposition.</p>
<p>This is one way of winning with a rook and a king. An alternative method is the box method, which we'll look at later in this section. Both techniques can be used together, but I think it would be helpful to learn them separately at first.</p>
<h4 id="heading-how-to-use-the-direct-opposition-to-win-with-a-rook-and-a-king">How to Use the Direct Opposition to Win with a Rook and a King</h4>
<p>Here's our starting position:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1755280196692/c088d0a3-fdcb-4156-8cdb-359661d32b3e.png" alt="rook and king vs king" class="image--center mx-auto" width="760" height="760" loading="lazy"></p>
<ol>
<li>Rb5+</li>
</ol>
<p>Forcing the black king to the sixth rank.</p>
<ol>
<li>... Kd6</li>
</ol>
<p>Now the king is trying to get closer and attack your rook, so you have to bring your own king closer for support.</p>
<ol start="2">
<li>Kd4 Ke6</li>
</ol>
<p>Creating direct opposition. If the black king moves backwards (seventh rank), it loses the opportunity to pass through or be on the sixth rank. If it moves to c6, it'll have fewer squares to work with. So the best move for the black king would be Ke6.</p>
<p>Now we'll use something called the box method - a technique used when playing with a rook and a king to shrink the space where the opposing king can move in. This is the current position of the game:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1755280211256/8cfe2105-00b6-48cb-a630-07dd70708c64.png" alt="rook and king vs king" class="image--center mx-auto" width="763" height="757" loading="lazy"></p>
<ol start="3">
<li>Rd5</li>
</ol>
<p>This move blocks the black king from moving to the d-file and forces it into a box that will gradually shrink if you make the right moves. Here:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1755280223698/21ddcb13-a973-4e0b-a230-e61d12b5b52c.png" alt="rook and king vs king" class="image--center mx-auto" width="760" height="759" loading="lazy"></p>
<p>The image above shows squares where the black king has been trapped in. The best move for the black king would be Kf6. Playing Ke7 or Kf7 would allow the white king to move closer. Remember, this is a lost position for black, but if you play against an opponent who wants to rely on luck to force a draw through a stalemate or timeout, then knowing exactly where to move your rook becomes very important.</p>
<p>Also, checks with the rook will do you no good in this position. If you check the king with Re5+, then the king will just escape to the d-file. So when you're this close to the opposing king:</p>
<ol start="3">
<li><p>... Kf6</p>
</li>
<li><p>Re5 Kf7</p>
</li>
<li><p>Kd5 Kf6</p>
</li>
</ol>
<p>The black king has gotten closer to your rook again. If you check it, it escapes through the fifth rank. When you have all three pieces in a similar position, move your king instead of a check. This forces the opposing king to remain boxed in.</p>
<ol start="6">
<li><p>Kd6 Kf7</p>
</li>
<li><p>Rf5+ Kg6</p>
</li>
<li><p>Ke6</p>
</li>
</ol>
<p>Providing support to the rook and ensuring that the black king remains in a smaller space. This is what the box looks like now:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1755280233810/fc4df6f2-0355-42ce-82c4-daba5c30fbfd.png" alt="rook and king vs king" class="image--center mx-auto" width="758" height="757" loading="lazy"></p>
<ol start="8">
<li><p>... Kg7</p>
</li>
<li><p>Rg5+ Kh6</p>
</li>
<li><p>Kf6 Kh7</p>
</li>
<li><p>Rh5+ Kg8</p>
</li>
<li><p>Rh6 Kf8</p>
</li>
<li><p>Rh8#</p>
</li>
</ol>
<p>Here are things to keep in mind when playing with a king and rook against a king:</p>
<ul>
<li><p>Cut off the enemy king with your rook.</p>
</li>
<li><p>Bring your king closer to support the rook and push the enemy king.</p>
</li>
<li><p>Shrink the box using the two points above.</p>
</li>
<li><p>Force the king to the edge of the board (first rank, eight rank, a-file, h-file). Checkmate is only possible when the enemy king is at the edge of the board and in opposition with your king.</p>
</li>
</ul>
<p>This can be overwhelming for beginners, so don't worry if you don't fully understand the process from start to finish. With constant practice, it should become easier and faster for you to recognize the patterns. I'll also provide some puzzles to help you practice.</p>
<p>Here's a replay of all the move and the notations:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1755280265687/7a572c0c-d47f-422f-ae44-b01e82f42892.gif" alt="rook and king vs king replay" class="image--center mx-auto" width="762" height="758" loading="lazy"></p>
<ol>
<li><p>Rb5+ Kd6</p>
</li>
<li><p>Kd4 Ke6</p>
</li>
<li><p>Rd5 Kf6</p>
</li>
<li><p>Re5 Kf7</p>
</li>
<li><p>Kd5 Kf6</p>
</li>
<li><p>Kd6 Kf7</p>
</li>
<li><p>Rf5+ Kg6</p>
</li>
<li><p>Ke6 Kg7</p>
</li>
<li><p>Rg5+ Kh6</p>
</li>
<li><p>Kf6 Kh7</p>
</li>
<li><p>Rh5+ Kg8</p>
</li>
<li><p>Rh6 Kf8</p>
</li>
<li><p>Rh8#</p>
</li>
</ol>
<h4 id="heading-practice-position-for-one-rook-and-king-vs-king-endgamecheckmate-pattern">Practice Position for One Rook and King vs King Endgame/Checkmate Pattern</h4>
<p>You can practice what you learned in the last section using this position:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1755280281748/0c091532-cb0d-4e62-8189-f51fbfd01d63.png" alt="rook and king vs king" class="image--center mx-auto" width="759" height="758" loading="lazy"></p>
<p>I’ve set up the position for you here: <a target="_blank" href="https://lichess.org/editor/6k1/8/8/5r2/8/3K4/8/8_b_-_-_0_1?color=black">https://lichess.org/editor/6k1/8/8/5r2/8/3K4/8/8_w_-_-_0_1?color=black</a>. Click on the link, then click on “CONTINUE FROM HERE” to practice the position against an engine.</p>
<h3 id="heading-how-to-play-the-queen-and-king-vs-king-checkmate-pattern">How to Play the Queen and King vs King Checkmate Pattern</h3>
<p>We’ll start with this board:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1755280311736/272b9d25-3b61-4946-a8ec-5c7fd41e6b03.png" alt="queen and king vs king" class="image--center mx-auto" width="760" height="758" loading="lazy"></p>
<p>There are a couple of ways to play endgame like the one in the image above. A lot of beginners struggle with this checkmate pattern because they often end in a stalemate or just chase the king around the board until they or their opponent runs out of time.</p>
<p>We can approach this endgame using the direct opposition and box method like we did in the previous section, but there's a more efficient and straightforward way of winning this position, with minimal effort from your king.</p>
<p>We'll use the knight move method. This implies that your queen should only move to squares that imitate a knight attack on the enemy king. Using this method, you can push the king towards the edge of the board.</p>
<p>Here are the possible squares where the queen can go to in order to imitate a knight attack:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1755280323211/2b3f57e3-7383-4557-907c-b2b8daa5f3bb.png" alt="possible knight attack squares for queen" class="image--center mx-auto" width="760" height="761" loading="lazy"></p>
<p>Let's start with the closest square:</p>
<ol>
<li>... Qd6</li>
</ol>
<p>This brings us to this position:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1755280332247/e23c4fc2-0465-4420-bde5-f7e12164f05a.png" alt="imaginary box for king" class="image--center mx-auto" width="758" height="760" loading="lazy"></p>
<p>We've pushed the king into a box. Now, no matter what the king plays, try to follow up with moves that imitate a knight attack (the L), and do not play a move that allows the king leave the shrinking box.</p>
<ol start="2">
<li>Ke3 Qd5</li>
</ol>
<p>The keeps the king in the box and brings the queen closer.</p>
<ol start="3">
<li><p>Ke2 Qd4</p>
</li>
<li><p>Kf3 Qe5</p>
</li>
</ol>
<p>The box has gotten smaller:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1755280345278/cc544086-1dd8-46ca-a8c3-7adfa7c820bd.png" alt="imaginary box for king shrinks " class="image--center mx-auto" width="760" height="760" loading="lazy"></p>
<p>No checks. No direct opposition. Just follow the king with the queen, as though you were playing as a knight.</p>
<ol start="5">
<li><p>Kf2 Qe4</p>
</li>
<li><p>Kg3 Qf5</p>
</li>
<li><p>Kg2 Qf4</p>
</li>
<li><p>Kg1 Qf3</p>
</li>
<li><p>Kh2 Qg4</p>
</li>
<li><p>Kh1</p>
</li>
</ol>
<p>You've successfully pushed the king to the edge of the box. At this point, don't be in a hurry to play another knight attack move with the queen – this will lead to a stalemate.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1755280354553/a96abe4f-cff0-46cd-98d0-844fa33c2a81.png" alt="queen traps kings at the edge of the board" class="image--center mx-auto" width="759" height="758" loading="lazy"></p>
<p>The queen's job is almost done. The white king only has two squares to move to: h2 and h1. It time to push the black king forward to support the queen in a checkmate. Since you've trapped the white king, it will continue to move between the two possible squares until the black king arrives.</p>
<ol start="10">
<li><p>... Ke7</p>
</li>
<li><p>Kh2 Kf6</p>
</li>
<li><p>Kh1 Kf5</p>
</li>
<li><p>Kh2 Kf4</p>
</li>
<li><p>Kh1 Kf3</p>
</li>
<li><p>Kh2 Qg2#</p>
</li>
</ol>
<p>Here's a replay and all the notations:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1755280366630/10e30dad-f43c-41f1-b3a5-7fca60c3cd4e.gif" alt="replay of queen and king vs king" class="image--center mx-auto" width="758" height="758" loading="lazy"></p>
<ol>
<li><p>... Qd6</p>
</li>
<li><p>Ke3 Qd5</p>
</li>
<li><p>Ke2 Qd4</p>
</li>
<li><p>Kf3 Qe5</p>
</li>
<li><p>Kf2 Qe4</p>
</li>
<li><p>Kg3 Qf5</p>
</li>
<li><p>Kg2 Qf4</p>
</li>
<li><p>Kg1 Qf3</p>
</li>
<li><p>Kh2 Qg4</p>
</li>
<li><p>Kh1 Ke7</p>
</li>
<li><p>Kh2 Kf6</p>
</li>
<li><p>Kh1 Kf5</p>
</li>
<li><p>Kh2 Kf4</p>
</li>
<li><p>Kh1 Kf3</p>
</li>
<li><p>Kh2 Qg2#</p>
</li>
</ol>
<h4 id="heading-practice-position-for-queen-and-king-vs-king-endgamecheckmate-pattern">Practice Position for Queen and King vs King Endgame/Checkmate Pattern</h4>
<p>You can practice what you learned in the last section using this position:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1755280380835/2a9fee98-d091-4320-9ca5-974ebba98b26.png" alt="practice position for queen and king vs king" class="image--center mx-auto" width="759" height="757" loading="lazy"></p>
<p>I’ve set up the position for you here: <a target="_blank" href="https://lichess.org/editor/6k1/8/8/5q2/8/3K4/8/8_w_-_-_0_1?color=black">https://lichess.org/editor/1r4k1/8/8/5r2/8/3K4/8/8_b_-_-_0_1?color=black</a>. Click on the link, then click on “CONTINUE FROM HERE” to practice the position against an engine.</p>
<p>For this position, choose to play as black before starting the game:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1755630967674/d50ef787-4523-48f2-93db-2a8f56825d21.png" alt="choose to play as black" class="image--center mx-auto" width="417" height="698" loading="lazy"></p>
<h3 id="heading-checkmate-patterns-ii">Checkmate Patterns II</h3>
<p>In this section, we’ll deal with checkmate patterns that can happen at any point. That is, you don't have to be in an endgame position/situation to play them.</p>
<p>In some cases, these positions can happen by chance, and in other cases, you have to plan and set them up yourself. The main objective here is to get used to recognizing patterns.</p>
<h4 id="heading-opera-mate">Opera Mate</h4>
<p>An Opera Mate usually involves the following:</p>
<ul>
<li><p>A rook or queen delivering a check along a back rank or file.</p>
</li>
<li><p>A bishop covering a diagonal escape square.</p>
</li>
<li><p>A king trapped by its own pieces or the edge of the board.</p>
</li>
</ul>
<p>Here's an example:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1755280405952/58db2a78-9e42-43e0-a678-2265b4150354.png" alt="opera mate " class="image--center mx-auto" width="761" height="754" loading="lazy"></p>
<p>In the position above, black played Bg7, threatening the white rook. But if we look closely at the position, white can deliver a checkmate by moving to c8.</p>
<p>With Rc8#, the king can't capture the rook because the bishop is protecting it, the king can't move to d7 because the bishop is attacking that square, and unfortunately for the king, its own pawn is blocking it from escaping through e7.</p>
<p>Here's another position:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1755280417490/2d752769-1af0-41df-898c-1fcad3863374.png" alt="opera mate" class="image--center mx-auto" width="760" height="759" loading="lazy"></p>
<p>Let's assume that it's white's turn to play again. Would it still be checkmate if the rook moves to c8? Yes it would – the position hasn’t really changed: the bishop is still protecting the rook on c8 and attacking the d7 square, and the pawn on e7 is still blocking the king.</p>
<p>Let's look at an example from <a target="_blank" href="https://lichess.org/practice/checkmates/checkmate-patterns-iii/PDkQDt6u/YWsqVJDL">Lichess</a>:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1755280441952/97afbd7b-3618-406e-8dab-d441968bc6bd.png" alt="opera mate " class="image--center mx-auto" width="745" height="740" loading="lazy"></p>
<p>This game still looks alive, as though both players are still setting up their strategies. It's black's turn to play. At this point, we'll assume that black has discovered a possible opera mate.</p>
<p>The black bishop is attacking the d1 and e2 squares, while the queen can check the king on d1, with additional support from the rook on d8. But, a closer look will reveal something: white has a bishop protecting the d1 square.</p>
<p>So, do you go on to attack or play it safe and find a different strategy? Well, let's evaluate the position, keeping the d1 square in mind.</p>
<p>For black:</p>
<ul>
<li><p>Queen can attack d1.</p>
</li>
<li><p>Rook can support and attack d1.</p>
</li>
<li><p>Bishop can support d1.</p>
</li>
</ul>
<p>For white:</p>
<ul>
<li>Bishop is protecting d1.</li>
</ul>
<p>From this evaluation, you can see that black has a very good advantage. In order to win this game, you must sacrifice the queen. Beginners often avoid sacrifices because we learn chess with the idea that the most power pieces must stay on the board. In this case, it’s the only path to victory.</p>
<p>So:</p>
<ol>
<li>... Qd1+</li>
</ol>
<p>That brings us to this position:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1755280458519/e67e476d-f79e-48e1-9d2f-edfa332d8db1.png" alt="opera mate" class="image--center mx-auto" width="746" height="742" loading="lazy"></p>
<p>Black has two options here:</p>
<ul>
<li><p>Capture the queen with the bishop.</p>
</li>
<li><p>Resign.</p>
</li>
</ul>
<p>Let's go with capturing the queen.</p>
<ol start="2">
<li>Bxd1</li>
</ol>
<p>And now, we have this position:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1755280468340/3eb6774d-eda7-47d1-9745-4dcc53dd4a30.png" alt="opera mate" class="image--center mx-auto" width="746" height="741" loading="lazy"></p>
<p>Remember the rook on d8?</p>
<ol start="2">
<li>... Rxd1#</li>
</ol>
<p>The rook captures the bishop and wins the game. The king can't capture the rook because it has support from the bishop on g4, it can't escape through e2 because the bishop is attacking that square, and the pawn on f2 is blocking the king.</p>
<p>This shows that you don't have to play until the endgame to win in chess. If you get better at recognizing patterns, you'd be shocked at how many chances you've missed to increase your advantage or win a game.</p>
<h4 id="heading-anastasias-mate">Anastasia's Mate</h4>
<p>Anastasia's Mate is a checkmate pattern that involves a knight and a queen (or rook) working together to trap the opposing king. It involves the following:</p>
<ul>
<li><p>The rook or queen delivering a check.</p>
</li>
<li><p>The knight blocking the king's escape squares (usually two escape squares).</p>
</li>
<li><p>The opposing king trapped by its own pieces.</p>
</li>
</ul>
<p>Consider this position:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1755280489359/cca92e2e-621f-4f2d-9ead-e491f712f7fc.png" alt="Anastasia's Mate" class="image--center mx-auto" width="759" height="760" loading="lazy"></p>
<p>From the look of things, white has a stronger position. That would be totally true if black didn't have a mate in two opportunity. When black plays Ne2+, it sets up the pattern for Anastasia's mate. That is:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1755280509251/2d9bf314-9ecc-4265-b884-7249d06a277d.png" alt="Anastasia's Mate" class="image--center mx-auto" width="760" height="759" loading="lazy"></p>
<p>The king has two possible squares to move to: h1 and h2.</p>
<ol>
<li><p>... Ne2+</p>
</li>
<li><p>Kh2</p>
</li>
</ol>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1755280547179/a78a17bb-ef6d-42b8-8980-d51a21f93272.png" alt="Anastasia's Mate" class="image--center mx-auto" width="760" height="759" loading="lazy"></p>
<p>Is the king safe?</p>
<ol start="2">
<li>... Rh5#</li>
</ol>
<p>The game ends:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1755280560054/72452d14-636c-4c4e-815f-cf7f324b87ce.png" alt="Anastasia's Mate" class="image--center mx-auto" width="762" height="756" loading="lazy"></p>
<p>The e2 knight blocks the king from going to either g1 or g3, while the rook attacks the h-file. It's easy to miss this pattern for beginners, because we're often used to endgame patterns that involve more "offensive" attacks.</p>
<p>Here's another example from <a target="_blank" href="https://lichess.org/practice/checkmates/checkmate-patterns-i/fE4k21MW/XOkS95uk">Lichess</a>:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1755280572013/ffa7a5bd-2953-4341-a2a3-e1920a7e9133.png" alt="Anastasia's Mate" class="image--center mx-auto" width="746" height="743" loading="lazy"></p>
<p>It's not very obvious that this position leads to an Anastasia's mate. You have a bishop attacking the queen, and the queen can capture it and gain more material advantage. But what happens when you sacrifice the queen by capturing the h7 square?</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1755280583338/a0b9dac7-2b19-4893-8f44-a66e95c11ca8.png" alt="Anastasia's Mate" class="image--center mx-auto" width="759" height="754" loading="lazy"></p>
<p>You've sacrificed the queen to force the king to the h7 square, setting it up for Rh5#.</p>
<p>So, even though you may recognize what the Anastasia's Mate looks like, you may have to intentionally lose some pieces to achieve it. This is also applicable to other aspects of chess. Sacrificing pieces can be a perfect way to force your opponent into dangerous situations.</p>
<h4 id="heading-back-rank-mate">Back Rank Mate</h4>
<p>This is a checkmate pattern that you'll encounter a lot in your chess journey. It involves trapping the king behind the pieces in front of it. That is:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1755280622411/5cba4327-6754-4e2c-94ae-760d34f49230.png" alt="Back Rank Mate" class="image--center mx-auto" width="760" height="754" loading="lazy"></p>
<p>From the image above, you can see the white king trapped behind the three pawns in front of it. To avoid this, you should always remember to create space for your king at some point after castling.</p>
<p>Here's an example from <a target="_blank" href="https://lichess.org/analysis/standard/2r1r1k1/5ppp/8/8/Q7/8/5PPP/4R1K1_w_-_-_0_1?color=white">Lichess</a>:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1755280631436/b1a0ddcc-9573-4415-8084-12462ec5abf0.png" alt="Back Rank Mate" class="image--center mx-auto" width="759" height="757" loading="lazy"></p>
<p>It's white's turn to play, and the black king still has three pieces blocking it. The white queen and the rook are both attacking the e8 square, so you can force an exchange that ends the game:</p>
<ol>
<li><p>Rxe8+ Rxe8</p>
</li>
<li><p>Qxe8#</p>
</li>
</ol>
<p>After the trade, you'll have the queen on e8, forcing a checkmate because the king has nowhere to escape to.</p>
<h4 id="heading-smothered-mate">Smothered Mate</h4>
<p>The smothered mate is a checkmate pattern where a knight delivers mate to the enemy king, which is completely trapped/surrounded (or “smothered”) by its own pieces.</p>
<p>Here's what it looks like:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1755280647104/cb3696e2-aa0f-4114-a8c4-c6d91acded39.png" alt="Smothered Mate" class="image--center mx-auto" width="757" height="759" loading="lazy"></p>
<p>This is a checkmate pattern that shows how powerful the knight can be in endgames. With any other piece, it would be difficult for black to make any significant moves in this situation. But since the knight can jump over pieces when moving and attacking, it can be used in unpredictable ways.</p>
<p>Let's look at an example from <a target="_blank" href="https://lichess.org/practice/checkmates/checkmate-patterns-i/fE4k21MW/UtwzJ9i4">Lichess</a>:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1755280658126/4b53556a-7a96-4e45-9e0b-11ed0c777667.png" alt="Smothered Mate" class="image--center mx-auto" width="759" height="756" loading="lazy"></p>
<p>Again, we'll be sacrificing a piece to gain an advantage. You can sacrifice the white queen with:</p>
<ol>
<li>Qxh7+</li>
</ol>
<p>This forces the black queen to capture:</p>
<ol>
<li>... Qxh7</li>
</ol>
<p>The problem with this is that the king is now trapped:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1755280674697/43bcbd82-1e7b-4b07-b147-63b213ea23cc.png" alt="Smothered Mate" class="image--center mx-auto" width="759" height="755" loading="lazy"></p>
<p>As beginners, it's often easier to capture a powerful piece than to analyze a position for potential mate patterns. It wouldn’t be surprising to see someone new to chess capturing the queen with the knight.</p>
<p>The best move here is Nf7#:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1755280684007/f57d19c2-9072-4cde-b732-93dc5c73a861.png" alt="Smothered Mate" class="image--center mx-auto" width="759" height="758" loading="lazy"></p>
<p>The king is under check and can't escape because it has been trapped by its own pieces.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>The handbook showed you some of the common checkmate patterns in chess. But these are not all of them, and not all checkmate patterns are easy to understand for beginners.</p>
<p>While you improve other aspects of your game like strategy and tactics, opening principles, solving puzzles, and so on, it becomes easier to understand certain concepts that seemed too hard at first.</p>
<p>One way to test your understanding of different concepts is by playing against other people or engines. A good place to do this is on Lichess. It’s free, has an active community, and a ton of tools to help you improve your game.</p>
<p>I hope this handbook has been helpful for you on your chess journey. You can <a target="_blank" href="https://lichess.org/@/IHECHIKARA">find me on Lichess @ IHECHIKARA</a>.</p>
<p>You can <a target="_blank" href="https://youtu.be/1AX7_aPWmbE?si=67txQ7Bc-IHZ0lhW">watch the video version of this handbook here</a>.</p>
<h2 id="heading-exercise-answers">Exercise Answers</h2>
<p>Here are the answers to the exercises and practice positions:</p>
<h4 id="heading-files-a-to-f-exercise">Files a to f Exercise</h4>
<p>The arrow is on the c-file. You can tell by looking at the alphabet that corresponds with the vertical line.</p>
<h4 id="heading-ranks-1-to-8-exercise">Ranks 1 to 8 Exercise</h4>
<p>The arrow is on the eight rank. You can tell by looking at the number that corresponds with the horizontal line.</p>
<h4 id="heading-how-to-denote-piece-promotion-in-algebraic-chess-notation">How to Denote Piece Promotion in Algebraic Chess Notation</h4>
<ul>
<li><p>The notation for a pawn that moves to d1 and gets promoted to a rook is d1=R.</p>
</li>
<li><p>The notation for a pawn that moves to b8 and gets promoted to a bishop d1=B.</p>
</li>
<li><p>Here is the final board position for the given notations:</p>
</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1755632639415/467a3c95-c234-4022-81fd-13867fa6b5ca.png" alt="final position for the given notations in the algebraic chess notations section" class="image--center mx-auto" width="790" height="793" loading="lazy"></p>
<h2 id="heading-practice-position-urls">Practice Position URLs</h2>
<p>Here are the links for all the practice positions:</p>
<ul>
<li><p>Two Rooks vs King Endgame/Checkmate Pattern URL: <a target="_blank" href="https://lichess.org/editor/1r4k1/8/8/5r2/8/3K4/8/8_b_-_-_0_1?color=black">https://lichess.org/editor/1r4k1/8/8/5r2/8/3K4/8/8_b_-_-_0_1?color=black</a>.</p>
</li>
<li><p>One Rook and King vs King Endgame/Checkmate Pattern URL: <a target="_blank" href="https://lichess.org/editor/6k1/8/8/5r2/8/3K4/8/8_b_-_-_0_1?color=black">https://lichess.org/editor/6k1/8/8/5r2/8/3K4/8/8_w_-_-_0_1?color=black</a>.</p>
</li>
<li><p>Queen and King vs King Endgame/Checkmate Pattern URL: <a target="_blank" href="https://lichess.org/editor/6k1/8/8/5q2/8/3K4/8/8_w_-_-_0_1?color=black">https://lichess.org/editor/1r4k1/8/8/5r2/8/3K4/8/8_b_-_-_0_1?color=black</a> (choose to play as black).</p>
</li>
<li><p>Practice many checkmate patterns here: <a target="_blank" href="https://lichess.org/practice/checkmates/checkmate-patterns-i/fE4k21MW/9rd7XwOw">https://lichess.org/practice/checkmates/checkmate-patterns-i/fE4k21MW/9rd7XwOw</a>. Click on “Practice list” to access more patterns.</p>
</li>
</ul>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Checkmate in Chess ]]>
                </title>
                <description>
                    <![CDATA[ Ready to turn your chess advantages into decisive victories? We've just released a new beginner-level course on the freeCodeCamp.org YouTube channel that focuses on the most important phase of the game: the endgame. This course is designed for player... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-checkmate-in-chess/</link>
                <guid isPermaLink="false">68a725840cbb7e6465d8f441</guid>
                
                    <category>
                        <![CDATA[ youtube ]]>
                    </category>
                
                    <category>
                        <![CDATA[ chess ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Beau Carnes ]]>
                </dc:creator>
                <pubDate>Thu, 21 Aug 2025 13:56:20 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1755784539541/bb6f83bc-9236-4fa5-aa5a-2168bf03cda7.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Ready to turn your chess advantages into decisive victories? We've just released a new beginner-level course on the <a target="_blank" href="http://freeCodeCamp.org">freeCodeCamp.org</a> YouTube channel that focuses on the most important phase of the game: the endgame.</p>
<p>This course is designed for players who already know the basics but want to deepen their strategic understanding. You'll learn how to recognize and execute common checkmate patterns, a key skill for increasing your chances of winning.  </p>
<p>Ihechikara Abba teaches this course. He has an ELO rating of 2200, which places him in the top 1% of chess players worldwide.</p>
<p>This course is divided into two main sections to build your skills:  </p>
<ul>
<li><p><strong>Algebraic Chess Notation:</strong> First, you'll master the standard method for recording and communicating chess moves. Understanding notation is essential for studying games and improving your play.  </p>
</li>
<li><p><strong>Endgame and Checkmate Patterns:</strong> The second section covers powerful endgame techniques. You'll learn classic checkmates, including the two-rook endgame, queen and king patterns, Anastasia's Mate, Smothered Mate, and more.  </p>
</li>
</ul>
<p>Watch the full course now on <a target="_blank" href="https://youtu.be/1AX7_aPWmbE">the freeCodeCamp.org YouTube channel</a> (1-hour watch).</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/1AX7_aPWmbE" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Mocking a GraphQL Wrapper around the Universal Chess Interface ]]>
                </title>
                <description>
                    <![CDATA[ By Jeff M Lowery _Photo by [Unsplash](https://unsplash.com/@samuelzeller?utm_source=ghost&utm_medium=referral&utm_campaign=api-credit">Samuel Zeller / <a href="https://unsplash.com/?utm_source=ghost&utm_medium=referral&utmcampaign=api-credit) The Un... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/mocking-a-graphql-wrapper-around-the-universal-chess-interface-1c5bb1acd821/</link>
                <guid isPermaLink="false">66d45f7aa326133d12440a11</guid>
                
                    <category>
                        <![CDATA[ Universal Chess Interface ]]>
                    </category>
                
                    <category>
                        <![CDATA[ chess ]]>
                    </category>
                
                    <category>
                        <![CDATA[ GraphQL ]]>
                    </category>
                
                    <category>
                        <![CDATA[ tech  ]]>
                    </category>
                
                    <category>
                        <![CDATA[ websocket ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Mon, 26 Feb 2018 00:18:20 +0000</pubDate>
                <media:content url="https://cdn-media-2.freecodecamp.org/w1280/5f9caff0740569d1a4cab0de.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Jeff M Lowery</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/04/image-253.png" alt="Image" width="600" height="400" loading="lazy">
_Photo by [Unsplash](https://unsplash.com/@samuelzeller?utm_source=ghost&amp;utm_medium=referral&amp;utm_campaign=api-credit"&gt;Samuel Zeller / &lt;a href="https://unsplash.com/?utm_source=ghost&amp;utm_medium=referral&amp;utm<em>campaign=api-credit)</em></p>
<p>The Universal Chess Interface (UCI) has been around a long time and used by many chess engines. What does GraphQL bring to the mix?</p>
<p>I had some email exchanges with an owner of a chess website recently, and he asked me what I knew about UCI and websockets. That got me looking closer at UCI and thinking about how and why one would wrap a GraphQL schema around it.</p>
<h3 id="heading-the-universal-chess-interface">The Universal Chess Interface</h3>
<p>The UCI has <a target="_blank" href="http://wbec-ridderkerk.nl/html/UCIProtocol.html">been around for over a decade</a>, and is based on standard I/O messaging between a chess engine and its client (usually a graphical UI). The client submits a message to the chess engine, and the engine <strong>may</strong> send back a response. I say <strong>may</strong> because UCI doesn’t require a response for some incoming messages to the chess engine.</p>
<p>The engine also <strong>might</strong> send back more than one response. During game analysis, the engine will be sending back <strong>info</strong> packets detailing it’s thinking. The client says what the start position is, tells it “Go”, and the engine keeps going until it arrives at a <strong>best move.</strong> During the process, the engine streams back messages about what it’s thinking.</p>
<p>The UCI specification is short, and you don’t need a deep understanding of it to see the basics of how it works — and it has worked well so far, so why monkey with it?</p>
<p>If the engine resides on a remote server, then just open a websocket and do as you would normally do. That works, of course, but it doesn’t hurt to look at the pros and cons of doing things slightly differently.</p>
<h3 id="heading-chess-engine-versus-chess-server">Chess Engine versus Chess Server</h3>
<p>I want to start by mocking up a UCI service. A next step will be to build a functional prototype and, as always seems to be the case, its not hard to find a Node.js package that helps with most of the work.</p>
<p>One of the more popular engines is called <a target="_blank" href="https://stockfishchess.org/">Stockfish</a>. Someone has taken the trouble of transpiling it from C++ to JavaScript so that the engine can be run wholly in Node.js.</p>
<p>It’s this simple:</p>
<ul>
<li>create and cd into a folder</li>
<li><code>npm init</code></li>
<li><code>npm install stockfish</code></li>
<li><code>node node_modules/stockfish/src/stockfish.js</code></li>
</ul>
<p>And now you are in a Stockfish command shell, and can start typing in commands.</p>
<p>The first thing to do is to fire up the UCI interface by typing <code>uci</code>. You should get a response like this:</p>
<pre><code>id name Stockfish.js <span class="hljs-number">8</span>
id author T. Romstad, M. Costalba, J. Kiiski, G. Linscott

option name Contempt type spin <span class="hljs-keyword">default</span> <span class="hljs-number">0</span> min <span class="hljs-number">-100</span> max <span class="hljs-number">100</span>
option name Threads type spin <span class="hljs-keyword">default</span> <span class="hljs-number">1</span> min <span class="hljs-number">1</span> max <span class="hljs-number">1</span>
option name Hash type spin <span class="hljs-keyword">default</span> <span class="hljs-number">16</span> min <span class="hljs-number">1</span> max <span class="hljs-number">2048</span>
option name Clear Hash type button
option name Ponder type check <span class="hljs-keyword">default</span> <span class="hljs-literal">false</span>
option name MultiPV type spin <span class="hljs-keyword">default</span> <span class="hljs-number">1</span> min <span class="hljs-number">1</span> max <span class="hljs-number">500</span>
option name Skill Level type spin <span class="hljs-keyword">default</span> <span class="hljs-number">20</span> min <span class="hljs-number">0</span> max <span class="hljs-number">20</span>
option name Move Overhead type spin <span class="hljs-keyword">default</span> <span class="hljs-number">30</span> min <span class="hljs-number">0</span> max <span class="hljs-number">5000</span>
option name Minimum Thinking Time type spin <span class="hljs-keyword">default</span> <span class="hljs-number">20</span> min <span class="hljs-number">0</span> max <span class="hljs-number">5000</span>
option name Slow Mover type spin <span class="hljs-keyword">default</span> <span class="hljs-number">89</span> min <span class="hljs-number">10</span> max <span class="hljs-number">1000</span>
option name nodestime type spin <span class="hljs-keyword">default</span> <span class="hljs-number">0</span> min <span class="hljs-number">0</span> max <span class="hljs-number">10000</span>
option name UCI_Chess960 type check <span class="hljs-keyword">default</span> <span class="hljs-literal">false</span>
option name UCI_Variant type combo <span class="hljs-keyword">default</span> chess <span class="hljs-keyword">var</span> chess <span class="hljs-keyword">var</span> giveaway <span class="hljs-keyword">var</span> atomic <span class="hljs-keyword">var</span> crazyhouse <span class="hljs-keyword">var</span> horde <span class="hljs-keyword">var</span> kingofthehill <span class="hljs-keyword">var</span> racingkings <span class="hljs-keyword">var</span> relay <span class="hljs-keyword">var</span> threecheck
option name Skill Level Maximum <span class="hljs-built_in">Error</span> type spin <span class="hljs-keyword">default</span> <span class="hljs-number">200</span> min <span class="hljs-number">0</span> max <span class="hljs-number">5000</span>
option name Skill Level Probability type spin <span class="hljs-keyword">default</span> <span class="hljs-number">128</span> min <span class="hljs-number">1</span> max <span class="hljs-number">1000</span>
uciok
</code></pre><p>It shows what the option settings are set to and then returns <code>**uciok**</code>, meaning the interface is ready. The next step is to set options and then call <code>**isready**</code>, and when the engine responds <code>**readyok**</code>, it can start analyzing a chess position.</p>
<p>I won’t actually be using this engine for my mock implementation, but it does come in handy if I want to examine what a command does using a real engine.</p>
<p>In a real server implementation, I would be firing up one engine per client (or perhaps more). <a target="_blank" href="http://graphql.org/">GraphQL</a> helps me define an API that would support multiple clients running multiple engines.</p>
<h3 id="heading-graphql">GraphQL</h3>
<p>For this mock, I’ve divide up the UCI component into HTTP requests of a call/response nature, and websocket subscriptions for handling streaming responses. This means that a socket is only open if the user wants to subscribe to detailed information about what the engine is thinking. Furthermore, I can refine the number and types of <strong>info</strong> messages I receive on the client, so that socket traffic is minimized.</p>
<h4 id="heading-each-command-gets-a-response"><strong>Each command gets a response</strong></h4>
<p>Because client-server interaction is happening (in most cases) over unreliable HTTP, it’s important that the client (running on the browser) knows that its message got through to the server. The UCI command <code>**setoption**</code>, for instance, doesn’t send a response back according to the specification.</p>
<p>That’s fine for an interface based on reliable sockets, not so good for HTTP requests. GraphQL ensures that there is a response sent back to every received request, if only to acknowledge that the request was received.</p>
<h4 id="heading-each-command-and-its-arguments-are-type-safe"><strong>Each command and its arguments are type-safe</strong></h4>
<p>GraphQL interfaces are schema-based, UCI interfaces are not (they’re based on descriptive text in the specification). If a client to sends an invalid command, the chess engine server should never have to deal with it. By defining UCI in terms of types in GraphQL, I can waylay an errant command at the API level — in GraphQL — before it gets to the engine.</p>
<h4 id="heading-graphql-resolvers-can-decompose-responses-into-json-structures"><strong>GraphQL resolvers can decompose responses into JSON structures</strong></h4>
<p>JavaScript is the language of the internet, and GraphQL returns JSON responses. By having the GraphQL resolvers take a UCI response and break it down in a fine-grained and structured way, the client is alleviated of the UCI response parsing task.</p>
<h4 id="heading-i-can-easily-mock-my-api-using-apollo-graphql-tools"><strong>I can easily mock my API using Apollo GraphQL Tools</strong></h4>
<p>After designing an API, but before heading off to implementation land, it’s useful to first check the API look and feel of using mocks. The <a target="_blank" href="https://github.com/apollographql/graphql-tools">graphql-tools</a> package makes <a target="_blank" href="https://medium.freecodecamp.org/mocking-graphql-with-graphql-tools-42c2dd9d0364">this easy and painless</a>. You can even mix mocks with real resolvers, giving you the option of iterative implementation of your API.</p>
<h4 id="heading-i-can-interact-with-the-api-through-the-graphiql-service">I can interact with the API through the GraphiQL service</h4>
<p><a target="_blank" href="https://github.com/graphql/graphiql">Graph<strong>i</strong>QL</a> is the interactive service that can be run atop a GraphQL server. This is convenient for doing ad hoc testing of the API, based on either a mock or implementation.</p>
<h3 id="heading-on-to-the-mocking">On to the Mocking!</h3>
<p>Let’s take a look at the dependencies first:</p>
<pre><code class="lang-json"><span class="hljs-string">"dependencies"</span>: {
    <span class="hljs-attr">"apollo-server-express"</span>: <span class="hljs-string">"^1.3.2"</span>,
    <span class="hljs-attr">"babel-cli"</span>: <span class="hljs-string">"^6.26.0"</span>,
    <span class="hljs-attr">"babel-preset-env"</span>: <span class="hljs-string">"^1.6.1"</span>,
    <span class="hljs-attr">"express"</span>: <span class="hljs-string">"^4.16.2"</span>,
    <span class="hljs-attr">"graphql"</span>: <span class="hljs-string">"^0.12.3"</span>,
    <span class="hljs-attr">"graphql-subscriptions"</span>: <span class="hljs-string">"^0.5.7"</span>,
    <span class="hljs-attr">"graphql-tag"</span>: <span class="hljs-string">"^2.7.3"</span>,
    <span class="hljs-attr">"graphql-tools"</span>: <span class="hljs-string">"^2.21.0"</span>,
    <span class="hljs-attr">"stockfish"</span>: <span class="hljs-string">"^8.0.0"</span>,
    <span class="hljs-attr">"subscriptions-transport-ws"</span>: <span class="hljs-string">"^0.9.5"</span>
  },
  <span class="hljs-string">"devDependencies"</span>: {
    <span class="hljs-attr">"casual"</span>: <span class="hljs-string">"^1.5.19"</span>,
    <span class="hljs-attr">"randexp"</span>: <span class="hljs-string">"^0.4.8"</span>
  },
</code></pre>
<p>I’m calling this server <strong>chessQ</strong>, and the server itself will be based on <code>**apollo-server-express**</code>, the Apollo Group’s GraphQL server implementation. The <code>**stockfish.js**</code> package, mentioned earlier, is included as an embedded engine. Though this mock doesn’t use it, it’s there for reference. In a real implementation, one would probably <a target="_blank" href="https://www.npmjs.com/package/node-uci">access an externally running engine</a>.</p>
<p>Included is <code>casual</code> and <code>randexp</code> for helping with the mocks. Finally, <code>**graphql-subscriptions**</code> and <code>**subscriptions-transport-ws**</code> will handle the streaming messages coming back from our mock while it is pretending to analyze.</p>
<h3 id="heading-the-chessq-schema">The chessQ schema</h3>
<p>Let me first say that I haven’t spent time polishing up the schema, so consider it a first draft. It’s functional, but it will probably change as I continue to develop it. At the end of this article, I’ll link to a stable branch that corresponds to what is described here. I won’t be going into painstaking detail on the code, but will link to relevant source in GitHub where appropriate. Watch for those.</p>
<p>First thing is to define <a target="_blank" href="https://github.com/JeffML/chessQ/blob/chessQ-mock/schema.js">the top-level queries</a>. These are the entry points for the client:</p>
<pre><code class="lang-js">type Query {
    <span class="hljs-attr">createEngine</span>: EngineResponse
    uci(engineId: <span class="hljs-built_in">String</span>!): UciResponse!
    register(engineId: <span class="hljs-built_in">String</span>!, name: <span class="hljs-built_in">String</span>, <span class="hljs-attr">code</span>: <span class="hljs-built_in">String</span>): <span class="hljs-built_in">String</span>
    registerLater(engineId: <span class="hljs-built_in">String</span>!): <span class="hljs-built_in">String</span>
    setSpinOption(engineId: <span class="hljs-built_in">String</span>!, name: <span class="hljs-built_in">String</span>!, value: Int!): <span class="hljs-built_in">String</span>!
    setButtonOption(engineId: <span class="hljs-built_in">String</span>!, name: <span class="hljs-built_in">String</span>!): <span class="hljs-built_in">String</span>!
    setCheckOption(engineId: <span class="hljs-built_in">String</span>!, name: <span class="hljs-built_in">String</span>!, value: <span class="hljs-built_in">Boolean</span>!): <span class="hljs-built_in">String</span>!
    setComboOption(engineId: <span class="hljs-built_in">String</span>!, name: <span class="hljs-built_in">String</span>!, value: <span class="hljs-built_in">String</span>!): <span class="hljs-built_in">String</span>!
    quit(engineId: <span class="hljs-built_in">String</span>!): <span class="hljs-built_in">String</span>!
    isready(engineId: <span class="hljs-built_in">String</span>!): <span class="hljs-built_in">String</span>!
  }
</code></pre>
<p>The <code>createEngine</code> request will return an <a target="_blank" href="https://github.com/JeffML/chessQ/blob/chessQ-mock/readySchema.js">EngineResponse</a>, inside of which is an engine instance identifier that is used for subsequent requests:</p>
<pre><code class="lang-json">{
  <span class="hljs-attr">"data"</span>: {
    <span class="hljs-attr">"createEngine"</span>: {
      <span class="hljs-attr">"engineId"</span>: <span class="hljs-string">"46d89031-03c3-4851-ae97-34e4b5d1d7c6"</span>
    }
  }
}
</code></pre>
<p>The <code>**uci**</code> request will return a <a target="_blank" href="https://github.com/JeffML/chessQ/blob/chessQ-mock/optionsSchema.js">UciResponse</a> detailing the current option settings. In the GraphQL schema, each type of option (spin, check, button, and combo) has its own specific fields:</p>
<pre><code class="lang-graphql"><span class="hljs-keyword">interface</span> Option {
    <span class="hljs-symbol">name:</span> String!
    <span class="hljs-symbol">type:</span> String!
  }

<span class="hljs-keyword">type</span> SpinOption <span class="hljs-keyword">implements</span> Option {
    <span class="hljs-symbol">name:</span> String!
    <span class="hljs-symbol">type:</span> String!
    <span class="hljs-symbol">value:</span> Int!
    <span class="hljs-symbol">min:</span> Int!
    <span class="hljs-symbol">max:</span> Int!
  }

<span class="hljs-keyword">type</span> ButtonOption <span class="hljs-keyword">implements</span> Option {
    <span class="hljs-symbol">name:</span> String!
    <span class="hljs-symbol">type:</span> String!
  }

<span class="hljs-keyword">type</span> CheckOption <span class="hljs-keyword">implements</span> Option {
    <span class="hljs-symbol">name:</span> String!
    <span class="hljs-symbol">type:</span> String!
    <span class="hljs-symbol">value:</span> Boolean!
  }

<span class="hljs-keyword">type</span> ComboOption <span class="hljs-keyword">implements</span> Option {
    <span class="hljs-symbol">name:</span> String!
    <span class="hljs-symbol">type:</span> String!
    <span class="hljs-symbol">value:</span> String!
    <span class="hljs-symbol">options:</span> [String!]!
  }
</code></pre>
<p>A mock <code>uci query</code> might be:</p>
<pre><code class="lang-graphql"><span class="hljs-keyword">query</span> uci {
  uci(<span class="hljs-symbol">engineId:</span> <span class="hljs-string">"46d89031-03c3-4851-ae97-34e4b5d1d7c6"</span>) {
    uciokay
    options {
      name
      <span class="hljs-keyword">type</span>
      <span class="hljs-punctuation">... </span><span class="hljs-keyword">on</span> SpinOption {
        value
        min
        max
      }
    }
  }
}
</code></pre>
<p>and the response:</p>
<pre><code class="lang-json">{
  <span class="hljs-attr">"data"</span>: {
    <span class="hljs-attr">"uci"</span>: {
      <span class="hljs-attr">"uciokay"</span>: <span class="hljs-literal">true</span>,
      <span class="hljs-attr">"options"</span>: [
        {
          <span class="hljs-attr">"name"</span>: <span class="hljs-string">"Porro tempora minus"</span>,
          <span class="hljs-attr">"type"</span>: <span class="hljs-string">"check"</span>
        },
        {
          <span class="hljs-attr">"name"</span>: <span class="hljs-string">"Id ducimus"</span>,
          <span class="hljs-attr">"type"</span>: <span class="hljs-string">"combo"</span>
        },
        {
          <span class="hljs-attr">"name"</span>: <span class="hljs-string">"Aliquam voluptates"</span>,
          <span class="hljs-attr">"type"</span>: <span class="hljs-string">"button"</span>
        },
        {
          <span class="hljs-attr">"name"</span>: <span class="hljs-string">"Voluptatibus illo ullam"</span>,
          <span class="hljs-attr">"type"</span>: <span class="hljs-string">"spin"</span>,
          <span class="hljs-attr">"value"</span>: <span class="hljs-number">109</span>,
          <span class="hljs-attr">"min"</span>: <span class="hljs-number">0</span>,
          <span class="hljs-attr">"max"</span>: <span class="hljs-number">126</span>
        },
        {
          <span class="hljs-attr">"name"</span>: <span class="hljs-string">"Temporibus et nisi"</span>,
          <span class="hljs-attr">"type"</span>: <span class="hljs-string">"check"</span>
        }
      ]
    }
  }
}
</code></pre>
<p>Technically, some of these commands could be thought of as Mutations, not Queries, since they change the state of the engine. But Mutations in GraphQL are primarily about sequential order-of-execution and that does not apply in this case: any option can be set in any order.</p>
<p>Ultimately, each engine instance will need to maintain some indication of its <a target="_blank" href="https://github.com/JeffML/chessQ/blob/chessQ-mock/readySchema.js">state</a> (not implemented in this mock). These might be:</p>
<pre><code class="lang-js">enum eEngineState {
    CREATED
    INITIALIZED
    READY
    RUNNING
    STOPPED
  }
</code></pre>
<p>If for instance, a <code>**go**</code> command is sent before the engine state is <code>**READY**</code>, then that would be an error.</p>
<h4 id="heading-the-ready-schema">The Ready Schema</h4>
<p>When the engine is READY, three new commands are possible:</p>
<ul>
<li><code>ucinewgame</code>: tell the engine a new game has started</li>
<li><code>position</code>: tell the engine what the starting position is (along with any moves from that position)</li>
<li><code>go</code>: start the engine!</li>
</ul>
<p>Before issuing the <code>**go**</code> command, the client has the option to subscribe to any <a target="_blank" href="https://github.com/JeffML/chessQ/blob/chessQ-mock/schema.js"><strong>info</strong> messages</a> streaming in through the websocket (otherwise, there will be just a <code>BestMove</code> HTTP response when the engine is finished).</p>
<p>Details on how to set up a subscription service using <a target="_blank" href="https://github.com/apollographql/graphql-subscriptions">graphql-subscriptions</a> can be found elsewhere, so here I will focus on the schema and resolver implementation.</p>
<p>The schema defines the types of <code>Subscriptions</code> available. For this mock, there is just one:</p>
<pre><code class="lang-graphql"><span class="hljs-keyword">type</span> Subscription {
    <span class="hljs-symbol">info:</span> Info
  }
</code></pre>
<p>The <code>Info</code> type, like the <code>Option</code> type, is a union of several specific info structures:</p>
<pre><code class="lang-graphql"><span class="hljs-keyword">type</span> Score {
    <span class="hljs-symbol">cp:</span> Int!
    <span class="hljs-symbol">depth:</span> Int!
    <span class="hljs-symbol">nodes:</span> Int!
    <span class="hljs-symbol">time:</span> Int!
    <span class="hljs-symbol">pv:</span> [Move!]!
  }

<span class="hljs-keyword">type</span> Depth {
    <span class="hljs-symbol">depth:</span> Int!
    <span class="hljs-symbol">seldepth:</span> Int!
    <span class="hljs-symbol">nodes:</span> Int
  }

<span class="hljs-keyword">type</span> Nps {
    <span class="hljs-symbol">value:</span> Int!
  }

<span class="hljs-keyword">type</span> BestMove {
    <span class="hljs-symbol">value:</span> Move!,
    <span class="hljs-symbol">ponder:</span> Move
  }

<span class="hljs-keyword">union</span> Info = Score | Depth | Nps | BestMove
</code></pre>
<p>The precise meaning of these <code>Info</code> messages is irrelevant to this discussion. The important thing is to know that they come in any order, except for the <code>BestMove</code> message, which is last.</p>
<p>The client subscribes to info messages using a <code>subscription</code> request like the following:</p>
<pre><code>subscription sub {
  info {
    ... on Score {
      pv
    }
    ... on BestMove {
      value
    }
  }
}
</code></pre><p>There’s a resolver to handle the <code>Subscription</code> request, which uses methods in the <code>**graphql-subscriptions**</code> package:</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> {PubSub, withFilter} <span class="hljs-keyword">from</span> <span class="hljs-string">'graphql-subscriptions'</span>;
...

resolvers: 
...
Subscription: {
      <span class="hljs-attr">info</span>: {
        <span class="hljs-attr">subscribe</span>: withFilter(<span class="hljs-function">() =&gt;</span> pubsub.asyncIterator(TOPIC), <span class="hljs-function">(<span class="hljs-params">payload, variables</span>) =&gt;</span> {
          <span class="hljs-keyword">return</span> <span class="hljs-literal">true</span>
        })
      }
    }...
</code></pre>
<p>In this subscription resolver, the the function passed to <code>withFilter</code> passes every message back. But a real subscribe resolver could be more discriminating based on parameters passed in by the client.</p>
<h4 id="heading-seeing-it-in-action">Seeing it in action</h4>
<p>You can query, mutate, and subscribe in GraphiQL, so there’s no need to write a client for testing purposes. The one gotcha is that GraphiQL will enter “subscription” mode once a subscription is requested, and won’t happily respond to further commands.</p>
<p>The solution is to have two GraphiQL tabs open in your browser, one for issuing queries and mutations, and the other for listening to subscribed messages.</p>
<p>Download the <a target="_blank" href="https://github.com/JeffML/chessQ/tree/chessQ-mock">chessQ</a> package, run <code>npm install</code> and then <code>npm run dev</code> . The chessQ mock application should now be running.</p>
<p>Open two tabs to <a target="_blank" href="http://localhost:3001/graphiql">http://localhost:3001/graphiql</a>.</p>
<p>In one tab, enter:</p>
<pre><code>subscription sub {
  info {
    __typename
    ... on Score {
      pv
    }
    ... on BestMove {
      value
    }
  }
}
</code></pre><p>You’ll see a message that says:</p>
<pre><code><span class="hljs-string">"Your subscription data will appear here after server publication!"</span>
</code></pre><p><img src="https://cdn-media-1.freecodecamp.org/images/E2xSU2QP22UL1MvOuIqnnlc1ixS6zEU3nSLw" alt="Image" width="643" height="304" loading="lazy">
<em>Ready to receive!</em></p>
<p>To generate messages, there is a <code>**go**</code> resolver (shown below) that iterates through a <a target="_blank" href="https://github.com/JeffML/chessQ/blob/chessQ-mock/InfoGenerator.js">static set of info messages</a> and publishes them one by one. Because the subscriber pane <strong>will only show one message</strong> at a time, there’s a simple <code>sleep</code> implementation that slows down the messaging so that you can see them fly by:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">sleep</span>(<span class="hljs-params">ms</span>) </span>{
  <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function"><span class="hljs-params">resolve</span> =&gt;</span> {
    <span class="hljs-built_in">setTimeout</span>(resolve, ms)
  })
}
...

resolvers: {...

Mutation: {
      <span class="hljs-attr">go</span>: <span class="hljs-keyword">async</span> () =&gt; {
        <span class="hljs-keyword">let</span> info;
        <span class="hljs-keyword">for</span> (info <span class="hljs-keyword">of</span> InfoGenerator()) {
          pubsub.publish(TOPIC, {info})
          <span class="hljs-keyword">await</span> sleep(<span class="hljs-number">1000</span>)
        }
        <span class="hljs-keyword">return</span> info;
      }
    },...
</code></pre>
<p>Finally, in the non-subscription tab, start the analysis with <code>**go**</code>:</p>
<pre><code class="lang-graphql"><span class="hljs-keyword">mutation</span> go {
  go {
    __typename
    value
  }
}
</code></pre>
<p>While this tab is awaiting the <code>go</code> response showing the <code>BestMove</code>, the <code>subscription</code> tab will be catching info messages and displaying them one-by-one.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/Sead--yLEPWQIqOBgZlLM9czMcSB61AgRMxQ" alt="Image" width="800" height="218" loading="lazy">
<em>Info messages coming in…</em></p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/Ag3amWB0PTUL--3UjwwK-96bpH7vEUN5pUAY" alt="Image" width="800" height="214" loading="lazy">
<em>Analysis complete!</em></p>
<h3 id="heading-further-thoughts">Further Thoughts</h3>
<p>Before rolling forth from mock to implementation, a couple of notes:</p>
<p>The simple pub/sub mechanism used in this example is neither robust or scalable. That’s okay, because there are <a target="_blank" href="https://redis.io/">Redis</a> and <a target="_blank" href="https://github.com/cdmbase/graphql-rabbitmq-subscriptions">RabbitMQ</a> implementations of graphql-subscription that are. A more refined subscription specification could also be defined and give fine-grained control to the subscriber as to which messages are received.</p>
<p>Not a lot of thought was given to managing websocket lifetime in this mock, which is something that needs to be considered if serving a large number of users.</p>
<p>All source code for this article can be found <a target="_blank" href="https://github.com/JeffML/chessQ/tree/chessQ-mock">here</a>.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Writing a chess microservice using Node.js and Seneca, Part 3 ]]>
                </title>
                <description>
                    <![CDATA[ By Jeff M Lowery Finishing up a three-part series on writing a rules engine with Seneca microservices. Parts 1 & 2 of this series covered: The Seneca microservices Node.js module How to write a service, how to identify it by pattern and how to call ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/writing-a-chess-microservice-using-node-js-and-seneca-part-3-ab38b8ef9b0a/</link>
                <guid isPermaLink="false">66d45f90ffe6b1f641b5fa19</guid>
                
                    <category>
                        <![CDATA[ chess ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Microservices ]]>
                    </category>
                
                    <category>
                        <![CDATA[ General Programming ]]>
                    </category>
                
                    <category>
                        <![CDATA[ technology ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Mon, 17 Jul 2017 00:12:35 +0000</pubDate>
                <media:content url="https://cdn-media-1.freecodecamp.org/images/1*brvN_0vi3hLWd3YQvvcJrw.jpeg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Jeff M Lowery</p>
<p>Finishing up a three-part series on writing a rules engine with Seneca microservices.</p>
<p>Parts <a target="_blank" href="https://medium.freecodecamp.org/follow-the-rules-with-seneca-b3cf3d08fe5d">1</a> &amp; <a target="_blank" href="https://medium.com/@jefflowery/follow-the-rules-with-seneca-ii-c22074debac">2</a> of this series covered:</p>
<ul>
<li>The Seneca microservices Node.js module</li>
<li>How to write a service, how to identify it by pattern and how to call it</li>
<li>How to string service calls together</li>
<li>How to enhance an existing service</li>
</ul>
<p>Along the way, I pondered what a service should return. I came to the conclusion that returning a data object (JSON in this case) was the most flexible. It allows services to <strong>embellish</strong> the output without affecting existing clients of the service.</p>
<p><strong>Embellish?</strong> By that I mean intermediate results can be maintained as a means of tracking information that might be useful later, to a service not yet written. In the present case, I had a <code>rawMoves</code> service that returned a list of moves. That was immediately sufficient for the clients I had. The service calculated moves along movement vectors, and combined them into a 1-dimensional array.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*BKDwcC-G7LiTG911r56aVQ.gif" alt="Image" width="200" height="200" loading="lazy">
<em>Queen movement vectors</em></p>
<p>Later though, I discovered that those movement vectors would have come in handy when a <code>legalMoves</code> service written later needed to take into account friendly pieces that were blocking movement. Vectors would have made those calculations simpler and more efficient, but they were “tossed out” by the <code>rawMoves</code> service.</p>
<p>To go back and add the vectors (in addition to the move list) meant changing the clients of the original service to accept an object, not an array. True, I could have made the original service stateful, but that would have been overkill. I had a choice: refactor the service and its clients, or <strong>Deal with It™️</strong>. In Part 2, I chose the latter.</p>
<p>Yet in this installment, time has come to refactor. <code>rawMoves</code> now returns <code>{moves, moveVectors}</code>, and the upstream clients of the service can choose what to pay attention to. Care has to be taken, though, that <code>moves</code> and <code>moveVectors</code> are in sync at all times.</p>
<p>Let’s see what the advantage is. In the original code, finding <code>legalMoves</code> was an involved process if given just a piece, move list, and friendly pieces elsewhere on the board (<a target="_blank" href="https://github.com/JeffML/ms-chess2a/blob/master/services/helpers/legalMovesWithBoard.js">example)</a>. Compare that code to one that uses <code>moveVectors</code>:</p>
<pre><code class="lang-js"><span class="hljs-built_in">module</span>.exports = <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">boardAndPiece, candidateMoves</span>) </span>{
    <span class="hljs-keyword">if</span> (!boardAndPiece.board) <span class="hljs-keyword">return</span> candidateMoves;

    <span class="hljs-keyword">const</span> rangeChecks = {
        <span class="hljs-attr">B</span>: vectorChecks,
        <span class="hljs-attr">R</span>: vectorChecks,
        <span class="hljs-attr">K</span>: vectorChecks,
        <span class="hljs-attr">Q</span>: vectorChecks,
        <span class="hljs-attr">P</span>: pawnChecks,
        <span class="hljs-attr">N</span>: knightChecks
    };

    <span class="hljs-keyword">var</span> rangeCheck = rangeChecks[boardAndPiece.piece.piece];
    <span class="hljs-keyword">return</span> rangeCheck(boardAndPiece, candidateMoves)
}

<span class="hljs-comment">//...</span>

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">vectorChecks</span>(<span class="hljs-params">boardAndPiece, candidateMoves</span>) </span>{
    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">const</span> [j, v] <span class="hljs-keyword">of</span> candidateMoves.moveVectors.entries()) {
        <span class="hljs-keyword">for</span> (<span class="hljs-keyword">const</span> [i, m] <span class="hljs-keyword">of</span> v.entries()) {
            <span class="hljs-keyword">const</span> p = boardAndPiece.board.pieceAt(m);
            <span class="hljs-keyword">if</span> (p) {
                <span class="hljs-keyword">if</span> (p.color === boardAndPiece.piece.color) {
                    candidateMoves.moveVectors[j] = v.slice(<span class="hljs-number">0</span>, i);
                    <span class="hljs-keyword">break</span>;
                } <span class="hljs-keyword">else</span> {
                    candidateMoves.moveVectors[j] = v.slice(<span class="hljs-number">0</span>, i + <span class="hljs-number">1</span>);
                    <span class="hljs-built_in">Object</span>.assign(candidateMoves.moveVectors[j].slice(<span class="hljs-number">-1</span>)[<span class="hljs-number">0</span>], {
                        <span class="hljs-attr">hasCaptured</span>: p
                    })
                    <span class="hljs-keyword">break</span>;
                }
            }
        }
    }

    <span class="hljs-keyword">return</span> {
        <span class="hljs-attr">moveVectors</span>: candidateMoves.moveVectors,
        <span class="hljs-attr">moves</span>: <span class="hljs-built_in">Array</span>.prototype.concat(...candidateMoves.moveVectors)
    }
}
</code></pre>
<p>Much, much simpler…and more efficient. The wrapping function is exported and used by the <code>legalMoves</code> <a target="_blank" href="https://github.com/JeffML/ms-chess3/blob/master/services/Movement.js">service</a>.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> legalMovesWithBoard = <span class="hljs-built_in">require</span>(<span class="hljs-string">"./helpers/legalMovesWithBoard"</span>)
<span class="hljs-comment">//...</span>
    <span class="hljs-built_in">this</span>.add(<span class="hljs-string">'role:movement,cmd:legalMoves'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">msg, reply</span>) </span>{
        <span class="hljs-built_in">this</span>.prior(msg, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">err, result</span>) </span>{
            <span class="hljs-keyword">if</span> (msg.board) {
                <span class="hljs-keyword">const</span> result2 = legalMovesWithBoard(msg, result);

    <span class="hljs-comment">//...</span>
</code></pre>
<h3 id="heading-back-to-the-game">Back to the Game</h3>
<h4 id="heading-service-overview">Service Overview</h4>
<p>All movement requests are handled by the <code>legalMoves</code> service, which relies on several other services and helper methods:</p>
<ul>
<li>Call the <code>rawMoves</code> service<br>This will return all moves of a lone piece on a virtual 15x15 chessboard (referred to as the <strong>movement mask</strong>). Explained in Part 1</li>
<li>Call the base <code>legalMoves</code> service<br>This will clip the <strong>movement mask</strong> at the edge of the “real” 8x8 board, with proper <a target="_blank" href="https://en.wikipedia.org/wiki/Algebraic_notation_%28chess%29">algebraic coordinates</a>. Explained in Part 2</li>
<li>Call the overriding <code>legalMoves</code> service<br>If there is a board as part of the incoming message (the service pattern), then a series of checks is done to account for the presence of friendly and opposing pieces, because these will affect movement. Explained in this part (Part 3).</li>
</ul>
<p>So <a target="_blank" href="https://medium.com/@jefflowery/follow-the-rules-with-seneca-ii-c22074debac">Part 2</a> took care of friendly pieces blocking other friendly pieces, but now there are those annoying enemy pieces to deal with. Like friendly pieces, enemy pieces can block movement, but they can also be captured. Under some conditions, enemy pieces may even increase our movement options.</p>
<p>Then there’s castling: the only move where two pieces can shift their position at once. Special considerations apply, some of which involve enemy pieces.</p>
<h4 id="heading-queen-rook-amp-bishop">Queen, Rook, &amp; Bishop</h4>
<p>The new rules involving enemy pieces extend or modify the original <code>legalMoves</code> service in Part 2 that dealt with friendly pieces only. The new microservice extension will need to know if the blocking piece is friend or foe. If friend, then movement is blocked at the square before. If foe, then movement is blocked by the square of the opposing piece (by capture). In the list of legal moves returned by a piece, we will denote captures by setting a <code>hasCaptured</code> flag, along with the type of enemy piece to be captured.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*HbU0Bv04ybhZe0LxCR_O6Q.png" alt="Image" width="320" height="320" loading="lazy">
<em>The Queen can go to f3, but not g4; it can go to d3 and c4 (by capture)</em></p>
<p>The <code>vectorChecks</code> helper method shown in the previous gist listing handles all vector-based movement for Queen, Rook, and Bishop.</p>
<h4 id="heading-knight">Knight</h4>
<p>Knights jump around the board, so are only blocked by friendly pieces that are on one of its potential landing squares. An enemy piece does not block, but would be captured if a Knight landed on it. The method used by the <code>legalMoves</code> service is easy to write.</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">knightChecks</span>(<span class="hljs-params">boardAndPiece, candidateMoves</span>) </span>{
    <span class="hljs-keyword">const</span> newMoves = [];

    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">const</span> m <span class="hljs-keyword">of</span> candidateMoves.moves) {
        <span class="hljs-keyword">const</span> p = boardAndPiece.board.pieceAt(m)
        <span class="hljs-keyword">if</span> (!p) {
            newMoves.push(m)
        } <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (p.color !== boardAndPiece.piece.color) {
            m.hasCaptured = p;
            newMoves.push(m)
        }
    }
    <span class="hljs-keyword">return</span> {
        <span class="hljs-attr">moves</span>: newMoves,
        <span class="hljs-attr">moveVectors</span>: [newMoves]
    };
}
</code></pre>
<h4 id="heading-pawn">Pawn</h4>
<p>Pawns at first seem like a pretty simple case. The pawn is blocked if any piece whether friend or enemy stands in front of it. But it can to move one square diagonally forward to capture an enemy that sits in that square.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*T4gv4p2TwUz9e3rLgaDIiA.png" alt="Image" width="320" height="320" loading="lazy">
<em>The pawn at e4 is blocked at e5, but can capture at f5</em></p>
<p>There is also the <strong>en passant</strong> rule, where a pawn can capture an adjacent enemy pawn that <strong>just</strong> moved two squares on the previous turn:</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*QfWgeV-2-_8tM_IQ9G5bUA.png" alt="Image" width="320" height="320" loading="lazy">
<em>The Black pawn at e4 can capture the White pawn at d4 by moving to d3(!)</em></p>
<p>And then there’s the issue of mandatory promotion once a pawn reaches the 8th rank. Confusingly, this refers to the eighth rank in front of the pawn, which would be the first rank of the board coordinates if playing Black.</p>
<p>All these considerations make for a rather involved set of rules to determine the pawn’s movement options. These can be <a target="_blank" href="https://github.com/JeffML/ms-chess3/blob/master/services/helpers/legalMovesWithBoard.js">found</a> in the accompanying <a target="_blank" href="https://github.com/JeffML/ms-chess3">source code</a> at GitHub.</p>
<h4 id="heading-king">King</h4>
<p>The Pawn was a bit of work, but the king even more so. There are several conditions:</p>
<ul>
<li>Is a potential move square controlled by an enemy piece?<br>Eliminate that option.</li>
<li>Is the king in check?<br>If so, it <strong>must</strong> move this turn  </li>
<li>If it is in check, and can’t move out of check, game over! Checkmate!  </li>
<li>If it is not in check, but there are no other legal moves by any friendly piece on the board, stalemate!</li>
<li>Can the King castle (queen side or king side)?  </li>
<li>King is in check: No.  </li>
<li>King has previously moved: No.  </li>
<li>Rook has previously moved: No.  </li>
<li>Intervening squares between K and R occupied: No.  </li>
<li>Intervening squares empty, but controlled by enemy piece: No.  </li>
<li>Otherwise: Yes.</li>
</ul>
<p>This service I will break down into detail. As you may recall, the <code>legalMoves</code> service is broken into two parts. One part treats a piece as if it is alone on the board. The other part deals with friendly and opposing pieces. Let’s look at the listing:</p>
<pre><code class="lang-js">    <span class="hljs-built_in">this</span>.add(<span class="hljs-string">'role:movement,cmd:legalMoves'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">msg, reply</span>) </span>{
        <span class="hljs-built_in">this</span>.prior(msg, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">err, result</span>) </span>{
            <span class="hljs-keyword">if</span> (msg.board) {
                <span class="hljs-keyword">const</span> result2 = legalMovesWithBoard(msg, result);
                <span class="hljs-keyword">if</span> (msg.piece.piece === <span class="hljs-string">'K'</span>) {
                    legalMovesWithKing.call(<span class="hljs-built_in">this</span>, msg, result2, reply)
                } <span class="hljs-keyword">else</span> {
                    reply(err, result2);
                }
            } <span class="hljs-keyword">else</span> {
                reply(err, result);
            }
        });
    });
</code></pre>
<p>For every piece but the King, we simply call the base service (via the Seneca framework’s <code>prior()</code> method) followed by the helper method <code>legalMovesWithBoard()</code>, parts of which were listed in the previous gists of this post.</p>
<p>If the piece is a King, the additional helper method <code>legalMovesWithKing()</code> is called. The calling parameters are the <code>this</code> reference, a <code>msg</code> object containing board and the piece being moved (the King), the <code>result2</code> which was came from the base <code>legalMoves</code> service call (this contains movement info), and the <code>reply</code> callback.</p>
<p>There’s a bit of code to slog through, so I will refer to sections by line number:</p>
<pre><code class="lang-js"><span class="hljs-built_in">module</span>.exports = <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">boardAndPiece, candidateMoves, reply</span>) </span>{
    <span class="hljs-keyword">const</span> opposingColor = boardAndPiece.piece.color === <span class="hljs-string">'W'</span> ? <span class="hljs-string">'black'</span> : <span class="hljs-string">'white'</span>;

    <span class="hljs-comment">//temporarily remove the K to avoid cycles</span>
    boardAndPiece.board.removePiece(boardAndPiece.piece);

    <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">canCastle</span>(<span class="hljs-params">king, rook, intervening, opposing</span>) </span>{
        <span class="hljs-comment">// console.log("canCastle", arguments)</span>

        <span class="hljs-keyword">const</span> opposingControlled = [...opposing.controlled]
        <span class="hljs-keyword">const</span> board = boardAndPiece.board;
        <span class="hljs-keyword">const</span> canCastle = !candidateMoves.inCheck &amp;&amp;
            !king.hasMoved &amp;&amp;
            rook &amp;&amp;
            rook.color === king.color &amp;&amp;
            !rook.hasMoved;
        <span class="hljs-keyword">if</span> (!canCastle) <span class="hljs-keyword">return</span> <span class="hljs-literal">false</span>;

        <span class="hljs-keyword">const</span> pieceInTheWay = !!intervening.find(<span class="hljs-function"><span class="hljs-params">sq</span> =&gt;</span> board.pieceAt(sq));
        <span class="hljs-keyword">if</span> (pieceInTheWay) <span class="hljs-keyword">return</span> <span class="hljs-literal">false</span>;

        <span class="hljs-keyword">const</span> passThruCheck = !!intervening.find(<span class="hljs-function"><span class="hljs-params">sq</span> =&gt;</span>
            opposingControlled.find(<span class="hljs-function"><span class="hljs-params">opp</span> =&gt;</span> (opp.rank === sq.rank &amp;&amp; opp.file == sq.file))
        )
        <span class="hljs-keyword">if</span> (passThruCheck) <span class="hljs-keyword">return</span> <span class="hljs-literal">false</span>;

        <span class="hljs-keyword">return</span> <span class="hljs-literal">true</span>;
    }

    <span class="hljs-built_in">this</span>.use(<span class="hljs-built_in">require</span>(<span class="hljs-string">'../SquareControl'</span>))

    <span class="hljs-built_in">this</span>.act({
        <span class="hljs-attr">role</span>: <span class="hljs-string">"board"</span>,
        <span class="hljs-attr">cmd</span>: <span class="hljs-string">"squaresControlledBy"</span>,
        <span class="hljs-attr">board</span>: boardAndPiece.board,
        <span class="hljs-attr">color</span>: opposingColor,
    }, <span class="hljs-function">(<span class="hljs-params">err, opposing</span>) =&gt;</span> {
        <span class="hljs-keyword">if</span> (err) {
            reply(err);
            <span class="hljs-keyword">return</span>;
        }

        <span class="hljs-keyword">const</span> king = boardAndPiece.piece;
        <span class="hljs-comment">// console.log(opposing.controlled)</span>
        <span class="hljs-comment">// add the removed K back in</span>
        boardAndPiece.board.addPiece(king);
        <span class="hljs-keyword">const</span> filteredMoves = candidateMoves.moves.filter(<span class="hljs-function"><span class="hljs-params">m</span> =&gt;</span>
            !!!opposing.controlled.find(<span class="hljs-function"><span class="hljs-params">o</span> =&gt;</span> o.rank === m.rank &amp;&amp; o.file === m.file)
        )

        <span class="hljs-keyword">const</span> kingSq = king.position;
        <span class="hljs-keyword">const</span> inCheck = !!opposing.controlled.find(<span class="hljs-function"><span class="hljs-params">o</span> =&gt;</span> o.rank === kingSq.rank &amp;&amp; o.file === kingSq.file)

        <span class="hljs-keyword">const</span> additional = {}
        additional.inCheck = inCheck;

        additional.checkMated = (inCheck &amp;&amp; filteredMoves.length === <span class="hljs-number">0</span>)

        <span class="hljs-keyword">const</span> rank = additional.color === <span class="hljs-string">'W'</span> ? <span class="hljs-number">1</span> : <span class="hljs-number">8</span>;
        <span class="hljs-keyword">let</span> rook = boardAndPiece.board.pieceAt(<span class="hljs-string">`a<span class="hljs-subst">${rank}</span>`</span>);
        <span class="hljs-keyword">let</span> intervening = [<span class="hljs-string">`b<span class="hljs-subst">${rank}</span>`</span>, <span class="hljs-string">`c<span class="hljs-subst">${rank}</span>`</span>, <span class="hljs-string">`d<span class="hljs-subst">${rank}</span>`</span>]

        additional.canQSideCastle = canCastle(king, rook, intervening, opposing)

        rook = boardAndPiece.board.pieceAt(<span class="hljs-string">`h<span class="hljs-subst">${rank}</span>`</span>);
        intervening = [<span class="hljs-string">`f<span class="hljs-subst">${rank}</span>`</span>, <span class="hljs-string">`g<span class="hljs-subst">${rank}</span>`</span>]

        additional.canKSideCastle = canCastle(king, rook, intervening, opposing)

        candidateMoves.moves = filteredMoves;
        <span class="hljs-keyword">delete</span> candidateMoves.moveVectors; <span class="hljs-comment">// no longer valid, and no longer needed</span>

        <span class="hljs-built_in">Object</span>.assign(candidateMoves, additional);
        <span class="hljs-built_in">console</span>.log(candidateMoves)
        reply(<span class="hljs-literal">null</span>, candidateMoves)
    });
};
</code></pre>
<p>Let start from the middle, at line 30. A service called <code>squaresControlledBy</code> is imported into the framework from <a target="_blank" href="https://gist.github.com/JeffML/a44d20e88767df03581b264e50b5a99d">SquareControl.js</a>. It gathers all legal moves of the opposing side and calls those the controlled squares. We need this information because the King cannot move into a square ‘controlled’ by the enemy. The King cannot move into check.</p>
<p>There’s a tricky bit to this, and that is because the <code>squaresControlledBy</code> service relies on the <code>legalMoves</code> service. What can happen is that:</p>
<ul>
<li><code>legalMoves</code> service is called for friendly piece</li>
<li>if the friendly piece is a King, <code>squaresControlledBy</code> is called for opposing side</li>
<li><code>squaresControlledBy</code> requests <code>legalMoves</code> for all opposing sides pieces</li>
<li>if <code>legalMoves</code> is requested for the opposing King, it will call service <code>squaresControlledBy</code> for <strong>its</strong> opposing side (our side).</li>
<li>we’ve come full circle, and round and round we go…</li>
</ul>
<p>These cycles are one of the gotchas of microservices, and have to be carefully accounted for. I won’t go into the various strategies for dealing with this, but Seneca provides trace options for actions <code>( — seneca.print.tree)</code>and service invocations <code>( — seneca.log.all)</code> that can be helpful in debugging.</p>
<p>The trick I used to avoid endless cycling was to temporarily remove the friendly king from the board (line 5) and later add it back in (line 46). I would say that best practice would be to not modify incoming service action data. There are potential hard-to-track side-effects. For purposes of finishing this series in a reasonable time frame, though, I will overlook a bit of fudging.</p>
<p>We push additional information (<code>inCheck</code>, castle options [lines 7–28], <code>checkmate</code>) to the <code>reply</code> by storing it in a local data structure and then using <code>Object.assign()</code> to merge it into the <code>candidateMoves</code> structure. The <code>candidateMoves</code> object will now have moves long with new properties provided by the additional object (lines 54–73).</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*eNTwiOlyhPNvZNyoJ5vgSA.png" alt="Image" width="320" height="320" loading="lazy">
<em>Black King can’t castle because it’s in check; White King can’t castle because of intervening friendly Bishop (kingside) and opposing control of d1 square (queenside)</em></p>
<p>That wraps it up! Remember, if you found this series useful and engaging, please don’t forget to recommend it (click that little heart icon). Feedback always welcome.</p>
<p>Full source (including tests) for this Part 3 of the series can be found <a target="_blank" href="https://github.com/JeffML/ms-chess3">here</a>.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Writing a chess microservice using Node.js and Seneca, Part 2 ]]>
                </title>
                <description>
                    <![CDATA[ By Jeff M Lowery Handling new requirements without refactoring Part 1 of this series talked about defining and calling microservices using Seneca. A handful of services were created to return all legal moves of a lone chess piece on a chessboard. The... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/follow-the-rules-with-seneca-ii-c22074debac/</link>
                <guid isPermaLink="false">66d45f6f9f2bec37e2da0626</guid>
                
                    <category>
                        <![CDATA[ chess ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Microservices ]]>
                    </category>
                
                    <category>
                        <![CDATA[ General Programming ]]>
                    </category>
                
                    <category>
                        <![CDATA[ tech  ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Wed, 14 Jun 2017 19:44:26 +0000</pubDate>
                <media:content url="https://cdn-media-1.freecodecamp.org/images/1*kKyKqEjIfVK--SJT2-SoXQ.jpeg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Jeff M Lowery</p>
<h4 id="heading-handling-new-requirements-without-refactoring">Handling new requirements without refactoring</h4>
<p><a target="_blank" href="https://medium.freecodecamp.com/follow-the-rules-with-seneca-b3cf3d08fe5d">Part 1</a> of this series talked about defining and calling microservices using Seneca. A handful of services were created to return all legal moves of a lone chess piece on a chessboard. The series continues in <a target="_blank" href="https://medium.com/@jefflowery/writing-a-chess-microservice-using-node-js-and-seneca-part-3-ab38b8ef9b0a">Part 3</a>.</p>
<h4 id="heading-a-quick-review">A quick review:</h4>
<ul>
<li>Seneca services are identified by a pattern consisting of <code>role</code> and <code>cmd</code> properties. Additional properties can be added to the pattern as well.</li>
</ul>
<pre><code class="lang-js"><span class="hljs-built_in">this</span>.add({
        <span class="hljs-attr">role</span>: <span class="hljs-string">"movement"</span>,
        <span class="hljs-attr">cmd</span>: <span class="hljs-string">"legalMoves"</span>   <span class="hljs-comment">//, otherProp: value, ...</span>
    }, <span class="hljs-function">(<span class="hljs-params">msg, reply</span>) =&gt;</span> {...}
</code></pre>
<ul>
<li>Services also have an implementation that takes a <code>msg</code> object and a reply callback. The<code>msg</code> object contains the pattern properties in addition to all other data sent to the service.</li>
<li><code>Seneca.act()</code>is used to indirectly invoke a service. The <code>act</code> method takes an object and a callback function. The object contains the <code>role</code>, <code>cmd</code>, and other properties that comprise the message to the service.</li>
</ul>
<pre><code class="lang-js">seneca.act({
            <span class="hljs-attr">role</span>: <span class="hljs-string">"movement"</span>,
            <span class="hljs-attr">cmd</span>: <span class="hljs-string">"legalMoves"</span>,
            <span class="hljs-attr">piece</span>: p,
            <span class="hljs-attr">board</span>: board
        }, <span class="hljs-function">(<span class="hljs-params">err, msg</span>) =&gt;</span> {
</code></pre>
<ul>
<li>When an action could be handled by more than one service that matches the pattern, the service with the <a target="_blank" href="http://senecajs.org/getting-started/#how-patterns-work">most specific pattern match</a> will be invoked.</li>
</ul>
<p>There were a handful of services defined in the <a target="_blank" href="https://medium.freecodecamp.com/follow-the-rules-with-seneca-b3cf3d08fe5d">first part</a> of this series. One of three<code>rawMoves</code> services took a piece and its position as parameters and returned 15 x 15 movement mask. These were truncated to an 8 x 8 board using a<code>legalSquares</code> service. The result was that the services together can return all the legal moves of any piece on any legal square of the otherwise empty chessboard.</p>
<h3 id="heading-microservices-and-technical-debt">Microservices and Technical Debt</h3>
<p>One of the motivations for microservices is to <a target="_blank" href="http://www.infoworld.com/article/2878659/application-development/reducing-technical-debt-with-microservices.html">reduce technical debt</a>. Every project has deadlines and, as they loom larger, expediency often trumps quality. FIXME and TODO comments litter the source code after a while. Those comments identify technical debt that “someday” will be taken care of.</p>
<h4 id="heading-someday-never-comes">Someday never comes</h4>
<p>Microservices focus on functional decomposition and loose coupling. Neither of those are new ideas, but it is a rethinking about how to implement those concepts. A microservice should be small, single-purposed, and extensible. Extending a service can happen with few or no side-effects. A new service can extend an existing service, and neither the old service nor the client that once called it will know the service implementation changed. Less refactoring of classes, methods, method signatures, process flow… all this makes it easier to deal with dreaded TD.</p>
<h3 id="heading-back-to-the-game-in-progress">Back to the game in progress…</h3>
<p>Moving a single chess piece around a lonely board is not really all that entertaining. In a real chess game the chessboard is shared with friendly and hostile pieces, and these impact each other’s movement.</p>
<p>Right now I have a<code>legalSquares</code> service which can be the basis of a more complete<code>legalMoves</code>service. If you recall, the <code>legalSquares</code> service would invoke a <code>rawMoves</code>service, then remove all the ‘bad’ squares that didn’t belong on a chessboard.</p>
<p>The new <code>legalMoves</code> service will take into account other pieces, something that <code>legalSquares</code> didn’t. This requires an extra parameter, one called <code>board</code>. The <code>board</code> is just going to be an array of <strong>ChessPiece</strong> instances, and will assume that the pieces on the board have already been checked for validity. For instance, two pieces don’t occupy the same square, pawns aren’t on the first rank, kings aren’t be next to each other, and so forth.</p>
<p>The following pattern will identify the service:</p>
<pre><code class="lang-js"><span class="hljs-string">'role: movement;cmd: legalMoves'</span>
</code></pre>
<p>This pattern is a stringified version of JSON called <strong>jsonic</strong>; you can use a regular JSON object if you prefer. The message to the service will contain the pattern. It will also contain a ChessPiece instance that has a piece type such as ‘K’ing, ‘Q’ueen, ‘R’ook and board position (see algebraic notation). Later I’ll add to this class a piece color (White or Black) so that the service can tell friend from foe. But for now the service will assume all pieces are friendly.</p>
<p>Since a friendly piece cannot be captured, it will restrict movement of other friendly pieces. Determining those restrictions is a bit of work. I made it harder for myself in the implementation of the <code>rawMoves</code> service… which brings me to:</p>
<h3 id="heading-microservices-are-not-a-panacea">Microservices are not a Panacea</h3>
<p>If you design a service that retrieves or calculates information and <strong>doesn’t</strong> pass that data on up the chain, some service upstream may have to redo that work later. In my example, <code>rawMoves</code> returned an array of move objects (file and rank positions on the board). Let’s take the method that generates diagonal moves for a piece using the <code>rawMoves</code> service:</p>
<pre><code class="lang-js"><span class="hljs-built_in">module</span>.exports = <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">diagonal</span>(<span class="hljs-params">position, range = <span class="hljs-number">7</span></span>) </span>{
    <span class="hljs-keyword">var</span> moves = [];
    <span class="hljs-keyword">const</span> cFile = position.file.charCodeAt()
    <span class="hljs-keyword">const</span> cRank = position.rank.charCodeAt();

<span class="hljs-keyword">for</span> (<span class="hljs-keyword">var</span> i = <span class="hljs-number">1</span>; i &lt; range + <span class="hljs-number">1</span>; i++) {
        moves.push({
            <span class="hljs-attr">file</span>: <span class="hljs-built_in">String</span>.fromCharCode(cFile - i),
            <span class="hljs-attr">rank</span>: <span class="hljs-built_in">String</span>.fromCharCode(cRank - i)
        });
        moves.push({
            <span class="hljs-attr">file</span>: <span class="hljs-built_in">String</span>.fromCharCode(cFile + i),
            <span class="hljs-attr">rank</span>: <span class="hljs-built_in">String</span>.fromCharCode(cRank + i)
        });
        moves.push({
            <span class="hljs-attr">file</span>: <span class="hljs-built_in">String</span>.fromCharCode(cFile - i),
            <span class="hljs-attr">rank</span>: <span class="hljs-built_in">String</span>.fromCharCode(cRank + i)
        });
        moves.push({
            <span class="hljs-attr">file</span>: <span class="hljs-built_in">String</span>.fromCharCode(cFile + i),
            <span class="hljs-attr">rank</span>: <span class="hljs-built_in">String</span>.fromCharCode(cRank - i)
        });
    }
    <span class="hljs-keyword">return</span> moves;
}
</code></pre>
<p>At first glance, there’s nothing wrong with this. But, those four<code>move.push</code> operations actually operate along <strong>movement vectors</strong>. I could have constructed four movement vectors, then returned a list of moves by concatenating them, like so:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">diagonalMoves</span>(<span class="hljs-params">position, range</span>) </span>{
    <span class="hljs-keyword">var</span> vectors = [[], [], [], []];
    <span class="hljs-keyword">const</span> cFile = position.file.charCodeAt()
    <span class="hljs-keyword">const</span> cRank = position.rank.charCodeAt();

    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">var</span> i = <span class="hljs-number">1</span>; i &lt; range + <span class="hljs-number">1</span>; i++) {
        vectors[<span class="hljs-number">0</span>].push({
            <span class="hljs-attr">file</span>: <span class="hljs-built_in">String</span>.fromCharCode(cFile - i),
            <span class="hljs-attr">rank</span>: <span class="hljs-built_in">String</span>.fromCharCode(cRank - i)
        });
        vectors[<span class="hljs-number">1</span>].push({
            <span class="hljs-attr">file</span>: <span class="hljs-built_in">String</span>.fromCharCode(cFile + i),
            <span class="hljs-attr">rank</span>: <span class="hljs-built_in">String</span>.fromCharCode(cRank + i)
        });
        vectors[<span class="hljs-number">2</span>].push({
            <span class="hljs-attr">file</span>: <span class="hljs-built_in">String</span>.fromCharCode(cFile - i),
            <span class="hljs-attr">rank</span>: <span class="hljs-built_in">String</span>.fromCharCode(cRank + i)
        });
        vectors[<span class="hljs-number">3</span>].push({
            <span class="hljs-attr">file</span>: <span class="hljs-built_in">String</span>.fromCharCode(cFile + i),
            <span class="hljs-attr">rank</span>: <span class="hljs-built_in">String</span>.fromCharCode(cRank - i)
        });
    }

    <span class="hljs-keyword">const</span> moves = <span class="hljs-built_in">Array</span>.prototype.concat(...vectors)
    <span class="hljs-keyword">return</span> moves;
}
</code></pre>
<p>As it stood, there was no point in doing this. But later on those vectors would have come in handy for truncating movements along diagonals (or ranks or files) when a friendly piece is in the way. Instead, I had to decompose the move list along vectors in services upstream — more work and inefficiency which you will see later.</p>
<p>The real flaw, though, was that I returned an array, rather than a data object. Data objects have properties that are extendable, not so arrays. As a consequence, all my upstream services depend on receiving a movement array, and <strong>only</strong> a movement array. No flexibility. I can’t now add a list of movement vectors <strong>in addition</strong> to a move list. But I could if I had returned an object from this method and the service that called it instead.</p>
<p>Lesson learned? Consider returning data objects from your services. Have your upstream services work on parts of the data, but pass all data they receive back upstream. Exceptions to this rule will abound, of course.</p>
<h3 id="heading-with-friends-like-these">With Friends like These…</h3>
<p>In Part 1, there was a service under the pattern:</p>
<p><code>role:"movement",cmd:"legalSquares"</code></p>
<p>It returned all moves of an unimpeded piece. Since this will be the base service for determining legal moves on a populated chessboard, I’ll rename the <code>cmd</code>to <code>legalMoves</code>. Now I want to extend that to take into account friendly pieces that might be blocking a path of my chosen piece.</p>
<h4 id="heading-the-extended-service">The extended service</h4>
<p>The service that extends <code>role:"movement",cmd:"legalMoves"</code> is… <code>role:"movement",cmd:"legalMoves"</code> !</p>
<p>Yep, it has the same service pattern as the service it calls. You may recall that services are identified by pattern, and so how it this going to work? When the program acts on <code>role:"movement",cmd:"legalMoves"</code>, it will use the most recently defined service. But the new service has to call the former<code>legalMoves</code> service. That can be solved easily:</p>
<pre><code class="lang-js"><span class="hljs-built_in">this</span>.add({
        <span class="hljs-attr">role</span>: <span class="hljs-string">"movement"</span>,
        <span class="hljs-attr">cmd</span>: <span class="hljs-string">"legalMoves"</span>
    }, <span class="hljs-function">(<span class="hljs-params">msg, reply</span>) =&gt;</span> {<span class="hljs-comment">//returns unimpeded moves}</span>

<span class="hljs-built_in">this</span>.add(<span class="hljs-string">'role:movement,cmd:legalMoves'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">msg, reply</span>) </span>{
        <span class="hljs-built_in">this</span>.
prior(msg, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">err, moves</span>) </span>{
            <span class="hljs-keyword">if</span> (msg.board) {
                <span class="hljs-keyword">const</span> boardMoves = legalMovesWithBoard(msg, moves);
                reply(err, boardMoves);
                <span class="hljs-keyword">return</span>;
            }
            reply(err, moves);
        });
    });
</code></pre>
<p>This new service is able to call the former service by using the <code>prior()</code> method in Seneca. If no <code>board</code> parameter is supplied in the incoming <code>msg</code> object, then this service will just act as a pass-thru to the former service. But what if there is a board?</p>
<p>I’m not going to show a complete code listing here (see link below), but the gist of it is:</p>
<pre><code class="lang-js"><span class="hljs-built_in">module</span>.exports = <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">msg, moves</span>) </span>{
    <span class="hljs-keyword">if</span> (!msg.board) <span class="hljs-keyword">return</span> moves;

<span class="hljs-keyword">const</span> blockers = moves.filter(<span class="hljs-function"><span class="hljs-params">m</span> =&gt;</span> {
        <span class="hljs-keyword">return</span> (msg.board.pieceAt(m))
    })

<span class="hljs-keyword">var</span> newMoves = [];
    <span class="hljs-keyword">const</span> pp = msg.piece.position;

<span class="hljs-keyword">const</span> rangeChecks = {
        <span class="hljs-attr">B</span>: diagonalChecks,
        <span class="hljs-attr">R</span>: rankAndFileChecks,
        <span class="hljs-attr">K</span>: panopticonChecks,
        <span class="hljs-attr">Q</span>: panopticonChecks,
        <span class="hljs-attr">P</span>: pawnChecks,
        <span class="hljs-attr">N</span>: knightChecks
    };

<span class="hljs-keyword">var</span> rangeCheck = rangeChecks[msg.piece.piece];
    <span class="hljs-comment">// console.error(msg.piece.piece, rangeCheck.name)</span>
    newMoves = moves.filter(<span class="hljs-function"><span class="hljs-params">m</span> =&gt;</span> {
        <span class="hljs-keyword">return</span> rangeCheck(m, blockers, pp);
    })
    <span class="hljs-keyword">return</span> newMoves;
}
</code></pre>
<p>Remember our old friend <code>diagonalMoves</code> from the <code>rawMoves</code> service? In order to do a range check on diagonals without handy vectors, the new <code>legalMoves</code> service calls this:</p>
<pre><code class="lang-js"><span class="hljs-comment">// m: proposed move</span>
<span class="hljs-comment">// blockers: blocking pieces</span>
<span class="hljs-comment">// pp: current piece position</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">diagonalChecks</span>(<span class="hljs-params">m, blockers, pp</span>) </span>{
    <span class="hljs-keyword">let</span> isGood = <span class="hljs-literal">true</span>;
<span class="hljs-keyword">for</span> (<span class="hljs-keyword">const</span> b <span class="hljs-keyword">of</span> blockers) {
        <span class="hljs-keyword">if</span> (b.rank &gt; pp.rank &amp;&amp; b.file &gt; pp.file) {
            <span class="hljs-keyword">if</span> (m.rank &gt; pp.rank &amp;&amp; m.file &gt; pp.file) {
                isGood = isGood &amp;&amp; (m.rank &lt; b.rank &amp;&amp; m.file &lt; b.file);
            }
        }
        <span class="hljs-keyword">if</span> (b.rank &gt; pp.rank &amp;&amp; b.file &lt; pp.file) {
            <span class="hljs-keyword">if</span> (m.rank &gt; pp.rank &amp;&amp; m.file &lt; pp.file) {
                isGood = isGood &amp;&amp; (m.rank &lt; b.rank &amp;&amp; m.file &gt; b.file)
            }
        }
        <span class="hljs-keyword">if</span> (b.rank &lt; pp.rank &amp;&amp; b.file &gt; pp.file) {
            <span class="hljs-keyword">if</span> (m.rank &lt; pp.rank &amp;&amp; m.file &gt; pp.file) {
                isGood = isGood &amp;&amp; (m.rank &gt; b.rank &amp;&amp; m.file &lt; b.file)
            }
        }
        <span class="hljs-keyword">if</span> (b.rank &lt; pp.rank &amp;&amp; b.file &lt; pp.file) {
            <span class="hljs-keyword">if</span> (m.rank &lt; pp.rank &amp;&amp; m.file &lt; pp.file) {
                isGood = isGood &amp;&amp; (m.rank &gt; b.rank &amp;&amp; m.file &gt; b.file)
            }
        }
    }
<span class="hljs-keyword">return</span> isGood;
}
</code></pre>
<p>Ugly, no? I’d be happy if some algorithmically-inclined reader reduced this to two lines in the comments section. Three, even.</p>
<p>So that takes care of friendly pieces. The next installment will deal with hostile pieces, which can be captured.</p>
<p>Full source code for this article can be found at <a target="_blank" href="https://github.com/JeffML/ms-chess2">GitHub</a>.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ A step-by-step guide to building a simple chess AI ]]>
                </title>
                <description>
                    <![CDATA[ By Lauri Hartikka Let’s explore some basic concepts that will help us create a simple chess AI: move-generation board evaluation minimax and alpha beta pruning. At each step, we’ll improve our algorithm with one of these time-tested chess-programmi... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/simple-chess-ai-step-by-step-1d55a9266977/</link>
                <guid isPermaLink="false">66c35ed3a365c359945c9b5f</guid>
                
                    <category>
                        <![CDATA[ Artificial Intelligence ]]>
                    </category>
                
                    <category>
                        <![CDATA[ chess ]]>
                    </category>
                
                    <category>
                        <![CDATA[ General Programming ]]>
                    </category>
                
                    <category>
                        <![CDATA[ technology ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Web Development ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Thu, 30 Mar 2017 19:26:08 +0000</pubDate>
                <media:content url="https://cdn-media-1.freecodecamp.org/images/1*eP0V-xfRWfW3QHJhALJ5RA.jpeg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Lauri Hartikka</p>
<p>Let’s explore some basic concepts that will help us create a simple chess AI:</p>
<ul>
<li>move-generation</li>
<li>board evaluation</li>
<li>minimax</li>
<li>and alpha beta pruning.</li>
</ul>
<p>At each step, we’ll improve our algorithm with one of these time-tested chess-programming techniques. I’ll demonstrate how each affects the algorithm’s playing style.</p>
<p>You can view the final AI algorithm here on <a target="_blank" href="https://github.com/lhartikk/simple-chess-ai">GitHub</a>.</p>
<h3 id="heading-step-1-move-generation-and-board-visualization">Step 1: Move generation and board visualization</h3>
<p>We’ll use the <a target="_blank" href="https://github.com/jhlywa/chess.js">chess.js</a> library for move generation, and <a target="_blank" href="https://github.com/oakmac/chessboardjs/">chessboard.js</a> for visualizing the board. The move generation library basically implements all the rules of chess. Based on this, we can calculate all legal moves for a given board state.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*_Z_qtrm9ayf_UhycYudE3g.png" alt="Image" width="800" height="572" loading="lazy">
<em>A visualization of the move generation function. The starting position is used as input and the output is all the possible moves from that position.</em></p>
<p>Using these libraries will help us focus only on the most interesting task: creating the algorithm that finds the best move.</p>
<p>We’ll start by creating a function that just returns a random move from all of the possible moves:</p>
<p>Although this algorithm isn’t a very solid chess player, it’s a good starting point, as we can actually play against it:</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*GzOiJRh6Z3FOC3xmPEmKrQ.gif" alt="Image" width="410" height="402" loading="lazy">
_Black plays random moves. Playable on [https://jsfiddle.net/lhartikk/m14epfwb/](https://jsfiddle.net/lhartikk/m14epfwb/" rel="noopener" target="<em>blank" title=")4</em></p>
<h3 id="heading-step-2-position-evaluation">Step 2 : Position evaluation</h3>
<p>Now let’s try to understand which side is stronger in a certain position. The simplest way to achieve this is to count the relative strength of the pieces on the board using the following table:</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*e4p9BrCzJUdlqx7KVGW9aA.png" alt="Image" width="413" height="488" loading="lazy"></p>
<p>With the evaluation function, we’re able to create an algorithm that chooses the move that gives the highest evaluation:</p>
<p>The only tangible improvement is that our algorithm will now capture a piece if it can.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*fTWDdJ2m3L72X6rqce9_tQ.gif" alt="Image" width="410" height="402" loading="lazy">
_Black plays with the aid of the simple evaluation function. Playable on [https://jsfiddle.net/lhartikk/m5q6fgtb/1/](https://jsfiddle.net/lhartikk/m5q6fgtb/1/" rel="noopener" target="<em>blank" title=")</em></p>
<h3 id="heading-step-3-search-tree-using-minimax">Step 3: Search tree using Minimax</h3>
<p>Next we’re going to create a search tree from which the algorithm can chose the best move. This is done by using the <a target="_blank" href="https://en.wikipedia.org/wiki/Minimax">Minimax</a> algorithm.</p>
<p>In this algorithm, the recursive tree of all possible moves is explored to a given depth, and the position is evaluated at the ending “leaves” of the tree.</p>
<p>After that, we return either the smallest or the largest value of the child to the parent node, depending on whether it’s a white or black to move. (That is, we try to either minimize or maximize the outcome at each level.)</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*UA5VlNs7s4gl80VknA099w.jpeg" alt="Image" width="791" height="312" loading="lazy">
<em>A visualization of the minimax algorithm in an artificial position. The best move for white is <strong>b2-c3</strong>, because we can guarantee that we can get to a position where the evaluation is <strong>-50</strong></em></p>
<p>With minimax in place, our algorithm is starting to understand some basic tactics of chess:</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*xRfitY19MvJW3ynGKWhQ5A.gif" alt="Image" width="396" height="398" loading="lazy">
_Minimax with depth level 2. Playable on: [https://jsfiddle.net/k96eoq0q/1/](https://jsfiddle.net/k96eoq0q/1/" rel="noopener" target="<em>blank" title=")</em></p>
<p>The effectiveness of the minimax algorithm is heavily based on the search depth we can achieve. This is something we’ll improve in the following step.</p>
<h3 id="heading-step-4-alpha-beta-pruning">Step 4: Alpha-beta pruning</h3>
<p><a target="_blank" href="https://en.wikipedia.org/wiki/Alpha%E2%80%93beta_pruning">Alpha-beta</a> pruning is an optimization method to the minimax algorithm that allows us to disregard some branches in the search tree. This helps us evaluate the minimax search tree much deeper, while using the same resources.</p>
<p>The alpha-beta pruning is based on the situation where we can stop evaluating a part of the search tree if we find a move that leads to a worse situation than a previously discovered move.</p>
<p>The alpha-beta pruning does not influence the outcome of the minimax algorithm — it only makes it faster.</p>
<p>The alpha-beta algorithm also is more efficient if we happen to visit <strong>first</strong> those paths that lead to good moves.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*96QEzhnsOkNqz7swB0qx8w.jpeg" alt="Image" width="791" height="312" loading="lazy">
<em>The positions we do not need to explore if alpha-beta pruning isused and the tree is visited in the described order.</em></p>
<p>With alpha-beta, we get a significant boost to the minimax algorithm, as is shown in the following example:</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*k3DrkWLNq33ei_t-094qpg.png" alt="Image" width="393" height="471" loading="lazy">
<em>The number of positions that are required to evaluate if we want to perform a search with depth of 4 and the “root” position is the one that is shown.</em></p>
<p>Follow <a target="_blank" href="https://jsfiddle.net/Laa0p1mh/3/">this link</a> to try the alpha-beta improved version of the chess AI.</p>
<h3 id="heading-step-5-improved-evaluation-function">Step 5: Improved evaluation function</h3>
<p>The initial evaluation function is quite naive as we only count the material that is found on the board. To improve this, we add to the evaluation a factor that takes in account the position of the pieces. For example, a knight on the center of the board is better (because it has more options and is thus more active) than a knight on the edge of the board.</p>
<p>We’ll use a slightly adjusted version of piece-square tables that are originally described in the <a target="_blank" href="https://chessprogramming.wikispaces.com/Simplified+evaluation+function">chess-programming-wiki</a>.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*iG6FUYZpU0_RKlqHnC8XxA.png" alt="Image" width="800" height="782" loading="lazy">
<em>The visualized piece-square tables visualized. We can decrease or increase the evaluation, depending on the location of the piece.</em></p>
<p>With the following improvement, we start to get an algorithm that plays some “decent” chess, at least from the viewpoint of a casual player:</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*sX_XwfPrOQ6c62iuVZ75fw.gif" alt="Image" width="396" height="398" loading="lazy">
_Improved evaluation and alpha-beta pruning with search depth of 3. Playable on [https://jsfiddle.net/q76uzxwe/1/](https://jsfiddle.net/q76uzxwe/1/" rel="noopener" target="<em>blank" title=")</em></p>
<h3 id="heading-conclusions">Conclusions</h3>
<p>The strength of even a simple chess-playing algorithm is that it doesn’t make stupid mistakes. This said, it still lacks strategic understanding.</p>
<p>With the methods I introduced here, we’ve been able to program a chess-playing-algorithm that can play basic chess. The “AI-part” (move-generation excluded) of the final algorithm is just 200 lines of code, meaning the basic concepts are quite simple to implement. You can check out the final version is on <a target="_blank" href="https://github.com/lhartikk/simple-chess-ai">GitHub</a>.</p>
<p>Some further improvements we could make to the algorithm would be for instance:</p>
<ul>
<li><a target="_blank" href="https://chessprogramming.wikispaces.com/Move+Ordering">move-ordering</a></li>
<li>faster <a target="_blank" href="https://chessprogramming.wikispaces.com/Move+Generation">move generation</a></li>
<li>and <a target="_blank" href="https://chessprogramming.wikispaces.com/Endgame">end-game</a> specific evaluation.</li>
</ul>
<p>If you want to learn more, check out the <a target="_blank" href="https://chessprogramming.wikispaces.com/">chess programming wiki</a>. It’s a helpful resource for exploring beyond these basic concepts I introduced here.</p>
<p>Thanks for reading!</p>
 ]]>
                </content:encoded>
            </item>
        
    </channel>
</rss>
