smallchesslib.h 100 KB

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