If the engine can choose between getting mated in 2 or mated in 3, it'll choose the line where it is mated in 3 (even though the mate in 2 might be 'more difficult' to spot for humans).
It can't really set traps, because it doesn't know what things might be difficult to spot for a human (or other engine) opponent. It just evaluates the position, without really knowing it's playing a game against somebody; a notable exception is the implementation of contempt, basically a slight modification of the evaluation in order to prevent drawing too early.
For example, in Stockfish, scores for won or lost positions are computed with the function mated_in
(and, more rarely, its negated form mate_in
). As you can see in the code, a loss is scored as a large negative value plus the number of ply until the loss, so the engine favors winning lines that are fast and losing lines that are slow.
The tie-breaking for draws is usually arbitrary. For instance, in Stockfish, scores for drawn positions are either the constant VALUE_DRAW
or computed by the function value_draw
to be VALUE_DRAW
plus one or plus twominus one. The bonus depends on the thread's node counter, which is essentially up to luck, so the variations in scores for drawn positions are not really based on the positions themselves. This small bit of noise in draw scoring is more to keep the search from fixating on certain three-fold repetitions than to help it choose among lines.