Stockfish - Function that predicts checkmate 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() &amp;&amp; generate&lt;MV_LEGAL&gt;(*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:

template&lt;&gt;
MoveStack* generate&lt;TRAP&gt;(const Position&amp; pos, MoveStack* mlist) {

  assert(pos.is_ok());
  MoveStack *last, *cur = mlist;
  // Generate all legal moves
  last = generate&lt;MV_LEGAL&gt;(pos, mlist);

  // If a legal move isn't a trap, remove it
  while (cur != last)
    for (i = 0; i = MAX_MOVES; i++)
      pos-&gt;do_move(mlist[i].move);
      if (!pos.is_trap())
          cur-&gt;move = (--last)-&gt;move;
      else
          cur++;
      pos-&gt;undo_move(mlist[i].move);

  return last;
}


Is there a more efficient way of doing this? Thank you for your help!
I don't understand why this is an issue. What you're asking is just chess engine search. Nothing more.


Generate all possible moves to a list
Make a move to the position
Search the new position with Stockfish (the search&lt;&gt; function)
Check the returned negamax value if the move leads to forced mate
Undo the move
Get the next move from the list, go back to (2) and repeat