I'm working on a function that can forecast whether, for a given position, I can be checkmated by the opponent. I have this function, already in Stockfish:

bool Position::is_mate() const {

  MoveStack moves[MAX_MOVES];
  return in_check() && generate<MV_LEGAL>(*this, moves) == moves;

This tells me that I am already being checkmated. Ideally, I would like to write a function:

bool Position::is_trap() const {
  for all of the opponent's legal moves
    if move i results in is_mate()
      return true

  return false

Both of these functions will be in position.cpp.

Subsequently, I want to generate a list of all legal moves that will result in is_trap() being true (all legal moves that will result in me being checkmated in the next turn). In movegen.cpp I have:

MoveStack* generate<TRAP>(const Position& pos, MoveStack* mlist) {

  MoveStack *last, *cur = mlist;
  // Generate all legal moves
  last = generate<MV_LEGAL>(pos, mlist);

  // If a legal move isn't a trap, remove it
  while (cur != last)
    for (i = 0; i = MAX_MOVES; i++)
      if (!pos.is_trap())
          cur->move = (--last)->move;

  return last;

Is there a more efficient way of doing this? Thank you for your help!

  • Just get stockfish to search to depth 2 or 3 and you'll get pretty much all of the possible mates.
    – konsolas
    Sep 9, 2017 at 8:36

1 Answer 1


I don't understand why this is an issue. What you're asking is just chess engine search. Nothing more.

  1. Generate all possible moves to a list
  2. Make a move to the position
  3. Search the new position with Stockfish (the search<> function)
  4. Check the returned negamax value if the move leads to forced mate
  5. Undo the move
  6. Get the next move from the list, go back to (2) and repeat

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.