]> git.sesse.net Git - stockfish/blob - src/movepick.cpp
Use MVV/LVA in score_evasions()
[stockfish] / src / movepick.cpp
1 /*
2   Stockfish, a UCI chess playing engine derived from Glaurung 2.1
3   Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
4   Copyright (C) 2008 Marco Costalba
5
6   Stockfish is free software: you can redistribute it and/or modify
7   it under the terms of the GNU General Public License as published by
8   the Free Software Foundation, either version 3 of the License, or
9   (at your option) any later version.
10
11
12   Stockfish is distributed in the hope that it will be useful,
13   but WITHOUT ANY WARRANTY; without even the implied warranty of
14   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15   GNU General Public License for more details.
16
17   You should have received a copy of the GNU General Public License
18   along with this program.  If not, see <http://www.gnu.org/licenses/>.
19 */
20
21
22 ////
23 //// Includes
24 ////
25
26 #include <cassert>
27
28 #include "history.h"
29 #include "movegen.h"
30 #include "movepick.h"
31 #include "search.h"
32 #include "value.h"
33
34
35 ////
36 //// Local definitions
37 ////
38
39 namespace {
40
41   /// Variables
42
43   MovePicker::MovegenPhase PhaseTable[32];
44   int MainSearchPhaseIndex;
45   int EvasionsPhaseIndex;
46   int QsearchWithChecksPhaseIndex;
47   int QsearchWithoutChecksPhaseIndex;
48
49 }
50
51
52
53 ////
54 //// Functions
55 ////
56
57
58 /// Constructor for the MovePicker class.  Apart from the position for which
59 /// it is asked to pick legal moves, MovePicker also wants some information
60 /// to help it to return the presumably good moves first, to decide which
61 /// moves to return (in the quiescence search, for instance, we only want to
62 /// search captures, promotions and some checks) and about how important good
63 /// move ordering is at the current node.
64
65 MovePicker::MovePicker(const Position& p, bool pvnode, Move ttm, Move mk,
66                        Move k1, Move k2, Depth d) : pos(p) {
67   pvNode = pvnode;
68   ttMove = ttm;
69   mateKiller = (mk == ttm)? MOVE_NONE : mk;
70   killer1 = k1;
71   killer2 = k2;
72   depth = d;
73   movesPicked = 0;
74   numOfMoves = 0;
75   numOfBadCaptures = 0;
76   dc = p.discovered_check_candidates(p.side_to_move());
77
78   if (p.is_check())
79     phaseIndex = EvasionsPhaseIndex;
80   else if (depth > Depth(0))
81     phaseIndex = MainSearchPhaseIndex;
82   else if (depth == Depth(0))
83     phaseIndex = QsearchWithChecksPhaseIndex;
84   else
85     phaseIndex = QsearchWithoutChecksPhaseIndex;
86
87   pinned = p.pinned_pieces(p.side_to_move());
88
89   finished = false;
90 }
91
92
93 /// MovePicker::get_next_move() is the most important method of the MovePicker
94 /// class.  It returns a new legal move every time it is called, until there
95 /// are no more moves left of the types we are interested in.
96
97 Move MovePicker::get_next_move() {
98
99   Move move;
100
101   while (true)
102   {
103     // If we already have a list of generated moves, pick the best move from
104     // the list, and return it.
105     move = pick_move_from_list();
106     if (move != MOVE_NONE)
107     {
108         assert(move_is_ok(move));
109         return move;
110     }
111
112     // Next phase
113     phaseIndex++;
114     switch (PhaseTable[phaseIndex]) {
115
116     case PH_TT_MOVE:
117         if (ttMove != MOVE_NONE)
118         {
119             assert(move_is_ok(ttMove));
120             if (move_is_legal(pos, ttMove, pinned))
121                 return ttMove;
122         }
123         break;
124
125     case PH_MATE_KILLER:
126         if (mateKiller != MOVE_NONE)
127         {
128             assert(move_is_ok(mateKiller));
129             if (move_is_legal(pos, mateKiller, pinned))
130                 return mateKiller;
131        }
132        break;
133
134     case PH_GOOD_CAPTURES:
135         numOfMoves = generate_captures(pos, moves);
136         score_captures();
137         movesPicked = 0;
138         break;
139
140     case PH_BAD_CAPTURES:
141         badCapturesPicked = 0;
142         break;
143
144     case PH_NONCAPTURES:
145         numOfMoves = generate_noncaptures(pos, moves);
146         score_noncaptures();
147         movesPicked = 0;
148         break;
149
150     case PH_EVASIONS:
151         assert(pos.is_check());
152         numOfMoves = generate_evasions(pos, moves);
153         score_evasions();
154         movesPicked = 0;
155         break;
156
157     case PH_QCAPTURES:
158         numOfMoves = generate_captures(pos, moves);
159         score_qcaptures();
160         movesPicked = 0;
161         break;
162
163     case PH_QCHECKS:
164         numOfMoves = generate_checks(pos, moves, dc);
165         movesPicked = 0;
166         break;
167
168     case PH_STOP:
169         return MOVE_NONE;
170
171     default:
172         assert(false);
173         return MOVE_NONE;
174     }
175   }
176 }
177
178
179 /// A variant of get_next_move() which takes a lock as a parameter, used to
180 /// prevent multiple threads from picking the same move at a split point.
181
182 Move MovePicker::get_next_move(Lock &lock) {
183
184    lock_grab(&lock);
185    if (finished)
186    {
187        lock_release(&lock);
188        return MOVE_NONE;
189    }
190    Move m = get_next_move();
191    if (m == MOVE_NONE)
192        finished = true;
193
194    lock_release(&lock);
195    return m;
196 }
197
198
199 /// MovePicker::score_captures(), MovePicker::score_noncaptures(),
200 /// MovePicker::score_evasions() and MovePicker::score_qcaptures() assign a
201 /// numerical move ordering score to each move in a move list.  The moves
202 /// with highest scores will be picked first by pick_move_from_list().
203
204 void MovePicker::score_captures() {
205   // Winning and equal captures in the main search are ordered by MVV/LVA.
206   // Suprisingly, this appears to perform slightly better than SEE based
207   // move ordering.  The reason is probably that in a position with a winning
208   // capture, capturing a more valuable (but sufficiently defended) piece
209   // first usually doesn't hurt. The opponent will have to recapture, and
210   // the hanging piece will still be hanging (except in the unusual cases
211   // where it is possible to recapture with the hanging piece). Exchanging
212   // big pieces before capturing a hanging piece probably helps to reduce
213   // the subtree size. Instead of calculating SEE here to filter out 
214   // loosing captures, we delay the filtering in pick_move_from_list()
215   Move m;
216
217   for (int i = 0; i < numOfMoves; i++)
218   {
219       m = moves[i].move;
220       if (move_promotion(m))
221           moves[i].score = QueenValueMidgame;
222       else
223           moves[i].score = int(pos.midgame_value_of_piece_on(move_to(m)))
224                           -int(pos.type_of_piece_on(move_from(m)));
225   }
226 }
227
228 void MovePicker::score_noncaptures() {
229   // First score by history, when no history is available then use
230   // piece/square tables values. This seems to be better then a
231   // random choice when we don't have an history for any move.
232   Move m;
233   int hs;
234
235   for (int i = 0; i < numOfMoves; i++)
236   {
237       m = moves[i].move;
238
239       if (m == killer1)
240           hs = HistoryMax + 2;
241       else if (m == killer2)
242           hs = HistoryMax + 1;
243       else
244           hs = H.move_ordering_score(pos.piece_on(move_from(m)), m);
245
246       // Ensure moves in history are always sorted as first
247       if (hs > 0)
248           hs += 1000;
249
250       moves[i].score = hs + pos.mg_pst_delta(m);
251   }
252 }
253
254 void MovePicker::score_evasions() {\r
255 \r
256   Move m;\r
257   int hs;\r
258 \r
259   // Use MVV/LVA ordering\r
260    for (int i = 0; i < numOfMoves; i++)\r
261    {\r
262       m = moves[i].move;\r
263 \r
264        if (m == ttMove)\r
265           hs = 2*HistoryMax;\r
266        else if (!pos.square_is_empty(move_to(m)))\r
267           hs = int(pos.midgame_value_of_piece_on(move_to(m)))\r
268               -int(pos.type_of_piece_on(move_from(m))) + HistoryMax;\r
269       else\r
270           hs = H.move_ordering_score(pos.piece_on(move_from(m)), m);\r
271 \r
272       moves[i].score = hs;\r
273   }\r
274 }
275
276 void MovePicker::score_qcaptures() {
277
278   // Use MVV/LVA ordering
279   for (int i = 0; i < numOfMoves; i++)
280   {
281       Move m = moves[i].move;
282       if (move_promotion(m))
283           moves[i].score = QueenValueMidgame;
284       else
285           moves[i].score = int(pos.midgame_value_of_piece_on(move_to(m)))
286                           -int(pos.type_of_piece_on(move_from(m)));
287   }
288 }
289
290
291 /// find_best_index() loops across the moves and returns index of
292 /// the highest scored one.
293
294 int MovePicker::find_best_index() {
295
296   int bestScore = -10000000, bestIndex = -1;
297
298   for (int i = movesPicked; i < numOfMoves; i++)
299       if (moves[i].score > bestScore)
300       {
301           bestIndex = i;
302           bestScore = moves[i].score;
303       }
304   return bestIndex;
305 }
306
307
308 /// MovePicker::pick_move_from_list() picks the move with the biggest score
309 /// from a list of generated moves (moves[] or badCaptures[], depending on
310 /// the current move generation phase).  It takes care not to return the
311 /// transposition table move if that has already been serched previously.
312 /// While picking captures in the PH_GOOD_CAPTURES phase (i.e. while picking
313 /// non-losing captures in the main search), it moves all captures with
314 /// negative SEE values to the badCaptures[] array.
315
316 Move MovePicker::pick_move_from_list() {
317
318   int bestIndex;
319   Move move;
320
321   switch (PhaseTable[phaseIndex]) {
322   case PH_GOOD_CAPTURES:
323       assert(!pos.is_check());
324       assert(movesPicked >= 0);
325
326       while (movesPicked < numOfMoves)
327       {
328           bestIndex = find_best_index();
329
330           if (bestIndex != -1) // Found a possibly good capture
331           {
332               move = moves[bestIndex].move;
333               int seeValue = pos.see(move);
334               if (seeValue < 0)
335               {
336                   // Losing capture, move it to the badCaptures[] array
337                   assert(numOfBadCaptures < 63);
338                   moves[bestIndex].score = seeValue;
339                   badCaptures[numOfBadCaptures++] = moves[bestIndex];
340                   moves[bestIndex] = moves[--numOfMoves];
341                   continue;
342               }
343               moves[bestIndex] = moves[movesPicked++];
344               if (   move != ttMove
345                   && move != mateKiller
346                   && pos.pl_move_is_legal(move, pinned))
347                   return move;
348           }
349       }
350       break;
351
352   case PH_NONCAPTURES:
353       assert(!pos.is_check());
354       assert(movesPicked >= 0);
355
356       while (movesPicked < numOfMoves)
357       {
358           // If this is a PV node or we have only picked a few moves, scan
359           // the entire move list for the best move.  If many moves have already
360           // been searched and it is not a PV node, we are probably failing low
361           // anyway, so we just pick the first move from the list.
362           bestIndex = (pvNode || movesPicked < 12) ? find_best_index() : movesPicked;
363
364           if (bestIndex != -1)
365           {
366               move = moves[bestIndex].move;
367               moves[bestIndex] = moves[movesPicked++];
368               if (   move != ttMove
369                   && move != mateKiller
370                   && pos.pl_move_is_legal(move, pinned))
371                   return move;
372           }
373       }
374       break;
375
376   case PH_EVASIONS:
377       assert(pos.is_check());
378       assert(movesPicked >= 0);
379
380       while (movesPicked < numOfMoves)
381       {
382           bestIndex = find_best_index();
383
384           if (bestIndex != -1)
385           {
386               move = moves[bestIndex].move;
387               moves[bestIndex] = moves[movesPicked++];
388               return move;
389           }
390     }
391     break;
392
393   case PH_BAD_CAPTURES:
394       assert(!pos.is_check());
395       assert(badCapturesPicked >= 0);
396       // It's probably a good idea to use SEE move ordering here, instead
397       // of just picking the first move.  FIXME
398       while (badCapturesPicked < numOfBadCaptures)
399       {
400           move = badCaptures[badCapturesPicked++].move;
401           if (   move != ttMove
402               && move != mateKiller
403               && pos.pl_move_is_legal(move, pinned))
404               return move;
405       }
406       break;
407
408   case PH_QCAPTURES:
409       assert(!pos.is_check());
410       assert(movesPicked >= 0);
411       while (movesPicked < numOfMoves)
412       {
413           bestIndex = (movesPicked < 4 ? find_best_index() : movesPicked);
414
415           if (bestIndex != -1)
416           {
417               move = moves[bestIndex].move;
418               moves[bestIndex] = moves[movesPicked++];
419               // Remember to change the line below if we decide to hash the qsearch!
420               // Maybe also postpone the legality check until after futility pruning?
421               if (/* move != ttMove && */ pos.pl_move_is_legal(move, pinned))
422                   return move;
423           }
424       }
425       break;
426
427   case PH_QCHECKS:
428       assert(!pos.is_check());
429       assert(movesPicked >= 0);
430       // Perhaps we should do something better than just picking the first
431       // move here?  FIXME
432       while (movesPicked < numOfMoves)
433       {
434           move = moves[movesPicked++].move;
435           // Remember to change the line below if we decide to hash the qsearch!
436           if (/* move != ttMove && */ pos.pl_move_is_legal(move, pinned))
437               return move;
438       }
439       break;
440
441   default:
442       break;
443   }
444   return MOVE_NONE;
445 }
446
447
448 /// MovePicker::current_move_type() returns the type of the just
449 /// picked next move. It can be used in search to further differentiate
450 /// according to the current move type: capture, non capture, escape, etc.
451 MovePicker::MovegenPhase MovePicker::current_move_type() const {
452
453   return PhaseTable[phaseIndex];
454 }
455
456
457 /// MovePicker::init_phase_table() initializes the PhaseTable[],
458 /// MainSearchPhaseIndex, EvasionPhaseIndex, QsearchWithChecksPhaseIndex
459 /// and QsearchWithoutChecksPhaseIndex variables. It is only called once
460 /// during program startup, and never again while the program is running.
461
462 void MovePicker::init_phase_table() {
463
464   int i = 0;
465
466   // Main search
467   MainSearchPhaseIndex = i - 1;
468   PhaseTable[i++] = PH_TT_MOVE;
469   PhaseTable[i++] = PH_MATE_KILLER;
470   PhaseTable[i++] = PH_GOOD_CAPTURES;
471   // PH_KILLER_1 and PH_KILLER_2 are not yet used.
472   // PhaseTable[i++] = PH_KILLER_1;
473   // PhaseTable[i++] = PH_KILLER_2;
474   PhaseTable[i++] = PH_NONCAPTURES;
475   PhaseTable[i++] = PH_BAD_CAPTURES;
476   PhaseTable[i++] = PH_STOP;
477
478   // Check evasions
479   EvasionsPhaseIndex = i - 1;
480   PhaseTable[i++] = PH_EVASIONS;
481   PhaseTable[i++] = PH_STOP;
482
483   // Quiescence search with checks
484   QsearchWithChecksPhaseIndex = i - 1;
485   PhaseTable[i++] = PH_QCAPTURES;
486   PhaseTable[i++] = PH_QCHECKS;
487   PhaseTable[i++] = PH_STOP;
488
489   // Quiescence search without checks
490   QsearchWithoutChecksPhaseIndex = i - 1;
491   PhaseTable[i++] = PH_QCAPTURES;
492   PhaseTable[i++] = PH_STOP;
493 }