Answers.Body: <p>Your question has nothing to do with Stockfish. Though it may be interesting to check the original source code.</p>
  <p>This is purely algorithmic.</p>
  <p>One dumb solution would be implementing a boolean function (is_check) that takes an array as input representing the board. Only white pieces can check the black king, except the white king and vice versa.</p>
  <p>If one of the following conditions is verified then there is a check on the board(return True) :</p>
  <ul>
  <li>If a knight is placed at (-+)2(-+)1 or (-+)1(-+)2 squares from your king</li>
  <li>If a pawn is placed at (-+)1+1 squares from your king (depends on the side you make the verification for as pawns move and attack only in one way)</li>
  <li>If your king is in diagonal of a bishop or a queen and that no other pieces interferes</li>
  <li>If your king is aligned (column/row) with a rook or a queen and that no other pieces interferes</li>
  </ul>
  <p>Otherwise return False.</p>
  <p>Note that such a function could be used in another method to check if a planned move is legal (if your king is in check after you played, your move is illegal)</p>
  
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2020-10-08T12:47:16.897Z
Answers.Text: If you're going to use it to see if a move is legal (i.e. you are not assuming legality of the current position, only the preceding one), you need to allow for checks from the opposing king.
Answers.UserDisplayName: Especially Lime
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2020-10-08T18:06:42.340Z
Answers.Text: Checkmate is slightly more complicated of course - because you'd have to then check every legal move that could be done in response and see if the king is still checked in all of them.  Stalemate would be the same only the king is not currently in check.  Draw by repetition or by X moves with no change in material, or insufficient material on both sides to complete, slightly more complicated, but not impossible.
Answers.UserDisplayName: Darrel Hoffman
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2020-10-09T01:22:01.250Z
Answers.Text: If you use it to decide whether the king is in check after the move, beware of pinned pieces. Thus, it must be re-calculated for non-king-moves.
Answers.UserDisplayName: Deduplicator
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2020-10-09T15:35:31.257Z
Answers.Text: @Deduplicator Why is it an issue whether something is pinned? A unit may check whether or not it is pinned.
Answers.UserDisplayName: Rosie F
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2020-10-10T00:49:09.620Z
Answers.Text: @DarrelHoffman: I would tend to assume that both checkmate and stalemate naturally fall out of the "find all of the legal moves" logic (which you obviously need to write anyway). If you can't find any legal moves, then it must be one or the other, and you need only look for check to determine which it is.
Answers.UserDisplayName: Kevin
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2020-10-12T13:30:08.663Z
Answers.Text: @Kevin Yeah, sorry, I shouldn't have said "legal moves" because obviously any move that leaves you in check is not legal.  Better might be to say "all possible moves if you were to ignore that rule", and then see if there's still a check in each of those cases, but I don't know if there's a term for that.
Answers.UserDisplayName: Darrel Hoffman
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2020-10-12T21:33:56.010Z
Answers.Text: @DarrelHoffman: What I'm suggesting is this: You design check, and all of the other "is this move legal?" rules into your engine first. Then, you design it to enumerate all of the legal moves, and use that enumeration to do the standard minimax tree search (with evaluation, pruning, etc.). If you find your tree search has reached a leaf node (i.e. there are no legal moves), then you go back to the check logic and ask "Is the player to move in check?" If so, then you have checkmate, and if not, then you have stalemate. No need for a separate evaluation pass at all.
Answers.UserDisplayName: Kevin
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2020-10-08T09:46:06.157Z
Answers.LastActivityDate: 2020-10-08T09:51:39.663Z
Answers.LastEditDate: 2020-10-08T09:51:39.663Z
Answers.UserDisplayName: Falquiero
Answers.Body: <blockquote>
  <p>Where and how in Stockfish's code is check detected?</p>
  </blockquote>
  <p>This is simple engine programming. You will need to build a bitboard of the attacking squares and two bitboards of your king, one for each color. You will then run AND on the two bitboards. If the result is non-zero, you know the king is in check.</p>
  <p>I can show you the code in Stockfish, but does my answer make sense to you? If not, please add a comment so I will try to grab some code.</p>
  
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2020-10-08T20:40:56.030Z
Answers.Text: How is the operation (Bitboard AND Bitboard) defined? This is ambiguous. Bitboard is a matrix, while the operands of AND are bits.
Answers.UserDisplayName: Klangen
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2020-10-08T22:25:40.983Z
Answers.Text: You operate over the matrix, ANDing the corresponding positions one by one.  So 64 "single ANDs" in total.
Answers.UserDisplayName: IronEagle
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2020-10-09T17:23:39.183Z
Answers.Text: @IronEagle You just need two 64 bits integers. And do like `a & b`.
Answers.UserDisplayName: SmallChess
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2020-10-09T17:25:45.613Z
Answers.Text: @SmallChess That’s another way to think of it (and probably closer to reality), I just wanted to emphasize that the AND operation is bit by bit, even with a matrix.
Answers.UserDisplayName: IronEagle
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2020-10-11T15:12:02.297Z
Answers.Text: I think this is sometimes called a “pointwise” operation, to distinguish from row- or column-wise operations (at least, this is true in the numpy and matlab parlance).
Answers.UserDisplayName: D. Ben Knoble
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2020-10-08T09:42:42.800Z
Answers.LastActivityDate: 2020-10-08T09:42:42.800Z
Answers.UserDisplayName: SmallChess
Answers.Body: <p>If you're curious about the Stockfish code, it can be <a href="https://github.com/official-stockfish/Stockfish/blob/0405f3540366cc16245d51531881c55d3726c8b5/src/position.cpp#L338" rel="noreferrer">found here</a>:</p>
  <pre><code> si-&gt;checkersBB = attackers_to(square&lt;KING&gt;(sideToMove)) &amp; pieces(~sideToMove);
  </code></pre>
  <ol>
  <li>We call the <code>attackers_to</code> method to figure out if any pieces are attacking the king's position, including pieces on the king's side.</li>
  </ol>
  <pre><code> Bitboard Position::attackers_to(Square s, Bitboard occupied) const {
  
      return  (pawn_attacks_bb(BLACK, s)       &amp; pieces(WHITE, PAWN))
           | (pawn_attacks_bb(WHITE, s)       &amp; pieces(BLACK, PAWN))
           | (attacks_bb&lt;KNIGHT&gt;(s)           &amp; pieces(KNIGHT))
           | (attacks_bb&lt;  ROOK&gt;(s, occupied) &amp; pieces(  ROOK, QUEEN))
           | (attacks_bb&lt;BISHOP&gt;(s, occupied) &amp; pieces(BISHOP, QUEEN))
           | (attacks_bb&lt;KING&gt;(s)             &amp; pieces(KING));
   }
  </code></pre>
  <ol start="2">
  <li><p>We then call the <code>pieces</code> function, which returns all the pieces owned by the opposite side</p>
  </li>
  <li><p>Finally, we run an AND operator to confirm if any of the opposite side's pieces are threatening the king.</p>
  </li>
  </ol>
  <p>The code is very well written and relatively straightforward to follow, in case you'd like to explore it further.</p>
  
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2020-10-08T21:03:57.117Z
Answers.LastActivityDate: 2020-10-09T23:27:39.840Z
Answers.LastEditDate: 2020-10-09T23:27:39.840Z
Answers.UserDisplayName: JonathanReez
Body: <p>I am writing a chess engine. I need to know how to tell if the king is in check. I was thinking that maybe I can use the approach that Stockfish uses. Where and how in Stockfish's code is check detected?</p>
  
