movegen.rs 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765
  1. use bitboard::Bitboard;
  2. use bitboard::Square;
  3. use bitboard::*;
  4. use game::Game;
  5. use hash::{Cache, EntryType};
  6. pub type Side = bool;
  7. pub const WHITE: Side = false;
  8. pub const BLACK: Side = true;
  9. pub type PieceType = u8;
  10. pub const NO_PIECE: PieceType = 255;
  11. pub const PAWN: PieceType = 0;
  12. pub const KNIGHT: PieceType = 1;
  13. pub const BISHOP: PieceType = 2;
  14. pub const ROOK: PieceType = 3;
  15. pub const QUEEN: PieceType = 4;
  16. pub const KING: PieceType = 5;
  17. #[derive(Copy, Clone, Debug, PartialEq, Eq)]
  18. pub struct SimpleMove {
  19. pub from: Square,
  20. pub to: Square,
  21. }
  22. #[derive(Debug, Copy, Clone, PartialEq, Eq)]
  23. pub enum Move {
  24. Default { mov: SimpleMove, piece_type: PieceType, captured: Option<PieceType> },
  25. Castling { side: Side, left: bool },
  26. EnPassant { mov: SimpleMove, beaten: Square },
  27. Promotion { mov: SimpleMove, promote_to: PieceType, captured: Option<PieceType> },
  28. Nullmove
  29. }
  30. #[derive(Debug, Copy, Clone, PartialEq, Eq)]
  31. pub struct MoveUndo {
  32. pub castling_rights_before: [bool; 4],
  33. pub halfmoves_since_last_event_before: i8,
  34. pub en_passant_before: Option<u8>,
  35. pub mov: Move
  36. }
  37. impl Default for Move {
  38. fn default() -> Move {
  39. Move::Nullmove
  40. }
  41. }
  42. impl Move {
  43. pub fn parse_square(sq: &str) -> Option<Square> {
  44. let col = sq.chars().nth(0)?;
  45. let row = sq.chars().nth(1)?;
  46. Some((row as u8 - '1' as u8) * 8 + 7 - (col as u8 - 'a' as u8))
  47. }
  48. pub fn square_to_string(sq: Square) -> String {
  49. let col = 7 - (sq % 8);
  50. let row = sq / 8;
  51. let colchar = (('a' as u8) + col) as char;
  52. let rowchar = (('1' as u8) + row) as char;
  53. let chars = [colchar, rowchar];
  54. //println!("{} {}", col, row);
  55. chars.iter().collect()
  56. }
  57. pub fn is_null(&self) -> bool {
  58. *self == Move::Nullmove
  59. }
  60. pub fn to_string(&self) -> String {
  61. match self {
  62. Move::Default{ mov, piece_type: _pt, captured: _c } => {
  63. Self::square_to_string(mov.from) + &Self::square_to_string(mov.to)
  64. },
  65. Move::Castling{ side, left } => {
  66. match (side, left) {
  67. (&WHITE, false) => {
  68. Self::square_to_string(3) + &Self::square_to_string(1)
  69. },
  70. (&WHITE, true) => {
  71. Self::square_to_string(3) + &Self::square_to_string(5)
  72. },
  73. (&BLACK, false) => {
  74. Self::square_to_string(56 + 3) + &Self::square_to_string(56 + 1)
  75. },
  76. (&BLACK, true) => {
  77. Self::square_to_string(56 + 3) + &Self::square_to_string(56 + 5)
  78. }
  79. }
  80. },
  81. Move::EnPassant{ mov, beaten: _ } => {
  82. Self::square_to_string(mov.from) + &Self::square_to_string(mov.to)
  83. },
  84. Move::Promotion{ mov, promote_to, captured: _c } => {
  85. Self::square_to_string(mov.from) + &Self::square_to_string(mov.to) +
  86. if *promote_to == QUEEN { "q" }
  87. else if *promote_to == ROOK { "r" }
  88. else if *promote_to == KNIGHT { "n" }
  89. else if *promote_to == BISHOP { "b" }
  90. else { "" }
  91. },
  92. Move::Nullmove => {
  93. String::from("0000")
  94. }
  95. }
  96. }
  97. pub fn is_capture(&self) -> bool {
  98. match self {
  99. Move::Default{ mov: _, piece_type: _, captured: c } => c.is_some(),
  100. Move::Promotion{ mov: _, promote_to: _, captured: c } => c.is_some(),
  101. Move::EnPassant{ mov: _, beaten: _ } => true,
  102. Move::Castling{ side: _, left: _ } => false,
  103. Move::Nullmove => false
  104. }
  105. }
  106. }
  107. /**
  108. * @brief Iterator to serialize bitboard bit for bit
  109. *
  110. * Extracts every bit out of the bitboard and returns each one as a separate bitboard.
  111. */
  112. pub struct BitboardIterator (pub Bitboard);
  113. impl Iterator for BitboardIterator {
  114. type Item = Bitboard;
  115. fn next(&mut self) -> Option<Bitboard> {
  116. if self.0 != 0 {
  117. let lsb = self.0 & (self.0.wrapping_neg());
  118. self.0 ^= lsb;
  119. //Some(lsb.trailing_zeros())
  120. Some(lsb)
  121. } else {
  122. None
  123. }
  124. }
  125. }
  126. impl SimpleMove {
  127. pub fn apply_to(self, bitboard: Bitboard) -> Bitboard {
  128. (bitboard & !from_square(self.from)) | from_square(self.to)
  129. }
  130. }
  131. pub fn generate_moves(game: &Game, side: Side) -> Vec<Move> {
  132. let mut moves: Vec<Move> = Vec::with_capacity(128);
  133. generate_pawn_pushes(game, side, &mut moves);
  134. generate_pawn_doublepushes(game, side, &mut moves);
  135. generate_pawn_captures(game, side, &mut moves);
  136. generate_promotions(game, side, &mut moves);
  137. generate_en_passant(game, side, &mut moves);
  138. generate_knight_moves(game, side, &mut moves, false);
  139. generate_bishop_moves(game, side, &mut moves, false);
  140. generate_rook_moves(game, side, &mut moves, false);
  141. generate_queen_moves(game, side, &mut moves, false);
  142. generate_king_moves(game, side, &mut moves, false);
  143. generate_castling_moves(game, side, &mut moves);
  144. return moves;
  145. }
  146. /**
  147. * generates moves that could possibly attack a king,
  148. * this function is used to check if the king is in check
  149. */
  150. pub fn generate_possattacking_moves(game: &Game, side: Side) -> Vec<Move> {
  151. let mut moves: Vec<Move> = Vec::with_capacity(32);
  152. generate_pawn_captures(game, side, &mut moves);
  153. generate_promotions(game, side, &mut moves);
  154. generate_knight_moves(game, side, &mut moves, true);
  155. generate_bishop_moves(game, side, &mut moves, true);
  156. generate_rook_moves(game, side, &mut moves, true);
  157. generate_queen_moves(game, side, &mut moves, true);
  158. generate_king_moves(game, side, &mut moves, true);
  159. return moves;
  160. }
  161. pub fn generate_legal_moves(game: &mut Game, side: Side) -> Vec<Move> {
  162. let moves = generate_moves(game, side);
  163. let check_legality = |mov: &Move| {
  164. let undo = game.apply(*mov);
  165. let legal = !is_check(game, side);
  166. game.undo_move(undo);
  167. return legal;
  168. };
  169. moves.into_iter().filter(check_legality).collect::<Vec<Move>>()
  170. }
  171. pub fn generate_legal_sorted_moves(game: &mut Game, hash: &mut Cache, killers: &[Move], side: Side) -> Vec<Move> {
  172. let moves = generate_moves(game, side);
  173. let illegal_value = crate::evaluate::MAX_VALUE;
  174. let mut mov_val_and_legality = |mov: &Move| {
  175. let undo = game.apply(*mov);
  176. let illegal = is_check(game, side);
  177. if illegal {
  178. game.undo_move(undo);
  179. return illegal_value;
  180. }
  181. if let Some(e) = hash.lookup(game) {
  182. game.undo_move(undo);
  183. if let EntryType::Value = e.entry_type {
  184. return e.value;
  185. }
  186. else if let EntryType::LowerBound = e.entry_type {
  187. return e.value - 1000;
  188. }
  189. else if let EntryType::UpperBound = e.entry_type {
  190. return e.value + 1000;
  191. }
  192. else {
  193. return crate::evaluate::evaluate(game) - if killers.contains(mov) { 200 } else { 0 };
  194. }
  195. }
  196. else {
  197. let eval = crate::evaluate::evaluate(game) - if killers.contains(mov) { 200 } else { 0 };
  198. game.undo_move(undo);
  199. return eval;
  200. }
  201. };
  202. let mut amovs: Vec<_> = moves.iter().map(|m| (*m, mov_val_and_legality(m))).collect();
  203. amovs.sort_unstable_by_key(|x| x.1);
  204. amovs.into_iter().filter(|x| x.1 != illegal_value).map(|(m, _v)| m).collect::<Vec<Move>>()
  205. }
  206. pub fn generate_attacking_moves(game: &Game, side: Side) -> Vec<Move> {
  207. let mut moves: Vec<Move> = Vec::with_capacity(32);
  208. generate_pawn_captures(game, side, &mut moves);
  209. generate_knight_moves(game, side, &mut moves, true);
  210. generate_bishop_moves(game, side, &mut moves, true);
  211. generate_rook_moves(game, side, &mut moves, true);
  212. generate_queen_moves(game, side, &mut moves, true);
  213. generate_king_moves(game, side, &mut moves, true);
  214. return moves;
  215. }
  216. pub fn sort_moves(game: &mut Game, hash: &mut Cache, killers: &[Move], move_list: &mut Vec<Move>) {
  217. move_list.sort_by_cached_key(|mov| {
  218. let undo = game.apply(*mov);
  219. if let Some(e) = hash.lookup(game) {
  220. game.undo_move(undo);
  221. if let EntryType::Value = e.entry_type {
  222. return e.value;
  223. }
  224. else if let EntryType::LowerBound = e.entry_type {
  225. return e.value - 1000;
  226. }
  227. else if let EntryType::UpperBound = e.entry_type {
  228. return e.value + 1000;
  229. }
  230. else {
  231. return crate::evaluate::evaluate(game) - if killers.contains(mov) { 200 } else { 0 };
  232. }
  233. }
  234. else {
  235. let eval = crate::evaluate::evaluate(game) - if killers.contains(mov) { 200 } else { 0 };
  236. game.undo_move(undo);
  237. return eval;
  238. }
  239. });
  240. }
  241. pub fn sort_moves_no_hash(game: &mut Game, move_list: &mut Vec<Move>) {
  242. move_list.sort_by_cached_key(|mov| {
  243. let undo = game.apply(*mov);
  244. let eval = crate::evaluate::evaluate(game);
  245. game.undo_move(undo);
  246. return eval;
  247. });
  248. }
  249. pub fn sort_quiescence(game: &mut Game, move_list: &mut Vec<Move>) {
  250. let value_piece = |pt| {
  251. match pt {
  252. PAWN => 1,
  253. KNIGHT => 2,
  254. BISHOP => 3,
  255. ROOK => 4,
  256. QUEEN => 5,
  257. KING => 6,
  258. _ => 0,
  259. }
  260. };
  261. move_list.sort_by_cached_key(|mov| {
  262. match *mov {
  263. Move::Default{ mov: _, piece_type, captured: Some(c) } => {
  264. value_piece(piece_type) - value_piece(c)
  265. },
  266. Move::Promotion{ mov: _, promote_to: _, captured: Some(c) } => {
  267. value_piece(PAWN) - value_piece(c)
  268. },
  269. Move::EnPassant{ mov: _, beaten } => {
  270. value_piece(PAWN) - value_piece(game.get_square(beaten).0)
  271. },
  272. _ => 0
  273. }
  274. });
  275. }
  276. fn generate_pawn_pushes(game: &Game, side: Side, move_list: &mut Vec<Move>) {
  277. let pawns = game.pawns(side);
  278. let others = game.get_all_side(!side);
  279. let pieces = game.get_all_side(side);
  280. let moved_pawns =
  281. match side {
  282. WHITE => north_one(pawns),
  283. BLACK => south_one(pawns)
  284. } & !(ROW_1 | ROW_8) & !(others | pieces);
  285. let iter = BitboardIterator(moved_pawns & !others);
  286. for p in iter {
  287. let origin = match side {
  288. WHITE => south_one(p),
  289. BLACK => north_one(p)
  290. };
  291. move_list.push(Move::Default { mov: SimpleMove { from: square(origin), to: square(p) }, piece_type: PAWN, captured: None });
  292. }
  293. }
  294. fn generate_pawn_doublepushes(game: &Game, side: Side, move_list: &mut Vec<Move>) {
  295. let pawns = game.pawns(side) & match side { WHITE => ROW_2, BLACK => ROW_7 };
  296. let others = game.get_all_side(!side);
  297. let pieces = game.get_all_side(side);
  298. let all_pieces = others | pieces;
  299. let moved_pawns =
  300. match side {
  301. WHITE => north_one(north_one(pawns) & !all_pieces),
  302. BLACK => south_one(south_one(pawns) & !all_pieces)
  303. } & !all_pieces;
  304. let iter = BitboardIterator(moved_pawns & !others);
  305. for p in iter {
  306. let origin = match side {
  307. WHITE => south_one(south_one(p)),
  308. BLACK => north_one(north_one(p))
  309. };
  310. move_list.push(Move::Default { mov: SimpleMove { from: square(origin), to: square(p) }, piece_type: PAWN, captured: None });
  311. }
  312. }
  313. fn generate_pawn_captures(game: &Game, side: Side, move_list: &mut Vec<Move>) {
  314. let pawns = game.pawns(side);
  315. let others = game.get_all_side(!side);
  316. let promotion_mask = ROW_1 | ROW_8;
  317. let pawn_iterator = BitboardIterator(pawns);
  318. for pawn in pawn_iterator {
  319. let left_cap = match side {
  320. WHITE => northeast_one(pawn),
  321. BLACK => southeast_one(pawn)
  322. };
  323. let right_cap = match side {
  324. WHITE => northwest_one(pawn),
  325. BLACK => southwest_one(pawn)
  326. };
  327. for cap in [left_cap, right_cap].iter() {
  328. if cap & others != 0 {
  329. let captured = game.find_piece(*cap);
  330. let simple_move = SimpleMove { from: square(pawn), to: square(*cap)};
  331. if cap & promotion_mask != 0 {
  332. move_list.push(Move::Promotion { mov: simple_move, promote_to: QUEEN, captured: captured });
  333. move_list.push(Move::Promotion { mov: simple_move, promote_to: ROOK, captured: captured });
  334. move_list.push(Move::Promotion { mov: simple_move, promote_to: BISHOP, captured: captured });
  335. move_list.push(Move::Promotion { mov: simple_move, promote_to: KNIGHT, captured: captured });
  336. } else {
  337. move_list.push(Move::Default { mov: simple_move, piece_type: PAWN, captured: captured });
  338. }
  339. }
  340. }
  341. }
  342. }
  343. fn generate_promotions(game: &Game, side: Side, move_list: &mut Vec<Move>) {
  344. let pawns = game.pawns(side);
  345. let others = game.get_all_side(!side);
  346. let pieces = game.get_all_side(side);
  347. let moved_pawns =
  348. match side {
  349. WHITE => north_one(pawns),
  350. BLACK => south_one(pawns)
  351. } & (ROW_1 | ROW_8) & !(others | pieces);
  352. let iter = BitboardIterator(moved_pawns);
  353. for p in iter {
  354. let origin = match side {
  355. WHITE => south_one(p),
  356. BLACK => north_one(p)
  357. };
  358. let movement = SimpleMove { from: square(origin), to: square(p) };
  359. //move_list.push(Move::Default { mov: SimpleMove { from: square(origin), to: square(p) }, piece_type: PAWN });
  360. move_list.push(Move::Promotion { mov: movement, promote_to: QUEEN, captured: None });
  361. move_list.push(Move::Promotion { mov: movement, promote_to: ROOK, captured: None });
  362. move_list.push(Move::Promotion { mov: movement, promote_to: BISHOP, captured: None });
  363. move_list.push(Move::Promotion { mov: movement, promote_to: KNIGHT, captured: None });
  364. }
  365. }
  366. fn generate_en_passant(game: &Game, side: Side, move_list: &mut Vec<Move>) {
  367. if let Some(ep) = game.en_passant {
  368. let pawncolumn = FILE_A >> ep;
  369. let pawnrow: Bitboard = match side {
  370. WHITE => ROW_5,
  371. BLACK => ROW_4
  372. };
  373. let beaten_pawn = pawncolumn & pawnrow;
  374. if beaten_pawn & game.get_piece(PAWN, !side) == 0 {
  375. return;
  376. }
  377. let pawn_left = (beaten_pawn << 1) & pawnrow;
  378. let pawn_right = (beaten_pawn >> 1) & pawnrow;
  379. let attacking_pawns = game.get_piece(PAWN, side);
  380. let target_square = pawncolumn & match side {
  381. WHITE => ROW_6,
  382. BLACK => ROW_3
  383. };
  384. if pawn_left & attacking_pawns != 0 {
  385. let mov = Move::EnPassant{ mov: SimpleMove{ from: square(pawn_left), to: square(target_square) }, beaten: square(beaten_pawn) };
  386. move_list.push(mov);
  387. }
  388. if pawn_right & attacking_pawns != 0 {
  389. let mov = Move::EnPassant{ mov: SimpleMove{ from: square(pawn_right), to: square(target_square) }, beaten: square(beaten_pawn) };
  390. move_list.push(mov);
  391. }
  392. }
  393. }
  394. fn generate_knight_moves(game: &Game, side: Side, move_list: &mut Vec<Move>, captures_only: bool) {
  395. let friends = game.get_all_side(side);
  396. let others = game.get_all_side(!side);
  397. let knights = game.knights(side);
  398. let knight_iter = BitboardIterator(knights);
  399. for k in knight_iter {
  400. let cap_targets = BitboardIterator(get_knight_targets(square(k)) & (!friends & others));
  401. let nocap_targets = BitboardIterator(get_knight_targets(square(k)) & (!friends & !others));
  402. for target in cap_targets {
  403. let simple_move = SimpleMove { from: square(k), to: square(target) };
  404. let captured = game.find_piece(target);
  405. move_list.push(Move::Default{ mov: simple_move, piece_type: KNIGHT, captured });
  406. }
  407. if !captures_only {
  408. for target in nocap_targets {
  409. let simple_move = SimpleMove { from: square(k), to: square(target) };
  410. move_list.push(Move::Default{ mov: simple_move, piece_type: KNIGHT, captured: None });
  411. }
  412. }
  413. }
  414. }
  415. pub fn get_knight_targets(square: Square) -> Bitboard {
  416. /// @brief array containing the possible targets for a knight on each square.
  417. /// entry at index i is a bitboard with all bits set where a knight on square i can jump
  418. const TARGETS: [Bitboard; 64] = [132096, 329728, 659712, 1319424, 2638848, 5277696, 10489856,
  419. 4202496, 33816580, 84410376, 168886289, 337772578, 675545156, 1351090312, 2685403152,
  420. 1075839008, 8657044482, 21609056261, 43234889994, 86469779988, 172939559976, 345879119952,
  421. 687463207072, 275414786112, 2216203387392, 5531918402816, 11068131838464, 22136263676928,
  422. 44272527353856, 88545054707712, 175990581010432, 70506185244672, 567348067172352,
  423. 1416171111120896, 2833441750646784, 5666883501293568, 11333767002587136, 22667534005174272,
  424. 45053588738670592, 18049583422636032, 145241105196122112, 362539804446949376,
  425. 725361088165576704, 1450722176331153408, 2901444352662306816, 5802888705324613632,
  426. 11533718717099671552, 4620693356194824192, 288234782788157440, 576469569871282176,
  427. 1224997833292120064, 2449995666584240128, 4899991333168480256, 9799982666336960512,
  428. 1152939783987658752, 2305878468463689728, 1128098930098176, 2257297371824128, 4796069720358912,
  429. 9592139440717824, 19184278881435648, 38368557762871296, 4679521487814656, 9077567998918656];
  430. TARGETS[square as usize]
  431. }
  432. fn generate_bishop_moves(game: &Game, side: Side, move_list: &mut Vec<Move>, captures_only: bool) {
  433. let friends = game.get_all_side(side);
  434. let others = game.get_all_side(!side);
  435. generate_sliding_moves(game, friends, others, game.bishops(side), BISHOP, false, true, move_list, captures_only);
  436. }
  437. fn generate_rook_moves(game: &Game, side: Side, move_list: &mut Vec<Move>, captures_only: bool) {
  438. let friends = game.get_all_side(side);
  439. let others = game.get_all_side(!side);
  440. generate_sliding_moves(game, friends, others, game.rooks(side), ROOK, true, false, move_list, captures_only);
  441. }
  442. fn generate_queen_moves(game: &Game, side: Side, move_list: &mut Vec<Move>, captures_only: bool) {
  443. let friends = game.get_all_side(side);
  444. let others = game.get_all_side(!side);
  445. generate_sliding_moves(game, friends, others, game.queens(side), QUEEN, true, true, move_list, captures_only);
  446. }
  447. fn generate_sliding_moves(game: &Game, friends: Bitboard, others: Bitboard, pieces: Bitboard, piece_type: PieceType,
  448. straight: bool, diagonal: bool, move_list: &mut Vec<Move>, captures_only: bool) {
  449. let pieces_iter = BitboardIterator(pieces);
  450. let mask = if captures_only { others } else { !(0 as Bitboard) };
  451. for piece in pieces_iter {
  452. let destinations = generate_sliding_destinations(friends, others, piece, straight, diagonal);
  453. let dest_iter = BitboardIterator(destinations & mask);
  454. for dest in dest_iter {
  455. let smove = SimpleMove{ from: square(piece), to: square(dest) };
  456. if dest & others != 0 {
  457. move_list.push(Move::Default { mov: smove, piece_type: piece_type, captured: game.find_piece(dest) });
  458. }
  459. else {
  460. move_list.push(Move::Default { mov: smove, piece_type: piece_type, captured: None });
  461. }
  462. }
  463. }
  464. }
  465. fn generate_sliding_destinations(friends: Bitboard, others: Bitboard,
  466. piece: Bitboard, straight: bool,
  467. diagonal: bool) -> Bitboard {
  468. let occupied = friends | others;
  469. let straights = [north_one, south_one, east_one, west_one];
  470. let diagonals = [northeast_one, southeast_one, northwest_one, southwest_one];
  471. let mut result: Bitboard = 0;
  472. if straight {
  473. for direction in straights.iter() {
  474. result |= generate_direction(piece, *direction, occupied);
  475. }
  476. }
  477. if diagonal {
  478. for direction in diagonals.iter() {
  479. result |= generate_direction(piece, *direction, occupied);
  480. }
  481. }
  482. return result & !friends;
  483. }
  484. fn generate_direction(piece: Bitboard, direction: fn(Bitboard) -> Bitboard, occupied: Bitboard) -> Bitboard {
  485. let mut result: Bitboard = 0;
  486. let mut b = piece;
  487. loop {
  488. b = direction(b);
  489. result |= b;
  490. if b & (occupied) != 0 || b == 0 {
  491. break;
  492. }
  493. }
  494. return result;
  495. }
  496. fn generate_king_moves(game: &Game, side: Side, move_list: &mut Vec<Move>, captures_only: bool) {
  497. let friends = game.get_all_side(side);
  498. let others = game.get_all_side(!side);
  499. let king = game.kings(side);
  500. //assert_eq!(king.count_ones(), 1); // assume only one king per player
  501. if king.count_ones() != 1 { return; }
  502. let mask =
  503. if captures_only {
  504. !friends & others
  505. }
  506. else {
  507. !friends
  508. };
  509. let area = (north_one(king)
  510. | south_one(king)
  511. | east_one(king)
  512. | west_one(king)
  513. | northeast_one(king)
  514. | northwest_one(king)
  515. | southwest_one(king)
  516. | southeast_one(king))
  517. & mask;
  518. let area_iter = BitboardIterator(area);
  519. for destination in area_iter {
  520. let simple_move = SimpleMove{ from: square(king), to: square(destination) };
  521. let captured = game.find_piece(destination);
  522. move_list.push(Move::Default { mov: simple_move, piece_type: KING, captured });
  523. }
  524. }
  525. fn generate_castling_moves(game: &Game, side: Side, move_list: &mut Vec<Move>) {
  526. let c1 = Move::Castling{ side: side, left: false };
  527. let c2 = Move::Castling{ side: side, left: true };
  528. let legal_castlings: &[bool] = match side {
  529. WHITE => &game.castling_rights[0..2],
  530. BLACK => &game.castling_rights[2..4],
  531. };
  532. let all_pieces = game.get_all_side(WHITE) | game.get_all_side(BLACK);
  533. // kingside castling
  534. if legal_castlings[0] {
  535. //info!("possible castling? {} {} {}", game.get_piece(KING, side), game.get_piece(ROOK, side), ((game.get_piece(KING, side) >> 3) & game.get_piece(ROOK, side)));
  536. if ((game.get_piece(KING, side) >> 3) & game.get_piece(ROOK, side)) != 0 &&
  537. ((game.get_piece(KING, side) >> 1) | (game.get_piece(KING, side) >> 2)) & all_pieces == 0 {
  538. let mut tg1 = game.clone();
  539. *tg1.get_piece_mut(KING, side) = game.get_piece(KING, side) >> 1;
  540. if !is_check(game, side) && !is_check(&tg1, side) {
  541. move_list.push(c1);
  542. }
  543. }
  544. }
  545. // queenside
  546. if legal_castlings[1] {
  547. //info!("possible castling? {} {} {}", game.get_piece(KING, side), game.get_piece(ROOK, side), ((game.get_piece(KING, side) >> 3) & game.get_piece(ROOK, side)));
  548. if ((game.get_piece(KING, side) << 4) & game.get_piece(ROOK, side)) != 0 &&
  549. ((game.get_piece(KING, side) << 1) | (game.get_piece(KING, side) << 2) | (game.get_piece(KING, side) << 3)) & all_pieces == 0 {
  550. let mut tg1 = game.clone();
  551. let mut tg2 = game.clone();
  552. *tg1.get_piece_mut(KING, side) = game.get_piece(KING, side) << 1;
  553. *tg2.get_piece_mut(KING, side) = game.get_piece(KING, side) << 2;
  554. if !is_check(game, side) && !is_check(&tg1, side) && !is_check(&tg2, side) {
  555. move_list.push(c2);
  556. }
  557. }
  558. }
  559. }
  560. pub fn is_check(game: &Game, side: Side) -> bool {
  561. let king = game.get_piece(KING, side);
  562. let king_square = square(king);
  563. let friends = game.get_all_side(side);
  564. let others = game.get_all_side(!side);
  565. let knights = get_knight_targets(king_square);
  566. if knights & game.get_piece(KNIGHT, !side) != 0 {
  567. return true;
  568. }
  569. let diagonal = generate_sliding_destinations(friends, others, king, false, true);
  570. let straight = generate_sliding_destinations(friends, others, king, true, false);
  571. if diagonal & game.get_piece(BISHOP, !side) != 0 {
  572. return true;
  573. }
  574. if diagonal & game.get_piece(QUEEN, !side) != 0 {
  575. return true;
  576. }
  577. if straight & game.get_piece(ROOK, !side) != 0 {
  578. return true;
  579. }
  580. if straight & game.get_piece(QUEEN, !side) != 0 {
  581. return true;
  582. }
  583. if side == BLACK {
  584. if ((southeast_one(king) | southwest_one(king)) & game.get_piece(PAWN, !side)) != 0 {
  585. return true;
  586. }
  587. }
  588. else {
  589. if ((northeast_one(king) | northwest_one(king)) & game.get_piece(PAWN, !side)) != 0 {
  590. return true;
  591. }
  592. }
  593. let king_area = north_one(king)
  594. | south_one(king)
  595. | east_one(king)
  596. | west_one(king)
  597. | northeast_one(king)
  598. | northwest_one(king)
  599. | southwest_one(king)
  600. | southeast_one(king);
  601. if king_area & game.get_piece(KING, !side) != 0 {
  602. return true;
  603. }
  604. return false;
  605. }
  606. /**
  607. * checks if side's king is in check
  608. */
  609. pub fn is_check_old(game: &Game, side: Side) -> bool {
  610. let king = game.get_piece(KING, side);
  611. let king_square = square(king);
  612. let possible_attacks = generate_possattacking_moves(game, !side);
  613. for mov in possible_attacks {
  614. if let Move::Default{ mov, piece_type: _, captured: _ } = mov {
  615. if mov.to == king_square {
  616. if !is_check(game, side) {
  617. panic!("incorrect non-check {}", game.beautiful_print());
  618. }
  619. return true;
  620. }
  621. }
  622. else if let Move::Promotion{ mov, promote_to: _, captured: _ } = mov {
  623. if mov.to == king_square {
  624. if !is_check(game, side) {
  625. panic!("incorrect non-check {}", game.beautiful_print());
  626. }
  627. return true;
  628. }
  629. }
  630. }
  631. if is_check(game, side) {
  632. panic!("incorrect check {}", game.beautiful_print());
  633. }
  634. false
  635. }
  636. /*
  637. #[cfg(test)]
  638. mod tests {
  639. use search::Game;
  640. use movegen::*;
  641. #[test]
  642. fn pawn_pushes() {
  643. let mut game: Game = Game::default();
  644. let pawn_moves = generate_pawn_moves(&game, WHITE);
  645. assert_eq!(pawn_moves, ());
  646. }
  647. }
  648. */