smallchesslib.h 99 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492
  1. #ifndef SMALLCHESSLIB_H
  2. #define SMALLCHESSLIB_H
  3. /**
  4. @file smallchesslib.h
  5. Small and simple single header C99 public domain chess library and engine.
  6. author: Miloslav Ciz (drummyfish)
  7. license: CC0 1.0 (public domain)
  8. found at https://creativecommons.org/publicdomain/zero/1.0/
  9. + additional waiver of all IP
  10. version: 0.8d
  11. Default notation format for this library is a coordinate one, i.e.
  12. squarefrom squareto [promotedpiece]
  13. e.g.: e2e4 or A2A1q
  14. This work's goal is to never be encumbered by any exclusive intellectual
  15. property rights. The work is therefore provided under CC0 1.0 + additional
  16. WAIVER OF ALL INTELLECTUAL PROPERTY RIGHTS that waives the rest of
  17. intellectual property rights not already waived by CC0 1.0. The WAIVER OF ALL
  18. INTELLECTUAL PROPERTY RGHTS is as follows:
  19. Each contributor to this work agrees that they waive any exclusive rights,
  20. including but not limited to copyright, patents, trademark, trade dress,
  21. industrial design, plant varieties and trade secrets, to any and all ideas,
  22. concepts, processes, discoveries, improvements and inventions conceived,
  23. discovered, made, designed, researched or developed by the contributor either
  24. solely or jointly with others, which relate to this work or result from this
  25. work. Should any waiver of such right be judged legally invalid or
  26. ineffective under applicable law, the contributor hereby grants to each
  27. affected person a royalty-free, non transferable, non sublicensable, non
  28. exclusive, irrevocable and unconditional license to this right.
  29. */
  30. #include <stdint.h>
  31. #ifndef SCL_DEBUG_AI
  32. /** AI will print out a Newick-like tree of searched moves. */
  33. #define SCL_DEBUG_AI 0
  34. #endif
  35. /**
  36. Maximum number of moves a chess piece can have (a queen in the middle of the
  37. board).
  38. */
  39. #define SCL_CHESS_PIECE_MAX_MOVES 25
  40. #define SCL_BOARD_SQUARES 64
  41. typedef uint8_t (*SCL_RandomFunction)(void);
  42. #if SCL_COUNT_EVALUATED_POSITIONS
  43. uint32_t SCL_positionsEvaluated = 0; /**< If enabled by
  44. SCL_COUNT_EVALUATED_POSITIONS, this
  45. will increment with every
  46. dynamically evaluated position (e.g.
  47. when AI computes its move). */
  48. #endif
  49. #ifndef SCL_CALL_WDT_RESET
  50. #define SCL_CALL_WDT_RESET \
  51. 0 /**< Option that should be enabled on some
  52. Arduinos. If 1, call to watchdog timer
  53. reset will be performed during dynamic
  54. evaluation (without it if AI takes long the
  55. program will reset). */
  56. #endif
  57. /**
  58. Returns a pseudorandom byte. This function has a period 256 and returns each
  59. possible byte value exactly once in the period.
  60. */
  61. uint8_t SCL_randomSimple(void);
  62. void SCL_randomSimpleSeed(uint8_t seed);
  63. /**
  64. Like SCL_randomSimple, but internally uses a 16 bit value, so the period is
  65. 65536.
  66. */
  67. uint8_t SCL_randomBetter(void);
  68. void SCL_randomBetterSeed(uint16_t seed);
  69. #ifndef SCL_EVALUATION_FUNCTION
  70. /**
  71. If defined, AI will always use the static evaluation function with this
  72. name. This helps avoid pointers to functions and can be faster but the
  73. function can't be changed at runtime.
  74. */
  75. #define SCL_EVALUATION_FUNCTION
  76. #undef SCL_EVALUATION_FUNCTION
  77. #endif
  78. #ifndef SCL_960_CASTLING
  79. /**
  80. If set, chess 960 (Fisher random) castling will be considered by the library
  81. rather than normal castling. 960 castling is slightly different (e.g.
  82. requires the inital rook positions to be stored in board state). The
  83. castling move is performed as "capturing own rook".
  84. */
  85. #define SCL_960_CASTLING 0
  86. #endif
  87. #ifndef SCL_ALPHA_BETA
  88. /**
  89. Turns alpha-beta pruning (AI optimization) on or off. This can gain
  90. performance and should normally be turned on. AI behavior should not
  91. change at all.
  92. */
  93. #define SCL_ALPHA_BETA 1
  94. #endif
  95. /**
  96. A set of game squares as a bit array, each bit representing one game square.
  97. Useful for representing e.g. possible moves. To easily iterate over the set
  98. use provided macros (SCL_SQUARE_SET_ITERATE, ...).
  99. */
  100. typedef uint8_t SCL_SquareSet[8];
  101. #define SCL_SQUARE_SET_EMPTY \
  102. { 0, 0, 0, 0, 0, 0, 0, 0 }
  103. void SCL_squareSetClear(SCL_SquareSet squareSet);
  104. void SCL_squareSetAdd(SCL_SquareSet squareSet, uint8_t square);
  105. uint8_t SCL_squareSetContains(const SCL_SquareSet squareSet, uint8_t square);
  106. uint8_t SCL_squareSetSize(const SCL_SquareSet squareSet);
  107. uint8_t SCL_squareSetEmpty(const SCL_SquareSet squareSet);
  108. /**
  109. Returns a random square from a square set.
  110. */
  111. uint8_t SCL_squareSetGetRandom(const SCL_SquareSet squareSet, SCL_RandomFunction randFunc);
  112. #define SCL_SQUARE_SET_ITERATE_BEGIN(squareSet) \
  113. { \
  114. uint8_t iteratedSquare = 0; \
  115. uint8_t iterationEnd = 0; \
  116. for(int8_t _i = 0; _i < 8 && !iterationEnd; ++_i) { \
  117. uint8_t _row = squareSet[_i]; \
  118. if(_row == 0) { \
  119. iteratedSquare += 8; \
  120. continue; \
  121. } \
  122. \
  123. for(uint8_t _j = 0; _j < 8 && !iterationEnd; ++_j) { \
  124. if(_row & 0x01) {
  125. /*
  126. Between SCL_SQUARE_SET_ITERATE_BEGIN and _END iteratedSquare variable
  127. represents the next square contained in the set. To break out of the
  128. iteration set iterationEnd to 1.
  129. */
  130. #define SCL_SQUARE_SET_ITERATE_END \
  131. } \
  132. _row >>= 1; \
  133. iteratedSquare++; \
  134. } \
  135. } /*for*/ \
  136. }
  137. #define SCL_SQUARE_SET_ITERATE(squareSet, command) \
  138. SCL_SQUARE_SET_ITERATE_BEGIN(squareSet){command} SCL_SQUARE_SET_ITERATE_END
  139. #define SCL_BOARD_STATE_SIZE 69
  140. /**
  141. Represents chess board state as a string in this format:
  142. - First 64 characters represent the chess board (A1, B1, ... H8), each field
  143. can be either a piece (PRNBKQprnbkq) or empty ('.'). I.e. the state looks
  144. like this:
  145. 0 (A1) RNBQKBNR
  146. PPPPPPPP
  147. ........
  148. ........
  149. ........
  150. ........
  151. pppppppp
  152. rnbqkbnr 63 (H8)
  153. - After this more bytes follow to represent global state, these are:
  154. - 64: bits holding en-passant and castling related information:
  155. - bits 0-3 (lsb): Column of the pawn that can, in current turn, be
  156. taken by en-passant (0xF means no pawn can be taken this way).
  157. - bit 4: Whether white is not prevented from short castling by previous
  158. king or rook movement.
  159. - bit 5: Same as 4, but for long castling.
  160. - bit 6: Same as 4, but for black.
  161. - bit 7: Same as 4, but for black and long castling.
  162. - 65: Number saying the number of ply (half-moves) that have already been
  163. played, also determining whose turn it currently is.
  164. - 66: Move counter used in the 50 move rule, says the number of ply since
  165. the last pawn move or capture.
  166. - 67: Extra byte, left for storing additional info in variants. For normal
  167. chess this byte should always be 0.
  168. - 68: The last byte is always 0 to properly terminate the string in case
  169. someone tries to print it.
  170. - The state is designed so as to be simple and also print-friendly, i.e. you
  171. can simply print it with line break after 8 characters to get a human
  172. readable representation of the board.
  173. NOTE: there is a much more compact representation which however trades some
  174. access speed which would affect the AI performance and isn't print friendly,
  175. so we don't use it. In it each square takes 4 bits, using 15 out of 16
  176. possible values (empty square and W and B pieces including 2 types of pawns,
  177. one "en-passant takeable"). Then only one extra byte needed is for castling
  178. info (4 bits) and ply count (4 bits).
  179. */
  180. typedef char SCL_Board[SCL_BOARD_STATE_SIZE];
  181. #define SCL_BOARD_ENPASSANT_CASTLE_BYTE 64
  182. #define SCL_BOARD_PLY_BYTE 65
  183. #define SCL_BOARD_MOVE_COUNT_BYTE 66
  184. #define SCL_BOARD_EXTRA_BYTE 67
  185. #if SCL_960_CASTLING
  186. #define _SCL_EXTRA_BYTE_VALUE (0 | (7 << 3)) // rooks on classic positions
  187. #else
  188. #define _SCL_EXTRA_BYTE_VALUE 0
  189. #endif
  190. #define SCL_BOARD_START_STATE \
  191. { \
  192. 82, 78, 66, 81, 75, 66, 78, 82, 80, 80, 80, 80, 80, 80, 80, 80, 46, 46, 46, 46, 46, 46, \
  193. 46, 46, 46, 46, 46, 46, 46, 46, 46, 46, 46, 46, 46, 46, 46, 46, 46, 46, 46, 46, 46, \
  194. 46, 46, 46, 46, 46, 112, 112, 112, 112, 112, 112, 112, 112, 114, 110, 98, 113, 107, \
  195. 98, 110, 114, (char)0xff, 0, 0, _SCL_EXTRA_BYTE_VALUE, 0 \
  196. }
  197. #define SCL_FEN_START "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1"
  198. #define SCL_FEN_HORDE "ppp2ppp/pppppppp/pppppppp/pppppppp/3pp3/8/PPPPPPPP/RNBQKBNR w KQ - 0 1"
  199. #define SCL_FEN_UPSIDE_DOWN "RNBKQBNR/PPPPPPPP/8/8/8/8/pppppppp/rnbkqbnr w - - 0 1"
  200. #define SCL_FEN_PEASANT_REVOLT "1nn1k1n1/4p3/8/8/8/8/PPPPPPPP/4K3 w - - 0 1"
  201. #define SCL_FEN_ENDGAME "4k3/pppppppp/8/8/8/8/PPPPPPPP/4K3 w - - 0 1"
  202. #define SCL_FEN_KNIGHTS "N6n/1N4n1/2N2n2/3Nn3/k2nN2K/2n2N2/1n4N1/n6N w - - 0 1"
  203. /**
  204. Holds an info required to undo a single move.
  205. */
  206. typedef struct {
  207. uint8_t squareFrom; ///< start square
  208. uint8_t squareTo; ///< target square
  209. char enPassantCastle; ///< previous en passant/castle byte
  210. char moveCount; ///< previous values of the move counter byte
  211. uint8_t other; /**< lowest 7 bits: previous value of target square,
  212. highest bit: if 1 then the move was promotion or
  213. en passant */
  214. } SCL_MoveUndo;
  215. #define SCL_GAME_STATE_PLAYING 0x00
  216. #define SCL_GAME_STATE_WHITE_WIN 0x01
  217. #define SCL_GAME_STATE_BLACK_WIN 0x02
  218. #define SCL_GAME_STATE_DRAW 0x10 ///< further unspecified draw
  219. #define SCL_GAME_STATE_DRAW_STALEMATE 0x11 ///< draw by stalemate
  220. #define SCL_GAME_STATE_DRAW_REPETITION 0x12 ///< draw by repetition
  221. #define SCL_GAME_STATE_DRAW_50 0x13 ///< draw by 50 move rule
  222. #define SCL_GAME_STATE_DRAW_DEAD 0x14 ///< draw by dead position
  223. #define SCL_GAME_STATE_END 0xff ///< end without known result
  224. /**
  225. Converts square in common notation (e.g. 'c' 8) to square number. Only accepts
  226. lowercase column.
  227. */
  228. #define SCL_SQUARE(colChar, rowInt) (((rowInt)-1) * 8 + ((colChar) - 'a'))
  229. #define SCL_S(c, r) SCL_SQUARE(c, r)
  230. void SCL_boardInit(SCL_Board board);
  231. void SCL_boardCopy(const SCL_Board boardFrom, SCL_Board boardTo);
  232. /**
  233. Initializes given chess 960 (Fisher random) position. If SCL_960_CASTLING
  234. is not set, castling will be disabled by this function.
  235. */
  236. void SCL_boardInit960(SCL_Board board, uint16_t positionNumber);
  237. void SCL_boardDisableCastling(SCL_Board board);
  238. uint32_t SCL_boardHash32(const SCL_Board board);
  239. #define SCL_PHASE_OPENING 0
  240. #define SCL_PHASE_MIDGAME 1
  241. #define SCL_PHASE_ENDGAME 2
  242. /**
  243. Estimates the game phase: opening, midgame or endgame.
  244. */
  245. uint8_t SCL_boardEstimatePhase(SCL_Board board);
  246. /**
  247. Sets the board position. The input string should be 64 characters long zero
  248. terminated C string representing the board as squares A1, A2, ..., H8 with
  249. each char being either a piece (RKBKQPrkbkqp) or an empty square ('.').
  250. */
  251. void SCL_boardSetPosition(
  252. SCL_Board board,
  253. const char* pieces,
  254. uint8_t castlingEnPassant,
  255. uint8_t moveCount,
  256. uint8_t ply);
  257. uint8_t SCL_boardsDiffer(SCL_Board b1, SCL_Board b2);
  258. /**
  259. Gets a random move on given board for the player whose move it is.
  260. */
  261. void SCL_boardRandomMove(
  262. SCL_Board board,
  263. SCL_RandomFunction randFunc,
  264. uint8_t* squareFrom,
  265. uint8_t* squareTo,
  266. char* resultProm);
  267. #define SCL_FEN_MAX_LENGTH 90
  268. /**
  269. Converts a position to FEN (Forsyth–Edwards Notation) string. The string has
  270. to have at least SCL_FEN_MAX_LENGTH bytes allocated to guarantee the
  271. function won't write to unallocated memory. The string will be terminated by
  272. 0 (this is included in SCL_FEN_MAX_LENGTH). The number of bytes written
  273. (including the terminating 0) is returned.
  274. */
  275. uint8_t SCL_boardToFEN(SCL_Board board, char* string);
  276. /**
  277. Loads a board from FEN (Forsyth–Edwards Notation) string. Returns 1 on
  278. success, 0 otherwise. XFEN isn't supported fully but a start position in
  279. chess960 can be loaded with this function.
  280. */
  281. uint8_t SCL_boardFromFEN(SCL_Board board, const char* string);
  282. /**
  283. Returns an approximate/heuristic board rating as a number, 0 meaning equal
  284. chances for both players, positive favoring white, negative favoring black.
  285. */
  286. typedef int16_t (*SCL_StaticEvaluationFunction)(SCL_Board);
  287. /*
  288. NOTE: int8_t as a return value was tried for evaluation function, which would
  289. be simpler, but it fails to capture important non-material position
  290. differences counted in fractions of pawn values, hence we have to use int16_t.
  291. */
  292. /**
  293. Basic static evaluation function. WARNING: this function supposes a standard
  294. chess game, for non-standard positions it may either not work well or even
  295. crash the program. You should use a different function for non-standard games.
  296. */
  297. int16_t SCL_boardEvaluateStatic(SCL_Board board);
  298. /**
  299. Dynamic evaluation function (search), i.e. unlike SCL_boardEvaluateStatic,
  300. this one performs a recursive search for deeper positions to get a more
  301. accurate score. Of course, this is much slower and hugely dependent on
  302. baseDepth (you mostly want to keep this under 5).
  303. */
  304. int16_t SCL_boardEvaluateDynamic(
  305. SCL_Board board,
  306. uint8_t baseDepth,
  307. uint8_t extensionExtraDepth,
  308. SCL_StaticEvaluationFunction evalFunction);
  309. #define SCL_EVALUATION_MAX_SCORE 32600 // don't increase this, we need a margin
  310. /**
  311. Checks if the board position is dead, i.e. mate is impossible (e.g. due to
  312. insufficient material), which by the rules results in a draw. WARNING: This
  313. function may fail to detect some dead positions as this is a non-trivial task.
  314. */
  315. uint8_t SCL_boardDead(SCL_Board board);
  316. /**
  317. Tests whether given player is in check.
  318. */
  319. uint8_t SCL_boardCheck(SCL_Board board, uint8_t white);
  320. /**
  321. Checks whether given move resets the move counter (used in the 50 move rule).
  322. */
  323. uint8_t SCL_boardMoveResetsCount(SCL_Board board, uint8_t squareFrom, uint8_t squareTo);
  324. uint8_t SCL_boardMate(SCL_Board board);
  325. /**
  326. Performs a move on a board WITHOUT checking if the move is legal. Returns an
  327. info with which the move can be undone.
  328. */
  329. SCL_MoveUndo
  330. SCL_boardMakeMove(SCL_Board board, uint8_t squareFrom, uint8_t squareTo, char promotePiece);
  331. void SCL_boardUndoMove(SCL_Board board, SCL_MoveUndo moveUndo);
  332. /**
  333. Checks if the game is over, i.e. the current player to move has no legal
  334. moves, the game is in dead position etc.
  335. */
  336. uint8_t SCL_boardGameOver(SCL_Board board);
  337. /**
  338. Checks if given move is legal.
  339. */
  340. uint8_t SCL_boardMoveIsLegal(SCL_Board board, uint8_t squareFrom, uint8_t squareTo);
  341. /**
  342. Checks if the player to move has at least one legal move.
  343. */
  344. uint8_t SCL_boardMovePossible(SCL_Board board);
  345. #define SCL_POSITION_NORMAL 0x00
  346. #define SCL_POSITION_CHECK 0x01
  347. #define SCL_POSITION_MATE 0x02
  348. #define SCL_POSITION_STALEMATE 0x03
  349. #define SCL_POSITION_DEAD 0x04
  350. uint8_t SCL_boardGetPosition(SCL_Board board);
  351. /**
  352. Returns 1 if the square is attacked by player of given color. This is used to
  353. examine checks, so for performance reasons the functions only checks whether
  354. or not the square is attacked (not the number of attackers).
  355. */
  356. uint8_t SCL_boardSquareAttacked(SCL_Board board, uint8_t square, uint8_t byWhite);
  357. /**
  358. Gets pseudo moves of a piece: all possible moves WITHOUT eliminating moves
  359. that lead to own check. To get only legal moves use SCL_boardGetMoves.
  360. */
  361. void SCL_boardGetPseudoMoves(
  362. SCL_Board board,
  363. uint8_t pieceSquare,
  364. uint8_t checkCastling,
  365. SCL_SquareSet result);
  366. /**
  367. Gets all legal moves of given piece.
  368. */
  369. void SCL_boardGetMoves(SCL_Board board, uint8_t pieceSquare, SCL_SquareSet result);
  370. static inline uint8_t SCL_boardWhitesTurn(SCL_Board board);
  371. static inline uint8_t SCL_pieceIsWhite(char piece);
  372. static inline uint8_t SCL_squareIsWhite(uint8_t square);
  373. char SCL_pieceToColor(uint8_t piece, uint8_t toWhite);
  374. /**
  375. Converts square coordinates to square number. Each coordinate must be a number
  376. <1,8>. Validity of the coordinates is NOT checked.
  377. */
  378. static inline uint8_t SCL_coordsToSquare(uint8_t row, uint8_t column);
  379. #ifndef SCL_VALUE_PAWN
  380. #define SCL_VALUE_PAWN 256
  381. #endif
  382. #ifndef SCL_VALUE_KNIGHT
  383. #define SCL_VALUE_KNIGHT 768
  384. #endif
  385. #ifndef SCL_VALUE_BISHOP
  386. #define SCL_VALUE_BISHOP 800
  387. #endif
  388. #ifndef SCL_VALUE_ROOK
  389. #define SCL_VALUE_ROOK 1280
  390. #endif
  391. #ifndef SCL_VALUE_QUEEN
  392. #define SCL_VALUE_QUEEN 2304
  393. #endif
  394. #ifndef SCL_VALUE_KING
  395. #define SCL_VALUE_KING 0
  396. #endif
  397. #define SCL_ENDGAME_MATERIAL_LIMIT \
  398. (2 * \
  399. (SCL_VALUE_PAWN * 4 + SCL_VALUE_QUEEN + SCL_VALUE_KING + SCL_VALUE_ROOK + SCL_VALUE_KNIGHT))
  400. #define SCL_START_MATERIAL \
  401. (16 * SCL_VALUE_PAWN + 4 * SCL_VALUE_ROOK + 4 * SCL_VALUE_KNIGHT + 4 * SCL_VALUE_BISHOP + \
  402. 2 * SCL_VALUE_QUEEN + 2 * SCL_VALUE_KING)
  403. #ifndef SCL_RECORD_MAX_LENGTH
  404. #define SCL_RECORD_MAX_LENGTH 256
  405. #endif
  406. #define SCL_RECORD_MAX_SIZE (SCL_RECORD_MAX_LENGTH * 2)
  407. /**
  408. Records a single chess game. The format is following:
  409. Each record item consists of 2 bytes which record a single move (ply):
  410. abxxxxxx cdyyyyyy
  411. xxxxxx Start square of the move, counted as A0, A1, ...
  412. yyyyyy End square of the move in the same format as the start square.
  413. ab 00 means this move isn't the last move of the game, other possible
  414. values are 01: white wins, 10: black wins, 11: draw or end for
  415. other reasons.
  416. cd In case of pawn promotion move this encodes the promoted piece as
  417. 00: queen, 01: rook, 10: bishop, 11: knight (pawn isn't allowed by
  418. chess rules).
  419. Every record should be ended by an ending move (ab != 00), empty record should
  420. have one move where xxxxxx == yyyyyy == 0 and ab == 11.
  421. */
  422. typedef uint8_t SCL_Record[SCL_RECORD_MAX_SIZE];
  423. #define SCL_RECORD_CONT 0x00
  424. #define SCL_RECORD_W_WIN 0x40
  425. #define SCL_RECORD_B_WIN 0x80
  426. #define SCL_RECORD_END 0xc0
  427. #define SCL_RECORD_PROM_Q 0x00
  428. #define SCL_RECORD_PROM_R 0x40
  429. #define SCL_RECORD_PROM_B 0x80
  430. #define SCL_RECORD_PROM_N 0xc0
  431. #define SCL_RECORD_ITEM(s0, s1, p, e) ((e) | (s0)), ((p) | (s1))
  432. void SCL_recordInit(SCL_Record r);
  433. void SCL_recordCopy(SCL_Record recordFrom, SCL_Record recordTo);
  434. /**
  435. Represents a complete game of chess (or a variant with different staring
  436. position). This struct along with associated functions allows to easily
  437. implement a chess game that allows undoing moves, detecting draws, recording
  438. the moves etc. On platforms with extremely little RAM one can reduce
  439. SCL_RECORD_MAX_LENGTH to reduce the size of this struct (which will however
  440. possibly limit how many moves can be undone).
  441. */
  442. typedef struct {
  443. SCL_Board board;
  444. SCL_Record record; /**< Holds the game record. This record is here
  445. firstly because games are usually recorded and
  446. secondly this allows undoing moves up to the
  447. beginning of the game. This infinite undoing will
  448. only work as long as the record is able to hold
  449. the whole game; if the record is full, undoing is
  450. no longet possible. */
  451. uint16_t state;
  452. uint16_t ply; ///< ply count (board ply counter is only 8 bit)
  453. uint32_t prevMoves[14]; ///< stores last moves, for repetition detection
  454. const char* startState; /**< Optional pointer to the starting board state.
  455. If this is null, standard chess start position is
  456. assumed. This is needed for undoing moves with
  457. game record. */
  458. } SCL_Game;
  459. /**
  460. Initializes a new chess game. The startState parameter is optional and allows
  461. for setting up chess variants that differ by starting positions, setting this
  462. to 0 will assume traditional starting position. WARNING: if startState is
  463. provided, the pointed to board mustn't be deallocated afterwards, the string
  464. is not internally copied (for memory saving reasons).
  465. */
  466. void SCL_gameInit(SCL_Game* game, const SCL_Board startState);
  467. void SCL_gameMakeMove(SCL_Game* game, uint8_t squareFrom, uint8_t squareTo, char promoteTo);
  468. uint8_t SCL_gameUndoMove(SCL_Game* game);
  469. /**
  470. Gets a move which if played now would cause a draw by repetition. Returns 1
  471. if such move exists, 0 otherwise. The results parameters can be set to 0 in
  472. which case they will be ignored and only the existence of a draw move will be
  473. tested.
  474. */
  475. uint8_t SCL_gameGetRepetiotionMove(SCL_Game* game, uint8_t* squareFrom, uint8_t* squareTo);
  476. /**
  477. Leads a game record from PGN string. The function will probably not strictly
  478. adhere to the PGN input format, but should accept most sanely written PGN
  479. strings.
  480. */
  481. void SCL_recordFromPGN(SCL_Record r, const char* pgn);
  482. uint16_t SCL_recordLength(const SCL_Record r);
  483. /**
  484. Gets the move out of a game record, returns the end state of the move
  485. (SCL_RECORD_CONT, SCL_RECORD_END etc.)
  486. */
  487. uint8_t SCL_recordGetMove(
  488. const SCL_Record r,
  489. uint16_t index,
  490. uint8_t* squareFrom,
  491. uint8_t* squareTo,
  492. char* promotedPiece);
  493. /**
  494. Adds another move to the game record. Terminating the record is handled so
  495. that the last move is always marked with end flag, endState is here to only
  496. indicate possible game result (otherwise pass SCL_RECORD_CONT). Returns 1 if
  497. the item was added, otherwise 0 (replay was already of maximum size).
  498. */
  499. uint8_t SCL_recordAdd(
  500. SCL_Record r,
  501. uint8_t squareFrom,
  502. uint8_t squareTo,
  503. char promotePiece,
  504. uint8_t endState);
  505. /**
  506. Removes the last move from the record, returns 1 if the replay is non-empty
  507. after the removal, otherwise 0.
  508. */
  509. uint8_t SCL_recordRemoveLast(SCL_Record r);
  510. /**
  511. Applies given number of half-moves (ply) to a given board (the board is
  512. automatically initialized at the beginning).
  513. */
  514. void SCL_recordApply(const SCL_Record r, SCL_Board b, uint16_t moves);
  515. int16_t SCL_pieceValue(char piece);
  516. int16_t SCL_pieceValuePositive(char piece);
  517. #define SCL_PRINT_FORMAT_NONE 0
  518. #define SCL_PRINT_FORMAT_NORMAL 1
  519. #define SCL_PRINT_FORMAT_COMPACT 2
  520. #define SCL_PRINT_FORMAT_UTF8 3
  521. #define SCL_PRINT_FORMAT_COMPACT_UTF8 4
  522. /**
  523. Gets the best move for the currently moving player as computed by AI. The
  524. return value is the value of the move (with the same semantics as the value
  525. of an evaluation function). baseDepth is depth in plys to which all moves will
  526. be checked. If baseDepth 0 is passed, the function makes a random move and
  527. returns the evaluation of the board. extensionExtraDepth is extra depth for
  528. checking specific situations like exchanges and checks. endgameExtraDepth is
  529. extra depth which is added to baseDepth in the endgame. If the randomness
  530. function is 0, AI will always make the first best move it finds, if it is
  531. not 0 and randomness is 0, AI will randomly pick between the equally best
  532. moves, if it is not 0 and randomness is positive, AI will randomly choose
  533. between best moves with some bias (may not pick the best rated move).
  534. */
  535. int16_t SCL_getAIMove(
  536. SCL_Board board,
  537. uint8_t baseDepth,
  538. uint8_t extensionExtraDepth,
  539. uint8_t endgameExtraDepth,
  540. SCL_StaticEvaluationFunction evalFunc,
  541. SCL_RandomFunction randFunc,
  542. uint8_t randomness,
  543. uint8_t repetitionMoveFrom,
  544. uint8_t repetitionMoveTo,
  545. uint8_t* resultFrom,
  546. uint8_t* resultTo,
  547. char* resultProm);
  548. /**
  549. Function that prints out a single character. This is passed to printing
  550. functions.
  551. */
  552. typedef void (*SCL_PutCharFunction)(char);
  553. /**
  554. Prints given chessboard using given format and an abstract printing function.
  555. */
  556. void SCL_printBoard(
  557. SCL_Board board,
  558. SCL_PutCharFunction putCharFunc,
  559. SCL_SquareSet highlightSquares,
  560. uint8_t selectSquare,
  561. uint8_t format,
  562. uint8_t offset,
  563. uint8_t labels,
  564. uint8_t blackDown);
  565. void SCL_printBoardSimple(
  566. SCL_Board board,
  567. SCL_PutCharFunction putCharFunc,
  568. uint8_t selectSquare,
  569. uint8_t format);
  570. void SCL_printSquareUTF8(uint8_t square, SCL_PutCharFunction putCharFunc);
  571. void SCL_printPGN(SCL_Record r, SCL_PutCharFunction putCharFunc, SCL_Board initialState);
  572. /**
  573. Reads a move from string (the notation format is described at the top of this
  574. file). The function is safe as long as the string is 0 terminated. Returns 1
  575. on success or 0 on fail (invalid move string).
  576. */
  577. uint8_t SCL_stringToMove(
  578. const char* moveString,
  579. uint8_t* resultFrom,
  580. uint8_t* resultTo,
  581. char* resultPromotion);
  582. char* SCL_moveToString(SCL_Board board, uint8_t s0, uint8_t s1, char promotion, char* string);
  583. /**
  584. Function used in drawing, it is called to draw the next pixel. The first
  585. parameter is the pixel color, the second one if the sequential number of the
  586. pixel.
  587. */
  588. typedef void (*SCL_PutPixelFunction)(uint8_t, uint16_t);
  589. #define SCL_BOARD_PICTURE_WIDTH 64
  590. /**
  591. Draws a simple 1bit 64x64 pixels board using a provided abstract function for
  592. drawing pixels. The function renders from top left to bottom right, i.e. no
  593. frame buffer is required.
  594. */
  595. void SCL_drawBoard(
  596. SCL_Board board,
  597. SCL_PutPixelFunction putPixel,
  598. uint8_t selectedSquare,
  599. SCL_SquareSet highlightSquares,
  600. uint8_t blackDown);
  601. /**
  602. Converts square number to string representation (e.g. "d2"). This function
  603. will modify exactly the first two bytes of the provided string.
  604. */
  605. static inline char* SCL_squareToString(uint8_t square, char* string);
  606. /**
  607. Converts a string, such as "A1" or "b4", to square number. The string must
  608. start with a letter (lower or upper case) and be followed by a number <1,8>.
  609. Validity of the string is NOT checked.
  610. */
  611. uint8_t SCL_stringToSquare(const char* square);
  612. //=============================================================================
  613. // privates:
  614. #define SCL_UNUSED(v) (void)(v)
  615. uint8_t SCL_currentRandom8 = 0;
  616. uint16_t SCL_currentRandom16 = 0;
  617. void SCL_randomSimpleSeed(uint8_t seed) {
  618. SCL_currentRandom8 = seed;
  619. }
  620. uint8_t SCL_randomSimple(void) {
  621. SCL_currentRandom8 *= 13;
  622. SCL_currentRandom8 += 7;
  623. return SCL_currentRandom8;
  624. }
  625. uint8_t SCL_randomBetter(void) {
  626. SCL_currentRandom16 *= 13;
  627. SCL_currentRandom16 += 7;
  628. return (SCL_currentRandom16 % 256) ^ (SCL_currentRandom16 / 256);
  629. }
  630. void SCL_randomBetterSeed(uint16_t seed) {
  631. SCL_currentRandom16 = seed;
  632. }
  633. void SCL_squareSetClear(SCL_SquareSet squareSet) {
  634. for(uint8_t i = 0; i < 8; ++i) squareSet[i] = 0;
  635. }
  636. uint8_t SCL_stringToSquare(const char* square) {
  637. return (square[1] - '1') * 8 +
  638. (square[0] - ((square[0] >= 'A' && square[0] <= 'Z') ? 'A' : 'a'));
  639. }
  640. char* SCL_moveToString(SCL_Board board, uint8_t s0, uint8_t s1, char promotion, char* string) {
  641. char* result = string;
  642. SCL_squareToString(s0, string);
  643. string += 2;
  644. string = SCL_squareToString(s1, string);
  645. string += 2;
  646. char c = board[s0];
  647. if(c == 'p' || c == 'P') {
  648. uint8_t rank = s1 / 8;
  649. if(rank == 0 || rank == 7) {
  650. *string = promotion;
  651. string++;
  652. }
  653. }
  654. *string = 0;
  655. return result;
  656. }
  657. uint8_t SCL_boardWhitesTurn(SCL_Board board) {
  658. return (board[SCL_BOARD_PLY_BYTE] % 2) == 0;
  659. }
  660. uint8_t SCL_coordsToSquare(uint8_t row, uint8_t column) {
  661. return row * 8 + column;
  662. }
  663. uint8_t SCL_pieceIsWhite(char piece) {
  664. return piece < 'a';
  665. }
  666. char* SCL_squareToString(uint8_t square, char* string) {
  667. string[0] = 'a' + square % 8;
  668. string[1] = '1' + square / 8;
  669. return string;
  670. }
  671. uint8_t SCL_squareIsWhite(uint8_t square) {
  672. return (square % 2) != ((square / 8) % 2);
  673. }
  674. char SCL_pieceToColor(uint8_t piece, uint8_t toWhite) {
  675. return (SCL_pieceIsWhite(piece) == toWhite) ? piece : (piece + (toWhite ? -32 : 32));
  676. }
  677. /**
  678. Records the rook starting positions in the board state. This is required in
  679. chess 960 in order to be able to correctly perform castling (castling rights
  680. knowledge isn't enough as one rook might have moved to the other side and we
  681. wouldn't know which one can castle and which not).
  682. */
  683. void _SCL_board960RememberRookPositions(SCL_Board board) {
  684. uint8_t pos = 0;
  685. uint8_t rooks = 2;
  686. while(pos < 8 && rooks != 0) {
  687. if(board[pos] == 'R') {
  688. board[SCL_BOARD_EXTRA_BYTE] = rooks == 2 ? pos :
  689. (board[SCL_BOARD_EXTRA_BYTE] | (pos << 3));
  690. rooks--;
  691. }
  692. pos++;
  693. }
  694. }
  695. void SCL_boardInit(SCL_Board board) {
  696. /*
  697. We might use SCL_BOARD_START_STATE and copy it to the board, but that might
  698. waste RAM on Arduino, so we init the board by code.
  699. */
  700. char* b = board;
  701. *b = 'R';
  702. b++;
  703. *b = 'N';
  704. b++;
  705. *b = 'B';
  706. b++;
  707. *b = 'Q';
  708. b++;
  709. *b = 'K';
  710. b++;
  711. *b = 'B';
  712. b++;
  713. *b = 'N';
  714. b++;
  715. *b = 'R';
  716. b++;
  717. char* b2 = board + 48;
  718. for(uint8_t i = 0; i < 8; ++i, b++, b2++) {
  719. *b = 'P';
  720. *b2 = 'p';
  721. }
  722. for(uint8_t i = 0; i < 32; ++i, b++) *b = '.';
  723. b += 8;
  724. *b = 'r';
  725. b++;
  726. *b = 'n';
  727. b++;
  728. *b = 'b';
  729. b++;
  730. *b = 'q';
  731. b++;
  732. *b = 'k';
  733. b++;
  734. *b = 'b';
  735. b++;
  736. *b = 'n';
  737. b++;
  738. *b = 'r';
  739. b++;
  740. for(uint8_t i = 0; i < SCL_BOARD_STATE_SIZE - SCL_BOARD_SQUARES; ++i, ++b) *b = 0;
  741. board[SCL_BOARD_ENPASSANT_CASTLE_BYTE] = (char)0xff;
  742. #if SCL_960_CASTLING
  743. _SCL_board960RememberRookPositions(board);
  744. #endif
  745. }
  746. void _SCL_boardPlaceOnNthAvailable(SCL_Board board, uint8_t pos, char piece) {
  747. char* c = board;
  748. while(1) {
  749. if(*c == '.') {
  750. if(pos == 0) break;
  751. pos--;
  752. }
  753. c++;
  754. }
  755. *c = piece;
  756. }
  757. void SCL_boardInit960(SCL_Board board, uint16_t positionNumber) {
  758. SCL_Board b;
  759. SCL_boardInit(b);
  760. for(uint8_t i = 0; i < SCL_BOARD_STATE_SIZE; ++i)
  761. board[i] = ((i >= 8 && i < 56) || i >= 64) ? b[i] : '.';
  762. uint8_t helper = positionNumber % 16;
  763. board[(helper / 4) * 2] = 'B';
  764. board[1 + (helper % 4) * 2] = 'B';
  765. helper = positionNumber / 16;
  766. // maybe there's a simpler way :)
  767. _SCL_boardPlaceOnNthAvailable(board, helper % 6, 'Q');
  768. _SCL_boardPlaceOnNthAvailable(board, 0, helper <= 23 ? 'N' : 'R');
  769. _SCL_boardPlaceOnNthAvailable(
  770. board, 0, (helper >= 7 && helper <= 23) ? 'R' : (helper > 41 ? 'K' : 'N'));
  771. _SCL_boardPlaceOnNthAvailable(
  772. board,
  773. 0,
  774. (helper <= 5 || helper >= 54) ?
  775. 'R' :
  776. (((helper >= 12 && helper <= 23) || (helper >= 30 && helper <= 41)) ? 'K' : 'N'));
  777. _SCL_boardPlaceOnNthAvailable(
  778. board,
  779. 0,
  780. (helper <= 11 || (helper <= 29 && helper >= 24)) ?
  781. 'K' :
  782. (((helper >= 18 && helper <= 23) || (helper >= 36 && helper <= 41) ||
  783. (helper >= 48 && helper <= 53)) ?
  784. 'R' :
  785. 'N'));
  786. uint8_t rooks = 0;
  787. for(uint8_t i = 0; i < 8; ++i)
  788. if(board[i] == 'R') rooks++;
  789. _SCL_boardPlaceOnNthAvailable(board, 0, rooks == 2 ? 'N' : 'R');
  790. for(uint8_t i = 0; i < 8; ++i) board[56 + i] = SCL_pieceToColor(board[i], 0);
  791. #if SCL_960_CASTLING
  792. _SCL_board960RememberRookPositions(board);
  793. #else
  794. SCL_boardDisableCastling(board);
  795. #endif
  796. }
  797. uint8_t SCL_boardsDiffer(SCL_Board b1, SCL_Board b2) {
  798. const char *p1 = b1, *p2 = b2;
  799. while(p1 < b1 + SCL_BOARD_STATE_SIZE) {
  800. if(*p1 != *p2) return 1;
  801. p1++;
  802. p2++;
  803. }
  804. return 0;
  805. }
  806. void SCL_recordInit(SCL_Record r) {
  807. r[0] = 0 | SCL_RECORD_END;
  808. r[1] = 0;
  809. }
  810. void SCL_recordFromPGN(SCL_Record r, const char* pgn) {
  811. SCL_Board board;
  812. SCL_boardInit(board);
  813. SCL_recordInit(r);
  814. uint8_t state = 0;
  815. uint8_t evenMove = 0;
  816. while(*pgn != 0) {
  817. switch(state) {
  818. case 0: // skipping tags and spaces, outside []
  819. if(*pgn == '1')
  820. state = 2;
  821. else if(*pgn == '[')
  822. state = 1;
  823. break;
  824. case 1: // skipping tags and spaces, inside []
  825. if(*pgn == ']') state = 0;
  826. break;
  827. case 2: // reading move number
  828. if(*pgn == '{')
  829. state = 3;
  830. else if((*pgn >= 'a' && *pgn <= 'h') || (*pgn >= 'A' && *pgn <= 'Z')) {
  831. state = 4;
  832. pgn--;
  833. }
  834. break;
  835. case 3: // initial comment
  836. if(*pgn == '}') state = 2;
  837. break;
  838. case 4: // reading move
  839. {
  840. char piece = 'p';
  841. char promoteTo = 'q';
  842. uint8_t castle = 0;
  843. uint8_t promotion = 0;
  844. int8_t coords[4];
  845. uint8_t ranks = 0, files = 0;
  846. for(uint8_t i = 0; i < 4; ++i) coords[i] = -1;
  847. while(*pgn != ' ' && *pgn != '\n' && *pgn != '\t' && *pgn != '{' && *pgn != 0) {
  848. if(*pgn == '=') promotion = 1;
  849. if(*pgn == 'O' || *pgn == '0') castle++;
  850. if(*pgn >= 'A' && *pgn <= 'Z') {
  851. if(promotion)
  852. promoteTo = *pgn;
  853. else
  854. piece = *pgn;
  855. } else if(*pgn >= 'a' && *pgn <= 'h') {
  856. coords[files * 2] = *pgn - 'a';
  857. files++;
  858. } else if(*pgn >= '1' && *pgn <= '8') {
  859. coords[1 + ranks * 2] = *pgn - '1';
  860. ranks++;
  861. }
  862. pgn++;
  863. }
  864. if(castle) {
  865. piece = 'K';
  866. coords[0] = 4;
  867. coords[1] = 0;
  868. coords[2] = castle < 3 ? 6 : 2;
  869. coords[3] = 0;
  870. if(evenMove) {
  871. coords[1] = 7;
  872. coords[3] = 7;
  873. }
  874. }
  875. piece = SCL_pieceToColor(piece, evenMove == 0);
  876. if(coords[2] < 0) {
  877. coords[2] = coords[0];
  878. coords[0] = -1;
  879. }
  880. if(coords[3] < 0) {
  881. coords[3] = coords[1];
  882. coords[1] = -1;
  883. }
  884. uint8_t squareTo = coords[3] * 8 + coords[2];
  885. if(coords[0] < 0 || coords[1] < 0) {
  886. // without complete starting coords we have to find the piece
  887. for(int i = 0; i < SCL_BOARD_SQUARES; ++i)
  888. if(board[i] == piece) {
  889. SCL_SquareSet s;
  890. SCL_squareSetClear(s);
  891. SCL_boardGetMoves(board, i, s);
  892. if(SCL_squareSetContains(s, squareTo) &&
  893. (coords[0] < 0 || coords[0] == i % 8) &&
  894. (coords[1] < 0 || coords[1] == i / 8)) {
  895. coords[0] = i % 8;
  896. coords[1] = i / 8;
  897. break;
  898. }
  899. }
  900. }
  901. uint8_t squareFrom = coords[1] * 8 + coords[0];
  902. SCL_boardMakeMove(board, squareFrom, squareTo, promoteTo);
  903. // for some reason tcc bugs here, the above line sets squareFrom to 0 lol
  904. // can be fixed with doing "squareFrom = coords[1] * 8 + coords[0];" again
  905. SCL_recordAdd(r, squareFrom, squareTo, promoteTo, SCL_RECORD_CONT);
  906. while(*pgn == ' ' || *pgn == '\n' || *pgn == '\t' || *pgn == '{') {
  907. if(*pgn == '{')
  908. while(*pgn != '}') pgn++;
  909. pgn++;
  910. }
  911. if(*pgn == 0) return;
  912. pgn--;
  913. if(evenMove) state = 2;
  914. evenMove = !evenMove;
  915. break;
  916. }
  917. default:
  918. break;
  919. }
  920. pgn++;
  921. }
  922. }
  923. uint16_t SCL_recordLength(const SCL_Record r) {
  924. if((r[0] & 0x3f) == (r[1] & 0x3f)) // empty record that's only terminator
  925. return 0;
  926. uint16_t result = 0;
  927. while((r[result] & 0xc0) == 0) result += 2;
  928. return (result / 2) + 1;
  929. }
  930. uint8_t SCL_recordGetMove(
  931. const SCL_Record r,
  932. uint16_t index,
  933. uint8_t* squareFrom,
  934. uint8_t* squareTo,
  935. char* promotedPiece) {
  936. index *= 2;
  937. uint8_t b = r[index];
  938. *squareFrom = b & 0x3f;
  939. uint8_t result = b & 0xc0;
  940. index++;
  941. b = r[index];
  942. *squareTo = b & 0x3f;
  943. b &= 0xc0;
  944. switch(b) {
  945. case SCL_RECORD_PROM_Q:
  946. *promotedPiece = 'q';
  947. break;
  948. case SCL_RECORD_PROM_R:
  949. *promotedPiece = 'r';
  950. break;
  951. case SCL_RECORD_PROM_B:
  952. *promotedPiece = 'b';
  953. break;
  954. case SCL_RECORD_PROM_N:
  955. default:
  956. *promotedPiece = 'n';
  957. break;
  958. }
  959. return result;
  960. }
  961. uint8_t SCL_recordAdd(
  962. SCL_Record r,
  963. uint8_t squareFrom,
  964. uint8_t squareTo,
  965. char promotePiece,
  966. uint8_t endState) {
  967. uint16_t l = SCL_recordLength(r);
  968. if(l >= SCL_RECORD_MAX_LENGTH) return 0;
  969. l *= 2;
  970. if(l != 0) r[l - 2] &= 0x3f; // remove the end flag from previous item
  971. if(endState == SCL_RECORD_CONT) endState = SCL_RECORD_END;
  972. r[l] = squareFrom | endState;
  973. uint8_t p;
  974. switch(promotePiece) {
  975. case 'n':
  976. case 'N':
  977. p = SCL_RECORD_PROM_N;
  978. break;
  979. case 'b':
  980. case 'B':
  981. p = SCL_RECORD_PROM_B;
  982. break;
  983. case 'r':
  984. case 'R':
  985. p = SCL_RECORD_PROM_R;
  986. break;
  987. case 'q':
  988. case 'Q':
  989. default:
  990. p = SCL_RECORD_PROM_Q;
  991. break;
  992. }
  993. l++;
  994. r[l] = squareTo | p;
  995. return 1;
  996. }
  997. uint8_t SCL_recordRemoveLast(SCL_Record r) {
  998. uint16_t l = SCL_recordLength(r);
  999. if(l == 0) return 0;
  1000. if(l == 1)
  1001. SCL_recordInit(r);
  1002. else {
  1003. l = (l - 2) * 2;
  1004. r[l] = (r[l] & 0x3f) | SCL_RECORD_END;
  1005. }
  1006. return 1;
  1007. }
  1008. void SCL_recordApply(const SCL_Record r, SCL_Board b, uint16_t moves) {
  1009. SCL_boardInit(b);
  1010. uint16_t l = SCL_recordLength(r);
  1011. if(moves > l) moves = l;
  1012. for(uint16_t i = 0; i < moves; ++i) {
  1013. uint8_t s0, s1;
  1014. char p;
  1015. SCL_recordGetMove(r, i, &s0, &s1, &p);
  1016. SCL_boardMakeMove(b, s0, s1, p);
  1017. }
  1018. }
  1019. void SCL_boardUndoMove(SCL_Board board, SCL_MoveUndo moveUndo) {
  1020. #if SCL_960_CASTLING
  1021. char squareToNow = board[moveUndo.squareTo];
  1022. #endif
  1023. board[moveUndo.squareFrom] = board[moveUndo.squareTo];
  1024. board[moveUndo.squareTo] = moveUndo.other & 0x7f;
  1025. board[SCL_BOARD_PLY_BYTE]--;
  1026. board[SCL_BOARD_ENPASSANT_CASTLE_BYTE] = moveUndo.enPassantCastle;
  1027. board[SCL_BOARD_MOVE_COUNT_BYTE] = moveUndo.moveCount;
  1028. if(moveUndo.other & 0x80) {
  1029. moveUndo.squareTo /= 8;
  1030. if(moveUndo.squareTo == 0 || moveUndo.squareTo == 7)
  1031. board[moveUndo.squareFrom] = SCL_pieceIsWhite(board[moveUndo.squareFrom]) ? 'P' : 'p';
  1032. // ^ was promotion
  1033. else
  1034. board[(moveUndo.squareFrom / 8) * 8 + (moveUndo.enPassantCastle & 0x0f)] =
  1035. (board[moveUndo.squareFrom] == 'P') ? 'p' : 'P'; // was en passant
  1036. }
  1037. #if !SCL_960_CASTLING
  1038. else if(
  1039. board[moveUndo.squareFrom] == 'k' && // black castling
  1040. moveUndo.squareFrom == 60) {
  1041. if(moveUndo.squareTo == 58) {
  1042. board[59] = '.';
  1043. board[56] = 'r';
  1044. } else if(moveUndo.squareTo == 62) {
  1045. board[61] = '.';
  1046. board[63] = 'r';
  1047. }
  1048. } else if(
  1049. board[moveUndo.squareFrom] == 'K' && // white castling
  1050. moveUndo.squareFrom == 4) {
  1051. if(moveUndo.squareTo == 2) {
  1052. board[3] = '.';
  1053. board[0] = 'R';
  1054. } else if(moveUndo.squareTo == 6) {
  1055. board[5] = '.';
  1056. board[7] = 'R';
  1057. }
  1058. }
  1059. #else // 960 castling
  1060. else if(
  1061. ((moveUndo.other & 0x7f) == 'r') && // black castling
  1062. (squareToNow == '.' || !SCL_pieceIsWhite(squareToNow))) {
  1063. board[moveUndo.squareTo < moveUndo.squareFrom ? 59 : 61] = '.';
  1064. board[moveUndo.squareTo < moveUndo.squareFrom ? 58 : 62] = '.';
  1065. board[moveUndo.squareFrom] = 'k';
  1066. board[moveUndo.squareTo] = 'r';
  1067. } else if(
  1068. ((moveUndo.other & 0x7f) == 'R') && // white castling
  1069. (squareToNow == '.' || SCL_pieceIsWhite(squareToNow))) {
  1070. board[moveUndo.squareTo < moveUndo.squareFrom ? 3 : 5] = '.';
  1071. board[moveUndo.squareTo < moveUndo.squareFrom ? 2 : 6] = '.';
  1072. board[moveUndo.squareFrom] = 'K';
  1073. board[moveUndo.squareTo] = 'R';
  1074. }
  1075. #endif
  1076. }
  1077. /**
  1078. Potentially disables castling rights according to whether something moved from
  1079. or to a square with a rook.
  1080. */
  1081. void _SCL_handleRookActivity(SCL_Board board, uint8_t rookSquare) {
  1082. #if !SCL_960_CASTLING
  1083. switch(rookSquare) {
  1084. case 0:
  1085. board[SCL_BOARD_ENPASSANT_CASTLE_BYTE] &= (uint8_t)~0x20;
  1086. break;
  1087. case 7:
  1088. board[SCL_BOARD_ENPASSANT_CASTLE_BYTE] &= (uint8_t)~0x10;
  1089. break;
  1090. case 56:
  1091. board[SCL_BOARD_ENPASSANT_CASTLE_BYTE] &= (uint8_t)~0x80;
  1092. break;
  1093. case 63:
  1094. board[SCL_BOARD_ENPASSANT_CASTLE_BYTE] &= (uint8_t)~0x40;
  1095. break;
  1096. default:
  1097. break;
  1098. }
  1099. #else // 960 castling
  1100. if(rookSquare == (board[SCL_BOARD_EXTRA_BYTE] & 0x07))
  1101. board[SCL_BOARD_ENPASSANT_CASTLE_BYTE] &= (uint8_t)~0x20;
  1102. else if(rookSquare == (board[SCL_BOARD_EXTRA_BYTE] >> 3))
  1103. board[SCL_BOARD_ENPASSANT_CASTLE_BYTE] &= (uint8_t)~0x10;
  1104. else if(rookSquare == 56 + (board[SCL_BOARD_EXTRA_BYTE] & 0x07))
  1105. board[SCL_BOARD_ENPASSANT_CASTLE_BYTE] &= (uint8_t)~0x80;
  1106. else if(rookSquare == 56 + (board[SCL_BOARD_EXTRA_BYTE] >> 3))
  1107. board[SCL_BOARD_ENPASSANT_CASTLE_BYTE] &= (uint8_t)~0x40;
  1108. #endif
  1109. }
  1110. SCL_MoveUndo
  1111. SCL_boardMakeMove(SCL_Board board, uint8_t squareFrom, uint8_t squareTo, char promotePiece) {
  1112. char s = board[squareFrom];
  1113. SCL_MoveUndo moveUndo;
  1114. moveUndo.squareFrom = squareFrom;
  1115. moveUndo.squareTo = squareTo;
  1116. moveUndo.moveCount = board[SCL_BOARD_MOVE_COUNT_BYTE];
  1117. moveUndo.enPassantCastle = board[SCL_BOARD_ENPASSANT_CASTLE_BYTE];
  1118. moveUndo.other = board[squareTo];
  1119. // reset the en-passant state
  1120. board[SCL_BOARD_ENPASSANT_CASTLE_BYTE] |= 0x0f;
  1121. if(SCL_boardMoveResetsCount(board, squareFrom, squareTo))
  1122. board[SCL_BOARD_MOVE_COUNT_BYTE] = 0;
  1123. else
  1124. board[SCL_BOARD_MOVE_COUNT_BYTE]++;
  1125. #if SCL_960_CASTLING
  1126. uint8_t castled = 0;
  1127. #endif
  1128. if((s == 'k') || (s == 'K')) {
  1129. #if !SCL_960_CASTLING
  1130. if((squareFrom == 4) || (squareFrom == 60)) // check castling
  1131. {
  1132. int8_t difference = squareTo - squareFrom;
  1133. char rook = SCL_pieceToColor('r', SCL_pieceIsWhite(s));
  1134. if(difference == 2) // short
  1135. {
  1136. board[squareTo - 1] = rook;
  1137. board[squareTo + 1] = '.';
  1138. } else if(difference == -2) // long
  1139. {
  1140. board[squareTo - 2] = '.';
  1141. board[squareTo + 1] = rook;
  1142. }
  1143. }
  1144. #else // 960 castling
  1145. uint8_t isWhite = SCL_pieceIsWhite(s);
  1146. char rook = SCL_pieceToColor('r', isWhite);
  1147. if(board[squareTo] == rook) {
  1148. castled = 1;
  1149. board[squareFrom] = '.';
  1150. board[squareTo] = '.';
  1151. if(squareTo > squareFrom) // short
  1152. {
  1153. board[isWhite ? 6 : (56 + 6)] = s;
  1154. board[isWhite ? 5 : (56 + 5)] = rook;
  1155. } else // long
  1156. {
  1157. board[isWhite ? 2 : (56 + 2)] = s;
  1158. board[isWhite ? 3 : (56 + 3)] = rook;
  1159. }
  1160. }
  1161. #endif
  1162. // after king move disable castling
  1163. board[SCL_BOARD_ENPASSANT_CASTLE_BYTE] &= ~(0x03 << ((s == 'K') ? 4 : 6));
  1164. } else if((s == 'p') || (s == 'P')) {
  1165. uint8_t row = squareTo / 8;
  1166. int8_t rowDiff = squareFrom / 8 - row;
  1167. if(rowDiff == 2 || rowDiff == -2) // record en passant column
  1168. {
  1169. board[SCL_BOARD_ENPASSANT_CASTLE_BYTE] =
  1170. (board[SCL_BOARD_ENPASSANT_CASTLE_BYTE] & 0xf0) | (squareFrom % 8);
  1171. }
  1172. if(row == 0 || row == 7) {
  1173. // promotion
  1174. s = SCL_pieceToColor(promotePiece, SCL_pieceIsWhite(s));
  1175. moveUndo.other |= 0x80;
  1176. } else {
  1177. // check en passant move
  1178. int8_t columnDiff = (squareTo % 8) - (squareFrom % 8);
  1179. if((columnDiff != 0) && (board[squareTo] == '.')) {
  1180. board[squareFrom + columnDiff] = '.';
  1181. moveUndo.other |= 0x80;
  1182. }
  1183. }
  1184. } else if((s == 'r') || (s == 'R'))
  1185. _SCL_handleRookActivity(board, squareFrom);
  1186. char taken = board[squareTo];
  1187. // taking a rook may also disable castling:
  1188. if(taken == 'R' || taken == 'r') _SCL_handleRookActivity(board, squareTo);
  1189. #if SCL_960_CASTLING
  1190. if(!castled)
  1191. #endif
  1192. {
  1193. board[squareTo] = s;
  1194. board[squareFrom] = '.';
  1195. }
  1196. board[SCL_BOARD_PLY_BYTE]++; // increase ply count
  1197. return moveUndo;
  1198. }
  1199. void SCL_boardSetPosition(
  1200. SCL_Board board,
  1201. const char* pieces,
  1202. uint8_t castlingEnPassant,
  1203. uint8_t moveCount,
  1204. uint8_t ply) {
  1205. for(uint8_t i = 0; i < SCL_BOARD_SQUARES; ++i, pieces++)
  1206. if(*pieces != 0)
  1207. board[i] = *pieces;
  1208. else
  1209. break;
  1210. board[SCL_BOARD_ENPASSANT_CASTLE_BYTE] = castlingEnPassant;
  1211. board[SCL_BOARD_PLY_BYTE] = ply;
  1212. board[SCL_BOARD_MOVE_COUNT_BYTE] = moveCount;
  1213. board[SCL_BOARD_STATE_SIZE - 1] = 0;
  1214. }
  1215. void SCL_squareSetAdd(SCL_SquareSet squareSet, uint8_t square) {
  1216. squareSet[square / 8] |= 0x01 << (square % 8);
  1217. }
  1218. uint8_t SCL_squareSetContains(const SCL_SquareSet squareSet, uint8_t square) {
  1219. return squareSet[square / 8] & (0x01 << (square % 8));
  1220. }
  1221. uint8_t SCL_squareSetSize(const SCL_SquareSet squareSet) {
  1222. uint8_t result = 0;
  1223. for(uint8_t i = 0; i < 8; ++i) {
  1224. uint8_t byte = squareSet[i];
  1225. for(uint8_t j = 0; j < 8; ++j) {
  1226. result += byte & 0x01;
  1227. byte >>= 1;
  1228. }
  1229. }
  1230. return result;
  1231. }
  1232. uint8_t SCL_squareSetEmpty(const SCL_SquareSet squareSet) {
  1233. for(uint8_t i = 0; i < 8; ++i)
  1234. if(squareSet[i] != 0) return 0;
  1235. return 1;
  1236. }
  1237. uint8_t SCL_squareSetGetRandom(const SCL_SquareSet squareSet, SCL_RandomFunction randFunc) {
  1238. uint8_t size = SCL_squareSetSize(squareSet);
  1239. if(size == 0) return 0;
  1240. uint8_t n = (randFunc() % size) + 1;
  1241. uint8_t i = 0;
  1242. while(i < SCL_BOARD_SQUARES) {
  1243. if(SCL_squareSetContains(squareSet, i)) {
  1244. n--;
  1245. if(n == 0) break;
  1246. }
  1247. ++i;
  1248. }
  1249. return i;
  1250. }
  1251. void SCL_boardCopy(const SCL_Board boardFrom, SCL_Board boardTo) {
  1252. for(uint8_t i = 0; i < SCL_BOARD_STATE_SIZE; ++i) boardTo[i] = boardFrom[i];
  1253. }
  1254. uint8_t SCL_boardSquareAttacked(SCL_Board board, uint8_t square, uint8_t byWhite) {
  1255. const char* currentSquare = board;
  1256. /* We need to place a temporary piece on the tested square in order to test if
  1257. the square is attacked (consider testing if attacked by a pawn). */
  1258. char previous = board[square];
  1259. board[square] = SCL_pieceToColor('r', !byWhite);
  1260. for(uint8_t i = 0; i < SCL_BOARD_SQUARES; ++i, ++currentSquare) {
  1261. char s = *currentSquare;
  1262. if((s == '.') || (SCL_pieceIsWhite(s) != byWhite)) continue;
  1263. SCL_SquareSet moves;
  1264. SCL_boardGetPseudoMoves(board, i, 0, moves);
  1265. if(SCL_squareSetContains(moves, square)) {
  1266. board[square] = previous;
  1267. return 1;
  1268. }
  1269. }
  1270. board[square] = previous;
  1271. return 0;
  1272. }
  1273. uint8_t SCL_boardCheck(SCL_Board board, uint8_t white) {
  1274. const char* square = board;
  1275. char kingChar = white ? 'K' : 'k';
  1276. for(uint8_t i = 0; i < SCL_BOARD_SQUARES; ++i, ++square)
  1277. if((*square == kingChar && SCL_boardSquareAttacked(board, i, !white))) return 1;
  1278. return 0;
  1279. }
  1280. uint8_t SCL_boardGameOver(SCL_Board board) {
  1281. uint8_t position = SCL_boardGetPosition(board);
  1282. return (position == SCL_POSITION_MATE) || (position == SCL_POSITION_STALEMATE) ||
  1283. (position == SCL_POSITION_DEAD);
  1284. }
  1285. uint8_t SCL_boardMovePossible(SCL_Board board) {
  1286. uint8_t white = SCL_boardWhitesTurn(board);
  1287. for(uint8_t i = 0; i < SCL_BOARD_SQUARES; ++i) {
  1288. char s = board[i];
  1289. if((s != '.') && (SCL_pieceIsWhite(s) == white)) {
  1290. SCL_SquareSet moves;
  1291. SCL_boardGetMoves(board, i, moves);
  1292. if(SCL_squareSetSize(moves) != 0) return 1;
  1293. }
  1294. }
  1295. return 0;
  1296. }
  1297. uint8_t SCL_boardMate(SCL_Board board) {
  1298. return SCL_boardGetPosition(board) == SCL_POSITION_MATE;
  1299. }
  1300. void SCL_boardGetPseudoMoves(
  1301. SCL_Board board,
  1302. uint8_t pieceSquare,
  1303. uint8_t checkCastling,
  1304. SCL_SquareSet result) {
  1305. char piece = board[pieceSquare];
  1306. SCL_squareSetClear(result);
  1307. uint8_t isWhite = SCL_pieceIsWhite(piece);
  1308. int8_t horizontalPosition = pieceSquare % 8;
  1309. int8_t pawnOffset = -8;
  1310. switch(piece) {
  1311. case 'P':
  1312. pawnOffset = 8;
  1313. /* FALLTHROUGH */
  1314. case 'p': {
  1315. uint8_t square = pieceSquare + pawnOffset;
  1316. uint8_t verticalPosition = pieceSquare / 8;
  1317. if(board[square] == '.') // forward move
  1318. {
  1319. SCL_squareSetAdd(result, square);
  1320. if(verticalPosition == (1 + (piece == 'p') * 5)) // start position?
  1321. {
  1322. uint8_t square2 = square + pawnOffset;
  1323. if(board[square2] == '.') SCL_squareSetAdd(result, square2);
  1324. }
  1325. }
  1326. #define checkDiagonal(hor, add) \
  1327. if(horizontalPosition != hor) { \
  1328. uint8_t square2 = square + add; \
  1329. char c = board[square2]; \
  1330. if(c != '.' && SCL_pieceIsWhite(c) != isWhite) SCL_squareSetAdd(result, square2); \
  1331. }
  1332. // diagonal moves
  1333. checkDiagonal(0, -1) checkDiagonal(7, 1)
  1334. uint8_t enPassantRow = 4;
  1335. uint8_t enemyPawn = 'p';
  1336. if(piece == 'p') {
  1337. enPassantRow = 3;
  1338. enemyPawn = 'P';
  1339. }
  1340. // en-passant moves
  1341. if(verticalPosition == enPassantRow) {
  1342. uint8_t enPassantColumn = board[SCL_BOARD_ENPASSANT_CASTLE_BYTE] & 0x0f;
  1343. uint8_t column = pieceSquare % 8;
  1344. for(int8_t offset = -1; offset < 2; offset += 2)
  1345. if((enPassantColumn == column + offset) &&
  1346. (board[pieceSquare + offset] == enemyPawn)) {
  1347. SCL_squareSetAdd(result, pieceSquare + pawnOffset + offset);
  1348. break;
  1349. }
  1350. }
  1351. #undef checkDiagonal
  1352. } break;
  1353. case 'r': // rook
  1354. case 'R':
  1355. case 'b': // bishop
  1356. case 'B':
  1357. case 'q': // queen
  1358. case 'Q': {
  1359. const int8_t offsets[8] = {-8, 1, 8, -1, -7, 9, -9, 7};
  1360. const int8_t columnDirs[8] = {0, 1, 0, -1, 1, 1, -1, -1};
  1361. uint8_t from = (piece == 'b' || piece == 'B') * 4;
  1362. uint8_t to = 4 + (piece != 'r' && piece != 'R') * 4;
  1363. for(uint8_t i = from; i < to; ++i) {
  1364. int8_t offset = offsets[i];
  1365. int8_t columnDir = columnDirs[i];
  1366. int8_t square = pieceSquare;
  1367. int8_t col = horizontalPosition;
  1368. while(1) {
  1369. square += offset;
  1370. col += columnDir;
  1371. if(square < 0 || square > 63 || col < 0 || col > 7) break;
  1372. char squareC = board[square];
  1373. if(squareC == '.')
  1374. SCL_squareSetAdd(result, square);
  1375. else {
  1376. if(SCL_pieceIsWhite(squareC) != isWhite) SCL_squareSetAdd(result, square);
  1377. break;
  1378. }
  1379. }
  1380. }
  1381. } break;
  1382. case 'n': // knight
  1383. case 'N': {
  1384. const int8_t offsets[4] = {6, 10, 15, 17};
  1385. const int8_t columnsMinus[4] = {2, -2, 1, -1};
  1386. const int8_t columnsPlus[4] = {-2, 2, -1, 1};
  1387. const int8_t *off, *col;
  1388. #define checkOffsets(op, comp, limit, dir) \
  1389. off = offsets; \
  1390. col = columns##dir; \
  1391. for(uint8_t i = 0; i < 4; ++i, ++off, ++col) { \
  1392. int8_t square = pieceSquare op(*off); \
  1393. if(square comp limit) /* out of board? */ \
  1394. break; \
  1395. int8_t horizontalCheck = horizontalPosition + (*col); \
  1396. if(horizontalCheck < 0 || horizontalCheck >= 8) continue; \
  1397. char squareC = board[square]; \
  1398. if((squareC == '.') || (SCL_pieceIsWhite(squareC) != isWhite)) \
  1399. SCL_squareSetAdd(result, square); \
  1400. }
  1401. checkOffsets(-, <, 0, Minus) checkOffsets(+, >=, SCL_BOARD_SQUARES, Plus)
  1402. #undef checkOffsets
  1403. } break;
  1404. case 'k': // king
  1405. case 'K': {
  1406. uint8_t verticalPosition = pieceSquare / 8;
  1407. uint8_t u = verticalPosition != 0, d = verticalPosition != 7, l = horizontalPosition != 0,
  1408. r = horizontalPosition != 7;
  1409. uint8_t square2 = pieceSquare - 9;
  1410. #define checkSquare(cond, add) \
  1411. if(cond && ((board[square2] == '.') || (SCL_pieceIsWhite(board[square2])) != isWhite)) \
  1412. SCL_squareSetAdd(result, square2); \
  1413. square2 += add;
  1414. checkSquare(l && u, 1) checkSquare(u, 1) checkSquare(r && u, 6) checkSquare(l, 2)
  1415. checkSquare(r, 6) checkSquare(l && d, 1) checkSquare(d, 1) checkSquare(r && d, 0)
  1416. #undef checkSquare
  1417. // castling:
  1418. if(checkCastling) {
  1419. uint8_t bitShift = 4 + 2 * (!isWhite);
  1420. if((board[SCL_BOARD_ENPASSANT_CASTLE_BYTE] & (0x03 << bitShift)) &&
  1421. !SCL_boardSquareAttacked(board, pieceSquare, !isWhite)) // no check?
  1422. {
  1423. #if !SCL_960_CASTLING
  1424. // short castle:
  1425. pieceSquare++;
  1426. if((board[SCL_BOARD_ENPASSANT_CASTLE_BYTE] & (0x01 << bitShift)) &&
  1427. (board[pieceSquare] == '.') && (board[pieceSquare + 1] == '.') &&
  1428. (board[pieceSquare + 2] == SCL_pieceToColor('r', isWhite)) &&
  1429. !SCL_boardSquareAttacked(board, pieceSquare, !isWhite))
  1430. SCL_squareSetAdd(result, pieceSquare + 1);
  1431. /* note: don't check the final square for check, it will potentially
  1432. be removed later (can't end up in check) */
  1433. // long castle:
  1434. pieceSquare -= 2;
  1435. if((board[SCL_BOARD_ENPASSANT_CASTLE_BYTE] & (0x02 << bitShift)) &&
  1436. (board[pieceSquare] == '.') && (board[pieceSquare - 1] == '.') &&
  1437. (board[pieceSquare - 2] == '.') &&
  1438. (board[pieceSquare - 3] == SCL_pieceToColor('r', isWhite)) &&
  1439. !SCL_boardSquareAttacked(board, pieceSquare, !isWhite))
  1440. SCL_squareSetAdd(result, pieceSquare - 1);
  1441. #else // 960 castling
  1442. for(int i = 0; i < 2; ++i) // short and long
  1443. if(board[SCL_BOARD_ENPASSANT_CASTLE_BYTE] & ((i + 1) << bitShift)) {
  1444. uint8_t rookPos = board[SCL_BOARD_EXTRA_BYTE] >> 3, targetPos = 5;
  1445. if(i == 1) {
  1446. rookPos = board[SCL_BOARD_EXTRA_BYTE] & 0x07, targetPos = 3;
  1447. }
  1448. if(!isWhite) {
  1449. rookPos += 56;
  1450. targetPos += 56;
  1451. }
  1452. uint8_t ok = board[rookPos] == SCL_pieceToColor('r', isWhite);
  1453. if(!ok) continue;
  1454. int8_t inc = 1 - 2 * (targetPos > rookPos);
  1455. while(targetPos != rookPos) // check vacant squares for the rook
  1456. {
  1457. if(board[targetPos] != '.' && targetPos != pieceSquare) {
  1458. ok = 0;
  1459. break;
  1460. }
  1461. targetPos += inc;
  1462. }
  1463. if(!ok) continue;
  1464. targetPos = i == 0 ? 6 : 2;
  1465. if(!isWhite) targetPos += 56;
  1466. inc = 1 - 2 * (targetPos > pieceSquare);
  1467. while(targetPos != pieceSquare) // check squares for the king
  1468. {
  1469. if((board[targetPos] != '.' && targetPos != rookPos) ||
  1470. SCL_boardSquareAttacked(board, targetPos, !isWhite)) {
  1471. ok = 0;
  1472. break;
  1473. }
  1474. targetPos += inc;
  1475. }
  1476. if(ok) SCL_squareSetAdd(result, rookPos);
  1477. }
  1478. #endif
  1479. }
  1480. }
  1481. } break;
  1482. default:
  1483. break;
  1484. }
  1485. }
  1486. void SCL_printSquareSet(SCL_SquareSet set, SCL_PutCharFunction putCharFunc) {
  1487. uint8_t first = 1;
  1488. putCharFunc('(');
  1489. for(uint8_t i = 0; i < SCL_BOARD_SQUARES; ++i) {
  1490. if(!SCL_squareSetContains(set, i)) continue;
  1491. if(!first)
  1492. putCharFunc(',');
  1493. else
  1494. first = 0;
  1495. putCharFunc('A' + i % 8);
  1496. putCharFunc('1' + i / 8);
  1497. }
  1498. putCharFunc(')');
  1499. }
  1500. void SCL_printSquareUTF8(uint8_t square, SCL_PutCharFunction putCharFunc) {
  1501. uint32_t val = 0;
  1502. switch(square) {
  1503. case 'r':
  1504. val = 0x9c99e200;
  1505. break;
  1506. case 'n':
  1507. val = 0x9e99e200;
  1508. break;
  1509. case 'b':
  1510. val = 0x9d99e200;
  1511. break;
  1512. case 'q':
  1513. val = 0x9b99e200;
  1514. break;
  1515. case 'k':
  1516. val = 0x9a99e200;
  1517. break;
  1518. case 'p':
  1519. val = 0x9f99e200;
  1520. break;
  1521. case 'R':
  1522. val = 0x9699e200;
  1523. break;
  1524. case 'N':
  1525. val = 0x9899e200;
  1526. break;
  1527. case 'B':
  1528. val = 0x9799e200;
  1529. break;
  1530. case 'Q':
  1531. val = 0x9599e200;
  1532. break;
  1533. case 'K':
  1534. val = 0x9499e200;
  1535. break;
  1536. case 'P':
  1537. val = 0x9999e200;
  1538. break;
  1539. case '.':
  1540. val = 0x9296e200;
  1541. break;
  1542. case ',':
  1543. val = 0x9196e200;
  1544. break;
  1545. default:
  1546. putCharFunc(square);
  1547. return;
  1548. break;
  1549. }
  1550. uint8_t count = 4;
  1551. while((val % 256 == 0) && (count > 0)) {
  1552. val /= 256;
  1553. count--;
  1554. }
  1555. while(count > 0) {
  1556. putCharFunc(val % 256);
  1557. val /= 256;
  1558. count--;
  1559. }
  1560. }
  1561. void SCL_boardGetMoves(SCL_Board board, uint8_t pieceSquare, SCL_SquareSet result) {
  1562. SCL_SquareSet allMoves;
  1563. SCL_squareSetClear(allMoves);
  1564. for(uint8_t i = 0; i < 8; ++i) result[i] = 0;
  1565. SCL_boardGetPseudoMoves(board, pieceSquare, 1, allMoves);
  1566. // Now only keep moves that don't lead to one's check:
  1567. SCL_SQUARE_SET_ITERATE_BEGIN(allMoves)
  1568. SCL_MoveUndo undo = SCL_boardMakeMove(board, pieceSquare, iteratedSquare, 'q');
  1569. if(!SCL_boardCheck(board, !SCL_boardWhitesTurn(board)))
  1570. SCL_squareSetAdd(result, iteratedSquare);
  1571. SCL_boardUndoMove(board, undo);
  1572. SCL_SQUARE_SET_ITERATE_END
  1573. }
  1574. uint8_t SCL_boardDead(SCL_Board board) {
  1575. /*
  1576. This byte represents material by bits:
  1577. MSB _ _ _ _ _ _ _ _ LSB
  1578. | | | | | \_ white knight
  1579. | | | | \__ white bishop on white
  1580. | | | \____ white bishop on black
  1581. | | \________ black knight
  1582. | \__________ black bishop on white
  1583. \____________ black bishop on black
  1584. */
  1585. uint8_t material = 0;
  1586. const char* p = board;
  1587. for(uint8_t i = 0; i < SCL_BOARD_SQUARES; ++i) {
  1588. char c = *p;
  1589. switch(c) {
  1590. case 'n':
  1591. material |= 0x01;
  1592. break;
  1593. case 'N':
  1594. material |= 0x10;
  1595. break;
  1596. case 'b':
  1597. material |= (0x02 << (!SCL_squareIsWhite(i)));
  1598. break;
  1599. case 'B':
  1600. material |= (0x20 << (!SCL_squareIsWhite(i)));
  1601. break;
  1602. case 'p':
  1603. case 'P':
  1604. case 'r':
  1605. case 'R':
  1606. case 'q':
  1607. case 'Q':
  1608. return 0; // REMOVE later if more complex check are performed
  1609. break;
  1610. default:
  1611. break;
  1612. }
  1613. p++;
  1614. }
  1615. // TODO: add other checks than only insufficient material
  1616. // possible combinations of insufficient material:
  1617. return (material == 0x00) || // king vs king
  1618. (material == 0x01) || // king and knight vs king
  1619. (material == 0x10) || // king and knight vs king
  1620. (material == 0x02) || // king and bishop vs king
  1621. (material == 0x20) || // king and bishop vs king
  1622. (material == 0x04) || // king and bishop vs king
  1623. (material == 0x40) || // king and bishop vs king
  1624. (material == 0x22) || // king and bishop vs king and bishop (same color)
  1625. (material == 0x44); // king and bishop vs king and bishop (same color)
  1626. }
  1627. uint8_t SCL_boardGetPosition(SCL_Board board) {
  1628. uint8_t check = SCL_boardCheck(board, SCL_boardWhitesTurn(board));
  1629. uint8_t moves = SCL_boardMovePossible(board);
  1630. if(check)
  1631. return moves ? SCL_POSITION_CHECK : SCL_POSITION_MATE;
  1632. else if(!moves)
  1633. return SCL_POSITION_STALEMATE;
  1634. if(SCL_boardDead(board)) return SCL_POSITION_DEAD;
  1635. return SCL_POSITION_NORMAL;
  1636. }
  1637. uint8_t SCL_stringToMove(
  1638. const char* moveString,
  1639. uint8_t* resultFrom,
  1640. uint8_t* resultTo,
  1641. char* resultPromotion) {
  1642. char c;
  1643. uint8_t* dst = resultFrom;
  1644. for(uint8_t i = 0; i < 2; ++i) {
  1645. c = *moveString;
  1646. *dst = (c >= 'a') ? (c - 'a') : (c - 'A');
  1647. if(*dst > 7) return 0;
  1648. moveString++;
  1649. c = *moveString;
  1650. *dst += 8 * (c - '1');
  1651. if(*dst > 63) return 0;
  1652. moveString++;
  1653. dst = resultTo;
  1654. }
  1655. c = *moveString;
  1656. if(c < 'A') c = c - 'A' + 'a';
  1657. switch(c) {
  1658. case 'N':
  1659. case 'n':
  1660. *resultPromotion = 'n';
  1661. break;
  1662. case 'B':
  1663. case 'b':
  1664. *resultPromotion = 'b';
  1665. break;
  1666. case 'R':
  1667. case 'r':
  1668. *resultPromotion = 'r';
  1669. break;
  1670. case 'Q':
  1671. case 'q':
  1672. default:
  1673. *resultPromotion = 'q';
  1674. break;
  1675. }
  1676. return 1;
  1677. }
  1678. void SCL_printBoard(
  1679. SCL_Board board,
  1680. SCL_PutCharFunction putCharFunc,
  1681. SCL_SquareSet highlightSquares,
  1682. uint8_t selectSquare,
  1683. uint8_t format,
  1684. uint8_t offset,
  1685. uint8_t labels,
  1686. uint8_t blackDown) {
  1687. if(labels) {
  1688. for(uint8_t i = 0; i < offset + 2; ++i) putCharFunc(' ');
  1689. for(uint8_t i = 0; i < 8; ++i) {
  1690. if((format != SCL_PRINT_FORMAT_COMPACT) && (format != SCL_PRINT_FORMAT_COMPACT_UTF8))
  1691. putCharFunc(' ');
  1692. putCharFunc(blackDown ? ('H' - i) : ('A' + i));
  1693. }
  1694. putCharFunc('\n');
  1695. }
  1696. int8_t i = 7;
  1697. int8_t add = 1;
  1698. if(!blackDown) {
  1699. i = 56;
  1700. add = -1;
  1701. }
  1702. for(int8_t row = 0; row < 8; ++row) {
  1703. for(uint8_t j = 0; j < offset; ++j) putCharFunc(' ');
  1704. if(labels) {
  1705. putCharFunc(!blackDown ? ('8' - row) : ('1' + row));
  1706. putCharFunc(' ');
  1707. }
  1708. const char* square = board + i;
  1709. for(int8_t col = 0; col < 8; ++col) {
  1710. switch(format) {
  1711. case SCL_PRINT_FORMAT_COMPACT:
  1712. putCharFunc(
  1713. (*square == '.') ?
  1714. (((i != selectSquare) ?
  1715. (!SCL_squareSetContains(highlightSquares, i) ? *square : '*') :
  1716. '#')) :
  1717. *square);
  1718. break;
  1719. case SCL_PRINT_FORMAT_UTF8: {
  1720. char squareChar = SCL_squareIsWhite(i) ? '.' : ',';
  1721. char pieceChar = (*square == '.') ? squareChar : *square;
  1722. if(i == selectSquare) {
  1723. putCharFunc('(');
  1724. if(*square == '.')
  1725. putCharFunc(')');
  1726. else
  1727. SCL_printSquareUTF8(pieceChar, putCharFunc);
  1728. } else if(!SCL_squareSetContains(highlightSquares, i)) {
  1729. SCL_printSquareUTF8(squareChar, putCharFunc);
  1730. SCL_printSquareUTF8(pieceChar, putCharFunc);
  1731. } else {
  1732. putCharFunc('[');
  1733. if(*square == '.')
  1734. putCharFunc(']');
  1735. else
  1736. SCL_printSquareUTF8(*square, putCharFunc);
  1737. }
  1738. break;
  1739. }
  1740. case SCL_PRINT_FORMAT_COMPACT_UTF8:
  1741. SCL_printSquareUTF8(
  1742. (*square == '.') ?
  1743. (SCL_squareSetContains(highlightSquares, i) ?
  1744. '*' :
  1745. (i == selectSquare ? '#' : ((SCL_squareIsWhite(i) ? '.' : ',')))) :
  1746. *square,
  1747. putCharFunc);
  1748. break;
  1749. case SCL_PRINT_FORMAT_NORMAL:
  1750. default: {
  1751. uint8_t c = *square;
  1752. char squareColor = SCL_squareIsWhite(i) ? ' ' : ':';
  1753. putCharFunc(
  1754. (i != selectSquare) ?
  1755. (!SCL_squareSetContains(highlightSquares, i) ? squareColor : '#') :
  1756. '@');
  1757. putCharFunc(c == '.' ? squareColor : *square);
  1758. break;
  1759. }
  1760. }
  1761. i -= add;
  1762. square -= add;
  1763. }
  1764. putCharFunc('\n');
  1765. i += add * 16;
  1766. } // for rows
  1767. }
  1768. int16_t SCL_pieceValuePositive(char piece) {
  1769. switch(piece) {
  1770. case 'p':
  1771. case 'P':
  1772. return SCL_VALUE_PAWN;
  1773. break;
  1774. case 'n':
  1775. case 'N':
  1776. return SCL_VALUE_KNIGHT;
  1777. break;
  1778. case 'b':
  1779. case 'B':
  1780. return SCL_VALUE_BISHOP;
  1781. break;
  1782. case 'r':
  1783. case 'R':
  1784. return SCL_VALUE_ROOK;
  1785. break;
  1786. case 'q':
  1787. case 'Q':
  1788. return SCL_VALUE_QUEEN;
  1789. break;
  1790. case 'k':
  1791. case 'K':
  1792. return SCL_VALUE_KING;
  1793. break;
  1794. default:
  1795. break;
  1796. }
  1797. return 0;
  1798. }
  1799. int16_t SCL_pieceValue(char piece) {
  1800. switch(piece) {
  1801. case 'P':
  1802. return SCL_VALUE_PAWN;
  1803. break;
  1804. case 'N':
  1805. return SCL_VALUE_KNIGHT;
  1806. break;
  1807. case 'B':
  1808. return SCL_VALUE_BISHOP;
  1809. break;
  1810. case 'R':
  1811. return SCL_VALUE_ROOK;
  1812. break;
  1813. case 'Q':
  1814. return SCL_VALUE_QUEEN;
  1815. break;
  1816. case 'K':
  1817. return SCL_VALUE_KING;
  1818. break;
  1819. case 'p':
  1820. return -1 * SCL_VALUE_PAWN;
  1821. break;
  1822. case 'n':
  1823. return -1 * SCL_VALUE_KNIGHT;
  1824. break;
  1825. case 'b':
  1826. return -1 * SCL_VALUE_BISHOP;
  1827. break;
  1828. case 'r':
  1829. return -1 * SCL_VALUE_ROOK;
  1830. break;
  1831. case 'q':
  1832. return -1 * SCL_VALUE_QUEEN;
  1833. break;
  1834. case 'k':
  1835. return -1 * SCL_VALUE_KING;
  1836. break;
  1837. default:
  1838. break;
  1839. }
  1840. return 0;
  1841. }
  1842. #define ATTACK_BONUS 3
  1843. #define MOBILITY_BONUS 10
  1844. #define CENTER_BONUS 7
  1845. #define CHECK_BONUS 5
  1846. #define KING_CASTLED_BONUS 30
  1847. #define KING_BACK_BONUS 15
  1848. #define KING_NOT_CENTER_BONUS 15
  1849. #define PAWN_NON_DOUBLE_BONUS 3
  1850. #define PAWN_PAIR_BONUS 3
  1851. #define KING_CENTERNESS 10
  1852. int16_t _SCL_rateKingEndgamePosition(uint8_t position) {
  1853. int16_t result = 0;
  1854. uint8_t rank = position / 8;
  1855. position %= 8;
  1856. if(position > 1 && position < 6) result += KING_CENTERNESS;
  1857. if(rank > 1 && rank < 6) result += KING_CENTERNESS;
  1858. return result;
  1859. }
  1860. int16_t SCL_boardEvaluateStatic(SCL_Board board) {
  1861. uint8_t position = SCL_boardGetPosition(board);
  1862. int16_t total = 0;
  1863. switch(position) {
  1864. case SCL_POSITION_MATE:
  1865. return SCL_boardWhitesTurn(board) ? -1 * SCL_EVALUATION_MAX_SCORE :
  1866. SCL_EVALUATION_MAX_SCORE;
  1867. break;
  1868. case SCL_POSITION_STALEMATE:
  1869. case SCL_POSITION_DEAD:
  1870. return 0;
  1871. break;
  1872. /*
  1873. main points are assigned as follows:
  1874. - points for material as a sum of all material on board
  1875. - for playing side: if a piece attacks piece of greater value, a fraction
  1876. of the value difference is gained (we suppose exchange), this is only
  1877. gained once per every attacking piece (maximum gain is taken), we only
  1878. take fraction so that actually taking the piece is favored
  1879. - ATTACK_BONUS points for any attacked piece
  1880. other points are assigned as follows (in total these shouldn't be more
  1881. than the value of one pawn)
  1882. - mobility: MOBILITY_BONUS points for each piece with at least 4 possible
  1883. moves
  1884. - center control: CENTER_BONUS points for a piece on a center square
  1885. - CHECK_BONUS points for check
  1886. - king:
  1887. - safety (non endgame): KING_BACK_BONUS points for king on staring rank,
  1888. additional KING_CASTLED_BONUS if the kind if on castled square or
  1889. closer to the edge, additional KING_NOT_CENTER_BONUS for king not on
  1890. its start neighbouring center square
  1891. - center closeness (endgame): up to 2 * KING_CENTERNESS points for
  1892. being closer to center
  1893. - non-doubled pawns: PAWN_NON_DOUBLE_BONUS points for each pawn without
  1894. same color pawn directly in front of it
  1895. - pawn structure: PAWN_PAIR_BONUS points for each pawn guarding own pawn
  1896. - advancing pawns: 1 point for each pawn's rank in its move
  1897. direction
  1898. */
  1899. case SCL_POSITION_CHECK:
  1900. total += SCL_boardWhitesTurn(board) ? -1 * CHECK_BONUS : CHECK_BONUS;
  1901. /* FALLTHROUGH */
  1902. case SCL_POSITION_NORMAL:
  1903. default: {
  1904. SCL_SquareSet moves;
  1905. const char* p = board;
  1906. int16_t positiveMaterial = 0;
  1907. uint8_t endgame = 0;
  1908. // first count material to see if this is endgame or not
  1909. for(uint8_t i = 0; i < SCL_BOARD_SQUARES; ++i, ++p) {
  1910. char s = *p;
  1911. if(s != '.') {
  1912. positiveMaterial += SCL_pieceValuePositive(s);
  1913. total += SCL_pieceValue(s);
  1914. }
  1915. }
  1916. endgame = positiveMaterial <= SCL_ENDGAME_MATERIAL_LIMIT;
  1917. p = board;
  1918. for(uint8_t i = 0; i < SCL_BOARD_SQUARES; ++i, ++p) {
  1919. char s = *p;
  1920. if(s != '.') {
  1921. uint8_t white = SCL_pieceIsWhite(s);
  1922. switch(s) {
  1923. case 'k': // king safety
  1924. if(endgame)
  1925. total -= _SCL_rateKingEndgamePosition(i);
  1926. else if(i >= 56) {
  1927. total -= KING_BACK_BONUS;
  1928. if(i != 59) {
  1929. total -= KING_NOT_CENTER_BONUS;
  1930. if(i >= 62 || i <= 58) total -= KING_CASTLED_BONUS;
  1931. }
  1932. }
  1933. break;
  1934. case 'K':
  1935. if(endgame)
  1936. total += _SCL_rateKingEndgamePosition(i);
  1937. else if(i <= 7) {
  1938. total += KING_BACK_BONUS;
  1939. if(i != 3) {
  1940. total += KING_NOT_CENTER_BONUS;
  1941. if(i <= 2 || i >= 6) total += KING_CASTLED_BONUS;
  1942. }
  1943. }
  1944. break;
  1945. case 'P': // pawns
  1946. case 'p': {
  1947. int8_t rank = i / 8;
  1948. if(rank != 0 && rank != 7) {
  1949. if(s == 'P') {
  1950. total += rank;
  1951. char* tmp = board + i + 8;
  1952. if(*tmp != 'P') total += PAWN_NON_DOUBLE_BONUS;
  1953. if(i % 8 != 7) {
  1954. tmp++;
  1955. if(*tmp == 'P') total += PAWN_PAIR_BONUS;
  1956. if(*(tmp - 16) == 'P') total += PAWN_PAIR_BONUS;
  1957. }
  1958. } else {
  1959. total -= 7 - rank;
  1960. char* tmp = board + i - 8;
  1961. if(*tmp != 'p') total -= PAWN_NON_DOUBLE_BONUS;
  1962. if(i % 8 != 7) {
  1963. tmp += 17;
  1964. if(*tmp == 'p') total -= PAWN_PAIR_BONUS;
  1965. if(*(tmp - 16) == 'p') total -= PAWN_PAIR_BONUS;
  1966. }
  1967. }
  1968. }
  1969. break;
  1970. }
  1971. default:
  1972. break;
  1973. }
  1974. if(i >= 27 && i <= 36 && (i >= 35 || i <= 28)) // center control
  1975. total += white ? CENTER_BONUS : (-1 * CENTER_BONUS);
  1976. // for performance we only take pseudo moves
  1977. SCL_boardGetPseudoMoves(board, i, 0, moves);
  1978. if(SCL_squareSetSize(moves) >= 4) // mobility
  1979. total += white ? MOBILITY_BONUS : (-1 * MOBILITY_BONUS);
  1980. int16_t exchangeBonus = 0;
  1981. SCL_SQUARE_SET_ITERATE_BEGIN(moves)
  1982. if(board[iteratedSquare] != '.') {
  1983. total += white ? ATTACK_BONUS : (-1 * ATTACK_BONUS);
  1984. if(SCL_boardWhitesTurn(board) == white) {
  1985. int16_t valueDiff = SCL_pieceValuePositive(board[iteratedSquare]) -
  1986. SCL_pieceValuePositive(s);
  1987. valueDiff /= 4; // only take a fraction to favor taking
  1988. if(valueDiff > exchangeBonus) exchangeBonus = valueDiff;
  1989. }
  1990. }
  1991. SCL_SQUARE_SET_ITERATE_END
  1992. if(exchangeBonus != 0) total += white ? exchangeBonus : -1 * exchangeBonus;
  1993. }
  1994. } // for each square
  1995. return total;
  1996. break;
  1997. } // normal position
  1998. } // switch
  1999. return 0;
  2000. }
  2001. #undef ATTACK_BONUS
  2002. #undef MOBILITY_BONUS
  2003. #undef CENTER_BONUS
  2004. #undef CHECK_BONUS
  2005. #undef KING_CASTLED_BONUS
  2006. #undef KING_BACK_BONUS
  2007. #undef PAWN_NON_DOUBLE_BONUS
  2008. #undef PAWN_PAIR_BONUS
  2009. #undef KING_CENTERNESS
  2010. SCL_StaticEvaluationFunction _SCL_staticEvaluationFunction;
  2011. int16_t _SCL_currentEval;
  2012. int8_t _SCL_depthHardLimit;
  2013. /**
  2014. Inner recursive function for SCL_boardEvaluateDynamic. It is passed a square
  2015. (or -1) at which last capture happened, to implement capture extension.
  2016. */
  2017. int16_t _SCL_boardEvaluateDynamic(
  2018. SCL_Board board,
  2019. int8_t depth,
  2020. int16_t alphaBeta,
  2021. int8_t takenSquare) {
  2022. #if SCL_COUNT_EVALUATED_POSITIONS
  2023. SCL_positionsEvaluated++;
  2024. #endif
  2025. #if SCL_CALL_WDT_RESET
  2026. wdt_reset();
  2027. #endif
  2028. uint8_t whitesTurn = SCL_boardWhitesTurn(board);
  2029. int8_t valueMultiply = whitesTurn ? 1 : -1;
  2030. int16_t bestMoveValue = -1 * SCL_EVALUATION_MAX_SCORE;
  2031. uint8_t shouldCompute = depth > 0;
  2032. uint8_t extended = 0;
  2033. uint8_t positionType = SCL_boardGetPosition(board);
  2034. if(!shouldCompute) {
  2035. /* here we do two extensions (deeper search): taking on a same square
  2036. (exchanges) and checks (good for mating and preventing mates): */
  2037. extended = (depth > _SCL_depthHardLimit) &&
  2038. (takenSquare >= 0 || (SCL_boardGetPosition(board) == SCL_POSITION_CHECK));
  2039. shouldCompute = extended;
  2040. }
  2041. #if SCL_DEBUG_AI
  2042. char moveStr[8];
  2043. uint8_t debugFirst = 1;
  2044. #endif
  2045. if(shouldCompute &&
  2046. (positionType == SCL_POSITION_NORMAL || positionType == SCL_POSITION_CHECK)) {
  2047. #if SCL_DEBUG_AI
  2048. putchar('(');
  2049. #endif
  2050. alphaBeta *= valueMultiply;
  2051. uint8_t end = 0;
  2052. const char* b = board;
  2053. depth--;
  2054. for(uint8_t i = 0; i < SCL_BOARD_SQUARES; ++i, ++b) {
  2055. char s = *b;
  2056. if(s != '.' && SCL_pieceIsWhite(s) == whitesTurn) {
  2057. SCL_SquareSet moves;
  2058. SCL_squareSetClear(moves);
  2059. SCL_boardGetMoves(board, i, moves);
  2060. if(!SCL_squareSetEmpty(moves)) {
  2061. SCL_SQUARE_SET_ITERATE_BEGIN(moves)
  2062. int8_t captureExtension = -1;
  2063. if(board[iteratedSquare] != '.' && // takes a piece
  2064. (takenSquare == -1 || // extend on first taken sq.
  2065. (extended && takenSquare != -1) || // ignore check extension
  2066. (iteratedSquare == takenSquare))) // extend on same sq. taken
  2067. captureExtension = iteratedSquare;
  2068. SCL_MoveUndo undo = SCL_boardMakeMove(board, i, iteratedSquare, 'q');
  2069. uint8_t s0Dummy, s1Dummy;
  2070. char pDummy;
  2071. SCL_UNUSED(s0Dummy);
  2072. SCL_UNUSED(s1Dummy);
  2073. SCL_UNUSED(pDummy);
  2074. #if SCL_DEBUG_AI
  2075. if(debugFirst)
  2076. debugFirst = 0;
  2077. else
  2078. putchar(',');
  2079. if(extended) putchar('*');
  2080. printf("%s ", SCL_moveToString(board, i, iteratedSquare, 'q', moveStr));
  2081. #endif
  2082. int16_t value = _SCL_boardEvaluateDynamic(
  2083. board,
  2084. depth, // this is depth - 1, we decremented it
  2085. #if SCL_ALPHA_BETA
  2086. valueMultiply * bestMoveValue,
  2087. #else
  2088. 0,
  2089. #endif
  2090. captureExtension) *
  2091. valueMultiply;
  2092. SCL_boardUndoMove(board, undo);
  2093. if(value > bestMoveValue) {
  2094. bestMoveValue = value;
  2095. #if SCL_ALPHA_BETA
  2096. // alpha-beta pruning:
  2097. if(value > alphaBeta) // no, >= can't be here
  2098. {
  2099. end = 1;
  2100. iterationEnd = 1;
  2101. }
  2102. #endif
  2103. }
  2104. SCL_SQUARE_SET_ITERATE_END
  2105. } // !squre set empty?
  2106. } // valid piece?
  2107. if(end) break;
  2108. } // for each square
  2109. #if SCL_DEBUG_AI
  2110. putchar(')');
  2111. #endif
  2112. } else // don't dive recursively, evaluate statically
  2113. {
  2114. bestMoveValue = valueMultiply *
  2115. #ifndef SCL_EVALUATION_FUNCTION
  2116. _SCL_staticEvaluationFunction(board);
  2117. #else
  2118. SCL_EVALUATION_FUNCTION(board);
  2119. #endif
  2120. /* For stalemate return the opposite value of the board, i.e. if the
  2121. position is good for white, then stalemate is good for black and vice
  2122. versa. */
  2123. if(positionType == SCL_POSITION_STALEMATE) bestMoveValue *= -1;
  2124. }
  2125. /* Here we either improve (if the move worsens the situation) or devalve (if
  2126. it improves the situation) the result: this needs to be done so that good
  2127. moves far away are seen as worse compared to equally good moves achieved
  2128. in fewer moves. Without this an AI in winning situation may just repeat
  2129. random moves and draw by repetition even if it has mate in 1 (it sees all
  2130. moves as leading to mate). */
  2131. bestMoveValue += bestMoveValue > _SCL_currentEval * valueMultiply ? -1 : 1;
  2132. #if SCL_DEBUG_AI
  2133. printf("%d", bestMoveValue * valueMultiply);
  2134. #endif
  2135. return bestMoveValue * valueMultiply;
  2136. }
  2137. int16_t SCL_boardEvaluateDynamic(
  2138. SCL_Board board,
  2139. uint8_t baseDepth,
  2140. uint8_t extensionExtraDepth,
  2141. SCL_StaticEvaluationFunction evalFunction) {
  2142. _SCL_staticEvaluationFunction = evalFunction;
  2143. _SCL_currentEval = evalFunction(board);
  2144. _SCL_depthHardLimit = 0;
  2145. _SCL_depthHardLimit -= extensionExtraDepth;
  2146. return _SCL_boardEvaluateDynamic(
  2147. board,
  2148. baseDepth,
  2149. SCL_boardWhitesTurn(board) ? SCL_EVALUATION_MAX_SCORE : (-1 * SCL_EVALUATION_MAX_SCORE),
  2150. -1);
  2151. }
  2152. void SCL_boardRandomMove(
  2153. SCL_Board board,
  2154. SCL_RandomFunction randFunc,
  2155. uint8_t* squareFrom,
  2156. uint8_t* squareTo,
  2157. char* resultProm) {
  2158. *resultProm = (randFunc() < 128) ? ((randFunc() < 128) ? 'r' : 'n') :
  2159. ((randFunc() < 128) ? 'b' : 'q');
  2160. SCL_SquareSet set;
  2161. uint8_t white = SCL_boardWhitesTurn(board);
  2162. const char* s = board;
  2163. SCL_squareSetClear(set);
  2164. // find squares with pieces that have legal moves
  2165. for(uint8_t i = 0; i < SCL_BOARD_SQUARES; ++i, ++s) {
  2166. char c = *s;
  2167. if(c != '.' && SCL_pieceIsWhite(c) == white) {
  2168. SCL_SquareSet moves;
  2169. SCL_boardGetMoves(board, i, moves);
  2170. if(SCL_squareSetSize(moves) != 0) SCL_squareSetAdd(set, i);
  2171. }
  2172. }
  2173. *squareFrom = SCL_squareSetGetRandom(set, randFunc);
  2174. SCL_boardGetMoves(board, *squareFrom, set);
  2175. *squareTo = SCL_squareSetGetRandom(set, randFunc);
  2176. }
  2177. void SCL_printBoardSimple(
  2178. SCL_Board board,
  2179. SCL_PutCharFunction putCharFunc,
  2180. uint8_t selectSquare,
  2181. uint8_t format) {
  2182. SCL_SquareSet s;
  2183. SCL_squareSetClear(s);
  2184. SCL_printBoard(board, putCharFunc, s, selectSquare, format, 1, 1, 0);
  2185. }
  2186. int16_t SCL_getAIMove(
  2187. SCL_Board board,
  2188. uint8_t baseDepth,
  2189. uint8_t extensionExtraDepth,
  2190. uint8_t endgameExtraDepth,
  2191. SCL_StaticEvaluationFunction evalFunc,
  2192. SCL_RandomFunction randFunc,
  2193. uint8_t randomness,
  2194. uint8_t repetitionMoveFrom,
  2195. uint8_t repetitionMoveTo,
  2196. uint8_t* resultFrom,
  2197. uint8_t* resultTo,
  2198. char* resultProm) {
  2199. #if SCL_DEBUG_AI
  2200. puts("===== AI debug =====");
  2201. putchar('(');
  2202. unsigned char debugFirst = 1;
  2203. char moveStr[8];
  2204. #endif
  2205. if(baseDepth == 0) {
  2206. SCL_boardRandomMove(board, randFunc, resultFrom, resultTo, resultProm);
  2207. #ifndef SCL_EVALUATION_FUNCTION
  2208. return evalFunc(board);
  2209. #else
  2210. return SCL_EVALUATION_FUNCTION(board);
  2211. #endif
  2212. }
  2213. if(SCL_boardEstimatePhase(board) == SCL_PHASE_ENDGAME) baseDepth += endgameExtraDepth;
  2214. *resultFrom = 0;
  2215. *resultTo = 0;
  2216. *resultProm = 'q';
  2217. int16_t bestScore = SCL_boardWhitesTurn(board) ? -1 * SCL_EVALUATION_MAX_SCORE - 1 :
  2218. (SCL_EVALUATION_MAX_SCORE + 1);
  2219. for(uint8_t i = 0; i < SCL_BOARD_SQUARES; ++i)
  2220. if(board[i] != '.' && SCL_boardWhitesTurn(board) == SCL_pieceIsWhite(board[i])) {
  2221. SCL_SquareSet moves;
  2222. SCL_squareSetClear(moves);
  2223. SCL_boardGetMoves(board, i, moves);
  2224. SCL_SQUARE_SET_ITERATE_BEGIN(moves)
  2225. int16_t score = 0;
  2226. #if SCL_DEBUG_AI
  2227. if(debugFirst)
  2228. debugFirst = 0;
  2229. else
  2230. putchar(',');
  2231. printf("%s ", SCL_moveToString(board, i, iteratedSquare, 'q', moveStr));
  2232. #endif
  2233. if(i != repetitionMoveFrom || iteratedSquare != repetitionMoveTo) {
  2234. SCL_MoveUndo undo = SCL_boardMakeMove(board, i, iteratedSquare, 'q');
  2235. score =
  2236. SCL_boardEvaluateDynamic(board, baseDepth - 1, extensionExtraDepth, evalFunc);
  2237. SCL_boardUndoMove(board, undo);
  2238. }
  2239. if(randFunc != 0 && randomness > 1 && score < 16000 && score > -16000) {
  2240. /*^ We limit randomizing by about half the max score for two reasons:
  2241. to prevent over/under flows and secondly we don't want to alter
  2242. the highest values for checkmate -- these are modified by tiny
  2243. values depending on their depth so as to prevent endless loops in
  2244. which most moves are winning, biasing such values would completely
  2245. kill that algorithm */
  2246. int16_t bias = randFunc();
  2247. bias = (bias - 128) / 2;
  2248. bias *= randomness - 1;
  2249. score += bias;
  2250. }
  2251. uint8_t comparison = score == bestScore;
  2252. if((comparison != 1) && ((SCL_boardWhitesTurn(board) && score > bestScore) ||
  2253. (!SCL_boardWhitesTurn(board) && score < bestScore)))
  2254. comparison = 2;
  2255. uint8_t replace = 0;
  2256. if(randFunc == 0)
  2257. replace = comparison == 2;
  2258. else
  2259. replace =
  2260. (comparison == 2) ||
  2261. ((comparison == 1) && (randFunc() < 160)); // not uniform distr. but simple
  2262. if(replace) {
  2263. *resultFrom = i;
  2264. *resultTo = iteratedSquare;
  2265. bestScore = score;
  2266. }
  2267. SCL_SQUARE_SET_ITERATE_END
  2268. }
  2269. #if SCL_DEBUG_AI
  2270. printf(")%d %s\n", bestScore, SCL_moveToString(board, *resultFrom, *resultTo, 'q', moveStr));
  2271. puts("===== AI debug end ===== ");
  2272. #endif
  2273. return bestScore;
  2274. }
  2275. uint8_t SCL_boardToFEN(SCL_Board board, char* string) {
  2276. uint8_t square = 56;
  2277. uint8_t spaces = 0;
  2278. uint8_t result = 0;
  2279. #define put(c) \
  2280. { \
  2281. *string = (c); \
  2282. string++; \
  2283. result++; \
  2284. }
  2285. while(1) // pieces
  2286. {
  2287. char s = board[square];
  2288. if(s == '.') {
  2289. spaces++;
  2290. } else {
  2291. if(spaces != 0) {
  2292. put('0' + spaces) spaces = 0;
  2293. }
  2294. put(s)
  2295. }
  2296. square++;
  2297. if(square % 8 == 0) {
  2298. if(spaces != 0) {
  2299. put('0' + spaces) spaces = 0;
  2300. }
  2301. if(square == 8) break;
  2302. put('/');
  2303. square -= 16;
  2304. }
  2305. }
  2306. put(' ');
  2307. put(SCL_boardWhitesTurn(board) ? 'w' : 'b');
  2308. put(' ');
  2309. uint8_t b = board[SCL_BOARD_ENPASSANT_CASTLE_BYTE] & 0xf0;
  2310. if(b != 0) // castling
  2311. {
  2312. if(b & 0x10) put('K');
  2313. if(b & 0x20) put('Q');
  2314. if(b & 0x40) put('k');
  2315. if(b & 0x80) put('q');
  2316. } else
  2317. put('-');
  2318. put(' ');
  2319. b = board[SCL_BOARD_ENPASSANT_CASTLE_BYTE] & 0x0f;
  2320. if(b < 8) {
  2321. put('a' + b);
  2322. put(SCL_boardWhitesTurn(board) ? '6' : '3');
  2323. } else
  2324. put('-');
  2325. for(uint8_t i = 0; i < 2; ++i) {
  2326. put(' ');
  2327. uint8_t moves = i == 0 ? ((uint8_t)board[SCL_BOARD_MOVE_COUNT_BYTE]) :
  2328. (((uint8_t)board[SCL_BOARD_PLY_BYTE]) / 2 + 1);
  2329. uint8_t hundreds = moves / 100;
  2330. uint8_t tens = (moves % 100) / 10;
  2331. if(hundreds != 0) {
  2332. put('0' + hundreds);
  2333. put('0' + tens);
  2334. } else if(tens != 0)
  2335. put('0' + tens);
  2336. put('0' + moves % 10);
  2337. }
  2338. *string = 0; // terminate the string
  2339. return result + 1;
  2340. #undef put
  2341. }
  2342. uint8_t SCL_boardFromFEN(SCL_Board board, const char* string) {
  2343. uint8_t square = 56;
  2344. while(1) {
  2345. char c = *string;
  2346. if(c == 0) return 0;
  2347. if(c != '/' && c != ' ') // ignore line separators
  2348. {
  2349. if(c < '9') // empty square sequence
  2350. {
  2351. while(c > '0') {
  2352. board[square] = '.';
  2353. square++;
  2354. c--;
  2355. }
  2356. } else // piece
  2357. {
  2358. board[square] = c;
  2359. square++;
  2360. }
  2361. } else {
  2362. if(square == 8) break;
  2363. square -= 16;
  2364. }
  2365. string++;
  2366. }
  2367. #define nextChar \
  2368. string++; \
  2369. if(*string == 0) return 0;
  2370. nextChar // space
  2371. board[SCL_BOARD_PLY_BYTE] = *string == 'b';
  2372. nextChar
  2373. nextChar // space
  2374. uint8_t castleEnPassant = 0x0;
  2375. while(*string != ' ') {
  2376. switch(*string) {
  2377. case 'K':
  2378. castleEnPassant |= 0x10;
  2379. break;
  2380. case 'Q':
  2381. castleEnPassant |= 0x20;
  2382. break;
  2383. case 'k':
  2384. castleEnPassant |= 0x40;
  2385. break;
  2386. case 'q':
  2387. castleEnPassant |= 0x80;
  2388. break;
  2389. default:
  2390. castleEnPassant |= 0xf0;
  2391. break; // for partial XFEN compat.
  2392. }
  2393. nextChar
  2394. }
  2395. nextChar // space
  2396. if(*string != '-') {
  2397. castleEnPassant |= *string - 'a';
  2398. nextChar
  2399. }
  2400. else castleEnPassant |= 0x0f;
  2401. nextChar
  2402. board[SCL_BOARD_ENPASSANT_CASTLE_BYTE] = castleEnPassant;
  2403. for(uint8_t i = 0; i < 2; ++i) {
  2404. nextChar // space
  2405. uint8_t ply = 0;
  2406. while(1) {
  2407. char c = *string;
  2408. if(c < '0' || c > '9') break;
  2409. ply = ply * 10 + (c - '0');
  2410. string++;
  2411. }
  2412. if(i == 0 && *string == 0) return 0;
  2413. if(i == 0)
  2414. board[SCL_BOARD_MOVE_COUNT_BYTE] = ply;
  2415. else
  2416. board[SCL_BOARD_PLY_BYTE] += (ply - 1) * 2;
  2417. }
  2418. #if SCL_960_CASTLING
  2419. _SCL_board960RememberRookPositions(board);
  2420. #endif
  2421. return 1;
  2422. #undef nextChar
  2423. }
  2424. uint8_t SCL_boardEstimatePhase(SCL_Board board) {
  2425. uint16_t totalMaterial = 0;
  2426. uint8_t ply = board[SCL_BOARD_PLY_BYTE];
  2427. for(uint8_t i = 0; i < SCL_BOARD_SQUARES; ++i) {
  2428. char s = *board;
  2429. if(s != '.') {
  2430. int16_t v = SCL_pieceValue(s);
  2431. if(!SCL_pieceIsWhite(s)) v *= -1;
  2432. totalMaterial += v;
  2433. }
  2434. board++;
  2435. }
  2436. if(totalMaterial < SCL_ENDGAME_MATERIAL_LIMIT) return SCL_PHASE_ENDGAME;
  2437. if(ply <= 10 && (totalMaterial >= SCL_START_MATERIAL - 3 * SCL_VALUE_PAWN))
  2438. return SCL_PHASE_OPENING;
  2439. return SCL_PHASE_MIDGAME;
  2440. }
  2441. #define SCL_IMAGE_COUNT 12
  2442. static const uint8_t SCL_images[8 * SCL_IMAGE_COUNT] = {
  2443. 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x81,
  2444. 0xff, 0xff, 0xff, 0xff, 0xff, 0x81, 0xff, 0xff, 0xff, 0xff, 0xff, 0x81, 0xe7, 0xf7,
  2445. 0xf7, 0xaa, 0xff, 0xbd, 0xe7, 0xf7, 0xf7, 0xaa, 0xff, 0xc3, 0xc3, 0xe3, 0xc1, 0x80,
  2446. 0xff, 0x99, 0xdb, 0xeb, 0xc9, 0x94, 0xe7, 0xc3, 0x81, 0xc1, 0x94, 0x80, 0xe7, 0xdb,
  2447. 0xbd, 0xdd, 0xbe, 0xbe, 0xc3, 0xc3, 0x91, 0xe3, 0x80, 0x80, 0xdb, 0x99, 0x8d, 0xeb,
  2448. 0xaa, 0xbe, 0xc3, 0x81, 0xe1, 0xc1, 0xc1, 0xc1, 0xdb, 0xbd, 0xdd, 0xe3, 0xdd, 0xdd,
  2449. 0x81, 0x81, 0xc1, 0x9c, 0xc1, 0xc1, 0x81, 0x81, 0xc1, 0x9c, 0xc1, 0xc1};
  2450. void SCL_drawBoard(
  2451. SCL_Board board,
  2452. SCL_PutPixelFunction putPixel,
  2453. uint8_t selectedSquare,
  2454. SCL_SquareSet highlightSquares,
  2455. uint8_t blackDown) {
  2456. uint8_t row = 0;
  2457. uint8_t col = 0;
  2458. uint8_t x = 0;
  2459. uint8_t y = 0;
  2460. uint16_t n = 0;
  2461. uint8_t s = 0;
  2462. uint8_t pictureLine = 0;
  2463. uint8_t loadLine = 1;
  2464. while(row < 8) {
  2465. if(loadLine) {
  2466. s = blackDown ? (row * 8 + (7 - col)) : ((7 - row) * 8 + col);
  2467. char piece = board[s];
  2468. if(piece == '.')
  2469. pictureLine = (y == 4) ? 0xef : 0xff;
  2470. else {
  2471. uint8_t offset = SCL_pieceIsWhite(piece) ? 6 : 0;
  2472. piece = SCL_pieceToColor(piece, 1);
  2473. switch(piece) {
  2474. case 'R':
  2475. offset += 1;
  2476. break;
  2477. case 'N':
  2478. offset += 2;
  2479. break;
  2480. case 'B':
  2481. offset += 3;
  2482. break;
  2483. case 'K':
  2484. offset += 4;
  2485. break;
  2486. case 'Q':
  2487. offset += 5;
  2488. break;
  2489. default:
  2490. break;
  2491. }
  2492. pictureLine = SCL_images[y * SCL_IMAGE_COUNT + offset];
  2493. }
  2494. if(SCL_squareSetContains(highlightSquares, s)) pictureLine &= (y % 2) ? 0xaa : 0x55;
  2495. if(s == selectedSquare) pictureLine &= (y == 0 || y == 7) ? 0x00 : ~0x81;
  2496. loadLine = 0;
  2497. }
  2498. putPixel(pictureLine & 0x80, n);
  2499. pictureLine <<= 1;
  2500. n++;
  2501. x++;
  2502. if(x == 8) {
  2503. col++;
  2504. loadLine = 1;
  2505. x = 0;
  2506. }
  2507. if(col == 8) {
  2508. y++;
  2509. col = 0;
  2510. x = 0;
  2511. }
  2512. if(y == 8) {
  2513. row++;
  2514. y = 0;
  2515. }
  2516. }
  2517. }
  2518. uint32_t SCL_boardHash32(const SCL_Board board) {
  2519. uint32_t result = (board[SCL_BOARD_PLY_BYTE] & 0x01) +
  2520. (((uint32_t)((uint8_t)board[SCL_BOARD_ENPASSANT_CASTLE_BYTE])) << 24) +
  2521. board[SCL_BOARD_MOVE_COUNT_BYTE];
  2522. const char* b = board;
  2523. for(uint8_t i = 0; i < SCL_BOARD_SQUARES; ++i, ++b) {
  2524. switch(*b) {
  2525. #define C(p, n) \
  2526. case p: \
  2527. result ^= (i + 1) * n; \
  2528. break;
  2529. // the below number are primes
  2530. C('P', 4003)
  2531. C('R', 84673)
  2532. C('N', 93911)
  2533. C('B', 999331)
  2534. C('Q', 909091)
  2535. C('K', 2796203)
  2536. C('p', 4793)
  2537. C('r', 19391)
  2538. C('n', 391939)
  2539. C('b', 108301)
  2540. C('q', 174763)
  2541. C('k', 2474431)
  2542. #undef C
  2543. default:
  2544. break;
  2545. }
  2546. }
  2547. // for extra spread of values we swap the low/high parts:
  2548. result = (result >> 16) | (result << 16);
  2549. return result;
  2550. }
  2551. void SCL_boardDisableCastling(SCL_Board board) {
  2552. board[SCL_BOARD_ENPASSANT_CASTLE_BYTE] &= 0x0f;
  2553. }
  2554. uint8_t SCL_boardMoveResetsCount(SCL_Board board, uint8_t squareFrom, uint8_t squareTo) {
  2555. return board[squareFrom] == 'P' || board[squareFrom] == 'p' || board[squareTo] != '.';
  2556. }
  2557. void SCL_printPGN(SCL_Record r, SCL_PutCharFunction putCharFunc, SCL_Board initialState) {
  2558. if(SCL_recordLength(r) == 0) return;
  2559. uint16_t pos = 0;
  2560. SCL_Board board;
  2561. if(initialState != 0)
  2562. for(uint8_t i = 0; i < SCL_BOARD_STATE_SIZE; ++i) board[i] = initialState[i];
  2563. else
  2564. SCL_boardInit(board);
  2565. while(1) {
  2566. uint8_t s0, s1;
  2567. char p;
  2568. uint8_t state = SCL_recordGetMove(r, pos, &s0, &s1, &p);
  2569. pos++;
  2570. if(pos % 2) {
  2571. uint8_t move = pos / 2 + 1;
  2572. if(move / 100 != 0) putCharFunc('0' + move / 100);
  2573. if(move / 10 != 0 || move / 100 != 0) putCharFunc('0' + (move % 100) / 10);
  2574. putCharFunc('0' + move % 10);
  2575. putCharFunc('.');
  2576. putCharFunc(' ');
  2577. }
  2578. #if !SCL_960_CASTLING
  2579. if((board[s0] == 'K' && s0 == 4 && (s1 == 2 || s1 == 6)) ||
  2580. (board[s0] == 'k' && s0 == 60 && (s1 == 62 || s1 == 58)))
  2581. #else
  2582. if((board[s0] == 'K' && board[s1] == 'R') || (board[s0] == 'k' && board[s1] == 'r'))
  2583. #endif
  2584. {
  2585. putCharFunc('O');
  2586. putCharFunc('-');
  2587. putCharFunc('O');
  2588. #if !SCL_960_CASTLING
  2589. if(s1 == 58 || s1 == 2)
  2590. #else
  2591. if((s1 == (board[SCL_BOARD_EXTRA_BYTE] & 0x07)) ||
  2592. (s1 == 56 + (board[SCL_BOARD_EXTRA_BYTE] & 0x07)))
  2593. #endif
  2594. {
  2595. putCharFunc('-');
  2596. putCharFunc('O');
  2597. }
  2598. } else {
  2599. uint8_t pawn = board[s0] == 'P' || board[s0] == 'p';
  2600. if(!pawn) {
  2601. putCharFunc(SCL_pieceToColor(board[s0], 1));
  2602. // disambiguation:
  2603. uint8_t specify = 0;
  2604. for(int i = 0; i < SCL_BOARD_SQUARES; ++i)
  2605. if(i != s0 && board[i] == board[s0]) {
  2606. SCL_SquareSet s;
  2607. SCL_squareSetClear(s);
  2608. SCL_boardGetMoves(board, i, s);
  2609. if(SCL_squareSetContains(s, s1)) specify |= (s0 % 8 != s1 % 8) ? 1 : 2;
  2610. }
  2611. if(specify & 0x01) putCharFunc('a' + s0 % 8);
  2612. if(specify & 0x02) putCharFunc('1' + s0 / 8);
  2613. }
  2614. if(board[s1] != '.' || (pawn && s0 % 8 != s1 % 8 && board[s1] == '.')) // capture?
  2615. {
  2616. if(pawn) putCharFunc('a' + s0 % 8);
  2617. putCharFunc('x');
  2618. }
  2619. putCharFunc('a' + s1 % 8);
  2620. putCharFunc('1' + s1 / 8);
  2621. if(pawn && (s1 >= 56 || s1 <= 7)) // promotion?
  2622. {
  2623. putCharFunc('=');
  2624. putCharFunc(SCL_pieceToColor(p, 1));
  2625. }
  2626. }
  2627. SCL_boardMakeMove(board, s0, s1, p);
  2628. uint8_t position = SCL_boardGetPosition(board);
  2629. if(position == SCL_POSITION_CHECK) putCharFunc('+');
  2630. if(position == SCL_POSITION_MATE) {
  2631. putCharFunc('#');
  2632. break;
  2633. } else if(state != SCL_RECORD_CONT) {
  2634. putCharFunc('*');
  2635. break;
  2636. }
  2637. putCharFunc(' ');
  2638. }
  2639. }
  2640. void SCL_recordCopy(SCL_Record recordFrom, SCL_Record recordTo) {
  2641. for(uint16_t i = 0; i < SCL_RECORD_MAX_SIZE; ++i) recordTo[i] = recordFrom[i];
  2642. }
  2643. void SCL_gameInit(SCL_Game* game, const SCL_Board startState) {
  2644. game->startState = startState;
  2645. if(startState != 0)
  2646. SCL_boardCopy(startState, game->board);
  2647. else
  2648. SCL_boardInit(game->board);
  2649. SCL_recordInit(game->record);
  2650. for(uint8_t i = 0; i < 14; ++i) game->prevMoves[i] = 0;
  2651. game->state = SCL_GAME_STATE_PLAYING;
  2652. game->ply = 0;
  2653. SCL_recordInit(game->record);
  2654. }
  2655. uint8_t SCL_gameGetRepetiotionMove(SCL_Game* game, uint8_t* squareFrom, uint8_t* squareTo) {
  2656. if(squareFrom != 0 && squareTo != 0) {
  2657. *squareFrom = 0;
  2658. *squareTo = 0;
  2659. }
  2660. /* pos. 1st 2nd 3rd
  2661. | | |
  2662. v v v
  2663. 01 23 45 67 89 AB CD EF
  2664. move ab cd ba dc ab cd ba dc */
  2665. if(game->ply >= 7 && game->prevMoves[0] == game->prevMoves[5] &&
  2666. game->prevMoves[0] == game->prevMoves[8] && game->prevMoves[0] == game->prevMoves[13] &&
  2667. game->prevMoves[1] == game->prevMoves[4] && game->prevMoves[1] == game->prevMoves[9] &&
  2668. game->prevMoves[1] == game->prevMoves[12] &&
  2669. game->prevMoves[2] == game->prevMoves[7] && game->prevMoves[2] == game->prevMoves[10] &&
  2670. game->prevMoves[3] == game->prevMoves[6] && game->prevMoves[3] == game->prevMoves[11]) {
  2671. if(squareFrom != 0 && squareTo != 0) {
  2672. *squareFrom = game->prevMoves[3];
  2673. *squareTo = game->prevMoves[2];
  2674. }
  2675. return 1;
  2676. }
  2677. return 0;
  2678. }
  2679. void SCL_gameMakeMove(SCL_Game* game, uint8_t squareFrom, uint8_t squareTo, char promoteTo) {
  2680. uint8_t repetitionS0, repetitionS1;
  2681. SCL_gameGetRepetiotionMove(game, &repetitionS0, &repetitionS1);
  2682. SCL_boardMakeMove(game->board, squareFrom, squareTo, promoteTo);
  2683. SCL_recordAdd(game->record, squareFrom, squareTo, promoteTo, SCL_RECORD_CONT);
  2684. // ^ TODO: SCL_RECORD_CONT
  2685. game->ply++;
  2686. for(uint8_t i = 0; i < 14 - 2; ++i) game->prevMoves[i] = game->prevMoves[i + 2];
  2687. game->prevMoves[12] = squareFrom;
  2688. game->prevMoves[13] = squareTo;
  2689. if(squareFrom == repetitionS0 && squareTo == repetitionS1)
  2690. game->state = SCL_GAME_STATE_DRAW_REPETITION;
  2691. else if(game->board[SCL_BOARD_MOVE_COUNT_BYTE] >= 50)
  2692. game->state = SCL_GAME_STATE_DRAW_50;
  2693. else {
  2694. uint8_t position = SCL_boardGetPosition(game->board);
  2695. switch(position) {
  2696. case SCL_POSITION_MATE:
  2697. game->state = SCL_boardWhitesTurn(game->board) ? SCL_GAME_STATE_BLACK_WIN :
  2698. SCL_GAME_STATE_WHITE_WIN;
  2699. break;
  2700. case SCL_POSITION_STALEMATE:
  2701. game->state = SCL_GAME_STATE_DRAW_STALEMATE;
  2702. break;
  2703. case SCL_POSITION_DEAD:
  2704. game->state = SCL_GAME_STATE_DRAW_DEAD;
  2705. break;
  2706. default:
  2707. break;
  2708. }
  2709. }
  2710. }
  2711. uint8_t SCL_gameUndoMove(SCL_Game* game) {
  2712. if(game->ply == 0) return 0;
  2713. if((game->ply - 1) > SCL_recordLength(game->record)) return 0; // can't undo, lacking record
  2714. SCL_Record r;
  2715. SCL_recordCopy(game->record, r);
  2716. uint16_t applyMoves = game->ply - 1;
  2717. SCL_gameInit(game, game->startState);
  2718. for(uint16_t i = 0; i < applyMoves; ++i) {
  2719. uint8_t s0, s1;
  2720. char p;
  2721. SCL_recordGetMove(r, i, &s0, &s1, &p);
  2722. SCL_gameMakeMove(game, s0, s1, p);
  2723. }
  2724. return 1;
  2725. }
  2726. uint8_t SCL_boardMoveIsLegal(SCL_Board board, uint8_t squareFrom, uint8_t squareTo) {
  2727. if(squareFrom >= SCL_BOARD_SQUARES || squareTo >= SCL_BOARD_SQUARES) return 0;
  2728. char piece = board[squareFrom];
  2729. if((piece == '.') || (SCL_boardWhitesTurn(board) != SCL_pieceIsWhite(piece))) return 0;
  2730. SCL_SquareSet moves;
  2731. SCL_boardGetMoves(board, squareFrom, moves);
  2732. return SCL_squareSetContains(moves, squareTo);
  2733. }
  2734. #endif // guard