chessengine.c 62 KB

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