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.

763 lines
25 KiB

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