chess.ino 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312
  1. #include <EEPROM.h>
  2. #include <SPI.h>
  3. #include <GD2.h>
  4. #include "chess_assets.h"
  5. void setup()
  6. {
  7. Serial.begin(1000000); // JCB
  8. GD.begin();
  9. LOAD_ASSETS();
  10. GD.BitmapHandle(1);
  11. GD.BitmapSource(CHECKER);
  12. GD.BitmapSize(NEAREST, REPEAT, REPEAT, 256, 256);
  13. GD.BitmapLayout(L8, CHECKER_WIDTH, CHECKER_HEIGHT);
  14. }
  15. /***************************************************************************/
  16. /* micro-Max, */
  17. /* A chess program smaller than 2KB (of non-blank source), by H.G. Muller */
  18. /* Port to Atmel ATMega644 and AVR GCC, by Andre Adrian */
  19. /***************************************************************************/
  20. /* version 4.8 (1953 characters) features: */
  21. /* - recursive negamax search */
  22. /* - all-capture MVV/LVA quiescence search */
  23. /* - (internal) iterative deepening */
  24. /* - best-move-first 'sorting' */
  25. /* - a hash table storing score and best move */
  26. /* - futility pruning */
  27. /* - king safety through magnetic, frozen king in middle-game */
  28. /* - R=2 null-move pruning */
  29. /* - keep hash and repetition-draw detection */
  30. /* - better defense against passers through gradual promotion */
  31. /* - extend check evasions in inner nodes */
  32. /* - reduction of all non-Pawn, non-capture moves except hash move (LMR) */
  33. /* - full FIDE rules (expt under-promotion) and move-legality checking */
  34. /* 26nov2008 no hash table */
  35. /* 29nov2008 all IO via myputchar(), mygetchar(), pseudo random generator */
  36. #define VERBOSE
  37. #define W while
  38. #define M 0x88
  39. #define S 128
  40. #define I 8000
  41. long N, T; /* N=evaluated positions+S, T=recursion limit */
  42. short Q,O,K,R,k=16; /* k=moving side */
  43. char *p,c[5],Z; /* p=pointer to c, c=user input, computer output, Z=recursion counter */
  44. char L,
  45. w[]={0,2,2,7,-1,8,12,23}, /* relative piece values */
  46. o[]={-16,-15,-17,0,1,16,0,1,16,15,17,0,14,18,31,33,0, /* step-vector lists */
  47. 7,-1,11,6,8,3,6, /* 1st dir. in o[] per piece*/
  48. 6,3,5,7,4,5,3,6}, /* initial piece setup */
  49. b[]={ /* board is left part, center-pts table is right part, and dummy */
  50. 22, 19, 21, 23, 20, 21, 19, 22, 28, 21, 16, 13, 12, 13, 16, 21,
  51. 18, 18, 18, 18, 18, 18, 18, 18, 22, 15, 10, 7, 6, 7, 10, 15,
  52. 0, 0, 0, 0, 0, 0, 0, 0, 18, 11, 6, 3, 2, 3, 6, 11,
  53. 0, 0, 0, 0, 0, 0, 0, 0, 16, 9, 4, 1, 0, 1, 4, 9,
  54. 0, 0, 0, 0, 0, 0, 0, 0, 16, 9, 4, 1, 0, 1, 4, 9,
  55. 0, 0, 0, 0, 0, 0, 0, 0, 18, 11, 6, 3, 2, 3, 6, 11,
  56. 9, 9, 9, 9, 9, 9, 9, 9, 22, 15, 10, 7, 6, 7, 10, 15,
  57. 14, 11, 13, 15, 12, 13, 11, 14, 28, 21, 16, 13, 12, 13, 16, 21, 0
  58. };
  59. volatile char breakpoint; /* for debugger */
  60. /* User interface routines */
  61. void myputchar(char c) {
  62. #ifdef DUMPDEV // JCB{
  63. fprintf(stderr, "%c", c);
  64. #endif // }JCB
  65. }
  66. void myputs(const char *s) {
  67. while(*s) myputchar(*s++);
  68. myputchar('\n');
  69. }
  70. char mygetchar(void) {
  71. return 10; /* self play computer with computer */
  72. #ifdef VERBOSE
  73. return getchar();
  74. #else
  75. return 10; /* self play computer with computer */
  76. #endif
  77. }
  78. /* 16bit pseudo random generator */
  79. #define MYRAND_MAX 65535
  80. unsigned short r = 1; /* pseudo random generator seed */
  81. void mysrand(unsigned short r_) {
  82. r = r_;
  83. }
  84. unsigned short myrand(void) {
  85. return r=((r<<11)+(r<<7)+r)>>1;
  86. }
  87. static void sp()
  88. {
  89. void* x;
  90. x = &x;
  91. Serial.println((size_t)x, HEX);
  92. }
  93. short D(short q, short l, short e, byte E,byte z, byte n) /* recursive minimax search */
  94. /* (q,l)=window, e=current eval. score, */
  95. /* E=e.p. sqr.z=prev.dest, n=depth; return score */
  96. {
  97. short m,v,i,P,V,s;
  98. unsigned char t,p,u,x,y,X,Y,H,B,j,d,h,F,G,C;
  99. signed char r;
  100. // if (0) { REPORT(Z); sp(); }
  101. if (++Z>30) { /* stack underrun check */
  102. breakpoint=1; /* AVR Studio 4 Breakpoint for stack underrun */
  103. myputchar('u');
  104. --Z;return e;
  105. }
  106. q--; /* adj. window: delay bonus */
  107. k^=24; /* change sides */
  108. d=Y=0; /* start iter. from scratch */
  109. X=myrand()&~M; /* start at random field */
  110. W(d++<n||d<3|| /* iterative deepening loop */
  111. z&K==I&&(N<T&d<98|| /* root: deepen upto time */
  112. (K=X,L=Y&~M,d=3))) /* time's up: go do best */
  113. {x=B=X; /* start scan at prev. best */
  114. h=Y&S; /* request try noncastl. 1st*/
  115. P=d<3?I:D(-l,1-l,-e,S,0,d-3); /* Search null move */
  116. m=-P<l|R>35?d>2?-I:e:-P; /* Prune or stand-pat */
  117. ++N; /* node count (for timing) */
  118. do{u=b[x]; /* scan board looking for */
  119. if(u&k) /* own piece (inefficient!)*/
  120. {r=p=u&7; /* p = piece type (set r>0) */
  121. j=o[p+16]; /* first step vector f.piece*/
  122. W(r=p>2&r<0?-r:-o[++j]) /* loop over directions o[] */
  123. {A: /* resume normal after best */
  124. y=x;F=G=S; /* (x,y)=move, (F,G)=castl.R*/
  125. do{ /* y traverses ray, or: */
  126. H=y=h?Y^h:y+r; /* sneak in prev. best move */
  127. if(y&M)break; /* board edge hit */
  128. m=E-S&b[E]&&y-E<2&E-y<2?I:m; /* bad castling */
  129. if(p<3&y==E)H^=16; /* shift capt.sqr. H if e.p.*/
  130. t=b[H];if(t&k|p<3&!(y-x&7)-!t)break; /* capt. own, bad pawn mode */
  131. i=37*w[t&7]+(t&192); /* value of capt. piece t */
  132. m=i<0?I:m; /* K capture */
  133. if(m>=l&d>1)goto C; /* abort on fail high */
  134. v=d-1?e:i-p; /* MVV/LVA scoring */
  135. if(d-!t>1) /* remaining depth */
  136. {v=p<6?b[x+8]-b[y+8]:0; /* center positional pts. */
  137. b[G]=b[H]=b[x]=0;b[y]=u|32; /* do move, set non-virgin */
  138. if(!(G&M))b[F]=k+6,v+=50; /* castling: put R & score */
  139. v-=p-4|R>29?0:20; /* penalize mid-game K move */
  140. if(p<3) /* pawns: */
  141. {v-=9*((x-2&M||b[x-2]-u)+ /* structure, undefended */
  142. (x+2&M||b[x+2]-u)-1 /* squares plus bias */
  143. +(b[x^16]==k+36)) /* kling to non-virgin King */
  144. -(R>>2); /* end-game Pawn-push bonus */
  145. V=y+r+1&S?647-p:2*(u&y+16&32); /* promotion or 6/7th bonus */
  146. b[y]+=V;i+=V; /* change piece, add score */
  147. }
  148. v+=e+i;V=m>q?m:q; /* new eval and alpha */
  149. C=d-1-(d>5&p>2&!t&!h);
  150. C=R>29|d<3|P-I?C:d; /* extend 1 ply if in check */
  151. do
  152. s=C>2|v>V?-D(-l,-V,-v, /* recursive eval. of reply */
  153. F,0,C):v; /* or fail low if futile */
  154. W(s>q&++C<d);v=s;
  155. if(z&&K-I&&v+I&&x==K&y==L) /* move pending & in root: */
  156. {Q=-e-i;O=F; /* exit if legal & found */
  157. R+=i>>7;--Z;return l; /* captured non-P material */
  158. }
  159. b[G]=k+6;b[F]=b[y]=0;b[x]=u;b[H]=t; /* undo move,G can be dummy */
  160. }
  161. if(v>m) /* new best, update max,best*/
  162. m=v,X=x,Y=y|S&F; /* mark double move with S */
  163. if(h){h=0;goto A;} /* redo after doing old best*/
  164. if(x+r-y|u&32| /* not 1st step,moved before*/
  165. p>2&(p-4|j-7|| /* no P & no lateral K move,*/
  166. b[G=x+3^r>>1&7]-k-6 /* no virgin R in corner G, */
  167. ||b[G^1]|b[G^2]) /* no 2 empty sq. next to R */
  168. )t+=p<5; /* fake capt. for nonsliding*/
  169. else F=y; /* enable e.p. */
  170. }W(!t); /* if not capt. continue ray*/
  171. }}}W((x=x+9&~M)-B); /* next sqr. of board, wrap */
  172. C:if(m>I-M|m<M-I)d=98; /* mate holds to any depth */
  173. m=m+I|P==I?m:0; /* best loses K: (stale)mate*/
  174. if(z&&d>2)
  175. {*c='a'+(X&7);c[1]='8'-(X>>4);c[2]='a'+(Y&7);c[3]='8'-(Y>>4&7);c[4]=0;
  176. breakpoint=2; /* AVR Studio 4 Breakpoint for moves, watch c[] */
  177. #ifdef DUMPDEV // JCB{
  178. fprintf(stderr, "%2d ply, %9d searched, score=%6d by %c%c%c%c\n",d-1,N-S,m,
  179. 'a'+(X&7),'8'-(X>>4),'a'+(Y&7),'8'-(Y>>4&7)); /* uncomment for Kibitz */
  180. #else
  181. REPORT(d);
  182. Serial.println(c);
  183. #endif // }JCB
  184. }
  185. } /* encoded in X S,8 bits */
  186. k^=24; /* change sides back */
  187. --Z;return m+=m<e; /* delayed-loss bonus */
  188. }
  189. void print_board()
  190. {
  191. short N=-1;
  192. W(++N<121)
  193. myputchar(N&8&&(N+=7)?10:".?inkbrq?I?NKBRQ"[b[N]&15]); /* Pawn is i */
  194. }
  195. static void p2(int &x, int &y, const char *c)
  196. {
  197. x = 16 * (32 + 32 * (c[0] - 'a'));
  198. y = 16 * ( 8 + 32 * ('8' - c[1]));
  199. }
  200. #define MOVETIME 10
  201. #define OVERSAMPLE 8
  202. int clocks[2];
  203. void draw_board()
  204. {
  205. // . ? i n k b r q ? I ? N K B R Q
  206. byte xlat[] = { 0, 0, 0, 1, 5, 2, 3, 4, 0, 6, 0, 7, 11,8, 9,10 };
  207. for (int i = 0; i < MOVETIME; i++) {
  208. GD.cmd_gradient(0, 0, 0x101010, 480, 272, 0x202060);
  209. GD.cmd_bgcolor(0x101020);
  210. GD.Begin(BITMAPS);
  211. GD.SaveContext();
  212. GD.ColorRGB(0xfff0c0);
  213. GD.ColorA(0xc0);
  214. GD.cmd_scale(F16(32), F16(32));
  215. GD.cmd_setmatrix();
  216. GD.Vertex2ii(32, 8, 1, 0);
  217. GD.RestoreContext();
  218. int moving = -1;
  219. if (c[0])
  220. moving = 16 * ('8' - c[3]) + (c[2] - 'a');
  221. GD.Begin(BITMAPS);
  222. GD.ColorRGB(0xe0e0e0);
  223. for (int y = 0; y < 8; y++)
  224. for (int x = 0; x < 8; x++) {
  225. int pos = 16 * y + x;
  226. byte piece = b[pos] & 15;
  227. if (pos != moving && piece != 0)
  228. GD.Vertex2ii(32 + 32 * x, 8 + 32 * y, 0, xlat[piece]);
  229. }
  230. if (c[0]) {
  231. GD.Begin(BITMAPS);
  232. byte piece = b[moving] & 15;
  233. GD.Cell(xlat[piece]);
  234. int x0, y0, x1, y1;
  235. p2(x0, y0, c + 0);
  236. p2(x1, y1, c + 2);
  237. GD.ColorRGB(0xffffff); //' a{
  238. GD.ColorA((255 / OVERSAMPLE) + 50);
  239. for (int j = 0; j < OVERSAMPLE; j++) {
  240. byte linear = 255 * (i * OVERSAMPLE + j) /
  241. (OVERSAMPLE * MOVETIME - 1);
  242. byte scurve = sinus(linear);
  243. int x = x0 + (long)(x1 - x0) * scurve / 255;
  244. int y = y0 + (long)(y1 - y0) * scurve / 255;
  245. GD.Vertex2f(x, y);
  246. } //' }a
  247. GD.ColorA(255);
  248. }
  249. GD.ColorRGB((k == 16) ? 0xffffffUL : 0x606060);
  250. GD.cmd_clock(384, 60, 50, OPT_FLAT | OPT_NOSECS, 0, 0, clocks[0], 0);
  251. GD.ColorRGB((k != 16) ? 0xffffffUL : 0x606060);
  252. GD.cmd_clock(384, 272 - 60, 50, OPT_FLAT | OPT_NOSECS, 0, 0, clocks[1], 0);
  253. GD.ColorRGB(0xffffff);
  254. GD.cmd_text(384, 136, 30, OPT_CENTER, c);
  255. GD.swap();
  256. }
  257. }
  258. void loop()
  259. {
  260. #ifdef VERBOSE // JCB{
  261. print_board();
  262. #endif // }JCB
  263. draw_board();
  264. K=I; /* invalid move */
  265. #if 0 // JCB{
  266. p=c;W((*p++=mygetchar())>10); /* read input line */
  267. if(*c-10)K=*c-16*c[1]+799,L=c[2]-16*c[3]+799; /* parse entered move */
  268. #endif // }JCB
  269. N=0;T=0x9; /* T=Computer Play strength */
  270. long t0 = millis();
  271. if(!(D(-I,I,Q,O,1,3)>-I+1)) /* think or check & do*/
  272. for (;;);
  273. int took = 60 * (millis() - t0) / 1000;
  274. clocks[(k==16)] += took;
  275. }