ychess is a chess implementation written in nim.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

703 lines
24 KiB

  1. import tables
  2. from strutils import parseInt
  3. type
  4. Color* = enum
  5. Black = -1, White = 1
  6. ## Board that saves the pieces
  7. Pieces* = array[0..119, int]
  8. ## Board that checks if pieces moved
  9. Moved* = array[0..119, bool]
  10. ## Game as object of different values
  11. Game* = object
  12. pieces*: Pieces
  13. moved: Moved
  14. toMove*: Color
  15. ## Move as object
  16. Move* = object
  17. start: int
  18. dest: int
  19. color: Color
  20. prom: int
  21. const
  22. # IDs for piece
  23. BlockID* = 999
  24. PawnID* = 1
  25. KnightID* = 2
  26. BishopID* = 3
  27. RookID* = 4
  28. QueenID* = 5
  29. KingID* = 6
  30. EnPassantID* = 7
  31. # IDs that are saved in the array
  32. Block* = BlockID
  33. WPawn* = PawnID
  34. WKnight* = KnightID
  35. WBishop* = BishopID
  36. WRook* = RookID
  37. WQueen* = QueenID
  38. WKing* = KingID
  39. WEnPassant* = EnPassantID
  40. BPawn* = -PawnID
  41. BKnight* = -KnightID
  42. BBishop* = -BishopID
  43. BRook* = -RookID
  44. BQueen* = -QueenID
  45. BKing* = -KingID
  46. BEnPassant* = EnPassantID
  47. # Directions of movement
  48. N = 10
  49. S = -N
  50. W = 1
  51. E = -W
  52. # Movement options for pieces (Bishop/Rook/Queen can repeat in the same direction)
  53. Knight_Moves = [N+N+E, N+N+W, E+E+N, E+E+S, S+S+E, S+S+W, W+W+N, W+W+S]
  54. Bishop_Moves = [N+E, N+W, S+E, S+W]
  55. Rook_Moves = [N, E, S, W]
  56. Queen_Moves = [N, E, S, W, N+E, N+W, S+E, S+W]
  57. King_Moves = [N, E, S, W, N+E, N+W, S+E, S+W]
  58. King_Moves_White_Castle = [E+E, W+W]
  59. Pawn_Moves_White = [N]
  60. Pawn_Moves_White_Double = [N+N]
  61. Pawn_Moves_White_Attack = [N+E, N+W]
  62. var PieceChar = {
  63. 0: " ",
  64. 1: "P",
  65. 2: "N",
  66. 3: "B",
  67. 4: "R",
  68. 5: "Q",
  69. 6: "K",
  70. 7: " ",
  71. -1: "p",
  72. -2: "n",
  73. -3: "b",
  74. -4: "r",
  75. -5: "q",
  76. -6: "k",
  77. -7: " ",
  78. 999: "-"
  79. }.newTable
  80. var FileChar = {
  81. "a": 7,
  82. "b": 6,
  83. "c": 5,
  84. "d": 4,
  85. "e": 3,
  86. "f": 2,
  87. "g": 1,
  88. "h": 0
  89. }.newTable
  90. proc getField*(pieces: Pieces, field: int): int =
  91. return pieces[field]
  92. proc setField(pieces: var Pieces, field: int, val: int): bool {.discardable.} =
  93. if (val in PieceChar):
  94. try:
  95. pieces[field] = val
  96. return true
  97. except Exception:
  98. return false
  99. proc getField*(moved: Moved, field: int): bool =
  100. return moved[field]
  101. proc setField(moved: var Moved, field: int, val: bool): bool {.discardable.} =
  102. try:
  103. moved[field] = val
  104. return true
  105. except Exception:
  106. return false
  107. proc initBoard(): Pieces =
  108. ## Create and return a board with pieces in starting position.
  109. let board = [
  110. Block, Block, Block, Block, Block, Block, Block, Block, Block, Block,
  111. Block, Block, Block, Block, Block, Block, Block, Block, Block, Block,
  112. Block, WRook, WKnight, WBishop, WKing, WQueen, WBishop, WKnight, WRook, Block,
  113. Block, WPawn, WPawn, WPawn, WPawn, WPawn, WPawn, WPawn, WPawn, Block,
  114. Block, 0, 0, 0, 0, 0, 0, 0, 0, Block,
  115. Block, 0, 0, 0, 0, 0, 0, 0, 0, Block,
  116. Block, 0, 0, 0, 0, 0, 0, 0, 0, Block,
  117. Block, 0, 0, 0, 0, 0, 0, 0, 0, Block,
  118. Block, BPawn, BPawn, BPawn, BPawn, BPawn, BPawn, BPawn, BPawn, Block,
  119. Block, BRook, BKnight, BBishop, BKing, BQueen, BBishop, BKnight, BRook, Block,
  120. Block, Block, Block, Block, Block, Block, Block, Block, Block, Block,
  121. Block, Block, Block, Block, Block, Block, Block, Block, Block, Block]
  122. return board
  123. proc initBoard(pieces: array[0..63, int]): Pieces =
  124. ## Create and return a board with pieces in position of choice
  125. let board = [
  126. Block, Block, Block, Block, Block, Block, Block, Block, Block, Block,
  127. Block, Block, Block, Block, Block, Block, Block, Block, Block, Block,
  128. Block, pieces[0], pieces[1], pieces[2], pieces[3], pieces[4], pieces[5],
  129. pieces[6], pieces[7], Block,
  130. Block, pieces[8], pieces[9], pieces[10], pieces[11], pieces[12], pieces[13],
  131. pieces[14], pieces[15], Block,
  132. Block, pieces[16], pieces[17], pieces[18], pieces[19], pieces[20], pieces[
  133. 21], pieces[22], pieces[23], Block,
  134. Block, pieces[24], pieces[25], pieces[26], pieces[27], pieces[28], pieces[
  135. 29], pieces[30], pieces[31], Block,
  136. Block, pieces[32], pieces[33], pieces[34], pieces[35], pieces[36], pieces[
  137. 37], pieces[38], pieces[39], Block,
  138. Block, pieces[40], pieces[41], pieces[42], pieces[43], pieces[44], pieces[
  139. 45], pieces[46], pieces[47], Block,
  140. Block, pieces[48], pieces[49], pieces[50], pieces[51], pieces[52], pieces[
  141. 53], pieces[54], pieces[55], Block,
  142. Block, pieces[56], pieces[57], pieces[58], pieces[59], pieces[60], pieces[
  143. 61], pieces[62], pieces[63], Block,
  144. Block, Block, Block, Block, Block, Block, Block, Block, Block, Block,
  145. Block, Block, Block, Block, Block, Block, Block, Block, Block, Block]
  146. return board
  147. proc initMoved(): Moved =
  148. ## Create and return a board of pieces moved.
  149. var moved: Moved
  150. return moved
  151. proc initGame*(): Game =
  152. ## Create and return a Game object.
  153. let game = Game(pieces: initBoard(), moved: initMoved(),
  154. to_move: Color.White)
  155. return game
  156. proc initGame*(pieces: array[0..63, int], color: Color): Game =
  157. ## Create ad return a Game object based on a position of choice.
  158. let pieces = initBoard(pieces)
  159. let compare = initBoard()
  160. var moved = initMoved()
  161. var same_piece: bool
  162. for ind in pieces.low..pieces.high:
  163. same_piece = (pieces[ind] != compare[ind])
  164. moved.setField(ind, same_piece)
  165. let game = Game(pieces: pieces, moved: moved,
  166. to_move: color)
  167. return game
  168. proc getMove*(start: int, dest: int, prom: int, color: Color): Move =
  169. ## Get a move object from `start` to `dest` with an eventual promition to `prom`
  170. var move = Move(start: start, dest: dest, prom: prom * ord(color), color: color)
  171. if (KnightID > prom or QueenID < prom):
  172. move.prom = QueenID
  173. return move
  174. proc getMove*(start: int, dest: int, color: Color): Move =
  175. ## Get a move object from `start` to `dest` with automatic promition to `queen`
  176. var move = Move(start: start, dest: dest, prom: QueenID * ord(color), color: color)
  177. return move
  178. proc echoBoard*(game: Game, color: Color) =
  179. ## Prints out the given `board` with its pieces as characters and line indices from perspecive of `color`.
  180. var line_str = ""
  181. if (color == Color.Black):
  182. for i in countup(0, len(game.pieces)-1):
  183. if (game.pieces.getField(i) == 999):
  184. continue
  185. line_str &= PieceChar[game.pieces[i]] & " "
  186. if ((i+2) %% 10 == 0):
  187. line_str &= $((int)((i)/10)-1) & "\n"
  188. echo line_str
  189. echo "h g f e d c b a"
  190. else:
  191. for i in countdown(len(game.pieces)-1, 0):
  192. if (game.pieces.getField(i) == 999):
  193. continue
  194. line_str &= PieceChar[game.pieces[i]] & " "
  195. if ((i-1) %% 10 == 0):
  196. line_str &= $((int)((i)/10)-1) & "\n"
  197. echo line_str
  198. echo "a b c d e f g h"
  199. proc fieldToInd*(file: string, line: int): int =
  200. ## Calculate board index from `file` and `line` of a chess board.
  201. try:
  202. return 1+(line+1)*10+FileChar[file]
  203. except IndexDefect, ValueError:
  204. return -1
  205. proc fieldToInd*(field: string): int =
  206. ## Calculate board index from `field` of a chess board.
  207. try:
  208. return fieldToInd($field[0], parseInt($field[1]))
  209. except IndexDefect, ValueError:
  210. return -1
  211. proc indToField*(ind: int): string =
  212. ## Calculate field name from board index `ind`.
  213. let line = (int)ind/10-1
  214. let file_ind = (ind)%%10-1
  215. for file, i in FileChar:
  216. if FileChar[file] == file_ind:
  217. return $file & $line
  218. proc notationToMove*(notation: string, color: Color): Move =
  219. ## Convert simplified algebraic chess `notation` to a move object, color of player is `color`.
  220. try:
  221. var move: Move
  222. var start = fieldToInd(notation[0..1])
  223. var dest = fieldToInd(notation[2..3])
  224. move = getMove(start, dest, color)
  225. if (len(notation) > 4):
  226. var promStr = $notation[4]
  227. var prom: int
  228. case promStr:
  229. of "Q":
  230. prom = QueenID * ord(color)
  231. of "R":
  232. prom = RookID * ord(color)
  233. of "B":
  234. prom = BishopID * ord(color)
  235. of "N":
  236. prom = KnightID * ord(color)
  237. move = getMove(start, dest, prom, color)
  238. return move
  239. except IndexError:
  240. var move: Move
  241. return move
  242. proc genBishopDests(game: Game, field: int, color: Color): seq[int] =
  243. ## Generate possible destinations for a bishop with specific `color` located at index `field` of `game`.
  244. ## Returns a sequence of possible indices to move to.
  245. try:
  246. var res = newSeq[int]()
  247. var dest: int
  248. var target: int
  249. for move in Bishop_Moves:
  250. dest = field+move
  251. target = game.pieces.getField(dest)
  252. while (target != 999 and (ord(color) * target <= 0) or target ==
  253. EnPassantID or target == -EnPassantID):
  254. res.add(dest)
  255. if (ord(color) * target < 0 and ord(color) * target > -EnPassantID):
  256. break
  257. dest = dest+move
  258. target = game.pieces.getField(dest)
  259. return res
  260. except IndexDefect:
  261. return @[]
  262. proc genRookDests(game: Game, field: int, color: Color): seq[int] =
  263. ## Generate possible destinations for a rook with specific `color` located at index `field` of `game`.
  264. ## Returns a sequence of possible indices to move to.
  265. try:
  266. var res = newSeq[int]()
  267. var dest: int
  268. var target: int
  269. for move in Rook_Moves:
  270. dest = field+move
  271. target = game.pieces.getField(dest)
  272. while (target != 999 and (ord(color) * target <= 0) or target ==
  273. EnPassantID or target == -EnPassantID):
  274. res.add(dest)
  275. if (ord(color) * target < 0 and ord(color) * target > -EnPassantID):
  276. break
  277. dest = dest+move
  278. target = game.pieces.getField(dest)
  279. return res
  280. except IndexDefect:
  281. return @[]
  282. proc genQueenDests(game: Game, field: int, color: Color): seq[int] =
  283. ## Generate possible destinations for a queen with specific `color` located at index `field` of `game`.
  284. ## Returns a sequence of possible indices to move to.
  285. try:
  286. var res = newSeq[int]()
  287. var dest: int
  288. var target: int
  289. for move in Queen_Moves:
  290. dest = field+move
  291. target = game.pieces.getField(dest)
  292. while (target != 999 and (ord(color) * target <= 0) or target ==
  293. EnPassantID or target == -EnPassantID):
  294. res.add(dest)
  295. if (ord(color) * target < 0 and ord(color) * target > -EnPassantID):
  296. break
  297. dest = dest+move
  298. target = game.pieces.getField(dest)
  299. return res
  300. except IndexDefect:
  301. return @[]
  302. proc genKingCastleDest(game: Game, field: int, color: Color): seq[int] =
  303. ## Generate possible castle destinations for a king with specific `color` located at index `field` of `game`
  304. ## Returns a sequence of possible indices to move to.
  305. try:
  306. var res = newSeq[int]()
  307. var dest: int
  308. var target: int
  309. var half_dest: int
  310. var half_target: int
  311. for castle in King_Moves_White_Castle:
  312. dest = field + castle
  313. target = game.pieces.getField(dest)
  314. half_dest = field + (int)castle/2
  315. half_target = game.pieces.getField(half_dest)
  316. if (target == 999 or (target != 0)):
  317. continue
  318. if (half_target == 999 or (half_target != 0)):
  319. continue
  320. res.add(dest)
  321. return res
  322. except IndexDefect:
  323. return @[]
  324. proc genKingDests(game: Game, field: int, color: Color): seq[int] =
  325. ## Generate possible destinations for a king with specific `color` located at index `field` of `game`.
  326. ## Returns a sequence of possible indices to move to.
  327. try:
  328. var res = newSeq[int]()
  329. var dest: int
  330. var target: int
  331. for move in King_Moves:
  332. dest = field + move
  333. target = game.pieces.getField(dest)
  334. if (target == 999 or (ord(color) * target > 0 and ord(color) * target != EnPassantID)):
  335. continue
  336. res.add(dest)
  337. res.add(game.genKingCastleDest(field, color))
  338. return res
  339. except IndexDefect:
  340. return @[]
  341. proc genKnightDests(game: Game, field: int, color: Color): seq[int] =
  342. ## Generate possible destinations for a knight with specific `color` located at index `field` of `game`.
  343. ## Returns a sequence of possible indices to move to.
  344. try:
  345. var res = newSeq[int]()
  346. var dest: int
  347. var target: int
  348. for move in Knight_Moves:
  349. dest = field + move
  350. target = game.pieces.getField(dest)
  351. if (target == 999 or (ord(color) * target > 0 and ord(color) * target != EnPassantID)):
  352. continue
  353. res.add(dest)
  354. return res
  355. except IndexDefect:
  356. return @[]
  357. proc genPawnAttackDests(game: Game, field: int, color: Color): seq[int] =
  358. ## Generate possible attack destinations for a pawn with specific `color` located at index `field` of `game`.
  359. ## Returns a sequence of possible indices to move to.
  360. try:
  361. var res = newSeq[int]()
  362. var dest: int
  363. var target: int
  364. for attacks in Pawn_Moves_White_Attack:
  365. dest = field + (attacks * ord(color))
  366. target = game.pieces.getField(dest)
  367. if (target == 999 or ord(color) * target >= 0):
  368. continue
  369. res.add(dest)
  370. return res
  371. except IndexDefect:
  372. return @[]
  373. proc genPawnDoubleDests(game: Game, field: int, color: Color): seq[int] =
  374. ## Generate possible double destinations for a pawn with specific `color` located at index `field` of `game`.
  375. ## Returns a sequence of possible indices to move to.
  376. try:
  377. var res = newSeq[int]()
  378. var dest: int
  379. var target: int
  380. for doubles in Pawn_Moves_White_Double:
  381. dest = field + doubles * ord(color)
  382. target = game.pieces.getField(dest)
  383. if (game.moved.getField(field) or (target != 0) or (
  384. game.pieces.getField(dest+(S*ord(color))) != 0)):
  385. continue
  386. res.add(dest)
  387. return res
  388. except IndexDefect:
  389. return @[]
  390. proc genPawnDests(game: Game, field: int, color: Color): seq[int] =
  391. ## Generate possible destinations for a pawn with specific `color` located at index `field` of `game`.
  392. ## Returns a sequence of possible indices to move to.
  393. try:
  394. var res = newSeq[int]()
  395. var dest: int
  396. var target: int
  397. for move in Pawn_Moves_White:
  398. dest = field + move * ord(color)
  399. target = game.pieces.getField(dest)
  400. if (target != 0 and target != ord(color) * EnPassantID):
  401. continue
  402. res.add(dest)
  403. res.add(game.genPawnAttackDests(field, color))
  404. res.add(game.genPawnDoubleDests(field, color))
  405. return res
  406. except IndexDefect:
  407. return @[]
  408. proc pieceOn(game: Game, color: Color, sequence: seq[int],
  409. pieceID: int): bool =
  410. ## Check if a piece with `pieceID` of a given `color` is in a field described in a `sequence` in a `game`.
  411. for check in sequence:
  412. if game.pieces.getField(check) == ord(color) * -1 * pieceID:
  413. return true
  414. return false
  415. proc isAttacked(game: Game, position: int, color: Color): bool =
  416. ## Check if a field is attacked by the opposite of `color` in a `game`.
  417. var attacked = false
  418. attacked = attacked or game.pieceOn(color, game.genPawnAttackDests(
  419. position, color), PawnID)
  420. attacked = attacked or game.pieceOn(color, game.genQueenDests(position,
  421. color), QueenID)
  422. attacked = attacked or game.pieceOn(color, game.genKingDests(position,
  423. color), KingID)
  424. attacked = attacked or game.pieceOn(color, game.genRookDests(position,
  425. color), RookID)
  426. attacked = attacked or game.pieceOn(color, game.genBishopDests(position,
  427. color), BishopID)
  428. attacked = attacked or game.pieceOn(color, game.genKnightDests(position,
  429. color), KnightID)
  430. return attacked
  431. proc isInCheck*(game: Game, color: Color): bool =
  432. ## Check if the King of a given `color` is in check in a `game`.
  433. var king_pos: int
  434. for i in countup(0, game.pieces.high):
  435. if game.pieces.getField(i) == ord(color) * KingID:
  436. king_pos = i
  437. return game.isAttacked(king_pos, color)
  438. proc uncheckedMove(game: var Game, start: int, dest: int): bool {.discardable.} =
  439. ## Moves a piece if possible from `start` position to `dest` position.
  440. ## Doesnt check boundaries, checks, movement.
  441. ## returns true if the piece moved, else false
  442. try:
  443. let piece = game.pieces.getField(start)
  444. if game.pieces.setField(start, 0):
  445. if game.pieces.setField(dest, piece):
  446. game.moved.setField(start, true)
  447. game.moved.setField(dest, true)
  448. return true
  449. else:
  450. game.pieces.setField(start, piece)
  451. except IndexDefect, ValueError:
  452. return false
  453. proc moveLeadsToCheck(game: Game, start: int, dest: int,
  454. color: Color): bool =
  455. ## Checks in a `game` if a move from `start` to `dest` puts the `color` king in check.
  456. var check = game
  457. check.uncheckedMove(start, dest)
  458. return check.isInCheck(color)
  459. proc removeEnPassant(pieces: var Pieces, color: Color): void =
  460. ## Removes every en passant of given `color` from the `game`.
  461. for field in pieces.low..pieces.high:
  462. if pieces.getField(field) == ord(color) * EnPassantID:
  463. pieces.setField(field, 0)
  464. proc genLegalKnightMoves(game: Game, field: int, color: Color): seq[Move] =
  465. ## Generates all legal knight moves starting from `field` in a `game` for a `color`.
  466. if game.pieces.getField(field) != KnightID * ord(color):
  467. return @[]
  468. var res = newSeq[Move]()
  469. var moves = game.genKnightDests(field, color)
  470. for dest in moves:
  471. if not game.moveLeadsToCheck(field, dest, color):
  472. res.add(getMove(field, dest, color))
  473. return res
  474. proc genLegalBishopMoves(game: Game, field: int, color: Color): seq[Move] =
  475. ## Generates all legal bishop moves starting from `field` in a `game` for a `color`.
  476. if game.pieces.getField(field) != BishopID * ord(color):
  477. return @[]
  478. var res = newSeq[Move]()
  479. var moves = game.genBishopDests(field, color)
  480. for dest in moves:
  481. if not game.moveLeadsToCheck(field, dest, color):
  482. res.add(getMove(field, dest, color))
  483. return res
  484. proc genLegalRookMoves(game: Game, field: int, color: Color): seq[Move] =
  485. ## Generates all legal rook moves starting from `field` in a `game` for a `color`.
  486. if game.pieces.getField(field) != RookID * ord(color):
  487. return @[]
  488. var res = newSeq[Move]()
  489. var moves = game.genRookDests(field, color)
  490. for dest in moves:
  491. if not game.moveLeadsToCheck(field, dest, color):
  492. res.add(getMove(field, dest, color))
  493. return res
  494. proc genLegalQueenMoves(game: Game, field: int, color: Color): seq[Move] =
  495. ## Generates all legal queen moves starting from `field` in a `game` for a `color`.
  496. if game.pieces.getField(field) != QueenID * ord(color):
  497. return @[]
  498. var res = newSeq[Move]()
  499. var moves = game.genQueenDests(field, color)
  500. for dest in moves:
  501. if not game.moveLeadsToCheck(field, dest, color):
  502. res.add(getMove(field, dest, color))
  503. return res
  504. proc genLegalKingMoves(game: Game, field: int, color: Color): seq[Move] =
  505. ## Generates all legal king moves starting from `field` in a `game` for a `color`.
  506. if game.pieces.getField(field) != KingID * ord(color):
  507. return @[]
  508. var res = newSeq[Move]()
  509. var moves = game.genKingDests(field, color)
  510. for dest in moves:
  511. if field - dest == W+W and game.isAttacked(dest+W, color):
  512. continue
  513. if field - dest == E+E and game.isAttacked(dest+E, color):
  514. continue
  515. if not game.moveLeadsToCheck(field, dest, color):
  516. res.add(getMove(field, dest, color))
  517. return res
  518. proc genPawnPromotion(move: Move, color: Color): seq[Move] =
  519. ## Generate all possible promotions of a `move` by `color`.
  520. var promotions = newSeq[Move]()
  521. let start = move.start
  522. let dest = move.dest
  523. if (90 < dest and dest < 99) or (20 < dest and dest < 29):
  524. for piece in KnightID..QueenID:
  525. promotions.add(getMove(start, dest, piece, color))
  526. return promotions
  527. proc genLegalPawnMoves(game: Game, field: int, color: Color): seq[Move] =
  528. ## Generates all legal pawn moves starting from `field` in a `game` for a `color`.
  529. if game.pieces.getField(field) != PawnID * ord(color):
  530. return @[]
  531. var res = newSeq[Move]()
  532. var moves = game.genPawnDests(field, color)
  533. for dest in moves:
  534. if not game.moveLeadsToCheck(field, dest, color):
  535. var promotions = genPawnPromotion(getMove(field, dest, color), color)
  536. if promotions != @[]:
  537. res.add(promotions)
  538. else:
  539. res.add(getMove(field, dest, color))
  540. return res
  541. proc genLegalMoves*(game: Game, field: int, color: Color): seq[Move] =
  542. ## Generates all legal moves starting from `field` in a `game` for a `color`.
  543. var legal_moves = newSeq[Move]()
  544. var target = ord(color) * game.pieces.getField(field)
  545. if 0 < target and target < EnPassantID:
  546. legal_moves = case target:
  547. of PawnID:
  548. game.genLegalPawnMoves(field, color)
  549. of KnightID:
  550. game.genLegalKnightMoves(field, color)
  551. of BishopID:
  552. game.genLegalBishopMoves(field, color)
  553. of RookID:
  554. game.genLegalRookMoves(field, color)
  555. of QueenID:
  556. game.genLegalQueenMoves(field, color)
  557. of KingID:
  558. game.genLegalKingMoves(field, color)
  559. else:
  560. @[]
  561. return legal_moves
  562. proc genLegalMoves*(game: Game, color: Color): seq[Move] =
  563. ## Generates all legal moves in a `game` for a `color`.
  564. var legal_moves = newSeq[Move]()
  565. for field in game.pieces.low..game.pieces.high:
  566. legal_moves.add(game.genLegalMoves(field, color))
  567. return legal_moves
  568. proc castling(game: var Game, kstart: int, dest_kingside: bool,
  569. color: Color): bool {.discardable.} =
  570. ## Tries to castle in a given `game` with the king of a given `color` from `start`.
  571. ## `dest_kingside` for kingside castling, else castling is queenside.
  572. ## This process checks for the legality of the move and performs the switch of `game.to_move`
  573. try:
  574. if game.toMove != color:
  575. return false
  576. var kdest = kstart
  577. var rstart: int
  578. var rdest: int
  579. if (dest_kingside):
  580. kdest = kstart + (E+E)
  581. rstart = kstart + (E+E+E)
  582. rdest = rstart + (W+W)
  583. else:
  584. rstart = kstart + (W+W+W+W)
  585. rdest = rstart + (E+E+E)
  586. kdest = kstart + (W+W)
  587. if not game.moved.getField(kstart) and not game.moved.getField(rstart):
  588. var check = false
  589. if (dest_kingside):
  590. check = check or game.isAttacked(kstart, color)
  591. check = check or game.isAttacked(kstart+(E), color)
  592. check = check or game.isAttacked(kstart+(E+E), color)
  593. else:
  594. check = check or game.isAttacked(kstart, color)
  595. check = check or game.isAttacked(kstart+(W), color)
  596. check = check or game.isAttacked(kstart+(W+W), color)
  597. if check:
  598. return false
  599. game.uncheckedMove(kstart, kdest)
  600. game.uncheckedMove(rstart, rdest)
  601. game.toMove = Color(ord(game.toMove)*(-1))
  602. return true
  603. return false
  604. except IndexDefect, ValueError:
  605. return false
  606. proc checkedMove*(game: var Game, move: Move): bool {.discardable.} =
  607. ## Tries to make a move in a given `game` with the piece of a given `color` from `start` to `dest`.
  608. ## This process checks for the legality of the move and performs the switch of `game.to_move`
  609. try:
  610. let start = move.start
  611. let dest = move.dest
  612. let color = move.color
  613. let prom = move.prom
  614. if game.toMove != color:
  615. return false
  616. var sequence = newSeq[Move]()
  617. let piece = game.pieces.getField(start)
  618. var create_en_passant = false
  619. var captured_en_passant = false
  620. var move: Move
  621. move = getMove(start, dest, color)
  622. if (piece == PawnID * ord(color)):
  623. create_en_passant = dest in game.genPawnDoubleDests(start, color)
  624. captured_en_passant = (game.pieces.getField(dest) == -1 * ord(color) * EnPassantID)
  625. sequence.add(game.genLegalMoves(start, color))
  626. if (move in sequence):
  627. game.pieces.removeEnPassant(color)
  628. if (piece == KingID * ord(color) and (start - dest == (W+W))):
  629. return game.castling(start, true, color)
  630. elif (piece == KingID * ord(color) and (start - dest == (E+E))):
  631. return game.castling(start, false, color)
  632. else:
  633. game.uncheckedMove(start, dest)
  634. game.toMove = Color(ord(game.toMove)*(-1))
  635. if create_en_passant:
  636. game.pieces.setField(dest-(N*ord(color)), EnPassantID * ord(color))
  637. if captured_en_passant:
  638. game.pieces.setField(dest-(N*ord(color)), 0)
  639. if ((90 < dest and dest < 99) or (20 < dest and dest < 29)) and
  640. game.pieces.getField(dest) == PawnID * ord(color):
  641. game.pieces.setField(dest, prom)
  642. return true
  643. except IndexDefect, ValueError:
  644. return false
  645. proc hasNoMoves(game: Game, color: Color): bool =
  646. ## Checks if a player of a given `color` has no legal moves in a `game`.
  647. return (game.genLegalMoves(color) == @[])
  648. proc isCheckmate*(game: Game, color: Color): bool =
  649. ## Checks if a player of a given `color` in a `game` is checkmate.
  650. return game.hasNoMoves(color) and game.isInCheck(color)
  651. proc isStalemate*(game: Game, color: Color): bool =
  652. ## Checks if a player of a given `color` in a `game` is stalemate.
  653. return game.hasNoMoves(color) and not game.isInCheck(color)