smallchesslib.h 91 KB

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