Comments.ContentLicense: CC BY-SA 4.0
Comments.CreationDate: 2020-10-07T23:16:08.200Z
Comments.Text: https://www.chessprogramming.org/Check
Comments.UserDisplayName: Filip Vondrášek
Comments.ContentLicense: CC BY-SA 4.0
Comments.CreationDate: 2020-10-07T23:49:46.620Z
Comments.Text: http://rin.io/chess-engine/ Not sure but the link above tells you how stockfish works.
  Perhaps you can find something there?
Comments.UserDisplayName: user24921
Comments.ContentLicense: CC BY-SA 4.0
Comments.CreationDate: 2020-10-08T21:04:34.900Z
Comments.Text: I assume you've had a read of the source? https://github.com/official-stockfish/Stockfish
Comments.UserDisplayName: Jason
Comments.ContentLicense: CC BY-SA 4.0
Comments.CreationDate: 2020-10-09T00:06:20.570Z
Comments.Text: Once you've written code to identify possible next moves, you can just check whether any of them involve capturing the king.
Comments.UserDisplayName: Acccumulation
Comments.ContentLicense: CC BY-SA 4.0
Comments.CreationDate: 2020-10-09T13:41:30.423Z
Comments.Text: This is not a chess question.
Comments.UserDisplayName: J...
Comments.ContentLicense: CC BY-SA 4.0
Comments.CreationDate: 2020-10-13T01:28:43.310Z
Comments.Text: @J Yes it is lol
Comments.UserDisplayName: fartgeek
Tags: <engines><stockfish><programming>
Title: How does Stockfish know if the king is in check?
ThreadText: # How does Stockfish know if the king is in check?
  
  (Asked by: username_0 on 2020-10-07)
  
  I am writing a chess engine. I need to know how to tell if the king is in check. I was thinking that maybe I can use the approach that Stockfish uses. Where and how in Stockfish's code is check detected?
  
  **Tags:** engines, stockfish, programming
  
  > **Comments:**
  > **username_1**: https://www.chessprogramming.org/Check  
  > **username_2**: http://rin.io/chess-engine/ Not sure but the link above tells you how stockfish works. Perhaps you can find something there?  
  > **username_3**: I assume you've had a read of the source? https://github.com/official-stockfish/Stockfish  
  > **username_4**: Once you've written code to identify possible next moves, you can just check whether any of them involve capturing the king.  
  > **username_5**: This is not a chess question.  
  > **username_0**: @J Yes it is lol  
  
  ---
  
  ## 3 answers
  
  ### Answer by username_16 on 2020-10-08. Score: 25 | Accepted answer
  
  If you're curious about the Stockfish code, it can be found here:
   si->checkersBB = attackers_to(square(sideToMove)) & pieces(~sideToMove);
  
  
  We call the attackers_to method to figure out if any pieces are attacking the king's position, including pieces on the king's side.
  
   Bitboard Position::attackers_to(Square s, Bitboard occupied) const {
  
      return  (pawn_attacks_bb(BLACK, s)       & pieces(WHITE, PAWN))
           | (pawn_attacks_bb(WHITE, s)       & pieces(BLACK, PAWN))
           | (attacks_bb(s)           & pieces(KNIGHT))
           | (attacks_bb<  ROOK>(s, occupied) & pieces(  ROOK, QUEEN))
           | (attacks_bb(s, occupied) & pieces(BISHOP, QUEEN))
           | (attacks_bb(s)             & pieces(KING));
   }
  
  
  We then call the pieces function, which returns all the pieces owned by the opposite side
  
  Finally, we run an AND operator to confirm if any of the opposite side's pieces are threatening the king.
  
  
  The code is very well written and relatively straightforward to follow, in case you'd like to explore it further.
  
  
  ---
  
  ### Answer by username_12 on 2020-10-08. Score: 18
  
  > Where and how in Stockfish's code is check detected?
  
  This is simple engine programming. You will need to build a bitboard of the attacking squares and two bitboards of your king, one for each color. You will then run AND on the two bitboards. If the result is non-zero, you know the king is in check.
  
  I can show you the code in Stockfish, but does my answer make sense to you? If not, please add a comment so I will try to grab some code.
  
  > **Comments:**
  > **username_13**: How is the operation (Bitboard AND Bitboard) defined? This is ambiguous. Bitboard is a matrix, while the operands of AND are bits.  
  > **username_14**: You operate over the matrix, ANDing the corresponding positions one by one.  So 64 "single ANDs" in total.  
  > **username_12**: @username_14 You just need two 64 bits integers. And do like `a & b`.  
  > **username_14**: @username_12 That’s another way to think of it (and probably closer to reality), I just wanted to emphasize that the AND operation is bit by bit, even with a matrix.  
  > **username_15**: I think this is sometimes called a “pointwise” operation, to distinguish from row- or column-wise operations (at least, this is true in the numpy and matlab parlance).  
  
  ---
  
  ### Answer by username_6 on 2020-10-08. Score: 15
  
  Your question has nothing to do with Stockfish. Though it may be interesting to check the original source code.
  
  This is purely algorithmic.
  
  One dumb solution would be implementing a boolean function (is\_check) that takes an array as input representing the board. Only white pieces can check the black king, except the white king and vice versa.
  
  If one of the following conditions is verified then there is a check on the board(return True) :
  
  * If a knight is placed at (-+)2(-+)1 or (-+)1(-+)2 squares from your king
  * If a pawn is placed at (-+)1+1 squares from your king (depends on the side you make the verification for as pawns move and attack only in one way)
  * If your king is in diagonal of a bishop or a queen and that no other pieces interferes
  * If your king is aligned (column/row) with a rook or a queen and that no other pieces interferes
  
  Otherwise return False.
  
  Note that such a function could be used in another method to check if a planned move is legal (if your king is in check after you played, your move is illegal)
  
  > **Comments:**
  > **username_7**: If you're going to use it to see if a move is legal (i.e. you are not assuming legality of the current position, only the preceding one), you need to allow for checks from the opposing king.  
  > **username_8**: Checkmate is slightly more complicated of course - because you'd have to then check every legal move that could be done in response and see if the king is still checked in all of them.  Stalemate would be the same only the king is not currently in check.  Draw by repetition or by X moves with no change in material, or insufficient material on both sides to complete, slightly more complicated, but not impossible.  
  > **username_9**: If you use it to decide whether the king is in check after the move, beware of pinned pieces. Thus, it must be re-calculated for non-king-moves.  
  > **username_10**: @username_9 Why is it an issue whether something is pinned? A unit may check whether or not it is pinned.  
  > **username_11**: @DarrelHoffman: I would tend to assume that both checkmate and stalemate naturally fall out of the "find all of the legal moves" logic (which you obviously need to write anyway). If you can't find any legal moves, then it must be one or the other, and you need only look for check to determine which it is.  
  > **username_8**: @username_11 Yeah, sorry, I shouldn't have said "legal moves" because obviously any move that leaves you in check is not legal.  Better might be to say "all possible moves if you were to ignore that rule", and then see if there's still a check in each of those cases, but I don't know if there's a term for that.  
  > **username_11**: @DarrelHoffman: What I'm suggesting is this: You design check, and all of the other "is this move legal?" rules into your engine first. Then, you design it to enumerate all of the legal moves, and use that enumeration to do the standard minimax tree search (with evaluation, pruning, etc.). If you find your tree search has reached a leaf node (i.e. there are no legal moves), then you go back to the check logic and ask "Is the player to move in check?" If so, then you have checkmate, and if not, then you have stalemate. No need for a separate evaluation pass at all.  
  
  ---
  
  