LittleRookChess.ino 64 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347
  1. /*
  2. LittleRookChess.ino
  3. A Simple Chess Engine (ported from U8glib)
  4. Universal 8bit Graphics Library (https://github.com/olikraus/u8g2/)
  5. Copyright (c) 2016, olikraus@gmail.com
  6. All rights reserved.
  7. Redistribution and use in source and binary forms, with or without modification,
  8. are permitted provided that the following conditions are met:
  9. * Redistributions of source code must retain the above copyright notice, this list
  10. of conditions and the following disclaimer.
  11. * Redistributions in binary form must reproduce the above copyright notice, this
  12. list of conditions and the following disclaimer in the documentation and/or other
  13. materials provided with the distribution.
  14. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
  15. CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
  16. INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
  17. MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  18. DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
  19. CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  20. SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  21. NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  22. LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  23. CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  24. STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  25. ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
  26. ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  27. Current Rule Limitation
  28. - no minor promotion, only "Queening" of the pawn
  29. - threefold repetition is not detected (same board situation appears three times)
  30. Note: Could be implemented, but requires tracking of the complete game
  31. - Fifty-move rule is not checked (no pawn move, no capture within last 50 moves)
  32. Words
  33. Ply a half move
  34. General Links
  35. http://chessprogramming.wikispaces.com/
  36. Arduino specific
  37. http://www.arduino.cc/cgi-bin/yabb2/YaBB.pl?num=1260055596
  38. Prefixes
  39. chess_ Generic Chess Application Interface
  40. ce_ Chess engine, used internally, these function should not be called directly
  41. cu_ Chess utility function
  42. stack_ Internal function for stack handling
  43. Issues
  44. 10.01.2011
  45. - castling to the right does not move the rook
  46. --> done
  47. - castling to the left: King can only move two squares
  48. --> done
  49. 11.01.2011
  50. Next Steps:
  51. - replace stack_NextCurrentPos with cu_NextPos, cleanup code according to the loop variable
  52. --> done
  53. - Castling: Need to check for fields under attack
  54. --> done
  55. - Check for WIN / LOOSE situation, perhaps call ce_Eval() once on the top-level board setup
  56. just after the real move
  57. - cleanup cu_Move
  58. --> almost done
  59. - add some heuristics to the eval procedure
  60. - add right side menu
  61. --> done
  62. - clean up chess_ManualMove
  63. --> done
  64. - finish menu (consider is_game_end, undo move)
  65. - end condition: if KING is under attack and if KING can not move to a field which is under attack...
  66. then the game is lost. What will be returned by the Eval procedure? is it -INF?
  67. --> finished
  68. - reduce the use of variable color, all should be reduced to board_orientation and ply&1
  69. - chess_GetNextMarked shoud make use of cu_NextPos
  70. --> done
  71. - chess_ManualMove: again cleanup, solve draw issue (KING is not in check and no legal moves are available)
  72. --> done
  73. 22.01.2011
  74. - simplify eval_t ce_Eval(void)
  75. - position eval does not work, still moves side pawn :-(
  76. maybe because all pieces are considered
  77. --> done
  78. 17. June 2016
  79. U8g2/Arduboy Port
  80. */
  81. #include <Arduino.h>
  82. #include <U8g2lib.h>
  83. #ifdef U8X8_HAVE_HW_SPI
  84. #include <SPI.h>
  85. #endif
  86. #ifdef U8X8_HAVE_HW_I2C
  87. #include <Wire.h>
  88. #endif
  89. /*
  90. U8glib Example Overview:
  91. Frame Buffer Examples: clearBuffer/sendBuffer. Fast, but may not work with all Arduino boards because of RAM consumption
  92. Page Buffer Examples: firstPage/nextPage. Less RAM usage, should work with all Arduino boards.
  93. U8x8 Text Only Example: No RAM usage, direct communication with display controller. No graphics, 8x8 Text only.
  94. This is a page buffer example.
  95. */
  96. void chess_Init(u8g2_t *u8g, uint8_t body_color);
  97. #define ARDUBOY
  98. //#define PI_SHIELD
  99. #ifdef ARDUBOY
  100. /*=== ARDUBOY Production, Kickstarter Edition ===*/
  101. U8G2_SSD1306_128X64_NONAME_1_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 12, /* dc=*/ 4, /* reset=*/ 6); // Arduboy (Production, Kickstarter Edition)
  102. void setup(void) {
  103. //u8g2.begin(/*Select=*/ A0, /*Right/Next=*/ 5, /*Left/Prev=*/ 9, /*Up=*/ 8, /*Down=*/ 10, /*Home/Cancel=*/ A1); // Arduboy DevKit
  104. u8g2.begin(/*Select=*/ 7, /*Right/Next=*/ A1, /*Left/Prev=*/ A2, /*Up=*/ A0, /*Down=*/ A3, /*Home/Cancel=*/ 8); // Arduboy 10 (Production)
  105. chess_Init(u8g2.getU8g2(), 1); /* assuming Arduboy OLED here, so make the body_color be 1 for the white OLED pixel */
  106. }
  107. #endif
  108. #ifdef PI_SHIELD
  109. /*=== Pax Instruments Shield ===*/
  110. U8G2_ST7567_PI_132X64_1_4W_HW_SPI u8g2(U8G2_R2, /* cs=*/ 7, /* dc=*/ 9, /* reset=*/ 8); // Pax Instruments Shield, LCD_BL=6
  111. void setup(void) {
  112. u8g2.begin(/*Select=*/ 4, /*Right/Next=*/ 5, /*Left/Prev=*/ A1, /*Up=*/ U8X8_PIN_NONE, /*Down=*/ U8X8_PIN_NONE, /*Home/Cancel=*/ A2); // Pax Instrument Shield
  113. /* U8g2 Project: Pax Instruments Shield: Enable Backlight */
  114. pinMode(6, OUTPUT);
  115. digitalWrite(6, 0);
  116. chess_Init(u8g2.getU8g2(), 0); /* assuming Arduboy OLED here, so make the body_color be 1 for the white OLED pixel */
  117. }
  118. #endif
  119. /* Ignore PROGMEM for now */
  120. #define CHESS_PROGMEM
  121. #define chess_pgm_read(p) (*(p))
  122. #define CHESS_PSTR(s) (s)
  123. #define u8g2_DrawStrP u8g2_DrawStr
  124. /* backward compatibility */
  125. #define u8g2_SetDefaultBackgroundColor(u8g2) \
  126. u8g2_SetDrawColor(u8g2, 0)
  127. #define u8g2_SetDefaultForegroundColor(u8g2) \
  128. u8g2_SetDrawColor(u8g2, 1)
  129. /* menu button definitions: mapped to the u8g2 menu events */
  130. #define CHESS_KEY_NONE 0
  131. #define CHESS_KEY_NEXT U8X8_MSG_GPIO_MENU_NEXT
  132. #define CHESS_KEY_PREV U8X8_MSG_GPIO_MENU_PREV
  133. #define CHESS_KEY_SELECT U8X8_MSG_GPIO_MENU_SELECT
  134. #define CHESS_KEY_BACK U8X8_MSG_GPIO_MENU_HOME
  135. /*
  136. SAN identifies each piece by a single upper case letter. The standard English
  137. values: pawn = "P", knight = "N", bishop = "B", rook = "R", queen = "Q", and
  138. king = "K".
  139. */
  140. /* numbers for the various pieces */
  141. #define PIECE_NONE 0
  142. #define PIECE_PAWN 1
  143. #define PIECE_KNIGHT 2
  144. #define PIECE_BISHOP 3
  145. #define PIECE_ROOK 4
  146. #define PIECE_QUEEN 5
  147. #define PIECE_KING 6
  148. /* color definitions */
  149. #define COLOR_WHITE 0
  150. #define COLOR_BLACK 1
  151. /* a mask, which includes COLOR and PIECE number */
  152. #define COLOR_PIECE_MASK 0x01f
  153. #define CP_MARK_MASK 0x20
  154. #define ILLEGAL_POSITION 255
  155. /* This is the build in upper limit of the search stack */
  156. /* This value defines the amount of memory allocated for the search stack */
  157. /* The search depth of this chess engine can never exceed this value */
  158. #define STACK_MAX_SIZE 5
  159. /* chess half move stack: twice the number of undo's, a user can do */
  160. #define CHM_USER_SIZE 6
  161. /* the CHM_LIST_SIZE must be larger than the maximum search depth */
  162. /* the overall size of ste half move stack */
  163. #define CHM_LIST_SIZE (STACK_MAX_SIZE+CHM_USER_SIZE+2)
  164. typedef int16_t eval_t; /* a variable type to store results from the evaluation */
  165. //#define EVAL_T_LOST -32768
  166. #define EVAL_T_MIN -32767
  167. #define EVAL_T_MAX 32767
  168. //#define EVAL_T_WIN 32767
  169. /* for maintainance of our own stack: this is the definition of one element on the stack */
  170. struct _stack_element_struct
  171. {
  172. /* the current source position which is investigated */
  173. uint8_t current_pos;
  174. uint8_t current_cp;
  175. uint8_t current_color; /* COLOR_WHITE or COLOR_BLACK: must be predefines */
  176. /* the move which belongs to that value, both values are game positions */
  177. uint8_t best_from_pos;
  178. uint8_t best_to_pos;
  179. /* the best value, which has been dicovered so far */
  180. eval_t best_eval;
  181. };
  182. typedef struct _stack_element_struct stack_element_t;
  183. typedef struct _stack_element_struct *stack_element_p;
  184. /* chess half move history */
  185. struct _chm_struct
  186. {
  187. uint8_t main_cp; /* the main piece, which is moved */
  188. uint8_t main_src; /* the source position of the main piece */
  189. uint8_t main_dest; /* the destination of the main piece */
  190. uint8_t other_cp; /* another piece: the captured one, the ROOK in case of castling or PIECE_NONE */
  191. uint8_t other_src; /* the delete position of other_cp. Often identical to main_dest except for e.p. and castling */
  192. uint8_t other_dest; /* only used for castling: ROOK destination pos */
  193. /* the position of the last pawn, which did a double move forward */
  194. /* this is required to check en passant conditions */
  195. /* this array can be indexed by the color of the current player */
  196. /* this is the condition BEFORE the move was done */
  197. uint8_t pawn_dbl_move[2];
  198. /* flags for the movement of rook and king; required for castling */
  199. /* a 1 means: castling is (still) possible */
  200. /* a 0 means: castling not possible */
  201. /* bit 0 left side white */
  202. /* bit 1 right side white */
  203. /* bit 2 left side black */
  204. /* bit 3 right side black */
  205. /* this is the condition BEFORE the move was done */
  206. uint8_t castling_possible;
  207. };
  208. typedef struct _chm_struct chm_t;
  209. typedef struct _chm_struct *chm_p;
  210. /* little rook chess, main structure */
  211. struct _lrc_struct
  212. {
  213. /* half-move (ply) counter: Counts the number of half-moves so far. Starts with 0 */
  214. /* the lowest bit is used to derive the color of the current player */
  215. /* will be set to zero in chess_SetupBoard() */
  216. uint8_t ply_count;
  217. /* the half move stack position counter, counts the number of elements in chm_list */
  218. uint8_t chm_pos;
  219. /* each element contains a colored piece, empty fields have value 0 */
  220. /* the field with index 0 is black (lower left) */
  221. uint8_t board[64];
  222. /* the position of the last pawn, which did a double move forward */
  223. /* this is required to check en passant conditions */
  224. /* this array can be indexed by the color of the current player */
  225. uint8_t pawn_dbl_move[2];
  226. /* flags for the movement of rook and king; required for castling */
  227. /* a 1 means: castling is (still) possible */
  228. /* a 0 means: castling not possible */
  229. /* bit 0 left side white */
  230. /* bit 1 right side white */
  231. /* bit 2 left side black */
  232. /* bit 3 right side black */
  233. uint8_t castling_possible;
  234. /* board orientation */
  235. /* 0: white is below COLOR_WHITE */
  236. /* 1: black is below COLOR_BLACK */
  237. /* bascially, this can be used as a color */
  238. uint8_t orientation;
  239. /* exchange colors of the pieces */
  240. /* 0: white has an empty body, use this for bright background color */
  241. /* 1: black has an empty body, use this for dark backround color */
  242. uint8_t strike_out_color;
  243. /* 0, when the game is ongoing */
  244. /* 1, when the game is stopped (lost or draw) */
  245. uint8_t is_game_end;
  246. /* the color of the side which lost the game */
  247. /* this value is only valid, when is_game_end is not 0 */
  248. /* values 0 and 1 represent WHITE and BLACK, 2 means a draw */
  249. uint8_t lost_side_color;
  250. /* checks are executed in ce_LoopRecur */
  251. /* these checks will put some marks on the board */
  252. /* this will be used by the interface to find out */
  253. /* legal moves */
  254. uint8_t check_src_pos;
  255. uint8_t check_mode; /* CHECK_MODE_NONE, CHECK_MODE_MOVEABLE, CHECK_MODE_TARGET_MOVE */
  256. /* count of the attacking pieces, indexed by color */
  257. uint8_t find_piece_cnt[2];
  258. /* sum of the attacking pieces, indexed by color */
  259. uint8_t find_piece_weight[2];
  260. /* points to the current element of the search stack */
  261. /* this stack is NEVER empty. The value 0 points to the first element of the stack */
  262. /* actually "curr_depth" represent half-moves (plies) */
  263. uint8_t curr_depth;
  264. uint8_t max_depth;
  265. stack_element_p curr_element;
  266. /* allocated memory for the search stack */
  267. stack_element_t stack_memory[STACK_MAX_SIZE];
  268. /* the half move stack, used for move undo and depth search, size is stored in chm_pos */
  269. chm_t chm_list[CHM_LIST_SIZE];
  270. };
  271. typedef struct _lrc_struct lrc_t;
  272. #define CHECK_MODE_NONE 0
  273. #define CHECK_MODE_MOVEABLE 1
  274. #define CHECK_MODE_TARGET_MOVE 2
  275. /*==============================================================*/
  276. /* global variables */
  277. /*==============================================================*/
  278. lrc_t lrc_obj;
  279. u8g2_t *lrc_u8g; /* pointer to the C object of u8g2 lib, this is used by the chess engine */
  280. /*==============================================================*/
  281. /* forward declarations */
  282. /*==============================================================*/
  283. /*
  284. apply no inline to some of the functions:
  285. avr-gcc very often inlines functions, however not inline saves a lot of program memory!
  286. On the other hand there are some really short procedures which should be inlined (like cp_GetColor)
  287. These procedures are marked static to prevent the generation of the expanded procedure, which
  288. also saves space.
  289. */
  290. uint8_t stack_Push(uint8_t color) U8G2_NOINLINE;
  291. void stack_Pop(void) U8G2_NOINLINE;
  292. void stack_InitCurrElement(void) U8G2_NOINLINE;
  293. void stack_Init(uint8_t max) U8G2_NOINLINE;
  294. void stack_SetMove(eval_t val, uint8_t to_pos) U8G2_NOINLINE;
  295. uint8_t cu_NextPos(uint8_t pos) U8G2_NOINLINE;
  296. static uint8_t cu_gpos2bpos(uint8_t gpos);
  297. static uint8_t cp_Construct(uint8_t color, uint8_t piece);
  298. static uint8_t cp_GetPiece(uint8_t cp);
  299. static uint8_t cp_GetColor(uint8_t cp);
  300. uint8_t cp_GetFromBoard(uint8_t pos) U8G2_NOINLINE;
  301. void cp_SetOnBoard(uint8_t pos, uint8_t cp) U8G2_NOINLINE;
  302. void cu_ClearBoard(void) U8G2_NOINLINE;
  303. void chess_SetupBoard(void) U8G2_NOINLINE;
  304. eval_t ce_Eval(void);
  305. void cu_ClearMoveHistory(void) U8G2_NOINLINE;
  306. void cu_ReduceHistoryByFullMove(void) U8G2_NOINLINE;
  307. void cu_UndoHalfMove(void) U8G2_NOINLINE;
  308. chm_p cu_PushHalfMove(void) U8G2_NOINLINE;
  309. void ce_CalculatePositionWeight(uint8_t pos);
  310. uint8_t ce_GetPositionAttackWeight(uint8_t pos, uint8_t color);
  311. void chess_Thinking(void);
  312. void ce_LoopPieces(void);
  313. /*==============================================================*/
  314. /* search stack */
  315. /*==============================================================*/
  316. /* get current element from stack */
  317. struct _stack_element_struct *stack_GetCurrElement(void)
  318. {
  319. return lrc_obj.curr_element;
  320. }
  321. uint8_t stack_Push(uint8_t color)
  322. {
  323. if ( lrc_obj.curr_depth == lrc_obj.max_depth )
  324. return 0;
  325. lrc_obj.curr_depth++;
  326. lrc_obj.curr_element = lrc_obj.stack_memory+lrc_obj.curr_depth;
  327. /* change view for the evaluation */
  328. color ^= 1;
  329. stack_GetCurrElement()->current_color = color;
  330. return 1;
  331. }
  332. void stack_Pop(void)
  333. {
  334. lrc_obj.curr_depth--;
  335. lrc_obj.curr_element = lrc_obj.stack_memory+lrc_obj.curr_depth;
  336. }
  337. /* reset the current element on the stack */
  338. void stack_InitCurrElement(void)
  339. {
  340. stack_element_p e = stack_GetCurrElement();
  341. e->best_eval = EVAL_T_MIN;
  342. e->best_from_pos = ILLEGAL_POSITION;
  343. e->best_to_pos = ILLEGAL_POSITION;
  344. }
  345. /* resets the search stack (and the check mode) */
  346. void stack_Init(uint8_t max)
  347. {
  348. lrc_obj.curr_depth = 0;
  349. lrc_obj.curr_element = lrc_obj.stack_memory;
  350. lrc_obj.max_depth = max;
  351. lrc_obj.check_mode = CHECK_MODE_NONE;
  352. stack_InitCurrElement();
  353. stack_GetCurrElement()->current_color = lrc_obj.ply_count;
  354. stack_GetCurrElement()->current_color &= 1;
  355. }
  356. /* assign evaluation value and store the move, if this is the best move */
  357. /* assumes, that current_pos contains the source position */
  358. void stack_SetMove(eval_t val, uint8_t to_pos)
  359. {
  360. stack_element_p e = stack_GetCurrElement();
  361. if ( e->best_eval < val )
  362. {
  363. e->best_eval = val;
  364. e->best_from_pos = e->current_pos;
  365. e->best_to_pos = to_pos;
  366. }
  367. }
  368. /*
  369. calculate next position on a 0x88 board
  370. loop is constructed in this way:
  371. i = 0;
  372. do
  373. {
  374. ...
  375. i = cu_NextPos(i);
  376. } while( i != 0 );
  377. next pos might be started with an illegal position like 255
  378. */
  379. uint8_t cu_NextPos(uint8_t pos)
  380. {
  381. /* calculate next gpos */
  382. pos++;
  383. if ( ( pos & 0x08 ) != 0 )
  384. {
  385. pos+= 0x10;
  386. pos&= 0xf0;
  387. }
  388. if ( ( pos & 0x80 ) != 0 )
  389. pos = 0;
  390. return pos;
  391. }
  392. uint8_t cu_PrevPos(uint8_t pos)
  393. {
  394. /* calculate prev gpos */
  395. pos--;
  396. if ( ( pos & 0x80 ) != 0 )
  397. pos = 0x077;
  398. else if ( ( pos & 0x08 ) != 0 )
  399. {
  400. pos &= 0xf0;
  401. pos |= 0x07;
  402. }
  403. return pos;
  404. }
  405. /*==============================================================*/
  406. /* position transltion */
  407. /*==============================================================*/
  408. /*
  409. there are two positions
  410. 1. game position (gpos): BCD encoded x-y values
  411. 2. board position (bpos): a number between 0 and 63, only used to access the board.
  412. */
  413. /*
  414. gpos: game position value
  415. returns: board position
  416. note: does not do any checks
  417. */
  418. static uint8_t cu_gpos2bpos(uint8_t gpos)
  419. {
  420. uint8_t bpos = gpos;
  421. bpos &= 0xf0;
  422. bpos >>= 1;
  423. gpos &= 0x0f;
  424. bpos |= gpos;
  425. return bpos;
  426. }
  427. #define gpos_IsIllegal(gpos) ((gpos) & 0x088)
  428. /*==============================================================*/
  429. /* colored piece handling */
  430. /*==============================================================*/
  431. #define cp_IsMarked(cp) ((cp) & CP_MARK_MASK)
  432. /*
  433. piece: one of PIECE_xxx
  434. color: COLOR_WHITE or COLOR_BLACK
  435. returns: A colored piece
  436. */
  437. static uint8_t cp_Construct(uint8_t color, uint8_t piece)
  438. {
  439. color <<= 4;
  440. color |= piece;
  441. return color;
  442. }
  443. /* inline is better than a macro */
  444. static uint8_t cp_GetPiece(uint8_t cp)
  445. {
  446. cp &= 0x0f;
  447. return cp;
  448. }
  449. /*
  450. we could use a macro:
  451. #define cp_GetColor(cp) (((cp) >> 4)&1)
  452. however, inlined functions are sometimes much better
  453. */
  454. static uint8_t cp_GetColor(uint8_t cp)
  455. {
  456. cp >>= 4;
  457. cp &= 1;
  458. return cp;
  459. }
  460. /*
  461. pos: game position
  462. returns the colored piece at the given position
  463. */
  464. uint8_t cp_GetFromBoard(uint8_t pos)
  465. {
  466. return lrc_obj.board[cu_gpos2bpos(pos)];
  467. }
  468. /*
  469. pos: game position
  470. cp: colored piece
  471. */
  472. void cp_SetOnBoard(uint8_t pos, uint8_t cp)
  473. {
  474. /*printf("cp_SetOnBoard gpos:%02x cp:%02x\n", pos, cp);*/
  475. lrc_obj.board[cu_gpos2bpos(pos)] = cp;
  476. }
  477. /*==============================================================*/
  478. /* global board access */
  479. /*==============================================================*/
  480. void cu_ClearBoard(void)
  481. {
  482. uint8_t i;
  483. /* clear the board */
  484. for( i = 0; i < 64; i++ )
  485. lrc_obj.board[i] = PIECE_NONE;
  486. lrc_obj.ply_count = 0;
  487. lrc_obj.orientation = COLOR_WHITE;
  488. lrc_obj.pawn_dbl_move[0] = ILLEGAL_POSITION;
  489. lrc_obj.pawn_dbl_move[1] = ILLEGAL_POSITION;
  490. lrc_obj.castling_possible = 0x0f;
  491. lrc_obj.is_game_end = 0;
  492. lrc_obj.lost_side_color = 0;
  493. /* clear half move history */
  494. cu_ClearMoveHistory();
  495. }
  496. /*
  497. test setup
  498. white wins in one move
  499. */
  500. void chess_SetupBoardTest01(void)
  501. {
  502. cu_ClearBoard();
  503. lrc_obj.board[7+7*8] = cp_Construct(COLOR_BLACK, PIECE_KING);
  504. lrc_obj.board[7+5*8] = cp_Construct(COLOR_WHITE, PIECE_PAWN);
  505. lrc_obj.board[3] = cp_Construct(COLOR_WHITE, PIECE_KING);
  506. lrc_obj.board[0+7*8] = cp_Construct(COLOR_BLACK, PIECE_ROOK);
  507. lrc_obj.board[6] = cp_Construct(COLOR_WHITE, PIECE_QUEEN);
  508. }
  509. /* setup the global board */
  510. void chess_SetupBoard(void)
  511. {
  512. uint8_t i;
  513. register uint8_t bp, wp;
  514. /* clear the board */
  515. cu_ClearBoard();
  516. /* precronstruct pawns */
  517. wp = cp_Construct(COLOR_WHITE, PIECE_PAWN);
  518. bp = cp_Construct(COLOR_BLACK, PIECE_PAWN);
  519. /* setup pawn */
  520. for( i = 0; i < 8; i++ )
  521. {
  522. lrc_obj.board[i+8] = wp;
  523. lrc_obj.board[i+6*8] = bp;
  524. }
  525. /* assign remaining pieces */
  526. lrc_obj.board[0] = cp_Construct(COLOR_WHITE, PIECE_ROOK);
  527. lrc_obj.board[1] = cp_Construct(COLOR_WHITE, PIECE_KNIGHT);
  528. lrc_obj.board[2] = cp_Construct(COLOR_WHITE, PIECE_BISHOP);
  529. lrc_obj.board[3] = cp_Construct(COLOR_WHITE, PIECE_QUEEN);
  530. lrc_obj.board[4] = cp_Construct(COLOR_WHITE, PIECE_KING);
  531. lrc_obj.board[5] = cp_Construct(COLOR_WHITE, PIECE_BISHOP);
  532. lrc_obj.board[6] = cp_Construct(COLOR_WHITE, PIECE_KNIGHT);
  533. lrc_obj.board[7] = cp_Construct(COLOR_WHITE, PIECE_ROOK);
  534. lrc_obj.board[0+7*8] = cp_Construct(COLOR_BLACK, PIECE_ROOK);
  535. lrc_obj.board[1+7*8] = cp_Construct(COLOR_BLACK, PIECE_KNIGHT);
  536. lrc_obj.board[2+7*8] = cp_Construct(COLOR_BLACK, PIECE_BISHOP);
  537. lrc_obj.board[3+7*8] = cp_Construct(COLOR_BLACK, PIECE_QUEEN);
  538. lrc_obj.board[4+7*8] = cp_Construct(COLOR_BLACK, PIECE_KING);
  539. lrc_obj.board[5+7*8] = cp_Construct(COLOR_BLACK, PIECE_BISHOP);
  540. lrc_obj.board[6+7*8] = cp_Construct(COLOR_BLACK, PIECE_KNIGHT);
  541. lrc_obj.board[7+7*8] = cp_Construct(COLOR_BLACK, PIECE_ROOK);
  542. //chess_SetupBoardTest01();
  543. }
  544. /*==============================================================*/
  545. /* checks */
  546. /*==============================================================*/
  547. /*
  548. checks if the position is somehow illegal
  549. */
  550. uint8_t cu_IsIllegalPosition(uint8_t pos, uint8_t my_color)
  551. {
  552. uint8_t board_cp;
  553. /* check, if the position is offboard */
  554. if ( gpos_IsIllegal(pos) != 0 )
  555. return 1;
  556. /* get the piece from the board */
  557. board_cp = cp_GetFromBoard(pos);
  558. /* check if hit our own pieces */
  559. if ( board_cp != 0 )
  560. if ( cp_GetColor(board_cp) == my_color )
  561. return 1;
  562. /* all ok, we could go to this position */
  563. return 0;
  564. }
  565. /*==============================================================*/
  566. /* evaluation procedure */
  567. /*==============================================================*/
  568. /*
  569. basic idea is to return a value between EVAL_T_MIN and EVAL_T_MAX
  570. */
  571. /*
  572. the weight table uses the PIECE number as index:
  573. #define PIECE_NONE 0
  574. #define PIECE_PAWN 1
  575. #define PIECE_KNIGHT 2
  576. #define PIECE_BISHOP 3
  577. #define PIECE_ROOK 4
  578. #define PIECE_QUEEN 5
  579. #define PIECE_KING 6
  580. the king itself is not counted
  581. */
  582. uint8_t ce_piece_weight[] = { 0, 1, 3, 3, 5, 9, 0 };
  583. uint8_t ce_pos_weight[] = { 0, 1, 1, 2, 2, 1, 1, 0};
  584. /*
  585. evaluate the current situation on the global board
  586. */
  587. eval_t ce_Eval(void)
  588. {
  589. uint8_t cp;
  590. uint8_t is_my_king_present = 0;
  591. uint8_t is_opposit_king_present = 0;
  592. eval_t material_my_color = 0;
  593. eval_t material_opposit_color = 0;
  594. eval_t position_my_color = 0;
  595. eval_t position_opposit_color = 0;
  596. eval_t result;
  597. uint8_t pos;
  598. pos = 0;
  599. do
  600. {
  601. /* get colored piece from the board */
  602. cp = cp_GetFromBoard(pos);
  603. if ( cp_GetPiece(cp) != PIECE_NONE )
  604. {
  605. if ( stack_GetCurrElement()->current_color == cp_GetColor(cp) )
  606. {
  607. /* this is our color */
  608. /* check if we found our king */
  609. if ( cp_GetPiece(cp) == PIECE_KING )
  610. is_my_king_present = 1;
  611. material_my_color += ce_piece_weight[cp_GetPiece(cp)];
  612. if ( cp_GetPiece(cp) == PIECE_PAWN || cp_GetPiece(cp) == PIECE_KNIGHT )
  613. {
  614. position_my_color += ce_pos_weight[pos&7]*ce_pos_weight[(pos>>4)&7];
  615. }
  616. }
  617. else
  618. {
  619. /* this is the opposit color */
  620. if ( cp_GetPiece(cp) == PIECE_KING )
  621. is_opposit_king_present = 1;
  622. material_opposit_color += ce_piece_weight[cp_GetPiece(cp)];
  623. if ( cp_GetPiece(cp) == PIECE_PAWN || cp_GetPiece(cp) == PIECE_KNIGHT )
  624. {
  625. position_opposit_color += ce_pos_weight[pos&7]*ce_pos_weight[(pos>>4)&7];
  626. }
  627. }
  628. }
  629. pos = cu_NextPos(pos);
  630. } while( pos != 0 );
  631. /* decide if we lost or won the game */
  632. if ( is_my_king_present == 0 )
  633. return EVAL_T_MIN; /*_LOST*/
  634. if ( is_opposit_king_present == 0 )
  635. return EVAL_T_MAX; /*_WIN*/
  636. /* here is the evaluation function */
  637. result = material_my_color - material_opposit_color;
  638. result <<= 3;
  639. result += position_my_color - position_opposit_color;
  640. return result;
  641. }
  642. /*==============================================================*/
  643. /* move backup and restore */
  644. /*==============================================================*/
  645. /* this procedure must be called to keep the size as low as possible */
  646. /* if the chm_list is large enough, it could hold the complete history */
  647. /* but for an embedded controler... it is deleted for every engine search */
  648. void cu_ClearMoveHistory(void)
  649. {
  650. lrc_obj.chm_pos = 0;
  651. }
  652. void cu_ReduceHistoryByFullMove(void)
  653. {
  654. uint8_t i;
  655. while( lrc_obj.chm_pos > CHM_USER_SIZE )
  656. {
  657. i = 0;
  658. for(;;)
  659. {
  660. if ( i+2 >= lrc_obj.chm_pos )
  661. break;
  662. lrc_obj.chm_list[i] = lrc_obj.chm_list[i+2];
  663. i++;
  664. }
  665. lrc_obj.chm_pos -= 2;
  666. }
  667. }
  668. void cu_UndoHalfMove(void)
  669. {
  670. chm_p chm;
  671. if ( lrc_obj.chm_pos == 0 )
  672. return;
  673. lrc_obj.chm_pos--;
  674. chm = lrc_obj.chm_list+lrc_obj.chm_pos;
  675. lrc_obj.pawn_dbl_move[0] = chm->pawn_dbl_move[0];
  676. lrc_obj.pawn_dbl_move[1] = chm->pawn_dbl_move[1];
  677. lrc_obj.castling_possible = chm->castling_possible;
  678. cp_SetOnBoard(chm->main_src, chm->main_cp);
  679. cp_SetOnBoard(chm->main_dest, PIECE_NONE);
  680. if ( chm->other_src != ILLEGAL_POSITION )
  681. cp_SetOnBoard(chm->other_src, chm->other_cp);
  682. if ( chm->other_dest != ILLEGAL_POSITION )
  683. cp_SetOnBoard(chm->other_dest, PIECE_NONE);
  684. }
  685. /*
  686. assumes, that the following members of the returned chm structure are filled
  687. uint8_t main_cp; the main piece, which is moved
  688. uint8_t main_src; the source position of the main piece
  689. uint8_t main_dest; the destination of the main piece
  690. uint8_t other_cp; another piece: the captured one, the ROOK in case of castling or PIECE_NONE
  691. uint8_t other_src; the delete position of other_cp. Often identical to main_dest except for e.p. and castling
  692. uint8_t other_dest; only used for castling: ROOK destination pos
  693. */
  694. chm_p cu_PushHalfMove(void)
  695. {
  696. chm_p chm;
  697. chm = lrc_obj.chm_list+lrc_obj.chm_pos;
  698. if ( lrc_obj.chm_pos < CHM_LIST_SIZE-1)
  699. lrc_obj.chm_pos++;
  700. chm->pawn_dbl_move[0] = lrc_obj.pawn_dbl_move[0];
  701. chm->pawn_dbl_move[1] = lrc_obj.pawn_dbl_move[1];
  702. chm->castling_possible = lrc_obj.castling_possible;
  703. return chm;
  704. }
  705. char chess_piece_to_char[] = "NBRQK";
  706. /*
  707. simple moves on empty field: Ka1-b2
  708. capture moves: Ka1xb2
  709. castling: 0-0 or 0-0-0
  710. */
  711. static void cu_add_pos(char *s, uint8_t pos) U8G2_NOINLINE;
  712. static void cu_add_pos(char *s, uint8_t pos)
  713. {
  714. *s = pos;
  715. *s &= 15;
  716. *s += 'a';
  717. s++;
  718. *s = pos;
  719. *s >>= 4;
  720. *s += '1';
  721. }
  722. const char *cu_GetHalfMoveStr(uint8_t idx)
  723. {
  724. chm_p chm;
  725. static char buf[7]; /*Ka1-b2*/
  726. char *p = buf;
  727. chm = lrc_obj.chm_list+idx;
  728. if ( cp_GetPiece(chm->main_cp) != PIECE_NONE )
  729. {
  730. if ( cp_GetPiece(chm->main_cp) > PIECE_PAWN )
  731. {
  732. *p++ = chess_piece_to_char[cp_GetPiece(chm->main_cp)-2];
  733. }
  734. cu_add_pos(p, chm->main_src);
  735. p+=2;
  736. if ( cp_GetPiece(chm->other_cp) == PIECE_NONE )
  737. *p++ = '-';
  738. else
  739. *p++ = 'x';
  740. cu_add_pos(p, chm->main_dest);
  741. p+=2;
  742. }
  743. *p = '\0';
  744. return buf;
  745. }
  746. /*==============================================================*/
  747. /* move */
  748. /*==============================================================*/
  749. /*
  750. Move a piece from source position to a destination on the board
  751. This function
  752. - does not perform any checking
  753. - however it processes "en passant" and casteling
  754. - backup the move and allow 1x undo
  755. 2011-02-05:
  756. - fill pawn_dbl_move[] for double pawn moves
  757. --> done
  758. - Implement casteling
  759. --> done
  760. - en passant
  761. --> done
  762. - pawn conversion/promotion
  763. --> done
  764. - half-move backup
  765. --> done
  766. - cleanup everything, minimize variables
  767. --> done
  768. */
  769. void cu_Move(uint8_t src, uint8_t dest)
  770. {
  771. /* start backup structure */
  772. chm_p chm = cu_PushHalfMove();
  773. /* these are the values from the board at the positions, provided as arguments to this function */
  774. uint8_t cp_src, cp_dest;
  775. /* Maybe a second position is cleared and one additional location is set */
  776. uint8_t clr_pos2;
  777. uint8_t set_pos2;
  778. uint8_t set_cp2;
  779. /* get values from board */
  780. cp_src = cp_GetFromBoard(src);
  781. cp_dest = cp_GetFromBoard(dest);
  782. /* fill backup structure */
  783. chm->main_cp = cp_src;
  784. chm->main_src = src;
  785. chm->main_dest = dest;
  786. chm->other_cp = cp_dest; /* prepace capture backup */
  787. chm->other_src = dest;
  788. chm->other_dest = ILLEGAL_POSITION;
  789. /* setup results as far as possible with some suitable values */
  790. clr_pos2 = ILLEGAL_POSITION; /* for en passant and castling, two positions might be cleared */
  791. set_pos2 = ILLEGAL_POSITION; /* only used for castling */
  792. set_cp2 = PIECE_NONE; /* ROOK for castling */
  793. /* check for PAWN */
  794. if ( cp_GetPiece(cp_src) == PIECE_PAWN )
  795. {
  796. /* double step: is the distance 2 rows */
  797. if ( (src - dest == 32) || ( dest - src == 32 ) )
  798. {
  799. /* remember the destination position */
  800. lrc_obj.pawn_dbl_move[cp_GetColor(cp_src)] = dest;
  801. }
  802. /* check if the PAWN is able to promote */
  803. else if ( (dest>>4) == 0 || (dest>>4) == 7 )
  804. {
  805. /* do simple "queening" */
  806. cp_src &= ~PIECE_PAWN;
  807. cp_src |= PIECE_QUEEN;
  808. }
  809. /* is it en passant capture? */
  810. /* check for side move */
  811. else if ( ((src + dest) & 1) != 0 )
  812. {
  813. /* check, if target field is empty */
  814. if ( cp_GetPiece(cp_dest) == PIECE_NONE )
  815. {
  816. /* this is en passant */
  817. /* no further checking required, because legal moves are assumed here */
  818. /* however... the captured pawn position must be valid */
  819. clr_pos2 = lrc_obj.pawn_dbl_move[cp_GetColor(cp_src) ^ 1];
  820. chm->other_src = clr_pos2;
  821. chm->other_cp = cp_GetFromBoard(clr_pos2);
  822. }
  823. }
  824. }
  825. /* check for the KING */
  826. else if ( cp_GetPiece(cp_src) == PIECE_KING )
  827. {
  828. /* disallow castling, if the KING has moved */
  829. if ( cp_GetColor(cp_src) == COLOR_WHITE )
  830. {
  831. /* if white KING has moved, disallow castling for white */
  832. lrc_obj.castling_possible &= 0x0c;
  833. }
  834. else
  835. {
  836. /* if black KING has moved, disallow castling for black */
  837. lrc_obj.castling_possible &= 0x03;
  838. }
  839. /* has it been castling to the left? */
  840. if ( src - dest == 2 )
  841. {
  842. /* let the ROOK move to pos2 */
  843. set_pos2 = src-1;
  844. set_cp2 = cp_GetFromBoard(src-4);
  845. /* the ROOK must be cleared from the original position */
  846. clr_pos2 = src-4;
  847. chm->other_cp = set_cp2;
  848. chm->other_src = clr_pos2;
  849. chm->other_dest = set_pos2;
  850. }
  851. /* has it been castling to the right? */
  852. else if ( dest - src == 2 )
  853. {
  854. /* let the ROOK move to pos2 */
  855. set_pos2 = src+1;
  856. set_cp2 = cp_GetFromBoard(src+3);
  857. /* the ROOK must be cleared from the original position */
  858. clr_pos2 = src+3;
  859. chm->other_cp = set_cp2;
  860. chm->other_src = clr_pos2;
  861. chm->other_dest = set_pos2;
  862. }
  863. }
  864. /* check for the ROOK */
  865. else if ( cp_GetPiece(cp_src) == PIECE_ROOK )
  866. {
  867. /* disallow white left castling */
  868. if ( src == 0x00 )
  869. lrc_obj.castling_possible &= ~0x01;
  870. /* disallow white right castling */
  871. if ( src == 0x07 )
  872. lrc_obj.castling_possible &= ~0x02;
  873. /* disallow black left castling */
  874. if ( src == 0x70 )
  875. lrc_obj.castling_possible &= ~0x04;
  876. /* disallow black right castling */
  877. if ( src == 0x77 )
  878. lrc_obj.castling_possible &= ~0x08;
  879. }
  880. /* apply new board situation */
  881. cp_SetOnBoard(dest, cp_src);
  882. if ( set_pos2 != ILLEGAL_POSITION )
  883. cp_SetOnBoard(set_pos2, set_cp2);
  884. cp_SetOnBoard(src, PIECE_NONE);
  885. if ( clr_pos2 != ILLEGAL_POSITION )
  886. cp_SetOnBoard(clr_pos2, PIECE_NONE);
  887. }
  888. /*
  889. this subprocedure decides for evaluation of the current board situation or further (deeper) investigation
  890. Argument pos is the new target position if the current piece
  891. */
  892. uint8_t ce_LoopRecur(uint8_t pos)
  893. {
  894. eval_t eval;
  895. /* 1. check if target position is occupied by the same player (my_color) */
  896. /* of if pos is somehow illegal or not valid */
  897. if ( cu_IsIllegalPosition(pos, stack_GetCurrElement()->current_color) != 0 )
  898. return 0;
  899. /* 2. move piece to the specified position, capture opponent piece if required */
  900. cu_Move(stack_GetCurrElement()->current_pos, pos);
  901. /* 3. */
  902. /* if depth reached: evaluate */
  903. /* else: go down next level */
  904. /* no eval if there had been any valid half-moves, so the default value (MIN) will be returned. */
  905. if ( stack_Push(stack_GetCurrElement()->current_color) == 0 )
  906. {
  907. eval = ce_Eval();
  908. }
  909. else
  910. {
  911. /* init the element, which has been pushed */
  912. stack_InitCurrElement();
  913. /* start over with ntext level */
  914. ce_LoopPieces();
  915. /* get the best move from opponents view, so invert the result */
  916. eval = -stack_GetCurrElement()->best_eval;
  917. stack_Pop();
  918. }
  919. /* 4. store result */
  920. stack_SetMove(eval, pos);
  921. /* 5. undo the move */
  922. cu_UndoHalfMove();
  923. /* 6. check special modes */
  924. /* the purpose of these checks is to mark special pieces and positions on the board */
  925. /* these marks can be checked by the user interface to highlight special positions */
  926. if ( lrc_obj.check_mode != 0 )
  927. {
  928. stack_element_p e = stack_GetCurrElement();
  929. if ( lrc_obj.check_mode == CHECK_MODE_MOVEABLE )
  930. {
  931. cp_SetOnBoard(e->current_pos, e->current_cp | CP_MARK_MASK );
  932. }
  933. else if ( lrc_obj.check_mode == CHECK_MODE_TARGET_MOVE )
  934. {
  935. if ( e->current_pos == lrc_obj.check_src_pos )
  936. {
  937. cp_SetOnBoard(pos, cp_GetFromBoard(pos) | CP_MARK_MASK );
  938. }
  939. }
  940. }
  941. return 1;
  942. }
  943. /*==============================================================*/
  944. /* move pieces which can move one or more steps into a direction */
  945. /*==============================================================*/
  946. /*
  947. subprocedure to generate various target positions for some pieces
  948. special cases are handled in the piece specific sub-procedure
  949. Arguments:
  950. d: a list of potential directions
  951. is_multi_step: if the piece can only do one step (zero for KING and KNIGHT)
  952. */
  953. static const uint8_t ce_dir_offset_rook[] CHESS_PROGMEM = { 1, 16, (uint8_t)-16, (uint8_t)-1, 0 };
  954. static const uint8_t ce_dir_offset_bishop[] CHESS_PROGMEM = { 15, 17, (uint8_t)-17, (uint8_t)-15, 0 };
  955. static const uint8_t ce_dir_offset_queen[] CHESS_PROGMEM = { 1, 16, (uint8_t)-16, (uint8_t)-1, 15, 17, (uint8_t)-17, (uint8_t)-15, 0 };
  956. static const uint8_t ce_dir_offset_knight[] CHESS_PROGMEM = {14, (uint8_t)-14, 18, (uint8_t)-18, 31, (uint8_t)-31, 33, (uint8_t)-33, 0};
  957. void ce_LoopDirsSingleMultiStep(const uint8_t *d, uint8_t is_multi_step)
  958. {
  959. uint8_t loop_pos;
  960. /* with all directions */
  961. for(;;)
  962. {
  963. if ( chess_pgm_read(d) == 0 )
  964. break;
  965. /* start again from the initial position */
  966. loop_pos = stack_GetCurrElement()->current_pos;
  967. /* check direction */
  968. do
  969. {
  970. /* check next position into one direction */
  971. loop_pos += chess_pgm_read(d);
  972. /*
  973. go further to ce_LoopRecur()
  974. 0 will be returned if the target position is illegal or a piece of the own color
  975. this is used to stop walking into one direction
  976. */
  977. if ( ce_LoopRecur(loop_pos) == 0 )
  978. break;
  979. /* stop if we had hit another piece */
  980. if ( cp_GetPiece(cp_GetFromBoard(loop_pos)) != PIECE_NONE )
  981. break;
  982. } while( is_multi_step );
  983. d++;
  984. }
  985. }
  986. void ce_LoopRook(void)
  987. {
  988. ce_LoopDirsSingleMultiStep(ce_dir_offset_rook, 1);
  989. }
  990. void ce_LoopBishop(void)
  991. {
  992. ce_LoopDirsSingleMultiStep(ce_dir_offset_bishop, 1);
  993. }
  994. void ce_LoopQueen(void)
  995. {
  996. ce_LoopDirsSingleMultiStep(ce_dir_offset_queen, 1);
  997. }
  998. void ce_LoopKnight(void)
  999. {
  1000. ce_LoopDirsSingleMultiStep(ce_dir_offset_knight, 0);
  1001. }
  1002. /*==============================================================*/
  1003. /* move king */
  1004. /*==============================================================*/
  1005. uint8_t cu_IsKingCastling(uint8_t mask, int8_t direction, uint8_t cnt) U8G2_NOINLINE;
  1006. /*
  1007. checks, if the king can do castling
  1008. Arguments:
  1009. mask: the bit-mask for the global "castling possible" flag
  1010. direction: left castling: -1, right castling 1
  1011. cnt: number of fields to be checked: 3 or 2
  1012. */
  1013. uint8_t cu_IsKingCastling(uint8_t mask, int8_t direction, uint8_t cnt)
  1014. {
  1015. uint8_t pos;
  1016. uint8_t opponent_color;
  1017. /* check if the current board state allows castling */
  1018. if ( (lrc_obj.castling_possible & mask) == 0 )
  1019. return 0; /* castling not allowed */
  1020. /* get the position of the KING, could be white or black king */
  1021. pos = stack_GetCurrElement()->current_pos;
  1022. /* calculate the color of the opponent */
  1023. opponent_color = 1;
  1024. opponent_color -= stack_GetCurrElement()->current_color;
  1025. /* if the KING itself is given check... */
  1026. if ( ce_GetPositionAttackWeight(pos, opponent_color) > 0 )
  1027. return 0;
  1028. /* check if fields in the desired direction are emtpy */
  1029. for(;;)
  1030. {
  1031. /* go to the next field */
  1032. pos += direction;
  1033. /* check for a piece */
  1034. if ( cp_GetPiece(cp_GetFromBoard(pos)) != PIECE_NONE )
  1035. return 0; /* castling not allowed */
  1036. /* if some of the fields are under attack */
  1037. if ( ce_GetPositionAttackWeight(pos, opponent_color) > 0 )
  1038. return 0;
  1039. cnt--;
  1040. if ( cnt == 0 )
  1041. break;
  1042. }
  1043. return 1; /* castling allowed */
  1044. }
  1045. void ce_LoopKing(void)
  1046. {
  1047. /*
  1048. there is an interessting timing problem in this procedure
  1049. it must be checked for castling first and as second step the normal
  1050. KING movement. If we would first check for normal moves, than
  1051. any marks might be overwritten by the ROOK in the case of castling.
  1052. */
  1053. /* castling (this must be done before checking normal moves (see above) */
  1054. if ( stack_GetCurrElement()->current_color == COLOR_WHITE )
  1055. {
  1056. /* white left castling */
  1057. if ( cu_IsKingCastling(1, -1, 3) != 0 )
  1058. {
  1059. /* check for attacked fields */
  1060. ce_LoopRecur(stack_GetCurrElement()->current_pos-2);
  1061. }
  1062. /* white right castling */
  1063. if ( cu_IsKingCastling(2, 1, 2) != 0 )
  1064. {
  1065. /* check for attacked fields */
  1066. ce_LoopRecur(stack_GetCurrElement()->current_pos+2);
  1067. }
  1068. }
  1069. else
  1070. {
  1071. /* black left castling */
  1072. if ( cu_IsKingCastling(4, -1, 3) != 0 )
  1073. {
  1074. /* check for attacked fields */
  1075. ce_LoopRecur(stack_GetCurrElement()->current_pos-2);
  1076. }
  1077. /* black right castling */
  1078. if ( cu_IsKingCastling(8, 1, 2) != 0 )
  1079. {
  1080. /* check for attacked fields */
  1081. ce_LoopRecur(stack_GetCurrElement()->current_pos+2);
  1082. }
  1083. }
  1084. /* reuse queen directions */
  1085. ce_LoopDirsSingleMultiStep(ce_dir_offset_queen, 0);
  1086. }
  1087. /*==============================================================*/
  1088. /* move pawn */
  1089. /*==============================================================*/
  1090. /*
  1091. doppelschritt: nur von der grundlinie aus, beide (!) felder vor dem bauern m�ssen frei sein
  1092. en passant: nur unmittelbar nachdem ein doppelschritt ausgef�hrt wurde.
  1093. */
  1094. void ce_LoopPawnSideCapture(uint8_t loop_pos)
  1095. {
  1096. if ( gpos_IsIllegal(loop_pos) == 0 )
  1097. {
  1098. /* get the piece from the board */
  1099. /* if the field is NOT empty */
  1100. if ( cp_GetPiece(cp_GetFromBoard(loop_pos)) != PIECE_NONE )
  1101. {
  1102. /* normal capture */
  1103. ce_LoopRecur(loop_pos);
  1104. /* TODO: check for pawn conversion/promotion */
  1105. }
  1106. else
  1107. {
  1108. /* check conditions for en passant capture */
  1109. if ( stack_GetCurrElement()->current_color == COLOR_WHITE )
  1110. {
  1111. if ( lrc_obj.pawn_dbl_move[COLOR_BLACK]+16 == loop_pos )
  1112. {
  1113. ce_LoopRecur(loop_pos);
  1114. /* note: pawn conversion/promotion can not occur */
  1115. }
  1116. }
  1117. else
  1118. {
  1119. if ( lrc_obj.pawn_dbl_move[COLOR_WHITE] == loop_pos+16 )
  1120. {
  1121. ce_LoopRecur(loop_pos);
  1122. /* note: pawn conversion/promotion can not occur */
  1123. }
  1124. }
  1125. }
  1126. }
  1127. }
  1128. void ce_LoopPawn(void)
  1129. {
  1130. uint8_t initial_pos = stack_GetCurrElement()->current_pos;
  1131. uint8_t my_color = stack_GetCurrElement()->current_color;
  1132. uint8_t loop_pos;
  1133. uint8_t line;
  1134. /* one step forward */
  1135. loop_pos = initial_pos;
  1136. line = initial_pos;
  1137. line >>= 4;
  1138. if ( my_color == COLOR_WHITE )
  1139. loop_pos += 16;
  1140. else
  1141. loop_pos -= 16;
  1142. if ( gpos_IsIllegal(loop_pos) == 0 )
  1143. {
  1144. /* if the field is empty */
  1145. if ( cp_GetPiece(cp_GetFromBoard(loop_pos)) == PIECE_NONE )
  1146. {
  1147. /* TODO: check for and loop through piece conversion/promotion */
  1148. ce_LoopRecur(loop_pos);
  1149. /* second step forward */
  1150. /* if pawn is on his starting line */
  1151. if ( (my_color == COLOR_WHITE && line == 1) || (my_color == COLOR_BLACK && line == 6 ) )
  1152. {
  1153. /* the place before the pawn is not occupied, so we can do double moves, see above */
  1154. if ( my_color == COLOR_WHITE )
  1155. loop_pos += 16;
  1156. else
  1157. loop_pos -= 16;
  1158. if ( cp_GetPiece(cp_GetFromBoard(loop_pos)) == PIECE_NONE )
  1159. {
  1160. /* this is a special case, other promotions of the pawn can not occur */
  1161. ce_LoopRecur(loop_pos);
  1162. }
  1163. }
  1164. }
  1165. }
  1166. /* capture */
  1167. loop_pos = initial_pos;
  1168. if ( my_color == COLOR_WHITE )
  1169. loop_pos += 15;
  1170. else
  1171. loop_pos -= 15;
  1172. ce_LoopPawnSideCapture(loop_pos);
  1173. loop_pos = initial_pos;
  1174. if ( my_color == COLOR_WHITE )
  1175. loop_pos += 17;
  1176. else
  1177. loop_pos -= 17;
  1178. ce_LoopPawnSideCapture(loop_pos);
  1179. }
  1180. /*==============================================================*/
  1181. /* attacked */
  1182. /*==============================================================*/
  1183. /*
  1184. from a starting position, search for a piece, that might jump to that postion.
  1185. return:
  1186. the two global variables
  1187. lrc_obj.find_piece_weight[0];
  1188. lrc_obj.find_piece_weight[1];
  1189. will be increased by the weight of the attacked pieces of that color.
  1190. it is usually required to reset these global variables to zero, before using
  1191. this function.
  1192. */
  1193. void ce_FindPieceByStep(uint8_t start_pos, uint8_t piece, const uint8_t *d, uint8_t is_multi_step)
  1194. {
  1195. uint8_t loop_pos, cp;
  1196. /* with all directions */
  1197. for(;;)
  1198. {
  1199. if ( chess_pgm_read(d) == 0 )
  1200. break;
  1201. /* start again from the initial position */
  1202. loop_pos = start_pos;
  1203. /* check direction */
  1204. do
  1205. {
  1206. /* check next position into one direction */
  1207. loop_pos += chess_pgm_read(d);
  1208. /* check if the board boundary has been crossed */
  1209. if ( (loop_pos & 0x088) != 0 )
  1210. break;
  1211. /* get the colored piece from the board */
  1212. cp = cp_GetFromBoard(loop_pos);
  1213. /* stop if we had hit another piece */
  1214. if ( cp_GetPiece(cp) != PIECE_NONE )
  1215. {
  1216. /* if it is the piece we are looking for, then add the weight */
  1217. if ( cp_GetPiece(cp) == piece )
  1218. {
  1219. lrc_obj.find_piece_weight[cp_GetColor(cp)] += ce_piece_weight[piece];
  1220. lrc_obj.find_piece_cnt[cp_GetColor(cp)]++;
  1221. }
  1222. /* in any case, break out of the inner loop */
  1223. break;
  1224. }
  1225. } while( is_multi_step );
  1226. d++;
  1227. }
  1228. }
  1229. void ce_FindPawnPiece(uint8_t dest_pos, uint8_t color)
  1230. {
  1231. uint8_t cp;
  1232. /* check if the board boundary has been crossed */
  1233. if ( (dest_pos & 0x088) == 0 )
  1234. {
  1235. /* get the colored piece from the board */
  1236. cp = cp_GetFromBoard(dest_pos);
  1237. /* only if there is a pawn of the matching color */
  1238. if ( cp_GetPiece(cp) == PIECE_PAWN )
  1239. {
  1240. if ( cp_GetColor(cp) == color )
  1241. {
  1242. /* the weight of the PAWN */
  1243. lrc_obj.find_piece_weight[color] += 1;
  1244. lrc_obj.find_piece_cnt[color]++;
  1245. }
  1246. }
  1247. }
  1248. }
  1249. /*
  1250. find out, which pieces do attack a specified field
  1251. used to
  1252. - check if the KING can do castling
  1253. - check if the KING must move
  1254. may be used in the eval procedure ... once...
  1255. the result is stored in the global array
  1256. uint8_t lrc_obj.find_piece_weight[2];
  1257. which is indexed with the color.
  1258. lrc_obj.find_piece_weight[COLOR_WHITE] is the sum of all white pieces
  1259. which can directly move to this field.
  1260. example:
  1261. if the black KING is at "pos" and lrc_obj.find_piece_weight[COLOR_WHITE] is not zero
  1262. (after executing ce_CalculatePositionWeight(pos)) then the KING must be protected or moveed, because
  1263. the KING was given check.
  1264. */
  1265. void ce_CalculatePositionWeight(uint8_t pos)
  1266. {
  1267. lrc_obj.find_piece_weight[0] = 0;
  1268. lrc_obj.find_piece_weight[1] = 0;
  1269. lrc_obj.find_piece_cnt[0] = 0;
  1270. lrc_obj.find_piece_cnt[1] = 0;
  1271. if ( (pos & 0x088) != 0 )
  1272. return;
  1273. ce_FindPieceByStep(pos, PIECE_ROOK, ce_dir_offset_rook, 1);
  1274. ce_FindPieceByStep(pos, PIECE_BISHOP, ce_dir_offset_bishop, 1);
  1275. ce_FindPieceByStep(pos, PIECE_QUEEN, ce_dir_offset_queen, 1);
  1276. ce_FindPieceByStep(pos, PIECE_KNIGHT, ce_dir_offset_knight, 0);
  1277. ce_FindPieceByStep(pos, PIECE_KING, ce_dir_offset_queen, 0);
  1278. ce_FindPawnPiece(pos+17, COLOR_BLACK);
  1279. ce_FindPawnPiece(pos+15, COLOR_BLACK);
  1280. ce_FindPawnPiece(pos-17, COLOR_WHITE);
  1281. ce_FindPawnPiece(pos-15, COLOR_WHITE);
  1282. }
  1283. /*
  1284. calculate the summed weight of pieces with specified color which can move to a specified position
  1285. argument:
  1286. pos: the position which should be analysed
  1287. color: the color of those pieces which should be analysed
  1288. e.g. if a black piece is at 'pos' and 'color' is white then this procedure returns the white atting count
  1289. */
  1290. uint8_t ce_GetPositionAttackWeight(uint8_t pos, uint8_t color)
  1291. {
  1292. ce_CalculatePositionWeight(pos);
  1293. return lrc_obj.find_piece_weight[color];
  1294. }
  1295. uint8_t ce_GetPositionAttackCount(uint8_t pos, uint8_t color)
  1296. {
  1297. ce_CalculatePositionWeight(pos);
  1298. return lrc_obj.find_piece_cnt[color];
  1299. }
  1300. /*==============================================================*/
  1301. /* depth search starts here: loop over all pieces of the current color on the board */
  1302. /*==============================================================*/
  1303. void ce_LoopPieces(void)
  1304. {
  1305. stack_element_p e = stack_GetCurrElement();
  1306. /* start with lower left position (A1) */
  1307. e->current_pos = 0;
  1308. do
  1309. {
  1310. e->current_cp = cp_GetFromBoard(e->current_pos);
  1311. /* check if the position on the board is empty */
  1312. if ( e->current_cp != 0 )
  1313. {
  1314. /* only generate moves for the current color */
  1315. if ( e->current_color == cp_GetColor(e->current_cp) )
  1316. {
  1317. chess_Thinking();
  1318. /* find out which piece is used */
  1319. switch(cp_GetPiece(e->current_cp))
  1320. {
  1321. case PIECE_NONE:
  1322. break;
  1323. case PIECE_PAWN:
  1324. ce_LoopPawn();
  1325. break;
  1326. case PIECE_KNIGHT:
  1327. ce_LoopKnight();
  1328. break;
  1329. case PIECE_BISHOP:
  1330. ce_LoopBishop();
  1331. break;
  1332. case PIECE_ROOK:
  1333. ce_LoopRook();
  1334. break;
  1335. case PIECE_QUEEN:
  1336. ce_LoopQueen();
  1337. break;
  1338. case PIECE_KING:
  1339. ce_LoopKing();
  1340. break;
  1341. }
  1342. }
  1343. }
  1344. e->current_pos = cu_NextPos(e->current_pos);
  1345. } while( e->current_pos != 0 );
  1346. }
  1347. /*==============================================================*/
  1348. /* user interface */
  1349. /*==============================================================*/
  1350. /*
  1351. eval_t chess_EvalCurrBoard(uint8_t color)
  1352. {
  1353. stack_Init(0);
  1354. stack_GetCurrElement()->current_color = color;
  1355. ce_LoopPieces();
  1356. return stack_GetCurrElement()->best_eval;
  1357. }
  1358. */
  1359. /* clear any marks on the board */
  1360. void chess_ClearMarks(void)
  1361. {
  1362. uint8_t i;
  1363. for( i = 0; i < 64; i++ )
  1364. lrc_obj.board[i] &= ~CP_MARK_MASK;
  1365. }
  1366. /*
  1367. Mark all pieces which can do moves. This is done by setting flags on the global board
  1368. */
  1369. void chess_MarkMovable(void)
  1370. {
  1371. stack_Init(0);
  1372. //stack_GetCurrElement()->current_color = color;
  1373. lrc_obj.check_mode = CHECK_MODE_MOVEABLE;
  1374. ce_LoopPieces();
  1375. }
  1376. /*
  1377. Checks, if the piece can move from src_pos to dest_pos
  1378. src_pos: The game position of a piece on the chess board
  1379. */
  1380. void chess_MarkTargetMoves(uint8_t src_pos)
  1381. {
  1382. stack_Init(0);
  1383. stack_GetCurrElement()->current_color = cp_GetColor(cp_GetFromBoard(src_pos));
  1384. lrc_obj.check_src_pos = src_pos;
  1385. lrc_obj.check_mode = CHECK_MODE_TARGET_MOVE;
  1386. ce_LoopPieces();
  1387. }
  1388. /*
  1389. first call should start with 255
  1390. this procedure will return 255 if
  1391. - there are no marks at all
  1392. - it has looped over all marks once
  1393. */
  1394. uint8_t chess_GetNextMarked(uint8_t arg, uint8_t is_prev)
  1395. {
  1396. uint8_t i;
  1397. uint8_t pos = arg;
  1398. for(i = 0; i < 64; i++)
  1399. {
  1400. if ( is_prev != 0 )
  1401. pos = cu_PrevPos(pos);
  1402. else
  1403. pos = cu_NextPos(pos);
  1404. if ( arg != 255 && pos == 0 )
  1405. return 255;
  1406. if ( cp_IsMarked(cp_GetFromBoard(pos)) )
  1407. return pos;
  1408. }
  1409. return 255;
  1410. }
  1411. /* make a manual move: this is a little bit more than cu_Move() */
  1412. void chess_ManualMove(uint8_t src, uint8_t dest)
  1413. {
  1414. uint8_t cp;
  1415. /* printf("chess_ManualMove %02x -> %02x\n", src, dest); */
  1416. /* if all other things fail, this is the place where the game is to be decided: */
  1417. /* ... if the KING is captured */
  1418. cp = cp_GetFromBoard(dest);
  1419. if ( cp_GetPiece(cp) == PIECE_KING )
  1420. {
  1421. lrc_obj.is_game_end = 1;
  1422. lrc_obj.lost_side_color = cp_GetColor(cp);
  1423. }
  1424. /* clear ply history here, to avoid memory overflow */
  1425. /* may be the last X moves can be kept here */
  1426. cu_ReduceHistoryByFullMove();
  1427. /* perform the move on the board */
  1428. cu_Move(src, dest);
  1429. /* update en passant double move positions: en passant position is removed after two half moves */
  1430. lrc_obj.pawn_dbl_move[lrc_obj.ply_count&1] = ILLEGAL_POSITION;
  1431. /* update the global half move counter */
  1432. lrc_obj.ply_count++;
  1433. /* make a small check about the end of the game */
  1434. /* use at least depth 1, because we must know if the king can still move */
  1435. /* this is: King moves at level 0 and will be captured at level 1 */
  1436. /* so we check if the king can move and will not be captured at search level 1 */
  1437. stack_Init(1);
  1438. ce_LoopPieces();
  1439. /* printf("chess_ManualMove/analysis best_from_pos %02x -> best_to_pos %02x\n", stack_GetCurrElement()->best_from_pos, stack_GetCurrElement()->best_to_pos); */
  1440. /* analyse the eval result */
  1441. /* check if the other player has any moves left */
  1442. if ( stack_GetCurrElement()->best_from_pos == ILLEGAL_POSITION )
  1443. {
  1444. uint8_t color;
  1445. /* conditions: */
  1446. /* 1. no King, should never happen, opposite color has won */
  1447. /* this is already checked above at the beginning if this procedure */
  1448. /* 2. King is under attack, opposite color has won */
  1449. /* 3. King is not under attack, game is a draw */
  1450. uint8_t i = 0;
  1451. color = lrc_obj.ply_count;
  1452. color &= 1;
  1453. do
  1454. {
  1455. cp = cp_GetFromBoard(i);
  1456. /* look for the King */
  1457. if ( cp_GetPiece(cp) == PIECE_KING )
  1458. {
  1459. if ( cp_GetColor(cp) == color )
  1460. {
  1461. /* check if KING is attacked */
  1462. if ( ce_GetPositionAttackCount(i, color^1) != 0 )
  1463. {
  1464. /* KING is under attack (check) and can not move: Game is lost */
  1465. lrc_obj.is_game_end = 1;
  1466. lrc_obj.lost_side_color = color;
  1467. }
  1468. else
  1469. {
  1470. /* KING is NOT under attack (check) but can not move: Game is a draw */
  1471. lrc_obj.is_game_end = 1;
  1472. lrc_obj.lost_side_color = 2;
  1473. }
  1474. /* break out of the loop */
  1475. break;
  1476. }
  1477. }
  1478. i = cu_NextPos(i);
  1479. } while( i != 0 );
  1480. }
  1481. }
  1482. /* let the computer do a move */
  1483. void chess_ComputerMove(uint8_t depth)
  1484. {
  1485. stack_Init(depth);
  1486. //stack_GetCurrElement()->current_color = lrc_obj.ply_count;
  1487. //stack_GetCurrElement()->current_color &= 1;
  1488. cu_ReduceHistoryByFullMove();
  1489. ce_LoopPieces();
  1490. chess_ManualMove(stack_GetCurrElement()->best_from_pos, stack_GetCurrElement()->best_to_pos);
  1491. }
  1492. /*==============================================================*/
  1493. /* unix code */
  1494. /*==============================================================*/
  1495. #ifdef UNIX_MAIN
  1496. #else
  1497. /*==============================================================*/
  1498. /* display menu */
  1499. /*==============================================================*/
  1500. extern const uint8_t chess_pieces_body_bm[] CHESS_PROGMEM; // forward decl
  1501. extern const uint8_t chess_black_pieces_bm[] CHESS_PROGMEM; // forward decl
  1502. // uint8_t chess_key_code = 0; // obsolete, u8g2 does proper debouncing
  1503. uint8_t chess_key_cmd = 0;
  1504. #define CHESS_STATE_MENU 0
  1505. #define CHESS_STATE_SELECT_START 1
  1506. #define CHESS_STATE_SELECT_PIECE 2
  1507. #define CHESS_STATE_SELECT_TARGET_POS 3
  1508. #define CHESS_STATE_THINKING 4
  1509. #define CHESS_STATE_GAME_END 5
  1510. uint8_t chess_state = CHESS_STATE_MENU;
  1511. uint8_t chess_source_pos = 255;
  1512. uint8_t chess_target_pos = 255;
  1513. #define MNU_FONT u8g2_font_5x8_tr
  1514. #define MNU_ENTRY_HEIGHT 9
  1515. const char *mnu_title = "Little Rook Chess";
  1516. const char *mnu_list[] = { "New Game (White)", "New Game (Black)", "Undo Move", "Return" };
  1517. uint8_t mnu_pos = 0;
  1518. uint8_t mnu_max = 4;
  1519. void mnu_DrawHome(uint8_t is_highlight)
  1520. {
  1521. uint8_t x = lrc_u8g->width - 35;
  1522. uint8_t y = (lrc_u8g->height-1);
  1523. uint8_t t;
  1524. u8g2_SetFont(lrc_u8g, u8g2_font_5x7_tr);
  1525. u8g2_SetDefaultForegroundColor(lrc_u8g);
  1526. if ( chess_state == CHESS_STATE_THINKING )
  1527. u8g2_DrawBitmap(lrc_u8g, x, y-8, 1, 8, chess_black_pieces_bm+24);
  1528. else
  1529. {
  1530. t = u8g2_DrawStrP(lrc_u8g, x, y -1, CHESS_PSTR("Options"));
  1531. if ( is_highlight )
  1532. u8g2_DrawFrame(lrc_u8g, x-1, y - MNU_ENTRY_HEIGHT +1, t, MNU_ENTRY_HEIGHT);
  1533. }
  1534. }
  1535. void mnu_DrawEntry(uint8_t y, const char *str, uint8_t is_clr_background, uint8_t is_highlight)
  1536. {
  1537. uint8_t t, x;
  1538. u8g2_SetFont(lrc_u8g, MNU_FONT);
  1539. t = u8g2_GetStrWidth(lrc_u8g, str);
  1540. x = u8g2_GetDisplayWidth(lrc_u8g);
  1541. x -= t;
  1542. x >>= 1;
  1543. if ( is_clr_background )
  1544. {
  1545. u8g2_SetDefaultBackgroundColor(lrc_u8g);
  1546. u8g2_DrawBox(lrc_u8g, x-3, (lrc_u8g->height-1) - (y+MNU_ENTRY_HEIGHT-1+2), t+5, MNU_ENTRY_HEIGHT+4);
  1547. }
  1548. u8g2_SetDefaultForegroundColor(lrc_u8g);
  1549. u8g2_DrawStr(lrc_u8g, x, (lrc_u8g->height-1) - y, str);
  1550. if ( is_highlight )
  1551. {
  1552. u8g2_DrawFrame(lrc_u8g, 0, (lrc_u8g->height-1) - y -MNU_ENTRY_HEIGHT +1, u8g2_GetDisplayWidth(lrc_u8g), MNU_ENTRY_HEIGHT);
  1553. }
  1554. }
  1555. void mnu_Draw(void)
  1556. {
  1557. uint8_t i;
  1558. uint8_t t,y;
  1559. /* calculate hight of the complete menu */
  1560. y = mnu_max;
  1561. y++; /* consider also some space for the title */
  1562. y++; /* consider also some space for the title */
  1563. y *= MNU_ENTRY_HEIGHT;
  1564. /* calculate how much space will be left */
  1565. t = u8g2_GetDisplayHeight(lrc_u8g);
  1566. t -= y;
  1567. /* topmost pos start half of that empty space from the top */
  1568. t >>= 1;
  1569. y = u8g2_GetDisplayHeight(lrc_u8g);
  1570. y -= t;
  1571. y -= MNU_ENTRY_HEIGHT;
  1572. mnu_DrawEntry(y, mnu_title, 0, 0);
  1573. y -= MNU_ENTRY_HEIGHT;
  1574. u8g2_DrawBitmap(lrc_u8g, 0, 1, 1, 8, chess_black_pieces_bm+24);
  1575. u8g2_DrawBitmap(lrc_u8g, 128-8, 1, 1, 8, chess_black_pieces_bm+24);
  1576. for( i = 0; i < mnu_max; i++ )
  1577. {
  1578. y -= MNU_ENTRY_HEIGHT;
  1579. mnu_DrawEntry(y, mnu_list[i], 0, i == mnu_pos);
  1580. }
  1581. }
  1582. void mnu_Step(uint8_t key_cmd)
  1583. {
  1584. if ( key_cmd == CHESS_KEY_NEXT )
  1585. {
  1586. if ( mnu_pos+1 < mnu_max )
  1587. mnu_pos++;
  1588. }
  1589. else if ( key_cmd == CHESS_KEY_PREV )
  1590. {
  1591. if ( mnu_pos > 0 )
  1592. mnu_pos--;
  1593. }
  1594. }
  1595. const uint8_t chess_pieces_body_bm[] CHESS_PROGMEM =
  1596. {
  1597. /* PAWN */ 0x00, 0x00, 0x00, 0x18, 0x18, 0x00, 0x00, 0x00, /* 0x00, 0x00, 0x00, 0x0c, 0x0c, 0x00, 0x00, 0x00, */
  1598. /* KNIGHT */ 0x00, 0x00, 0x1c, 0x2c, 0x04, 0x04, 0x0e, 0x00,
  1599. /* BISHOP */ 0x00, 0x00, 0x1c, 0x1c, 0x1c, 0x08, 0x00, 0x00, /* 0x00, 0x00, 0x08, 0x1c, 0x1c, 0x08, 0x00, 0x00, */
  1600. /* ROOK */ 0x00, 0x00, 0x00, 0x1c, 0x1c, 0x1c, 0x1c, 0x00,
  1601. /* QUEEN */ 0x00, 0x00, 0x14, 0x1c, 0x08, 0x1c, 0x08, 0x00,
  1602. /* KING */ 0x00, 0x00, 0x00, 0x08, 0x3e, 0x1c, 0x08, 0x00,
  1603. };
  1604. #ifdef NOT_REQUIRED
  1605. /* white pieces are constructed by painting black pieces and cutting out the white area */
  1606. const uint8_t chess_white_pieces_bm[] CHESS_PROGMEM =
  1607. {
  1608. /* PAWN */ 0x00, 0x00, 0x0c, 0x12, 0x12, 0x0c, 0x1e, 0x00,
  1609. /* KNIGHT */ 0x00, 0x1c, 0x22, 0x52, 0x6a, 0x0a, 0x11, 0x1f,
  1610. /* BISHOP */ 0x00, 0x08, 0x14, 0x22, 0x22, 0x14, 0x08, 0x7f,
  1611. /* ROOK */ 0x00, 0x55, 0x7f, 0x22, 0x22, 0x22, 0x22, 0x7f,
  1612. /* QUEEN */ 0x00, 0x55, 0x2a, 0x22, 0x14, 0x22, 0x14, 0x7f,
  1613. /* KING */ 0x08, 0x1c, 0x49, 0x77, 0x41, 0x22, 0x14, 0x7f,
  1614. };
  1615. #endif
  1616. const uint8_t chess_black_pieces_bm[] CHESS_PROGMEM =
  1617. {
  1618. /* PAWN */ 0x00, 0x00, 0x18, 0x3c, 0x3c, 0x18, 0x3c, 0x00, /* 0x00, 0x00, 0x0c, 0x1e, 0x1e, 0x0c, 0x1e, 0x00, */
  1619. /* KNIGHT */ 0x00, 0x1c, 0x3e, 0x7e, 0x6e, 0x0e, 0x1f, 0x1f,
  1620. /* BISHOP */ 0x00, 0x1c, 0x2e, 0x3e, 0x3e, 0x1c, 0x08, 0x7f, /*0x00, 0x08, 0x1c, 0x3e, 0x3e, 0x1c, 0x08, 0x7f,*/
  1621. /* ROOK */ 0x00, 0x55, 0x7f, 0x3e, 0x3e, 0x3e, 0x3e, 0x7f,
  1622. /* QUEEN */ 0x00, 0x55, 0x3e, 0x3e, 0x1c, 0x3e, 0x1c, 0x7f,
  1623. /* KING -*/ 0x08, 0x1c, 0x49, 0x7f, 0x7f, 0x3e, 0x1c, 0x7f,
  1624. };
  1625. #if defined(DOGXL160_HW_GR)
  1626. #define BOXSIZE 13
  1627. #define BOXOFFSET 3
  1628. #else
  1629. #define BOXSIZE 8
  1630. #define BOXOFFSET 1
  1631. #endif
  1632. u8g2_uint_t chess_low_edge;
  1633. uint8_t chess_boxsize = 8;
  1634. uint8_t chess_boxoffset = 1;
  1635. void chess_DrawFrame(uint8_t pos, uint8_t is_bold)
  1636. {
  1637. u8g2_uint_t x0, y0;
  1638. x0 = pos;
  1639. x0 &= 15;
  1640. if ( lrc_obj.orientation != COLOR_WHITE )
  1641. x0 ^= 7;
  1642. y0 = pos;
  1643. y0>>= 4;
  1644. if ( lrc_obj.orientation != COLOR_WHITE )
  1645. y0 ^= 7;
  1646. x0 *= chess_boxsize;
  1647. y0 *= chess_boxsize;
  1648. u8g2_SetDefaultForegroundColor(lrc_u8g);
  1649. u8g2_DrawFrame(lrc_u8g, x0, chess_low_edge - y0 - chess_boxsize+1, chess_boxsize, chess_boxsize);
  1650. if ( is_bold )
  1651. {
  1652. x0--;
  1653. y0++;
  1654. u8g2_DrawFrame(lrc_u8g, x0, chess_low_edge - y0 - chess_boxsize +1, chess_boxsize+2, chess_boxsize+2);
  1655. }
  1656. }
  1657. void chess_DrawBoard(void)
  1658. {
  1659. uint8_t i, j, cp;
  1660. const uint8_t *ptr; /* pointer into CHESS_PROGMEM */
  1661. {
  1662. uint8_t x_offset = 1;
  1663. u8g2_SetDefaultForegroundColor(lrc_u8g);
  1664. for( i = 0; i < 8*8; i+=8 )
  1665. {
  1666. for( j = 0; j < 8*8; j+=8 )
  1667. {
  1668. if ( ((i^j) & 8) == 0 )
  1669. {
  1670. if ( lrc_obj.orientation == COLOR_WHITE )
  1671. {
  1672. cp = lrc_obj.board[i+j/8];
  1673. }
  1674. else
  1675. {
  1676. cp = lrc_obj.board[(7-i/8)*8+7-j/8];
  1677. }
  1678. if ( cp_GetPiece(cp) == PIECE_NONE )
  1679. {
  1680. u8g2_DrawPixel(lrc_u8g, j+0+x_offset, chess_low_edge - i-0);
  1681. u8g2_DrawPixel(lrc_u8g, j+0+x_offset, chess_low_edge - i-2);
  1682. u8g2_DrawPixel(lrc_u8g, j+0+x_offset, chess_low_edge - i-4);
  1683. u8g2_DrawPixel(lrc_u8g, j+0+x_offset, chess_low_edge - i-6);
  1684. u8g2_DrawPixel(lrc_u8g, j+2+x_offset, chess_low_edge - i-0);
  1685. u8g2_DrawPixel(lrc_u8g, j+2+x_offset, chess_low_edge - i-6);
  1686. u8g2_DrawPixel(lrc_u8g, j+4+x_offset, chess_low_edge - i-0);
  1687. u8g2_DrawPixel(lrc_u8g, j+4+x_offset, chess_low_edge - i-6);
  1688. u8g2_DrawPixel(lrc_u8g, j+6+x_offset, chess_low_edge - i-0);
  1689. u8g2_DrawPixel(lrc_u8g, j+6+x_offset, chess_low_edge - i-2);
  1690. u8g2_DrawPixel(lrc_u8g, j+6+x_offset, chess_low_edge - i-4);
  1691. u8g2_DrawPixel(lrc_u8g, j+6+x_offset, chess_low_edge - i-6);
  1692. }
  1693. }
  1694. }
  1695. }
  1696. }
  1697. for ( i = 0; i < 8; i++ )
  1698. {
  1699. for ( j = 0; j < 8; j++ )
  1700. {
  1701. /* get piece from global board */
  1702. if ( lrc_obj.orientation == COLOR_WHITE )
  1703. {
  1704. cp = lrc_obj.board[i*8+j];
  1705. }
  1706. else
  1707. {
  1708. cp = lrc_obj.board[(7-i)*8+7-j];
  1709. }
  1710. if ( cp_GetPiece(cp) != PIECE_NONE )
  1711. {
  1712. ptr = chess_black_pieces_bm;
  1713. ptr += (cp_GetPiece(cp)-1)*8;
  1714. u8g2_SetDefaultForegroundColor(lrc_u8g);
  1715. u8g2_DrawBitmap(lrc_u8g, j*chess_boxsize+chess_boxoffset-1, chess_low_edge - (i*chess_boxsize+chess_boxsize-chess_boxoffset), 1, 8, ptr);
  1716. if ( cp_GetColor(cp) == lrc_obj.strike_out_color )
  1717. {
  1718. ptr = chess_pieces_body_bm;
  1719. ptr += (cp_GetPiece(cp)-1)*8;
  1720. u8g2_SetDefaultBackgroundColor(lrc_u8g);
  1721. u8g2_DrawBitmap(lrc_u8g, j*chess_boxsize+chess_boxoffset-1, chess_low_edge - (i*chess_boxsize+chess_boxsize-chess_boxoffset), 1, 8, ptr);
  1722. }
  1723. }
  1724. }
  1725. }
  1726. u8g2_SetDefaultForegroundColor(lrc_u8g);
  1727. if ( (chess_source_pos & 0x88) == 0 )
  1728. {
  1729. chess_DrawFrame(chess_source_pos, 1);
  1730. }
  1731. if ( (chess_target_pos & 0x88) == 0 )
  1732. {
  1733. chess_DrawFrame(chess_target_pos, 0);
  1734. }
  1735. }
  1736. void chess_Thinking(void)
  1737. {
  1738. }
  1739. void chess_Init(u8g2_t *u8g, uint8_t body_color)
  1740. {
  1741. lrc_u8g = u8g;
  1742. chess_low_edge = u8g2_GetDisplayHeight(lrc_u8g);
  1743. chess_low_edge--;
  1744. u8g2_SetBitmapMode(u8g, 1); // restore previous behaviour
  1745. {
  1746. chess_boxsize = 8;
  1747. chess_boxoffset = 1;
  1748. }
  1749. lrc_obj.strike_out_color = body_color;
  1750. chess_SetupBoard();
  1751. }
  1752. void chess_Draw(void)
  1753. {
  1754. if ( chess_state == CHESS_STATE_MENU )
  1755. {
  1756. if ( lrc_obj.ply_count == 0)
  1757. mnu_max = 2;
  1758. else
  1759. mnu_max = 4;
  1760. mnu_Draw();
  1761. }
  1762. else
  1763. {
  1764. chess_DrawBoard();
  1765. {
  1766. uint8_t i;
  1767. uint8_t entries = lrc_obj.chm_pos;
  1768. if ( entries > 4 )
  1769. entries = 4;
  1770. u8g2_SetFont(lrc_u8g, u8g2_font_5x7_tr);
  1771. u8g2_SetDefaultForegroundColor(lrc_u8g);
  1772. for( i = 0; i < entries; i++ )
  1773. {
  1774. u8g2_DrawStr(lrc_u8g, u8g2_GetDisplayWidth(lrc_u8g)-35, 8*(i+1), cu_GetHalfMoveStr(lrc_obj.chm_pos-entries+i));
  1775. }
  1776. }
  1777. if ( chess_state == CHESS_STATE_SELECT_PIECE )
  1778. mnu_DrawHome(chess_source_pos == 255);
  1779. else if ( chess_state == CHESS_STATE_SELECT_TARGET_POS )
  1780. mnu_DrawHome(chess_target_pos == 255);
  1781. else
  1782. mnu_DrawHome(0);
  1783. if ( chess_state == CHESS_STATE_GAME_END )
  1784. {
  1785. switch( lrc_obj.lost_side_color )
  1786. {
  1787. case COLOR_WHITE:
  1788. mnu_DrawEntry(u8g2_GetDisplayHeight(lrc_u8g) / 2-2, "Black wins", 1, 1);
  1789. break;
  1790. case COLOR_BLACK:
  1791. mnu_DrawEntry(u8g2_GetDisplayHeight(lrc_u8g) / 2-2, "White wins", 1, 1);
  1792. break;
  1793. default:
  1794. mnu_DrawEntry(u8g2_GetDisplayHeight(lrc_u8g) / 2-2, "Stalemate", 1, 1);
  1795. break;
  1796. }
  1797. }
  1798. }
  1799. }
  1800. void chess_Step(uint8_t keycode)
  1801. {
  1802. chess_key_cmd = keycode;
  1803. /*
  1804. if ( keycode == CHESS_KEY_NONE )
  1805. {
  1806. chess_key_cmd = chess_key_code;
  1807. chess_key_code = CHESS_KEY_NONE;
  1808. }
  1809. else
  1810. {
  1811. chess_key_cmd = CHESS_KEY_NONE;
  1812. chess_key_code = keycode;
  1813. }
  1814. */
  1815. //chess_ComputerMove(2);
  1816. switch(chess_state)
  1817. {
  1818. case CHESS_STATE_MENU:
  1819. mnu_Step(chess_key_cmd);
  1820. if ( chess_key_cmd == CHESS_KEY_SELECT )
  1821. {
  1822. if ( mnu_pos == 0 )
  1823. {
  1824. chess_SetupBoard();
  1825. lrc_obj.orientation = 0;
  1826. chess_state = CHESS_STATE_SELECT_START;
  1827. }
  1828. else if ( mnu_pos == 1 )
  1829. {
  1830. chess_SetupBoard();
  1831. lrc_obj.orientation = 1;
  1832. chess_state = CHESS_STATE_THINKING;
  1833. }
  1834. else if ( mnu_pos == 2 )
  1835. {
  1836. if ( lrc_obj.ply_count >= 2 )
  1837. {
  1838. cu_UndoHalfMove();
  1839. cu_UndoHalfMove();
  1840. lrc_obj.ply_count-=2;
  1841. if ( lrc_obj.ply_count == 0 )
  1842. mnu_pos = 0;
  1843. }
  1844. chess_state = CHESS_STATE_SELECT_START;
  1845. }
  1846. else if ( mnu_pos == 3 )
  1847. {
  1848. chess_state = CHESS_STATE_SELECT_START;
  1849. }
  1850. }
  1851. break;
  1852. case CHESS_STATE_SELECT_START:
  1853. chess_ClearMarks();
  1854. chess_MarkMovable();
  1855. chess_source_pos = chess_GetNextMarked(255, 0);
  1856. chess_target_pos = ILLEGAL_POSITION;
  1857. chess_state = CHESS_STATE_SELECT_PIECE;
  1858. break;
  1859. case CHESS_STATE_SELECT_PIECE:
  1860. if ( chess_key_cmd == CHESS_KEY_NEXT )
  1861. {
  1862. chess_source_pos = chess_GetNextMarked(chess_source_pos, lrc_obj.orientation);
  1863. }
  1864. else if ( chess_key_cmd == CHESS_KEY_PREV )
  1865. {
  1866. chess_source_pos = chess_GetNextMarked(chess_source_pos, 1-lrc_obj.orientation );
  1867. }
  1868. else if ( chess_key_cmd == CHESS_KEY_SELECT )
  1869. {
  1870. if ( chess_source_pos == 255 )
  1871. {
  1872. chess_state = CHESS_STATE_MENU;
  1873. }
  1874. else
  1875. {
  1876. chess_ClearMarks();
  1877. chess_MarkTargetMoves(chess_source_pos);
  1878. chess_target_pos = chess_GetNextMarked(255, 0);
  1879. chess_state = CHESS_STATE_SELECT_TARGET_POS;
  1880. }
  1881. }
  1882. break;
  1883. case CHESS_STATE_SELECT_TARGET_POS:
  1884. if ( chess_key_cmd == CHESS_KEY_NEXT )
  1885. {
  1886. chess_target_pos = chess_GetNextMarked(chess_target_pos, lrc_obj.orientation);
  1887. if ( chess_target_pos == 255 )
  1888. chess_target_pos = chess_GetNextMarked(chess_target_pos, lrc_obj.orientation);
  1889. }
  1890. else if ( chess_key_cmd == CHESS_KEY_PREV )
  1891. {
  1892. chess_target_pos = chess_GetNextMarked(chess_target_pos, 1-lrc_obj.orientation);
  1893. if ( chess_target_pos == 255 )
  1894. chess_target_pos = chess_GetNextMarked(chess_target_pos, 1-lrc_obj.orientation);
  1895. }
  1896. else if ( chess_key_cmd == CHESS_KEY_BACK )
  1897. {
  1898. chess_ClearMarks();
  1899. chess_MarkMovable();
  1900. chess_target_pos = ILLEGAL_POSITION;
  1901. chess_state = CHESS_STATE_SELECT_PIECE;
  1902. }
  1903. else if ( chess_key_cmd == CHESS_KEY_SELECT )
  1904. {
  1905. chess_ManualMove(chess_source_pos, chess_target_pos);
  1906. if ( lrc_obj.is_game_end != 0 )
  1907. chess_state = CHESS_STATE_GAME_END;
  1908. else
  1909. chess_state = CHESS_STATE_THINKING;
  1910. /* clear marks as some kind of feedback to the user... it simply looks better */
  1911. chess_source_pos = ILLEGAL_POSITION;
  1912. chess_target_pos = ILLEGAL_POSITION;
  1913. chess_ClearMarks();
  1914. }
  1915. break;
  1916. case CHESS_STATE_THINKING:
  1917. chess_ComputerMove(2);
  1918. if ( lrc_obj.is_game_end != 0 )
  1919. chess_state = CHESS_STATE_GAME_END;
  1920. else
  1921. chess_state = CHESS_STATE_SELECT_START;
  1922. //chess_state = CHESS_STATE_THINKING
  1923. break;
  1924. case CHESS_STATE_GAME_END:
  1925. if ( chess_key_cmd != CHESS_KEY_NONE )
  1926. {
  1927. chess_state = CHESS_STATE_MENU;
  1928. chess_SetupBoard();
  1929. }
  1930. break;
  1931. }
  1932. }
  1933. #endif /* UNIX_MAIN */
  1934. void loop(void) {
  1935. static uint8_t keycode = 0;
  1936. u8g2.firstPage();
  1937. do {
  1938. chess_Draw();
  1939. if ( keycode == 0 )
  1940. keycode = u8g2.getMenuEvent();
  1941. } while ( u8g2.nextPage() );
  1942. if ( keycode == 0 )
  1943. keycode = u8g2.getMenuEvent();
  1944. if ( keycode == U8X8_MSG_GPIO_MENU_DOWN )
  1945. keycode = CHESS_KEY_NEXT;
  1946. if ( keycode == U8X8_MSG_GPIO_MENU_UP )
  1947. keycode = CHESS_KEY_PREV;
  1948. //if ( keycode == U8X8_MSG_GPIO_MENU_HOME )
  1949. // keycode = CHESS_KEY_SELECT;
  1950. chess_Step(keycode);
  1951. keycode = 0;
  1952. delay(1);
  1953. }