pattern.c 69 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364
  1. /*
  2. * pattern.c: the pattern-reconstruction game known as `nonograms'.
  3. */
  4. #include <stdio.h>
  5. #include <stdlib.h>
  6. #include <string.h>
  7. #include <assert.h>
  8. #include <ctype.h>
  9. #include <limits.h>
  10. #ifdef NO_TGMATH_H
  11. # include <math.h>
  12. #else
  13. # include <tgmath.h>
  14. #endif
  15. #include "puzzles.h"
  16. enum {
  17. COL_BACKGROUND,
  18. COL_EMPTY,
  19. COL_FULL,
  20. COL_TEXT,
  21. COL_UNKNOWN,
  22. COL_GRID,
  23. COL_CURSOR,
  24. COL_ERROR,
  25. COL_CURSOR_GUIDE,
  26. NCOLOURS
  27. };
  28. #define PREFERRED_TILE_SIZE 24
  29. #define TILE_SIZE (ds->tilesize)
  30. #define BORDER (3 * TILE_SIZE / 4)
  31. #define TLBORDER(d) ( (d) / 5 + 2 )
  32. #define GUTTER (TILE_SIZE / 2)
  33. #define FROMCOORD(d, x) \
  34. ( ((x) - (BORDER + GUTTER + TILE_SIZE * TLBORDER(d))) / TILE_SIZE )
  35. #define SIZE(d) (2*BORDER + GUTTER + TILE_SIZE * (TLBORDER(d) + (d)))
  36. #define GETTILESIZE(d, w) ((double)w / (2.0 + (double)TLBORDER(d) + (double)(d)))
  37. #define TOCOORD(d, x) (BORDER + GUTTER + TILE_SIZE * (TLBORDER(d) + (x)))
  38. struct game_params {
  39. int w, h;
  40. };
  41. #define GRID_UNKNOWN 2
  42. #define GRID_FULL 1
  43. #define GRID_EMPTY 0
  44. typedef struct game_state_common {
  45. /* Parts of the game state that don't change during play. */
  46. int w, h;
  47. int rowsize;
  48. int *rowdata, *rowlen;
  49. bool *immutable;
  50. int refcount;
  51. enum { FS_SMALL, FS_LARGE } fontsize;
  52. } game_state_common;
  53. struct game_state {
  54. game_state_common *common;
  55. unsigned char *grid;
  56. bool completed, cheated;
  57. };
  58. #define FLASH_TIME 0.13F
  59. static game_params *default_params(void)
  60. {
  61. game_params *ret = snew(game_params);
  62. ret->w = ret->h = 15;
  63. return ret;
  64. }
  65. static const struct game_params pattern_presets[] = {
  66. {10, 10},
  67. {15, 15},
  68. {20, 20},
  69. #ifndef SLOW_SYSTEM
  70. {25, 25},
  71. {30, 30},
  72. #endif
  73. };
  74. static bool game_fetch_preset(int i, char **name, game_params **params)
  75. {
  76. game_params *ret;
  77. char str[80];
  78. if (i < 0 || i >= lenof(pattern_presets))
  79. return false;
  80. ret = snew(game_params);
  81. *ret = pattern_presets[i];
  82. sprintf(str, "%dx%d", ret->w, ret->h);
  83. *name = dupstr(str);
  84. *params = ret;
  85. return true;
  86. }
  87. static void free_params(game_params *params)
  88. {
  89. sfree(params);
  90. }
  91. static game_params *dup_params(const game_params *params)
  92. {
  93. game_params *ret = snew(game_params);
  94. *ret = *params; /* structure copy */
  95. return ret;
  96. }
  97. static void decode_params(game_params *ret, char const *string)
  98. {
  99. char const *p = string;
  100. ret->w = atoi(p);
  101. while (*p && isdigit((unsigned char)*p)) p++;
  102. if (*p == 'x') {
  103. p++;
  104. ret->h = atoi(p);
  105. while (*p && isdigit((unsigned char)*p)) p++;
  106. } else {
  107. ret->h = ret->w;
  108. }
  109. }
  110. static char *encode_params(const game_params *params, bool full)
  111. {
  112. char ret[400];
  113. int len;
  114. len = sprintf(ret, "%dx%d", params->w, params->h);
  115. assert(len < lenof(ret));
  116. ret[len] = '\0';
  117. return dupstr(ret);
  118. }
  119. static config_item *game_configure(const game_params *params)
  120. {
  121. config_item *ret;
  122. char buf[80];
  123. ret = snewn(3, config_item);
  124. ret[0].name = "Width";
  125. ret[0].type = C_STRING;
  126. sprintf(buf, "%d", params->w);
  127. ret[0].u.string.sval = dupstr(buf);
  128. ret[1].name = "Height";
  129. ret[1].type = C_STRING;
  130. sprintf(buf, "%d", params->h);
  131. ret[1].u.string.sval = dupstr(buf);
  132. ret[2].name = NULL;
  133. ret[2].type = C_END;
  134. return ret;
  135. }
  136. static game_params *custom_params(const config_item *cfg)
  137. {
  138. game_params *ret = snew(game_params);
  139. ret->w = atoi(cfg[0].u.string.sval);
  140. ret->h = atoi(cfg[1].u.string.sval);
  141. return ret;
  142. }
  143. static const char *validate_params(const game_params *params, bool full)
  144. {
  145. if (params->w <= 0 || params->h <= 0)
  146. return "Width and height must both be greater than zero";
  147. if (params->w > INT_MAX - 1 || params->h > INT_MAX - 1 ||
  148. params->w > INT_MAX / params->h)
  149. return "Puzzle must not be unreasonably large";
  150. return NULL;
  151. }
  152. /* ----------------------------------------------------------------------
  153. * Puzzle generation code.
  154. *
  155. * For this particular puzzle, it seemed important to me to ensure
  156. * a unique solution. I do this the brute-force way, by having a
  157. * solver algorithm alongside the generator, and repeatedly
  158. * generating a random grid until I find one whose solution is
  159. * unique. It turns out that this isn't too onerous on a modern PC
  160. * provided you keep grid size below around 30. Any offers of
  161. * better algorithms, however, will be very gratefully received.
  162. *
  163. * Another annoyance of this approach is that it limits the
  164. * available puzzles to those solvable by the algorithm I've used.
  165. * My algorithm only ever considers a single row or column at any
  166. * one time, which means it's incapable of solving the following
  167. * difficult example (found by Bella Image around 1995/6, when she
  168. * and I were both doing maths degrees):
  169. *
  170. * 2 1 2 1
  171. *
  172. * +--+--+--+--+
  173. * 1 1 | | | | |
  174. * +--+--+--+--+
  175. * 2 | | | | |
  176. * +--+--+--+--+
  177. * 1 | | | | |
  178. * +--+--+--+--+
  179. * 1 | | | | |
  180. * +--+--+--+--+
  181. *
  182. * Obviously this cannot be solved by a one-row-or-column-at-a-time
  183. * algorithm (it would require at least one row or column reading
  184. * `2 1', `1 2', `3' or `4' to get started). However, it can be
  185. * proved to have a unique solution: if the top left square were
  186. * empty, then the only option for the top row would be to fill the
  187. * two squares in the 1 columns, which would imply the squares
  188. * below those were empty, leaving no place for the 2 in the second
  189. * row. Contradiction. Hence the top left square is full, and the
  190. * unique solution follows easily from that starting point.
  191. *
  192. * (The game ID for this puzzle is 4x4:2/1/2/1/1.1/2/1/1 , in case
  193. * it's useful to anyone.)
  194. */
  195. #ifndef STANDALONE_PICTURE_GENERATOR
  196. static int float_compare(const void *av, const void *bv)
  197. {
  198. const float *a = (const float *)av;
  199. const float *b = (const float *)bv;
  200. if (*a < *b)
  201. return -1;
  202. else if (*a > *b)
  203. return +1;
  204. else
  205. return 0;
  206. }
  207. static void generate(random_state *rs, int w, int h, unsigned char *retgrid)
  208. {
  209. float *fgrid;
  210. float *fgrid2;
  211. int step, i, j;
  212. float threshold;
  213. fgrid = snewn(w*h, float);
  214. for (i = 0; i < h; i++) {
  215. for (j = 0; j < w; j++) {
  216. fgrid[i*w+j] = random_upto(rs, 100000000UL) / 100000000.F;
  217. }
  218. }
  219. /*
  220. * The above gives a completely random splattering of black and
  221. * white cells. We want to gently bias this in favour of _some_
  222. * reasonably thick areas of white and black, while retaining
  223. * some randomness and fine detail.
  224. *
  225. * So we evolve the starting grid using a cellular automaton.
  226. * Currently, I'm doing something very simple indeed, which is
  227. * to set each square to the average of the surrounding nine
  228. * cells (or the average of fewer, if we're on a corner).
  229. */
  230. for (step = 0; step < 1; step++) {
  231. fgrid2 = snewn(w*h, float);
  232. for (i = 0; i < h; i++) {
  233. for (j = 0; j < w; j++) {
  234. float sx, xbar;
  235. int n, p, q;
  236. /*
  237. * Compute the average of the surrounding cells.
  238. */
  239. n = 0;
  240. sx = 0.F;
  241. for (p = -1; p <= +1; p++) {
  242. for (q = -1; q <= +1; q++) {
  243. if (i+p < 0 || i+p >= h || j+q < 0 || j+q >= w)
  244. continue;
  245. /*
  246. * An additional special case not mentioned
  247. * above: if a grid dimension is 2xn then
  248. * we do not average across that dimension
  249. * at all. Otherwise a 2x2 grid would
  250. * contain four identical squares.
  251. */
  252. if ((h==2 && p!=0) || (w==2 && q!=0))
  253. continue;
  254. n++;
  255. sx += fgrid[(i+p)*w+(j+q)];
  256. }
  257. }
  258. xbar = sx / n;
  259. fgrid2[i*w+j] = xbar;
  260. }
  261. }
  262. sfree(fgrid);
  263. fgrid = fgrid2;
  264. }
  265. fgrid2 = snewn(w*h, float);
  266. memcpy(fgrid2, fgrid, w*h*sizeof(float));
  267. qsort(fgrid2, w*h, sizeof(float), float_compare);
  268. /* Choose a threshold that makes half the pixels black. In case of
  269. * an odd number of pixels, select randomly between just under and
  270. * just over half. */
  271. {
  272. int index = w * h / 2;
  273. if (w & h & 1)
  274. index += random_upto(rs, 2);
  275. if (index < w*h)
  276. threshold = fgrid2[index];
  277. else
  278. threshold = fgrid2[w*h-1] + 1;
  279. }
  280. sfree(fgrid2);
  281. for (i = 0; i < h; i++) {
  282. for (j = 0; j < w; j++) {
  283. retgrid[i*w+j] = (fgrid[i*w+j] >= threshold ? GRID_FULL :
  284. GRID_EMPTY);
  285. }
  286. }
  287. sfree(fgrid);
  288. }
  289. #endif
  290. static int compute_rowdata(int *ret, unsigned char *start, int len, int step)
  291. {
  292. int i, n;
  293. n = 0;
  294. for (i = 0; i < len; i++) {
  295. if (start[i*step] == GRID_FULL) {
  296. int runlen = 1;
  297. while (i+runlen < len && start[(i+runlen)*step] == GRID_FULL)
  298. runlen++;
  299. ret[n++] = runlen;
  300. i += runlen;
  301. }
  302. if (i < len && start[i*step] == GRID_UNKNOWN)
  303. return -1;
  304. }
  305. return n;
  306. }
  307. #define UNKNOWN 0
  308. #define BLOCK 1
  309. #define DOT 2
  310. #define STILL_UNKNOWN 3
  311. #ifdef STANDALONE_SOLVER
  312. static bool verbose = false;
  313. #endif
  314. static bool do_recurse(unsigned char *known, unsigned char *deduced,
  315. unsigned char *row,
  316. unsigned char *minpos_done, unsigned char *maxpos_done,
  317. unsigned char *minpos_ok, unsigned char *maxpos_ok,
  318. int *data, int len,
  319. int freespace, int ndone, int lowest)
  320. {
  321. int i, j, k;
  322. /* This algorithm basically tries all possible ways the given rows of
  323. * black blocks can be laid out in the row/column being examined.
  324. * Special care is taken to avoid checking the tail of a row/column
  325. * if the same conditions have already been checked during this recursion
  326. * The algorithm also takes care to cut its losses as soon as an
  327. * invalid (partial) solution is detected.
  328. */
  329. if (data[ndone]) {
  330. if (lowest >= minpos_done[ndone] && lowest <= maxpos_done[ndone]) {
  331. if (lowest >= minpos_ok[ndone] && lowest <= maxpos_ok[ndone]) {
  332. for (i=0; i<lowest; i++)
  333. deduced[i] |= row[i];
  334. }
  335. return lowest >= minpos_ok[ndone] && lowest <= maxpos_ok[ndone];
  336. } else {
  337. if (lowest < minpos_done[ndone]) minpos_done[ndone] = lowest;
  338. if (lowest > maxpos_done[ndone]) maxpos_done[ndone] = lowest;
  339. }
  340. for (i=0; i<=freespace; i++) {
  341. j = lowest;
  342. for (k=0; k<i; k++) {
  343. if (known[j] == BLOCK) goto next_iter;
  344. row[j++] = DOT;
  345. }
  346. for (k=0; k<data[ndone]; k++) {
  347. if (known[j] == DOT) goto next_iter;
  348. row[j++] = BLOCK;
  349. }
  350. if (j < len) {
  351. if (known[j] == BLOCK) goto next_iter;
  352. row[j++] = DOT;
  353. }
  354. if (do_recurse(known, deduced, row, minpos_done, maxpos_done,
  355. minpos_ok, maxpos_ok, data, len, freespace-i, ndone+1, j)) {
  356. if (lowest < minpos_ok[ndone]) minpos_ok[ndone] = lowest;
  357. if (lowest + i > maxpos_ok[ndone]) maxpos_ok[ndone] = lowest + i;
  358. if (lowest + i > maxpos_done[ndone]) maxpos_done[ndone] = lowest + i;
  359. }
  360. next_iter:
  361. j++;
  362. }
  363. return lowest >= minpos_ok[ndone] && lowest <= maxpos_ok[ndone];
  364. } else {
  365. for (i=lowest; i<len; i++) {
  366. if (known[i] == BLOCK) return false;
  367. row[i] = DOT;
  368. }
  369. for (i=0; i<len; i++)
  370. deduced[i] |= row[i];
  371. return true;
  372. }
  373. }
  374. static bool do_row(unsigned char *known, unsigned char *deduced,
  375. unsigned char *row,
  376. unsigned char *minpos_done, unsigned char *maxpos_done,
  377. unsigned char *minpos_ok, unsigned char *maxpos_ok,
  378. unsigned char *start, int len, int step, int *data,
  379. unsigned int *changed
  380. #ifdef STANDALONE_SOLVER
  381. , const char *rowcol, int index, int cluewid
  382. #endif
  383. )
  384. {
  385. int rowlen, i, freespace;
  386. bool done_any;
  387. assert(len >= 0); /* avoid compile warnings about the memsets below */
  388. freespace = len+1;
  389. for (rowlen = 0; data[rowlen]; rowlen++) {
  390. minpos_done[rowlen] = minpos_ok[rowlen] = len - 1;
  391. maxpos_done[rowlen] = maxpos_ok[rowlen] = 0;
  392. freespace -= data[rowlen]+1;
  393. }
  394. for (i = 0; i < len; i++) {
  395. known[i] = start[i*step];
  396. deduced[i] = 0;
  397. }
  398. for (i = len - 1; i >= 0 && known[i] == DOT; i--)
  399. freespace--;
  400. if (rowlen == 0) {
  401. memset(deduced, DOT, len);
  402. } else if (rowlen == 1 && data[0] == len) {
  403. memset(deduced, BLOCK, len);
  404. } else {
  405. do_recurse(known, deduced, row, minpos_done, maxpos_done, minpos_ok,
  406. maxpos_ok, data, len, freespace, 0, 0);
  407. }
  408. done_any = false;
  409. for (i=0; i<len; i++)
  410. if (deduced[i] && deduced[i] != STILL_UNKNOWN && !known[i]) {
  411. start[i*step] = deduced[i];
  412. if (changed) changed[i]++;
  413. done_any = true;
  414. }
  415. #ifdef STANDALONE_SOLVER
  416. if (verbose && done_any) {
  417. char buf[80];
  418. int thiscluewid;
  419. printf("%s %2d: [", rowcol, index);
  420. for (thiscluewid = -1, i = 0; data[i]; i++)
  421. thiscluewid += sprintf(buf, " %d", data[i]);
  422. printf("%*s", cluewid - thiscluewid, "");
  423. for (i = 0; data[i]; i++)
  424. printf(" %d", data[i]);
  425. printf(" ] ");
  426. for (i = 0; i < len; i++)
  427. putchar(known[i] == BLOCK ? '#' :
  428. known[i] == DOT ? '.' : '?');
  429. printf(" -> ");
  430. for (i = 0; i < len; i++)
  431. putchar(start[i*step] == BLOCK ? '#' :
  432. start[i*step] == DOT ? '.' : '?');
  433. putchar('\n');
  434. }
  435. #endif
  436. return done_any;
  437. }
  438. static bool solve_puzzle(const game_state *state, unsigned char *grid,
  439. int w, int h,
  440. unsigned char *matrix, unsigned char *workspace,
  441. unsigned int *changed_h, unsigned int *changed_w,
  442. int *rowdata
  443. #ifdef STANDALONE_SOLVER
  444. , int cluewid
  445. #else
  446. , int dummy
  447. #endif
  448. )
  449. {
  450. int i, j, max;
  451. bool ok;
  452. int max_h, max_w;
  453. assert((state!=NULL && state->common->rowdata!=NULL) ^ (grid!=NULL));
  454. max = max(w, h);
  455. memset(matrix, 0, w*h);
  456. if (state) {
  457. for (i=0; i<w*h; i++) {
  458. if (state->common->immutable[i])
  459. matrix[i] = state->grid[i];
  460. }
  461. }
  462. /* For each column, compute how many squares can be deduced
  463. * from just the row-data and initial clues.
  464. * Later, changed_* will hold how many squares were changed
  465. * in every row/column in the previous iteration
  466. * Changed_* is used to choose the next rows / cols to re-examine
  467. */
  468. for (i=0; i<h; i++) {
  469. int freespace, rowlen;
  470. if (state && state->common->rowdata) {
  471. memcpy(rowdata, state->common->rowdata + state->common->rowsize*(w+i), max*sizeof(int));
  472. rowlen = state->common->rowlen[w+i];
  473. } else {
  474. rowlen = compute_rowdata(rowdata, grid+i*w, w, 1);
  475. }
  476. rowdata[rowlen] = 0;
  477. if (rowlen == 0) {
  478. changed_h[i] = w;
  479. } else {
  480. for (j=0, freespace=w+1; rowdata[j]; j++)
  481. freespace -= rowdata[j] + 1;
  482. for (j=0, changed_h[i]=0; rowdata[j]; j++)
  483. if (rowdata[j] > freespace)
  484. changed_h[i] += rowdata[j] - freespace;
  485. }
  486. for (j = 0; j < w; j++)
  487. if (matrix[i*w+j])
  488. changed_h[i]++;
  489. }
  490. for (i=0,max_h=0; i<h; i++)
  491. if (changed_h[i] > max_h)
  492. max_h = changed_h[i];
  493. for (i=0; i<w; i++) {
  494. int freespace, rowlen;
  495. if (state && state->common->rowdata) {
  496. memcpy(rowdata, state->common->rowdata + state->common->rowsize*i, max*sizeof(int));
  497. rowlen = state->common->rowlen[i];
  498. } else {
  499. rowlen = compute_rowdata(rowdata, grid+i, h, w);
  500. }
  501. rowdata[rowlen] = 0;
  502. if (rowlen == 0) {
  503. changed_w[i] = h;
  504. } else {
  505. for (j=0, freespace=h+1; rowdata[j]; j++)
  506. freespace -= rowdata[j] + 1;
  507. for (j=0, changed_w[i]=0; rowdata[j]; j++)
  508. if (rowdata[j] > freespace)
  509. changed_w[i] += rowdata[j] - freespace;
  510. }
  511. for (j = 0; j < h; j++)
  512. if (matrix[j*w+i])
  513. changed_w[i]++;
  514. }
  515. for (i=0,max_w=0; i<w; i++)
  516. if (changed_w[i] > max_w)
  517. max_w = changed_w[i];
  518. /* Solve the puzzle.
  519. * Process rows/columns individually. Deductions involving more than one
  520. * row and/or column at a time are not supported.
  521. * Take care to only process rows/columns which have been changed since they
  522. * were previously processed.
  523. * Also, prioritize rows/columns which have had the most changes since their
  524. * previous processing, as they promise the greatest benefit.
  525. * Extremely rectangular grids (e.g. 10x20, 15x40, etc.) are not treated specially.
  526. */
  527. do {
  528. for (; max_h && max_h >= max_w; max_h--) {
  529. for (i=0; i<h; i++) {
  530. if (changed_h[i] >= max_h) {
  531. if (state && state->common->rowdata) {
  532. memcpy(rowdata, state->common->rowdata + state->common->rowsize*(w+i), max*sizeof(int));
  533. rowdata[state->common->rowlen[w+i]] = 0;
  534. } else {
  535. rowdata[compute_rowdata(rowdata, grid+i*w, w, 1)] = 0;
  536. }
  537. do_row(workspace, workspace+max, workspace+2*max,
  538. workspace+3*max, workspace+4*max,
  539. workspace+5*max, workspace+6*max,
  540. matrix+i*w, w, 1, rowdata, changed_w
  541. #ifdef STANDALONE_SOLVER
  542. , "row", i+1, cluewid
  543. #endif
  544. );
  545. changed_h[i] = 0;
  546. }
  547. }
  548. for (i=0,max_w=0; i<w; i++)
  549. if (changed_w[i] > max_w)
  550. max_w = changed_w[i];
  551. }
  552. for (; max_w && max_w >= max_h; max_w--) {
  553. for (i=0; i<w; i++) {
  554. if (changed_w[i] >= max_w) {
  555. if (state && state->common->rowdata) {
  556. memcpy(rowdata, state->common->rowdata + state->common->rowsize*i, max*sizeof(int));
  557. rowdata[state->common->rowlen[i]] = 0;
  558. } else {
  559. rowdata[compute_rowdata(rowdata, grid+i, h, w)] = 0;
  560. }
  561. do_row(workspace, workspace+max, workspace+2*max,
  562. workspace+3*max, workspace+4*max,
  563. workspace+5*max, workspace+6*max,
  564. matrix+i, h, w, rowdata, changed_h
  565. #ifdef STANDALONE_SOLVER
  566. , "col", i+1, cluewid
  567. #endif
  568. );
  569. changed_w[i] = 0;
  570. }
  571. }
  572. for (i=0,max_h=0; i<h; i++)
  573. if (changed_h[i] > max_h)
  574. max_h = changed_h[i];
  575. }
  576. } while (max_h>0 || max_w>0);
  577. ok = true;
  578. for (i=0; i<h; i++) {
  579. for (j=0; j<w; j++) {
  580. if (matrix[i*w+j] == UNKNOWN)
  581. ok = false;
  582. }
  583. }
  584. return ok;
  585. }
  586. #ifndef STANDALONE_PICTURE_GENERATOR
  587. static unsigned char *generate_soluble(random_state *rs, int w, int h)
  588. {
  589. int i, j, max;
  590. bool ok;
  591. unsigned char *grid, *matrix, *workspace;
  592. unsigned int *changed_h, *changed_w;
  593. int *rowdata;
  594. max = max(w, h);
  595. grid = snewn(w*h, unsigned char);
  596. /* Allocate this here, to avoid having to reallocate it again for every geneerated grid */
  597. matrix = snewn(w*h, unsigned char);
  598. workspace = snewn(max*7, unsigned char);
  599. changed_h = snewn(max+1, unsigned int);
  600. changed_w = snewn(max+1, unsigned int);
  601. rowdata = snewn(max+1, int);
  602. do {
  603. generate(rs, w, h, grid);
  604. /*
  605. * The game is a bit too easy if any row or column is
  606. * completely black or completely white. An exception is
  607. * made for rows/columns that are under 3 squares,
  608. * otherwise nothing will ever be successfully generated.
  609. */
  610. ok = true;
  611. if (w > 2) {
  612. for (i = 0; i < h; i++) {
  613. int colours = 0;
  614. for (j = 0; j < w; j++)
  615. colours |= (grid[i*w+j] == GRID_FULL ? 2 : 1);
  616. if (colours != 3)
  617. ok = false;
  618. }
  619. }
  620. if (h > 2) {
  621. for (j = 0; j < w; j++) {
  622. int colours = 0;
  623. for (i = 0; i < h; i++)
  624. colours |= (grid[i*w+j] == GRID_FULL ? 2 : 1);
  625. if (colours != 3)
  626. ok = false;
  627. }
  628. }
  629. if (!ok)
  630. continue;
  631. ok = solve_puzzle(NULL, grid, w, h, matrix, workspace,
  632. changed_h, changed_w, rowdata, 0);
  633. } while (!ok);
  634. sfree(matrix);
  635. sfree(workspace);
  636. sfree(changed_h);
  637. sfree(changed_w);
  638. sfree(rowdata);
  639. return grid;
  640. }
  641. #endif
  642. #ifdef STANDALONE_PICTURE_GENERATOR
  643. static unsigned char *picture;
  644. #endif
  645. static char *new_game_desc(const game_params *params, random_state *rs,
  646. char **aux, bool interactive)
  647. {
  648. unsigned char *grid;
  649. int i, j, max, rowlen, *rowdata;
  650. char intbuf[80], *desc;
  651. int desclen, descpos;
  652. #ifdef STANDALONE_PICTURE_GENERATOR
  653. game_state *state;
  654. int *index;
  655. #endif
  656. max = max(params->w, params->h);
  657. #ifdef STANDALONE_PICTURE_GENERATOR
  658. /*
  659. * Fixed input picture.
  660. */
  661. grid = snewn(params->w * params->h, unsigned char);
  662. memcpy(grid, picture, params->w * params->h);
  663. /*
  664. * Now winnow the immutable square set as far as possible.
  665. */
  666. state = snew(game_state);
  667. state->grid = grid;
  668. state->common = snew(game_state_common);
  669. state->common->rowdata = NULL;
  670. state->common->immutable = snewn(params->w * params->h, bool);
  671. for (i = 0; i < params->w * params->h; i++)
  672. state->common->immutable[i] = true;
  673. index = snewn(params->w * params->h, int);
  674. for (i = 0; i < params->w * params->h; i++)
  675. index[i] = i;
  676. shuffle(index, params->w * params->h, sizeof(*index), rs);
  677. {
  678. unsigned char *matrix = snewn(params->w*params->h, unsigned char);
  679. unsigned char *workspace = snewn(max*7, unsigned char);
  680. unsigned int *changed_h = snewn(max+1, unsigned int);
  681. unsigned int *changed_w = snewn(max+1, unsigned int);
  682. int *rowdata = snewn(max+1, int);
  683. for (i = 0; i < params->w * params->h; i++) {
  684. state->common->immutable[index[i]] = false;
  685. if (!solve_puzzle(state, grid, params->w, params->h,
  686. matrix, workspace, changed_h, changed_w,
  687. rowdata, 0))
  688. state->common->immutable[index[i]] = true;
  689. }
  690. sfree(workspace);
  691. sfree(changed_h);
  692. sfree(changed_w);
  693. sfree(rowdata);
  694. sfree(matrix);
  695. }
  696. #else
  697. grid = generate_soluble(rs, params->w, params->h);
  698. #endif
  699. rowdata = snewn(max, int);
  700. /*
  701. * Save the solved game in aux.
  702. */
  703. if (aux) {
  704. char *ai = snewn(params->w * params->h + 2, char);
  705. /*
  706. * String format is exactly the same as a solve move, so we
  707. * can just dupstr this in solve_game().
  708. */
  709. ai[0] = 'S';
  710. for (i = 0; i < params->w * params->h; i++)
  711. ai[i+1] = grid[i] ? '1' : '0';
  712. ai[params->w * params->h + 1] = '\0';
  713. *aux = ai;
  714. }
  715. /*
  716. * Seed is a slash-separated list of row contents; each row
  717. * contents section is a dot-separated list of integers. Row
  718. * contents are listed in the order (columns left to right,
  719. * then rows top to bottom).
  720. *
  721. * Simplest way to handle memory allocation is to make two
  722. * passes, first computing the seed size and then writing it
  723. * out.
  724. */
  725. desclen = 0;
  726. for (i = 0; i < params->w + params->h; i++) {
  727. if (i < params->w)
  728. rowlen = compute_rowdata(rowdata, grid+i, params->h, params->w);
  729. else
  730. rowlen = compute_rowdata(rowdata, grid+(i-params->w)*params->w,
  731. params->w, 1);
  732. if (rowlen > 0) {
  733. for (j = 0; j < rowlen; j++) {
  734. desclen += 1 + sprintf(intbuf, "%d", rowdata[j]);
  735. }
  736. } else {
  737. desclen++;
  738. }
  739. }
  740. desc = snewn(desclen, char);
  741. descpos = 0;
  742. for (i = 0; i < params->w + params->h; i++) {
  743. if (i < params->w)
  744. rowlen = compute_rowdata(rowdata, grid+i, params->h, params->w);
  745. else
  746. rowlen = compute_rowdata(rowdata, grid+(i-params->w)*params->w,
  747. params->w, 1);
  748. if (rowlen > 0) {
  749. for (j = 0; j < rowlen; j++) {
  750. int len = sprintf(desc+descpos, "%d", rowdata[j]);
  751. if (j+1 < rowlen)
  752. desc[descpos + len] = '.';
  753. else
  754. desc[descpos + len] = '/';
  755. descpos += len+1;
  756. }
  757. } else {
  758. desc[descpos++] = '/';
  759. }
  760. }
  761. assert(descpos == desclen);
  762. assert(desc[desclen-1] == '/');
  763. desc[desclen-1] = '\0';
  764. #ifdef STANDALONE_PICTURE_GENERATOR
  765. for (i = 0; i < params->w * params->h; i++)
  766. if (state->common->immutable[i])
  767. break;
  768. if (i < params->w * params->h) {
  769. /*
  770. * At least one immutable square, so we need a suffix.
  771. */
  772. int run;
  773. desc = sresize(desc, desclen + params->w * params->h + 3, char);
  774. desc[descpos-1] = ',';
  775. run = 0;
  776. for (i = 0; i < params->w * params->h; i++) {
  777. if (!state->common->immutable[i]) {
  778. run++;
  779. if (run == 25) {
  780. desc[descpos++] = 'z';
  781. run = 0;
  782. }
  783. } else {
  784. desc[descpos++] = run + (grid[i] == GRID_FULL ? 'A' : 'a');
  785. run = 0;
  786. }
  787. }
  788. if (run > 0)
  789. desc[descpos++] = run + 'a';
  790. desc[descpos] = '\0';
  791. }
  792. sfree(state->common->immutable);
  793. sfree(state->common);
  794. sfree(state);
  795. #endif
  796. sfree(rowdata);
  797. sfree(grid);
  798. return desc;
  799. }
  800. static const char *validate_desc(const game_params *params, const char *desc)
  801. {
  802. int i, n, rowspace;
  803. const char *p;
  804. for (i = 0; i < params->w + params->h; i++) {
  805. if (i < params->w)
  806. rowspace = params->h + 1;
  807. else
  808. rowspace = params->w + 1;
  809. if (*desc && isdigit((unsigned char)*desc)) {
  810. do {
  811. p = desc;
  812. while (*desc && isdigit((unsigned char)*desc)) desc++;
  813. n = atoi(p);
  814. if (n <= 0)
  815. return "all clues must be positive";
  816. if (n > INT_MAX - 1)
  817. return "at least one clue is grossly excessive";
  818. rowspace -= n+1;
  819. if (rowspace < 0) {
  820. if (i < params->w)
  821. return "at least one column contains more numbers than will fit";
  822. else
  823. return "at least one row contains more numbers than will fit";
  824. }
  825. } while (*desc++ == '.');
  826. } else {
  827. desc++; /* expect a slash immediately */
  828. }
  829. if (desc[-1] == '/') {
  830. if (i+1 == params->w + params->h)
  831. return "too many row/column specifications";
  832. } else if (desc[-1] == '\0' || desc[-1] == ',') {
  833. if (i+1 < params->w + params->h)
  834. return "too few row/column specifications";
  835. } else
  836. return "unrecognised character in game specification";
  837. }
  838. if (desc[-1] == ',') {
  839. /*
  840. * Optional extra piece of game description which fills in
  841. * some grid squares as extra clues.
  842. */
  843. i = 0;
  844. while (i < params->w * params->h) {
  845. int c = (unsigned char)*desc++;
  846. if ((c >= 'a' && c <= 'z') ||
  847. (c >= 'A' && c <= 'Z')) {
  848. int len = tolower(c) - 'a';
  849. i += len;
  850. if (len < 25 && i < params->w*params->h)
  851. i++;
  852. if (i > params->w * params->h) {
  853. return "too much data in clue-squares section";
  854. }
  855. } else if (!c) {
  856. return "too little data in clue-squares section";
  857. } else {
  858. return "unrecognised character in clue-squares section";
  859. }
  860. }
  861. if (*desc) {
  862. return "too much data in clue-squares section";
  863. }
  864. }
  865. return NULL;
  866. }
  867. static game_state *new_game(midend *me, const game_params *params,
  868. const char *desc)
  869. {
  870. int i, j;
  871. const char *p;
  872. game_state *state = snew(game_state);
  873. state->common = snew(game_state_common);
  874. state->common->refcount = 1;
  875. state->common->w = params->w;
  876. state->common->h = params->h;
  877. state->grid = snewn(state->common->w * state->common->h, unsigned char);
  878. memset(state->grid, GRID_UNKNOWN, state->common->w * state->common->h);
  879. state->common->immutable = snewn(state->common->w * state->common->h,
  880. bool);
  881. memset(state->common->immutable, 0,
  882. state->common->w * state->common->h * sizeof(bool));
  883. state->common->rowsize = max(state->common->w, state->common->h);
  884. state->common->rowdata = snewn(state->common->rowsize * (state->common->w + state->common->h), int);
  885. state->common->rowlen = snewn(state->common->w + state->common->h, int);
  886. state->completed = state->cheated = false;
  887. for (i = 0; i < params->w + params->h; i++) {
  888. state->common->rowlen[i] = 0;
  889. if (*desc && isdigit((unsigned char)*desc)) {
  890. do {
  891. p = desc;
  892. while (*desc && isdigit((unsigned char)*desc)) desc++;
  893. state->common->rowdata[state->common->rowsize * i + state->common->rowlen[i]++] =
  894. atoi(p);
  895. } while (*desc++ == '.');
  896. } else {
  897. desc++; /* expect a slash immediately */
  898. }
  899. }
  900. /*
  901. * Choose a font size based on the clues. If any column clue is
  902. * more than one digit, switch to the smaller size.
  903. */
  904. state->common->fontsize = FS_LARGE;
  905. for (i = 0; i < params->w; i++)
  906. for (j = 0; j < state->common->rowlen[i]; j++)
  907. if (state->common->rowdata[state->common->rowsize * i + j] >= 10)
  908. state->common->fontsize = FS_SMALL;
  909. /*
  910. * We might also need to use the small font if there are lots of
  911. * row clues. We assume that all clues are one digit and that a
  912. * single-digit clue takes up 1.5 tiles, of which the clue is 0.5
  913. * tiles and the space is 1.0 tiles.
  914. */
  915. for (i = params->w; i < params->w + params->h; i++)
  916. if ((state->common->rowlen[i] * 3 - 2) >
  917. TLBORDER(state->common->w) * 2)
  918. state->common->fontsize = FS_SMALL;
  919. if (desc[-1] == ',') {
  920. /*
  921. * Optional extra piece of game description which fills in
  922. * some grid squares as extra clues.
  923. */
  924. i = 0;
  925. while (i < params->w * params->h) {
  926. int c = (unsigned char)*desc++;
  927. bool full = isupper(c);
  928. int len = tolower(c) - 'a';
  929. i += len;
  930. if (len < 25 && i < params->w*params->h) {
  931. state->grid[i] = full ? GRID_FULL : GRID_EMPTY;
  932. state->common->immutable[i] = true;
  933. i++;
  934. }
  935. }
  936. }
  937. return state;
  938. }
  939. static game_state *dup_game(const game_state *state)
  940. {
  941. game_state *ret = snew(game_state);
  942. ret->common = state->common;
  943. ret->common->refcount++;
  944. ret->grid = snewn(ret->common->w * ret->common->h, unsigned char);
  945. memcpy(ret->grid, state->grid, ret->common->w * ret->common->h);
  946. ret->completed = state->completed;
  947. ret->cheated = state->cheated;
  948. return ret;
  949. }
  950. static void free_game(game_state *state)
  951. {
  952. if (--state->common->refcount == 0) {
  953. sfree(state->common->rowdata);
  954. sfree(state->common->rowlen);
  955. sfree(state->common->immutable);
  956. sfree(state->common);
  957. }
  958. sfree(state->grid);
  959. sfree(state);
  960. }
  961. static char *solve_game(const game_state *state, const game_state *currstate,
  962. const char *ai, const char **error)
  963. {
  964. unsigned char *matrix;
  965. int w = state->common->w, h = state->common->h;
  966. int i;
  967. char *ret;
  968. int max;
  969. bool ok;
  970. unsigned char *workspace;
  971. unsigned int *changed_h, *changed_w;
  972. int *rowdata;
  973. /*
  974. * If we already have the solved state in ai, copy it out.
  975. */
  976. if (ai)
  977. return dupstr(ai);
  978. max = max(w, h);
  979. matrix = snewn(w*h, unsigned char);
  980. workspace = snewn(max*7, unsigned char);
  981. changed_h = snewn(max+1, unsigned int);
  982. changed_w = snewn(max+1, unsigned int);
  983. rowdata = snewn(max+1, int);
  984. ok = solve_puzzle(state, NULL, w, h, matrix, workspace,
  985. changed_h, changed_w, rowdata, 0);
  986. sfree(workspace);
  987. sfree(changed_h);
  988. sfree(changed_w);
  989. sfree(rowdata);
  990. if (!ok) {
  991. sfree(matrix);
  992. *error = "Solving algorithm cannot complete this puzzle";
  993. return NULL;
  994. }
  995. ret = snewn(w*h+2, char);
  996. ret[0] = 'S';
  997. for (i = 0; i < w*h; i++) {
  998. assert(matrix[i] == BLOCK || matrix[i] == DOT);
  999. ret[i+1] = (matrix[i] == BLOCK ? '1' : '0');
  1000. }
  1001. ret[w*h+1] = '\0';
  1002. sfree(matrix);
  1003. return ret;
  1004. }
  1005. static bool game_can_format_as_text_now(const game_params *params)
  1006. {
  1007. return true;
  1008. }
  1009. static char *game_text_format(const game_state *state)
  1010. {
  1011. int w = state->common->w, h = state->common->h, i, j;
  1012. int left_gap = 0, top_gap = 0, ch = 2, cw = 1, limit = 1;
  1013. int len, topleft, lw, lh, gw, gh; /* {line,grid}_{width,height} */
  1014. char *board, *buf;
  1015. for (i = 0; i < w; ++i) {
  1016. top_gap = max(top_gap, state->common->rowlen[i]);
  1017. for (j = 0; j < state->common->rowlen[i]; ++j)
  1018. while (state->common->rowdata[i*state->common->rowsize + j] >= limit) {
  1019. ++cw;
  1020. limit *= 10;
  1021. }
  1022. }
  1023. for (i = 0; i < h; ++i) {
  1024. int rowlen = 0;
  1025. bool predecessors = false;
  1026. for (j = 0; j < state->common->rowlen[i+w]; ++j) {
  1027. int copy = state->common->rowdata[(i+w)*state->common->rowsize + j];
  1028. rowlen += predecessors;
  1029. predecessors = true;
  1030. do ++rowlen; while (copy /= 10);
  1031. }
  1032. left_gap = max(left_gap, rowlen);
  1033. }
  1034. cw = max(cw, 3);
  1035. gw = w*cw + 2;
  1036. gh = h*ch + 1;
  1037. lw = gw + left_gap;
  1038. lh = gh + top_gap;
  1039. len = lw * lh;
  1040. topleft = lw * top_gap + left_gap;
  1041. board = snewn(len + 1, char);
  1042. sprintf(board, "%*s\n", len - 2, "");
  1043. for (i = 0; i < lh; ++i) {
  1044. board[lw - 1 + i*lw] = '\n';
  1045. if (i < top_gap) continue;
  1046. board[lw - 2 + i*lw] = ((i - top_gap) % ch ? '|' : '+');
  1047. }
  1048. for (i = 0; i < w; ++i) {
  1049. for (j = 0; j < state->common->rowlen[i]; ++j) {
  1050. int cell = topleft + i*cw + 1 + lw*(j - state->common->rowlen[i]);
  1051. int nch = sprintf(board + cell, "%*d", cw - 1,
  1052. state->common->rowdata[i*state->common->rowsize + j]);
  1053. board[cell + nch] = ' '; /* de-NUL-ify */
  1054. }
  1055. }
  1056. buf = snewn(left_gap, char);
  1057. for (i = 0; i < h; ++i) {
  1058. char *p = buf, *start = board + top_gap*lw + left_gap + (i*ch+1)*lw;
  1059. for (j = 0; j < state->common->rowlen[i+w]; ++j) {
  1060. if (p > buf) *p++ = ' ';
  1061. p += sprintf(p, "%d", state->common->rowdata[(i+w)*state->common->rowsize + j]);
  1062. }
  1063. memcpy(start - (p - buf), buf, p - buf);
  1064. }
  1065. for (i = 0; i < w; ++i) {
  1066. for (j = 0; j < h; ++j) {
  1067. int cell = topleft + i*cw + j*ch*lw;
  1068. int center = cell + cw/2 + (ch/2)*lw;
  1069. int dx, dy;
  1070. board[cell] = false ? center : '+';
  1071. for (dx = 1; dx < cw; ++dx) board[cell + dx] = '-';
  1072. for (dy = 1; dy < ch; ++dy) board[cell + dy*lw] = '|';
  1073. if (state->grid[i*w+j] == GRID_UNKNOWN) continue;
  1074. for (dx = 1; dx < cw; ++dx)
  1075. for (dy = 1; dy < ch; ++dy)
  1076. board[cell + dx + dy*lw] =
  1077. state->grid[i*w+j] == GRID_FULL ? '#' : '.';
  1078. }
  1079. }
  1080. memcpy(board + topleft + h*ch*lw, board + topleft, gw - 1);
  1081. sfree(buf);
  1082. return board;
  1083. }
  1084. struct game_ui {
  1085. bool dragging;
  1086. int drag_start_x;
  1087. int drag_start_y;
  1088. int drag_end_x;
  1089. int drag_end_y;
  1090. int drag, release, state;
  1091. int cur_x, cur_y;
  1092. bool cur_visible;
  1093. };
  1094. static game_ui *new_ui(const game_state *state)
  1095. {
  1096. game_ui *ret;
  1097. ret = snew(game_ui);
  1098. ret->dragging = false;
  1099. ret->cur_x = ret->cur_y = 0;
  1100. ret->cur_visible = getenv_bool("PUZZLES_SHOW_CURSOR", false);
  1101. return ret;
  1102. }
  1103. static void free_ui(game_ui *ui)
  1104. {
  1105. sfree(ui);
  1106. }
  1107. static void game_changed_state(game_ui *ui, const game_state *oldstate,
  1108. const game_state *newstate)
  1109. {
  1110. }
  1111. static const char *current_key_label(const game_ui *ui,
  1112. const game_state *state, int button)
  1113. {
  1114. if (IS_CURSOR_SELECT(button)) {
  1115. if (!ui->cur_visible) return "";
  1116. switch (state->grid[ui->cur_y * state->common->w + ui->cur_x]) {
  1117. case GRID_UNKNOWN:
  1118. return button == CURSOR_SELECT ? "Black" : "White";
  1119. case GRID_FULL:
  1120. return button == CURSOR_SELECT ? "White" : "Grey";
  1121. case GRID_EMPTY:
  1122. return button == CURSOR_SELECT ? "Grey" : "Black";
  1123. }
  1124. }
  1125. return "";
  1126. }
  1127. struct game_drawstate {
  1128. bool started;
  1129. int w, h;
  1130. int tilesize;
  1131. unsigned char *visible, *numcolours;
  1132. int cur_x, cur_y;
  1133. char *strbuf; /* Used for formatting clues. */
  1134. };
  1135. static char *interpret_move(const game_state *state, game_ui *ui,
  1136. const game_drawstate *ds,
  1137. int x, int y, int button)
  1138. {
  1139. bool control = button & MOD_CTRL, shift = button & MOD_SHFT;
  1140. button &= ~MOD_MASK;
  1141. x = FROMCOORD(state->common->w, x);
  1142. y = FROMCOORD(state->common->h, y);
  1143. if (x >= 0 && x < state->common->w && y >= 0 && y < state->common->h &&
  1144. (button == LEFT_BUTTON || button == RIGHT_BUTTON ||
  1145. button == MIDDLE_BUTTON)) {
  1146. #ifdef STYLUS_BASED
  1147. int currstate = state->grid[y * state->common->w + x];
  1148. #endif
  1149. ui->dragging = true;
  1150. if (button == LEFT_BUTTON) {
  1151. ui->drag = LEFT_DRAG;
  1152. ui->release = LEFT_RELEASE;
  1153. #ifdef STYLUS_BASED
  1154. ui->state = (currstate + 2) % 3; /* FULL -> EMPTY -> UNKNOWN */
  1155. #else
  1156. ui->state = GRID_FULL;
  1157. #endif
  1158. } else if (button == RIGHT_BUTTON) {
  1159. ui->drag = RIGHT_DRAG;
  1160. ui->release = RIGHT_RELEASE;
  1161. #ifdef STYLUS_BASED
  1162. ui->state = (currstate + 1) % 3; /* EMPTY -> FULL -> UNKNOWN */
  1163. #else
  1164. ui->state = GRID_EMPTY;
  1165. #endif
  1166. } else /* if (button == MIDDLE_BUTTON) */ {
  1167. ui->drag = MIDDLE_DRAG;
  1168. ui->release = MIDDLE_RELEASE;
  1169. ui->state = GRID_UNKNOWN;
  1170. }
  1171. ui->drag_start_x = ui->drag_end_x = x;
  1172. ui->drag_start_y = ui->drag_end_y = y;
  1173. ui->cur_visible = false;
  1174. return MOVE_UI_UPDATE;
  1175. }
  1176. if (ui->dragging && button == ui->drag) {
  1177. /*
  1178. * There doesn't seem much point in allowing a rectangle
  1179. * drag; people will generally only want to drag a single
  1180. * horizontal or vertical line, so we make that easy by
  1181. * snapping to it.
  1182. *
  1183. * Exception: if we're _middle_-button dragging to tag
  1184. * things as UNKNOWN, we may well want to trash an entire
  1185. * area and start over!
  1186. */
  1187. if (ui->state != GRID_UNKNOWN) {
  1188. if (abs(x - ui->drag_start_x) > abs(y - ui->drag_start_y))
  1189. y = ui->drag_start_y;
  1190. else
  1191. x = ui->drag_start_x;
  1192. }
  1193. if (x < 0) x = 0;
  1194. if (y < 0) y = 0;
  1195. if (x >= state->common->w) x = state->common->w - 1;
  1196. if (y >= state->common->h) y = state->common->h - 1;
  1197. ui->drag_end_x = x;
  1198. ui->drag_end_y = y;
  1199. return MOVE_UI_UPDATE;
  1200. }
  1201. if (ui->dragging && button == ui->release) {
  1202. int x1, x2, y1, y2, xx, yy;
  1203. bool move_needed = false;
  1204. x1 = min(ui->drag_start_x, ui->drag_end_x);
  1205. x2 = max(ui->drag_start_x, ui->drag_end_x);
  1206. y1 = min(ui->drag_start_y, ui->drag_end_y);
  1207. y2 = max(ui->drag_start_y, ui->drag_end_y);
  1208. for (yy = y1; yy <= y2; yy++)
  1209. for (xx = x1; xx <= x2; xx++)
  1210. if (!state->common->immutable[yy * state->common->w + xx] &&
  1211. state->grid[yy * state->common->w + xx] != ui->state)
  1212. move_needed = true;
  1213. ui->dragging = false;
  1214. if (move_needed) {
  1215. char buf[80];
  1216. sprintf(buf, "%c%d,%d,%d,%d",
  1217. (char)(ui->state == GRID_FULL ? 'F' :
  1218. ui->state == GRID_EMPTY ? 'E' : 'U'),
  1219. x1, y1, x2-x1+1, y2-y1+1);
  1220. return dupstr(buf);
  1221. } else
  1222. return MOVE_UI_UPDATE;
  1223. }
  1224. if (IS_CURSOR_MOVE(button)) {
  1225. int x = ui->cur_x, y = ui->cur_y, newstate;
  1226. char buf[80];
  1227. move_cursor(button, &ui->cur_x, &ui->cur_y, state->common->w, state->common->h, false);
  1228. ui->cur_visible = true;
  1229. if (!control && !shift) return MOVE_UI_UPDATE;
  1230. newstate = control ? shift ? GRID_UNKNOWN : GRID_FULL : GRID_EMPTY;
  1231. if (state->grid[y * state->common->w + x] == newstate &&
  1232. state->grid[ui->cur_y * state->common->w + ui->cur_x] == newstate)
  1233. return MOVE_UI_UPDATE;
  1234. sprintf(buf, "%c%d,%d,%d,%d", control ? shift ? 'U' : 'F' : 'E',
  1235. min(x, ui->cur_x), min(y, ui->cur_y),
  1236. abs(x - ui->cur_x) + 1, abs(y - ui->cur_y) + 1);
  1237. return dupstr(buf);
  1238. }
  1239. if (IS_CURSOR_SELECT(button)) {
  1240. int currstate = state->grid[ui->cur_y * state->common->w + ui->cur_x];
  1241. int newstate;
  1242. char buf[80];
  1243. if (!ui->cur_visible) {
  1244. ui->cur_visible = true;
  1245. return MOVE_UI_UPDATE;
  1246. }
  1247. if (button == CURSOR_SELECT2)
  1248. newstate = currstate == GRID_UNKNOWN ? GRID_EMPTY :
  1249. currstate == GRID_EMPTY ? GRID_FULL : GRID_UNKNOWN;
  1250. else
  1251. newstate = currstate == GRID_UNKNOWN ? GRID_FULL :
  1252. currstate == GRID_FULL ? GRID_EMPTY : GRID_UNKNOWN;
  1253. sprintf(buf, "%c%d,%d,%d,%d",
  1254. (char)(newstate == GRID_FULL ? 'F' :
  1255. newstate == GRID_EMPTY ? 'E' : 'U'),
  1256. ui->cur_x, ui->cur_y, 1, 1);
  1257. return dupstr(buf);
  1258. }
  1259. return NULL;
  1260. }
  1261. static game_state *execute_move(const game_state *from, const char *move)
  1262. {
  1263. game_state *ret;
  1264. int x1, x2, y1, y2, xx, yy;
  1265. int val;
  1266. if (move[0] == 'S' &&
  1267. strlen(move) == from->common->w * from->common->h + 1) {
  1268. int i;
  1269. ret = dup_game(from);
  1270. for (i = 0; i < ret->common->w * ret->common->h; i++)
  1271. ret->grid[i] = (move[i+1] == '1' ? GRID_FULL : GRID_EMPTY);
  1272. ret->completed = ret->cheated = true;
  1273. return ret;
  1274. } else if ((move[0] == 'F' || move[0] == 'E' || move[0] == 'U') &&
  1275. sscanf(move+1, "%d,%d,%d,%d", &x1, &y1, &x2, &y2) == 4 &&
  1276. x1 >= 0 && x2 >= 0 && x1+x2 <= from->common->w &&
  1277. y1 >= 0 && y2 >= 0 && y1+y2 <= from->common->h) {
  1278. x2 += x1;
  1279. y2 += y1;
  1280. val = (move[0] == 'F' ? GRID_FULL :
  1281. move[0] == 'E' ? GRID_EMPTY : GRID_UNKNOWN);
  1282. ret = dup_game(from);
  1283. for (yy = y1; yy < y2; yy++)
  1284. for (xx = x1; xx < x2; xx++)
  1285. if (!ret->common->immutable[yy * ret->common->w + xx])
  1286. ret->grid[yy * ret->common->w + xx] = val;
  1287. /*
  1288. * An actual change, so check to see if we've completed the
  1289. * game.
  1290. */
  1291. if (!ret->completed) {
  1292. int *rowdata = snewn(ret->common->rowsize, int);
  1293. int i, len;
  1294. ret->completed = true;
  1295. for (i=0; i<ret->common->w; i++) {
  1296. len = compute_rowdata(rowdata, ret->grid+i,
  1297. ret->common->h, ret->common->w);
  1298. if (len != ret->common->rowlen[i] ||
  1299. memcmp(ret->common->rowdata+i*ret->common->rowsize,
  1300. rowdata, len * sizeof(int))) {
  1301. ret->completed = false;
  1302. break;
  1303. }
  1304. }
  1305. for (i=0; i<ret->common->h; i++) {
  1306. len = compute_rowdata(rowdata, ret->grid+i*ret->common->w,
  1307. ret->common->w, 1);
  1308. if (len != ret->common->rowlen[i+ret->common->w] ||
  1309. memcmp(ret->common->rowdata +
  1310. (i+ret->common->w)*ret->common->rowsize,
  1311. rowdata, len * sizeof(int))) {
  1312. ret->completed = false;
  1313. break;
  1314. }
  1315. }
  1316. sfree(rowdata);
  1317. }
  1318. return ret;
  1319. } else
  1320. return NULL;
  1321. }
  1322. /* ----------------------------------------------------------------------
  1323. * Error-checking during gameplay.
  1324. */
  1325. /*
  1326. * The difficulty in error-checking Pattern is to make the error check
  1327. * _weak_ enough. The most obvious way would be to check each row and
  1328. * column by calling (a modified form of) do_row() to recursively
  1329. * analyse the row contents against the clue set and see if the
  1330. * GRID_UNKNOWNs could be filled in in any way that would end up
  1331. * correct. However, this turns out to be such a strong error check as
  1332. * to constitute a spoiler in many situations: you make a typo while
  1333. * trying to fill in one row, and not only does the row light up to
  1334. * indicate an error, but several columns crossed by the move also
  1335. * light up and draw your attention to deductions you hadn't even
  1336. * noticed you could make.
  1337. *
  1338. * So instead I restrict error-checking to 'complete runs' within a
  1339. * row, by which I mean contiguous sequences of GRID_FULL bounded at
  1340. * both ends by either GRID_EMPTY or the ends of the row. We identify
  1341. * all the complete runs in a row, and verify that _those_ are
  1342. * consistent with the row's clue list. Sequences of complete runs
  1343. * separated by solid GRID_EMPTY are required to match contiguous
  1344. * sequences in the clue list, whereas if there's at least one
  1345. * GRID_UNKNOWN between any two complete runs then those two need not
  1346. * be contiguous in the clue list.
  1347. *
  1348. * To simplify the edge cases, I pretend that the clue list for the
  1349. * row is extended with a 0 at each end, and I also pretend that the
  1350. * grid data for the row is extended with a GRID_EMPTY and a
  1351. * zero-length run at each end. This permits the contiguity checker to
  1352. * handle the fiddly end effects (e.g. if the first contiguous
  1353. * sequence of complete runs in the grid matches _something_ in the
  1354. * clue list but not at the beginning, this is allowable iff there's a
  1355. * GRID_UNKNOWN before the first one) with minimal faff, since the end
  1356. * effects just drop out as special cases of the normal inter-run
  1357. * handling (in this code the above case is not 'at the end of the
  1358. * clue list' at all, but between the implicit initial zero run and
  1359. * the first nonzero one).
  1360. *
  1361. * We must also be a little careful about how we search for a
  1362. * contiguous sequence of runs. In the clue list (1 1 2 1 2 3),
  1363. * suppose we see a GRID_UNKNOWN and then a length-1 run. We search
  1364. * for 1 in the clue list and find it at the very beginning. But now
  1365. * suppose we find a length-2 run with no GRID_UNKNOWN before it. We
  1366. * can't naively look at the next clue from the 1 we found, because
  1367. * that'll be the second 1 and won't match. Instead, we must backtrack
  1368. * by observing that the 2 we've just found must be contiguous with
  1369. * the 1 we've already seen, so we search for the sequence (1 2) and
  1370. * find it starting at the second 1. Now if we see a 3, we must
  1371. * rethink again and search for (1 2 3).
  1372. */
  1373. struct errcheck_state {
  1374. /*
  1375. * rowdata and rowlen point at the clue data for this row in the
  1376. * game state.
  1377. */
  1378. int *rowdata;
  1379. int rowlen;
  1380. /*
  1381. * rowpos indicates the lowest position where it would be valid to
  1382. * see our next run length. It might be equal to rowlen,
  1383. * indicating that the next run would have to be the terminating 0.
  1384. */
  1385. int rowpos;
  1386. /*
  1387. * ncontig indicates how many runs we've seen in a contiguous
  1388. * block. This is taken into account when searching for the next
  1389. * run we find, unless ncontig is zeroed out first by encountering
  1390. * a GRID_UNKNOWN.
  1391. */
  1392. int ncontig;
  1393. };
  1394. static bool errcheck_found_run(struct errcheck_state *es, int r)
  1395. {
  1396. /* Macro to handle the pretence that rowdata has a 0 at each end */
  1397. #define ROWDATA(k) ((k)<0 || (k)>=es->rowlen ? 0 : es->rowdata[(k)])
  1398. /*
  1399. * See if we can find this new run length at a position where it
  1400. * also matches the last 'ncontig' runs we've seen.
  1401. */
  1402. int i, newpos;
  1403. for (newpos = es->rowpos; newpos <= es->rowlen; newpos++) {
  1404. if (ROWDATA(newpos) != r)
  1405. goto notfound;
  1406. for (i = 1; i <= es->ncontig; i++)
  1407. if (ROWDATA(newpos - i) != ROWDATA(es->rowpos - i))
  1408. goto notfound;
  1409. es->rowpos = newpos+1;
  1410. es->ncontig++;
  1411. return true;
  1412. notfound:;
  1413. }
  1414. return false;
  1415. #undef ROWDATA
  1416. }
  1417. static bool check_errors(const game_state *state, int i)
  1418. {
  1419. int start, step, end, j;
  1420. int val, runlen;
  1421. struct errcheck_state aes, *es = &aes;
  1422. es->rowlen = state->common->rowlen[i];
  1423. es->rowdata = state->common->rowdata + state->common->rowsize * i;
  1424. /* Pretend that we've already encountered the initial zero run */
  1425. es->ncontig = 1;
  1426. es->rowpos = 0;
  1427. if (i < state->common->w) {
  1428. start = i;
  1429. step = state->common->w;
  1430. end = start + step * state->common->h;
  1431. } else {
  1432. start = (i - state->common->w) * state->common->w;
  1433. step = 1;
  1434. end = start + step * state->common->w;
  1435. }
  1436. runlen = -1;
  1437. for (j = start - step; j <= end; j += step) {
  1438. if (j < start || j == end)
  1439. val = GRID_EMPTY;
  1440. else
  1441. val = state->grid[j];
  1442. if (val == GRID_UNKNOWN) {
  1443. runlen = -1;
  1444. es->ncontig = 0;
  1445. } else if (val == GRID_FULL) {
  1446. if (runlen >= 0)
  1447. runlen++;
  1448. } else if (val == GRID_EMPTY) {
  1449. if (runlen > 0) {
  1450. if (!errcheck_found_run(es, runlen))
  1451. return true; /* error! */
  1452. }
  1453. runlen = 0;
  1454. }
  1455. }
  1456. /* Signal end-of-row by sending errcheck_found_run the terminating
  1457. * zero run, which will be marked as contiguous with the previous
  1458. * run if and only if there hasn't been a GRID_UNKNOWN before. */
  1459. if (!errcheck_found_run(es, 0))
  1460. return true; /* error at the last minute! */
  1461. return false; /* no error */
  1462. }
  1463. /* ----------------------------------------------------------------------
  1464. * Drawing routines.
  1465. */
  1466. static void game_compute_size(const game_params *params, int tilesize,
  1467. const game_ui *ui, int *x, int *y)
  1468. {
  1469. /* Ick: fake up `ds->tilesize' for macro expansion purposes */
  1470. struct { int tilesize; } ads, *ds = &ads;
  1471. ads.tilesize = tilesize;
  1472. *x = SIZE(params->w);
  1473. *y = SIZE(params->h);
  1474. }
  1475. static void game_set_size(drawing *dr, game_drawstate *ds,
  1476. const game_params *params, int tilesize)
  1477. {
  1478. ds->tilesize = tilesize;
  1479. }
  1480. static float *game_colours(frontend *fe, int *ncolours)
  1481. {
  1482. float *ret = snewn(3 * NCOLOURS, float);
  1483. int i;
  1484. frontend_default_colour(fe, &ret[COL_BACKGROUND * 3]);
  1485. for (i = 0; i < 3; i++) {
  1486. ret[COL_GRID * 3 + i] = 0.3F;
  1487. ret[COL_UNKNOWN * 3 + i] = 0.5F;
  1488. ret[COL_TEXT * 3 + i] = 0.0F;
  1489. ret[COL_FULL * 3 + i] = 0.0F;
  1490. ret[COL_EMPTY * 3 + i] = 1.0F;
  1491. ret[COL_CURSOR_GUIDE * 3 + i] = 0.5F;
  1492. }
  1493. ret[COL_CURSOR * 3 + 0] = 1.0F;
  1494. ret[COL_CURSOR * 3 + 1] = 0.25F;
  1495. ret[COL_CURSOR * 3 + 2] = 0.25F;
  1496. ret[COL_ERROR * 3 + 0] = 1.0F;
  1497. ret[COL_ERROR * 3 + 1] = 0.0F;
  1498. ret[COL_ERROR * 3 + 2] = 0.0F;
  1499. *ncolours = NCOLOURS;
  1500. return ret;
  1501. }
  1502. static game_drawstate *game_new_drawstate(drawing *dr, const game_state *state)
  1503. {
  1504. struct game_drawstate *ds = snew(struct game_drawstate);
  1505. ds->started = false;
  1506. ds->w = state->common->w;
  1507. ds->h = state->common->h;
  1508. ds->visible = snewn(ds->w * ds->h, unsigned char);
  1509. ds->tilesize = 0; /* not decided yet */
  1510. memset(ds->visible, 255, ds->w * ds->h);
  1511. ds->numcolours = snewn(ds->w + ds->h, unsigned char);
  1512. memset(ds->numcolours, 255, ds->w + ds->h);
  1513. ds->cur_x = ds->cur_y = 0;
  1514. ds->strbuf = snewn(state->common->rowsize *
  1515. MAX_DIGITS(*state->common->rowdata) + 1, char);
  1516. return ds;
  1517. }
  1518. static void game_free_drawstate(drawing *dr, game_drawstate *ds)
  1519. {
  1520. sfree(ds->visible);
  1521. sfree(ds->numcolours);
  1522. sfree(ds->strbuf);
  1523. sfree(ds);
  1524. }
  1525. static void grid_square(drawing *dr, game_drawstate *ds,
  1526. int y, int x, int state, bool cur)
  1527. {
  1528. int xl, xr, yt, yb, dx, dy, dw, dh;
  1529. draw_rect(dr, TOCOORD(ds->w, x), TOCOORD(ds->h, y),
  1530. TILE_SIZE, TILE_SIZE, COL_GRID);
  1531. xl = (x % 5 == 0 ? 1 : 0);
  1532. yt = (y % 5 == 0 ? 1 : 0);
  1533. xr = (x % 5 == 4 || x == ds->w-1 ? 1 : 0);
  1534. yb = (y % 5 == 4 || y == ds->h-1 ? 1 : 0);
  1535. dx = TOCOORD(ds->w, x) + 1 + xl;
  1536. dy = TOCOORD(ds->h, y) + 1 + yt;
  1537. dw = TILE_SIZE - xl - xr - 1;
  1538. dh = TILE_SIZE - yt - yb - 1;
  1539. draw_rect(dr, dx, dy, dw, dh,
  1540. (state == GRID_FULL ? COL_FULL :
  1541. state == GRID_EMPTY ? COL_EMPTY : COL_UNKNOWN));
  1542. if (cur) {
  1543. draw_rect_outline(dr, dx, dy, dw, dh, COL_CURSOR);
  1544. draw_rect_outline(dr, dx+1, dy+1, dw-2, dh-2, COL_CURSOR);
  1545. }
  1546. draw_update(dr, TOCOORD(ds->w, x), TOCOORD(ds->h, y),
  1547. TILE_SIZE, TILE_SIZE);
  1548. }
  1549. /*
  1550. * Draw the numbers for a single row or column.
  1551. */
  1552. static void draw_numbers(
  1553. drawing *dr, game_drawstate *ds, const game_state *state,
  1554. int i, bool erase, int colour)
  1555. {
  1556. int rowlen = state->common->rowlen[i];
  1557. int *rowdata = state->common->rowdata + state->common->rowsize * i;
  1558. int nfit;
  1559. int j;
  1560. int rx, ry, rw, rh;
  1561. int fontsize;
  1562. if (i < state->common->w) {
  1563. rx = TOCOORD(state->common->w, i);
  1564. ry = 0;
  1565. rw = TILE_SIZE;
  1566. rh = BORDER + TLBORDER(state->common->h) * TILE_SIZE;
  1567. } else {
  1568. rx = 0;
  1569. ry = TOCOORD(state->common->h, i - state->common->w);
  1570. rw = BORDER + TLBORDER(state->common->w) * TILE_SIZE;
  1571. rh = TILE_SIZE;
  1572. }
  1573. clip(dr, rx, ry, rw, rh);
  1574. if (erase)
  1575. draw_rect(dr, rx, ry, rw, rh, COL_BACKGROUND);
  1576. /*
  1577. * Choose a font size that's suitable for the lengths of clue.
  1578. * Only column clues are interesting because row clues can be
  1579. * spaced out independent of the tile size. For column clues, we
  1580. * want to go as large as practical while leaving decent space
  1581. * between horizintally adjacent clues. We currently distinguish
  1582. * two cases: FS_LARGE is when all column clues are single digits,
  1583. * and FS_SMALL in all other cases.
  1584. *
  1585. * If we assume that a digit is about 0.6em wide, and we want
  1586. * about that space between clues, then FS_LARGE should be
  1587. * TILESIZE/1.2. If we also assume that clues are at most two
  1588. * digits long then the case where adjacent clues are two digits
  1589. * long requries FS_SMALL to be TILESIZE/1.8.
  1590. */
  1591. fontsize = (TILE_SIZE + 0.5F) /
  1592. (state->common->fontsize == FS_LARGE ? 1.2F : 1.8F);
  1593. /*
  1594. * Normally I space the numbers out by the same distance as the
  1595. * tile size. However, if there are more numbers than available
  1596. * spaces, I have to squash them up a bit.
  1597. */
  1598. if (i < state->common->w)
  1599. nfit = TLBORDER(state->common->h);
  1600. else
  1601. nfit = TLBORDER(state->common->w);
  1602. nfit = max(rowlen, nfit) - 1;
  1603. assert(nfit > 0);
  1604. if (i < state->common->w) {
  1605. for (j = 0; j < rowlen; j++) {
  1606. int x, y;
  1607. char str[MAX_DIGITS(*rowdata) + 1];
  1608. x = rx;
  1609. y = BORDER + TILE_SIZE * (TLBORDER(state->common->h)-1);
  1610. y -= ((rowlen-j-1)*TILE_SIZE) * (TLBORDER(state->common->h)-1) / nfit;
  1611. sprintf(str, "%d", rowdata[j]);
  1612. draw_text(dr, x+TILE_SIZE/2, y+TILE_SIZE/2, FONT_VARIABLE,
  1613. fontsize, ALIGN_HCENTRE | ALIGN_VCENTRE, colour, str);
  1614. }
  1615. } else {
  1616. int x, y;
  1617. size_t off = 0;
  1618. const char *spaces = " ";
  1619. assert(rowlen <= state->common->rowsize);
  1620. *ds->strbuf = '\0';
  1621. /* Squish up a bit if there are lots of clues. */
  1622. if (rowlen > TLBORDER(state->common->w)) spaces++;
  1623. for (j = 0; j < rowlen; j++)
  1624. off += sprintf(ds->strbuf + off, "%s%d",
  1625. j ? spaces : "", rowdata[j]);
  1626. y = ry;
  1627. x = BORDER + TILE_SIZE * (TLBORDER(state->common->w)-1);
  1628. draw_text(dr, x+TILE_SIZE, y+TILE_SIZE/2, FONT_VARIABLE,
  1629. fontsize, ALIGN_HRIGHT | ALIGN_VCENTRE, colour, ds->strbuf);
  1630. }
  1631. unclip(dr);
  1632. draw_update(dr, rx, ry, rw, rh);
  1633. }
  1634. static void game_redraw(drawing *dr, game_drawstate *ds,
  1635. const game_state *oldstate, const game_state *state,
  1636. int dir, const game_ui *ui,
  1637. float animtime, float flashtime)
  1638. {
  1639. int i, j;
  1640. int x1, x2, y1, y2;
  1641. int cx, cy;
  1642. bool cmoved;
  1643. if (!ds->started) {
  1644. /*
  1645. * Draw the grid outline.
  1646. */
  1647. draw_rect(dr, TOCOORD(ds->w, 0) - 1, TOCOORD(ds->h, 0) - 1,
  1648. ds->w * TILE_SIZE + 3, ds->h * TILE_SIZE + 3,
  1649. COL_GRID);
  1650. ds->started = true;
  1651. draw_update(dr, 0, 0, SIZE(ds->w), SIZE(ds->h));
  1652. }
  1653. if (ui->dragging) {
  1654. x1 = min(ui->drag_start_x, ui->drag_end_x);
  1655. x2 = max(ui->drag_start_x, ui->drag_end_x);
  1656. y1 = min(ui->drag_start_y, ui->drag_end_y);
  1657. y2 = max(ui->drag_start_y, ui->drag_end_y);
  1658. } else {
  1659. x1 = x2 = y1 = y2 = -1; /* placate gcc warnings */
  1660. }
  1661. if (ui->cur_visible) {
  1662. cx = ui->cur_x; cy = ui->cur_y;
  1663. } else {
  1664. cx = cy = -1;
  1665. }
  1666. cmoved = (cx != ds->cur_x || cy != ds->cur_y);
  1667. /*
  1668. * Now draw any grid squares which have changed since last
  1669. * redraw.
  1670. */
  1671. for (i = 0; i < ds->h; i++) {
  1672. for (j = 0; j < ds->w; j++) {
  1673. int val;
  1674. bool cc = false;
  1675. /*
  1676. * Work out what state this square should be drawn in,
  1677. * taking any current drag operation into account.
  1678. */
  1679. if (ui->dragging && x1 <= j && j <= x2 && y1 <= i && i <= y2 &&
  1680. !state->common->immutable[i * state->common->w + j])
  1681. val = ui->state;
  1682. else
  1683. val = state->grid[i * state->common->w + j];
  1684. if (cmoved) {
  1685. /* the cursor has moved; if we were the old or
  1686. * the new cursor position we need to redraw. */
  1687. if (j == cx && i == cy) cc = true;
  1688. if (j == ds->cur_x && i == ds->cur_y) cc = true;
  1689. }
  1690. /*
  1691. * Briefly invert everything twice during a completion
  1692. * flash.
  1693. */
  1694. if (flashtime > 0 &&
  1695. (flashtime <= FLASH_TIME/3 || flashtime >= FLASH_TIME*2/3) &&
  1696. val != GRID_UNKNOWN)
  1697. val = (GRID_FULL ^ GRID_EMPTY) ^ val;
  1698. if (ds->visible[i * ds->w + j] != val || cc) {
  1699. grid_square(dr, ds, i, j, val,
  1700. (j == cx && i == cy));
  1701. ds->visible[i * ds->w + j] = val;
  1702. }
  1703. }
  1704. }
  1705. ds->cur_x = cx; ds->cur_y = cy;
  1706. /*
  1707. * Redraw any numbers which have changed their colour due to error
  1708. * indication.
  1709. */
  1710. for (i = 0; i < state->common->w + state->common->h; i++) {
  1711. int colour = check_errors(state, i) ? COL_ERROR : COL_TEXT;
  1712. if (colour == COL_TEXT && ((cx >= 0 && i == cx) || (cy >= 0 && i == cy + ds->w))) {
  1713. colour = COL_CURSOR_GUIDE;
  1714. }
  1715. if (ds->numcolours[i] != colour) {
  1716. draw_numbers(dr, ds, state, i, true, colour);
  1717. ds->numcolours[i] = colour;
  1718. }
  1719. }
  1720. }
  1721. static float game_anim_length(const game_state *oldstate,
  1722. const game_state *newstate, int dir, game_ui *ui)
  1723. {
  1724. return 0.0F;
  1725. }
  1726. static float game_flash_length(const game_state *oldstate,
  1727. const game_state *newstate, int dir, game_ui *ui)
  1728. {
  1729. if (!oldstate->completed && newstate->completed &&
  1730. !oldstate->cheated && !newstate->cheated)
  1731. return FLASH_TIME;
  1732. return 0.0F;
  1733. }
  1734. static void game_get_cursor_location(const game_ui *ui,
  1735. const game_drawstate *ds,
  1736. const game_state *state,
  1737. const game_params *params,
  1738. int *x, int *y, int *w, int *h)
  1739. {
  1740. if(ui->cur_visible) {
  1741. *x = TOCOORD(ds->w, ui->cur_x);
  1742. *y = TOCOORD(ds->h, ui->cur_y);
  1743. *w = *h = TILE_SIZE;
  1744. }
  1745. }
  1746. static int game_status(const game_state *state)
  1747. {
  1748. return state->completed ? +1 : 0;
  1749. }
  1750. static void game_print_size(const game_params *params, const game_ui *ui,
  1751. float *x, float *y)
  1752. {
  1753. int pw, ph;
  1754. /*
  1755. * I'll use 5mm squares by default.
  1756. */
  1757. game_compute_size(params, 500, ui, &pw, &ph);
  1758. *x = pw / 100.0F;
  1759. *y = ph / 100.0F;
  1760. }
  1761. static void game_print(drawing *dr, const game_state *state, const game_ui *ui,
  1762. int tilesize)
  1763. {
  1764. int w = state->common->w, h = state->common->h;
  1765. int ink = print_mono_colour(dr, 0);
  1766. int x, y, i;
  1767. /* Ick: fake up `ds->tilesize' for macro expansion purposes */
  1768. game_drawstate ads, *ds = &ads;
  1769. game_set_size(dr, ds, NULL, tilesize);
  1770. /*
  1771. * Border.
  1772. */
  1773. print_line_width(dr, TILE_SIZE / 16);
  1774. draw_rect_outline(dr, TOCOORD(w, 0), TOCOORD(h, 0),
  1775. w*TILE_SIZE, h*TILE_SIZE, ink);
  1776. /*
  1777. * Grid.
  1778. */
  1779. for (x = 1; x < w; x++) {
  1780. print_line_width(dr, TILE_SIZE / (x % 5 ? 128 : 24));
  1781. draw_line(dr, TOCOORD(w, x), TOCOORD(h, 0),
  1782. TOCOORD(w, x), TOCOORD(h, h), ink);
  1783. }
  1784. for (y = 1; y < h; y++) {
  1785. print_line_width(dr, TILE_SIZE / (y % 5 ? 128 : 24));
  1786. draw_line(dr, TOCOORD(w, 0), TOCOORD(h, y),
  1787. TOCOORD(w, w), TOCOORD(h, y), ink);
  1788. }
  1789. /*
  1790. * Clues.
  1791. */
  1792. for (i = 0; i < state->common->w + state->common->h; i++)
  1793. draw_numbers(dr, ds, state, i, false, ink);
  1794. /*
  1795. * Solution.
  1796. */
  1797. print_line_width(dr, TILE_SIZE / 128);
  1798. for (y = 0; y < h; y++)
  1799. for (x = 0; x < w; x++) {
  1800. if (state->grid[y*w+x] == GRID_FULL)
  1801. draw_rect(dr, TOCOORD(w, x), TOCOORD(h, y),
  1802. TILE_SIZE, TILE_SIZE, ink);
  1803. else if (state->grid[y*w+x] == GRID_EMPTY)
  1804. draw_circle(dr, TOCOORD(w, x) + TILE_SIZE/2,
  1805. TOCOORD(h, y) + TILE_SIZE/2,
  1806. TILE_SIZE/12, ink, ink);
  1807. }
  1808. }
  1809. #ifdef COMBINED
  1810. #define thegame pattern
  1811. #endif
  1812. const struct game thegame = {
  1813. "Pattern", "games.pattern", "pattern",
  1814. default_params,
  1815. game_fetch_preset, NULL,
  1816. decode_params,
  1817. encode_params,
  1818. free_params,
  1819. dup_params,
  1820. true, game_configure, custom_params,
  1821. validate_params,
  1822. new_game_desc,
  1823. validate_desc,
  1824. new_game,
  1825. dup_game,
  1826. free_game,
  1827. true, solve_game,
  1828. true, game_can_format_as_text_now, game_text_format,
  1829. NULL, NULL, /* get_prefs, set_prefs */
  1830. new_ui,
  1831. free_ui,
  1832. NULL, /* encode_ui */
  1833. NULL, /* decode_ui */
  1834. NULL, /* game_request_keys */
  1835. game_changed_state,
  1836. current_key_label,
  1837. interpret_move,
  1838. execute_move,
  1839. PREFERRED_TILE_SIZE, game_compute_size, game_set_size,
  1840. game_colours,
  1841. game_new_drawstate,
  1842. game_free_drawstate,
  1843. game_redraw,
  1844. game_anim_length,
  1845. game_flash_length,
  1846. game_get_cursor_location,
  1847. game_status,
  1848. true, false, game_print_size, game_print,
  1849. false, /* wants_statusbar */
  1850. false, NULL, /* timing_state */
  1851. REQUIRE_RBUTTON, /* flags */
  1852. };
  1853. #ifdef STANDALONE_SOLVER
  1854. int main(int argc, char **argv)
  1855. {
  1856. game_params *p;
  1857. game_state *s;
  1858. char *id = NULL, *desc;
  1859. const char *err;
  1860. while (--argc > 0) {
  1861. char *p = *++argv;
  1862. if (*p == '-') {
  1863. if (!strcmp(p, "-v")) {
  1864. verbose = true;
  1865. } else {
  1866. fprintf(stderr, "%s: unrecognised option `%s'\n", argv[0], p);
  1867. return 1;
  1868. }
  1869. } else {
  1870. id = p;
  1871. }
  1872. }
  1873. if (!id) {
  1874. fprintf(stderr, "usage: %s <game_id>\n", argv[0]);
  1875. return 1;
  1876. }
  1877. desc = strchr(id, ':');
  1878. if (!desc) {
  1879. fprintf(stderr, "%s: game id expects a colon in it\n", argv[0]);
  1880. return 1;
  1881. }
  1882. *desc++ = '\0';
  1883. p = default_params();
  1884. decode_params(p, id);
  1885. err = validate_desc(p, desc);
  1886. if (err) {
  1887. fprintf(stderr, "%s: %s\n", argv[0], err);
  1888. return 1;
  1889. }
  1890. s = new_game(NULL, p, desc);
  1891. {
  1892. int w = p->w, h = p->h, i, j, max, cluewid = 0;
  1893. unsigned char *matrix, *workspace;
  1894. unsigned int *changed_h, *changed_w;
  1895. int *rowdata;
  1896. matrix = snewn(w*h, unsigned char);
  1897. max = max(w, h);
  1898. workspace = snewn(max*7, unsigned char);
  1899. changed_h = snewn(max+1, unsigned int);
  1900. changed_w = snewn(max+1, unsigned int);
  1901. rowdata = snewn(max+1, int);
  1902. if (verbose) {
  1903. int thiswid;
  1904. /*
  1905. * Work out the maximum text width of the clue numbers
  1906. * in a row or column, so we can print the solver's
  1907. * working in a nicely lined up way.
  1908. */
  1909. for (i = 0; i < (w+h); i++) {
  1910. char buf[80];
  1911. for (thiswid = -1, j = 0; j < s->common->rowlen[i]; j++)
  1912. thiswid += sprintf
  1913. (buf, " %d",
  1914. s->common->rowdata[s->common->rowsize*i+j]);
  1915. if (cluewid < thiswid)
  1916. cluewid = thiswid;
  1917. }
  1918. }
  1919. solve_puzzle(s, NULL, w, h, matrix, workspace,
  1920. changed_h, changed_w, rowdata, cluewid);
  1921. for (i = 0; i < h; i++) {
  1922. for (j = 0; j < w; j++) {
  1923. int c = (matrix[i*w+j] == UNKNOWN ? '?' :
  1924. matrix[i*w+j] == BLOCK ? '#' :
  1925. matrix[i*w+j] == DOT ? '.' :
  1926. '!');
  1927. putchar(c);
  1928. }
  1929. printf("\n");
  1930. }
  1931. }
  1932. return 0;
  1933. }
  1934. #endif
  1935. #ifdef STANDALONE_PICTURE_GENERATOR
  1936. /*
  1937. * Main program for the standalone picture generator. To use it,
  1938. * simply provide it with an XBM-format bitmap file (note XBM, not
  1939. * XPM) on standard input, and it will output a game ID in return.
  1940. * For example:
  1941. *
  1942. * $ ./patternpicture < calligraphic-A.xbm
  1943. * 15x15:2/4/2/2/2/3/3/3.1/3.1/3.1/11/14/12/6/1/2/2/3/4/5/1.3/2.3/1.3/2.3/1.4/9/1.1.3/2.2.3/5.4/3.2
  1944. *
  1945. * That looks easy, of course - all the program has done is to count
  1946. * up the clue numbers! But in fact, it's done more than that: it's
  1947. * also checked that the result is uniquely soluble from just the
  1948. * numbers. If it hadn't been, then it would have also left some
  1949. * filled squares in the playing area as extra clues.
  1950. *
  1951. * $ ./patternpicture < cube.xbm
  1952. * 15x15:10/2.1/1.1.1/1.1.1/1.1.1/1.1.1/1.1.1/1.1.1/1.1.1/1.10/1.1.1/1.1.1/1.1.1/2.1/10/10/1.2/1.1.1/1.1.1/1.1.1/10.1/1.1.1/1.1.1/1.1.1/1.1.1/1.1.1/1.1.1/1.1.1/1.2/10,TNINzzzzGNzw
  1953. *
  1954. * This enables a reasonably convenient design workflow for coming up
  1955. * with pictorial Pattern puzzles which _are_ uniquely soluble without
  1956. * those inelegant pre-filled squares. Fire up a bitmap editor (X11
  1957. * bitmap(1) is good enough), save a trial .xbm, and then test it by
  1958. * running a command along the lines of
  1959. *
  1960. * $ ./pattern $(./patternpicture < test.xbm)
  1961. *
  1962. * If the resulting window pops up with some pre-filled squares, then
  1963. * that tells you which parts of the image are giving rise to
  1964. * ambiguities, so try making tweaks in those areas, try the test
  1965. * command again, and see if it helps. Once you have a design for
  1966. * which the Pattern starting grid comes out empty, there's your game
  1967. * ID.
  1968. */
  1969. #include <time.h>
  1970. int main(int argc, char **argv)
  1971. {
  1972. game_params *par;
  1973. char *params, *desc;
  1974. random_state *rs;
  1975. time_t seed = time(NULL);
  1976. char buf[4096];
  1977. int i;
  1978. int x, y;
  1979. par = default_params();
  1980. if (argc > 1)
  1981. decode_params(par, argv[1]); /* get difficulty */
  1982. par->w = par->h = -1;
  1983. /*
  1984. * Now read an XBM file from standard input. This is simple and
  1985. * hacky and will do very little error detection, so don't feed
  1986. * it bogus data.
  1987. */
  1988. picture = NULL;
  1989. x = y = 0;
  1990. while (fgets(buf, sizeof(buf), stdin)) {
  1991. buf[strcspn(buf, "\r\n")] = '\0';
  1992. if (!strncmp(buf, "#define", 7)) {
  1993. /*
  1994. * Lines starting `#define' give the width and height.
  1995. */
  1996. char *num = buf + strlen(buf);
  1997. char *symend;
  1998. while (num > buf && isdigit((unsigned char)num[-1]))
  1999. num--;
  2000. symend = num;
  2001. while (symend > buf && isspace((unsigned char)symend[-1]))
  2002. symend--;
  2003. if (symend-5 >= buf && !strncmp(symend-5, "width", 5))
  2004. par->w = atoi(num);
  2005. else if (symend-6 >= buf && !strncmp(symend-6, "height", 6))
  2006. par->h = atoi(num);
  2007. } else {
  2008. /*
  2009. * Otherwise, break the string up into words and take
  2010. * any word of the form `0x' plus hex digits to be a
  2011. * byte.
  2012. */
  2013. char *p, *wordstart;
  2014. if (!picture) {
  2015. if (par->w < 0 || par->h < 0) {
  2016. printf("failed to read width and height\n");
  2017. return 1;
  2018. }
  2019. picture = snewn(par->w * par->h, unsigned char);
  2020. for (i = 0; i < par->w * par->h; i++)
  2021. picture[i] = GRID_UNKNOWN;
  2022. }
  2023. p = buf;
  2024. while (*p) {
  2025. while (*p && (*p == ',' || isspace((unsigned char)*p)))
  2026. p++;
  2027. wordstart = p;
  2028. while (*p && !(*p == ',' || *p == '}' ||
  2029. isspace((unsigned char)*p)))
  2030. p++;
  2031. if (*p)
  2032. *p++ = '\0';
  2033. if (wordstart[0] == '0' &&
  2034. (wordstart[1] == 'x' || wordstart[1] == 'X') &&
  2035. !wordstart[2 + strspn(wordstart+2,
  2036. "0123456789abcdefABCDEF")]) {
  2037. unsigned long byte = strtoul(wordstart+2, NULL, 16);
  2038. for (i = 0; i < 8; i++) {
  2039. int bit = (byte >> i) & 1;
  2040. if (y < par->h && x < par->w)
  2041. picture[y * par->w + x] =
  2042. bit ? GRID_FULL : GRID_EMPTY;
  2043. x++;
  2044. }
  2045. if (x >= par->w) {
  2046. x = 0;
  2047. y++;
  2048. }
  2049. }
  2050. }
  2051. }
  2052. }
  2053. for (i = 0; i < par->w * par->h; i++)
  2054. if (picture[i] == GRID_UNKNOWN) {
  2055. fprintf(stderr, "failed to read enough bitmap data\n");
  2056. return 1;
  2057. }
  2058. rs = random_new((void*)&seed, sizeof(time_t));
  2059. desc = new_game_desc(par, rs, NULL, false);
  2060. params = encode_params(par, false);
  2061. printf("%s:%s\n", params, desc);
  2062. sfree(desc);
  2063. sfree(params);
  2064. free_params(par);
  2065. random_free(rs);
  2066. return 0;
  2067. }
  2068. #endif
  2069. /* vim: set shiftwidth=4 tabstop=8: */