filling.c 65 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233
  1. /*
  2. * filling.c: An implementation of the Nikoli game fillomino.
  3. * Copyright (C) 2007 Jonas Kölker. See LICENSE for the license.
  4. */
  5. /* TODO:
  6. *
  7. * - use a typedef instead of int for numbers on the board
  8. * + replace int with something else (signed short?)
  9. * - the type should be signed (for -board[i] and -SENTINEL)
  10. * - the type should be somewhat big: board[i] = i
  11. * - Using shorts gives us 181x181 puzzles as upper bound.
  12. *
  13. * - in board generation, after having merged regions such that no
  14. * more merges are necessary, try splitting (big) regions.
  15. * + it seems that smaller regions make for better puzzles; see
  16. * for instance the 7x7 puzzle in this file (grep for 7x7:).
  17. *
  18. * - symmetric hints (solo-style)
  19. * + right now that means including _many_ hints, and the puzzles
  20. * won't look any nicer. Not worth it (at the moment).
  21. *
  22. * - make the solver do recursion/backtracking.
  23. * + This is for user-submitted puzzles, not for puzzle
  24. * generation (on the other hand, never say never).
  25. *
  26. * - prove that only w=h=2 needs a special case
  27. *
  28. * - solo-like pencil marks?
  29. *
  30. * - a user says that the difficulty is unevenly distributed.
  31. * + partition into levels? Will they be non-crap?
  32. *
  33. * - Allow square contents > 9?
  34. * + I could use letters for digits (solo does this), but
  35. * letters don't have numeric significance (normal people hate
  36. * base36), which is relevant here (much more than in solo).
  37. * + [click, 1, 0, enter] => [10 in clicked square]?
  38. * + How much information is needed to solve? Does one need to
  39. * know the algorithm by which the largest number is set?
  40. *
  41. * - eliminate puzzle instances with done chunks (1's in particular)?
  42. * + that's what the qsort call is all about.
  43. * + the 1's don't bother me that much.
  44. * + but this takes a LONG time (not always possible)?
  45. * - this may be affected by solver (lack of) quality.
  46. * - weed them out by construction instead of post-cons check
  47. * + but that interleaves make_board and new_game_desc: you
  48. * have to alternate between changing the board and
  49. * changing the hint set (instead of just creating the
  50. * board once, then changing the hint set once -> done).
  51. *
  52. * - use binary search when discovering the minimal sovable point
  53. * + profile to show a need (but when the solver gets slower...)
  54. * + 7x9 @ .011s, 9x13 @ .075s, 17x13 @ .661s (all avg with n=100)
  55. * + but the hints are independent, not linear, so... what?
  56. */
  57. #include <assert.h>
  58. #include <ctype.h>
  59. #ifdef NO_TGMATH_H
  60. # include <math.h>
  61. #else
  62. # include <tgmath.h>
  63. #endif
  64. #include <stdarg.h>
  65. #include <stdio.h>
  66. #include <stdlib.h>
  67. #include <string.h>
  68. #include "puzzles.h"
  69. static bool verbose;
  70. static void printv(const char *fmt, ...) {
  71. #ifndef PALM
  72. if (verbose) {
  73. va_list va;
  74. va_start(va, fmt);
  75. vprintf(fmt, va);
  76. va_end(va);
  77. }
  78. #endif
  79. }
  80. /*****************************************************************************
  81. * GAME CONFIGURATION AND PARAMETERS *
  82. *****************************************************************************/
  83. struct game_params {
  84. int w, h;
  85. };
  86. struct shared_state {
  87. struct game_params params;
  88. int *clues;
  89. int refcnt;
  90. };
  91. struct game_state {
  92. int *board;
  93. struct shared_state *shared;
  94. bool completed, cheated;
  95. };
  96. static const struct game_params filling_defaults[3] = {
  97. {9, 7}, {13, 9}, {17, 13}
  98. };
  99. static game_params *default_params(void)
  100. {
  101. game_params *ret = snew(game_params);
  102. *ret = filling_defaults[1]; /* struct copy */
  103. return ret;
  104. }
  105. static bool game_fetch_preset(int i, char **name, game_params **params)
  106. {
  107. char buf[64];
  108. if (i < 0 || i >= lenof(filling_defaults)) return false;
  109. *params = snew(game_params);
  110. **params = filling_defaults[i]; /* struct copy */
  111. sprintf(buf, "%dx%d", filling_defaults[i].w, filling_defaults[i].h);
  112. *name = dupstr(buf);
  113. return true;
  114. }
  115. static void free_params(game_params *params)
  116. {
  117. sfree(params);
  118. }
  119. static game_params *dup_params(const game_params *params)
  120. {
  121. game_params *ret = snew(game_params);
  122. *ret = *params; /* struct copy */
  123. return ret;
  124. }
  125. static void decode_params(game_params *ret, char const *string)
  126. {
  127. ret->w = ret->h = atoi(string);
  128. while (*string && isdigit((unsigned char) *string)) ++string;
  129. if (*string == 'x') ret->h = atoi(++string);
  130. }
  131. static char *encode_params(const game_params *params, bool full)
  132. {
  133. char buf[64];
  134. sprintf(buf, "%dx%d", params->w, params->h);
  135. return dupstr(buf);
  136. }
  137. static config_item *game_configure(const game_params *params)
  138. {
  139. config_item *ret;
  140. char buf[64];
  141. ret = snewn(3, config_item);
  142. ret[0].name = "Width";
  143. ret[0].type = C_STRING;
  144. sprintf(buf, "%d", params->w);
  145. ret[0].u.string.sval = dupstr(buf);
  146. ret[1].name = "Height";
  147. ret[1].type = C_STRING;
  148. sprintf(buf, "%d", params->h);
  149. ret[1].u.string.sval = dupstr(buf);
  150. ret[2].name = NULL;
  151. ret[2].type = C_END;
  152. return ret;
  153. }
  154. static game_params *custom_params(const config_item *cfg)
  155. {
  156. game_params *ret = snew(game_params);
  157. ret->w = atoi(cfg[0].u.string.sval);
  158. ret->h = atoi(cfg[1].u.string.sval);
  159. return ret;
  160. }
  161. static const char *validate_params(const game_params *params, bool full)
  162. {
  163. if (params->w < 1) return "Width must be at least one";
  164. if (params->h < 1) return "Height must be at least one";
  165. if (params->w > INT_MAX / params->h)
  166. return "Width times height must not be unreasonably large";
  167. return NULL;
  168. }
  169. /*****************************************************************************
  170. * STRINGIFICATION OF GAME STATE *
  171. *****************************************************************************/
  172. #define EMPTY 0
  173. /* Example of plaintext rendering:
  174. * +---+---+---+---+---+---+---+
  175. * | 6 | | | 2 | | | 2 |
  176. * +---+---+---+---+---+---+---+
  177. * | | 3 | | 6 | | 3 | |
  178. * +---+---+---+---+---+---+---+
  179. * | 3 | | | | | | 1 |
  180. * +---+---+---+---+---+---+---+
  181. * | | 2 | 3 | | 4 | 2 | |
  182. * +---+---+---+---+---+---+---+
  183. * | 2 | | | | | | 3 |
  184. * +---+---+---+---+---+---+---+
  185. * | | 5 | | 1 | | 4 | |
  186. * +---+---+---+---+---+---+---+
  187. * | 4 | | | 3 | | | 3 |
  188. * +---+---+---+---+---+---+---+
  189. *
  190. * This puzzle instance is taken from the nikoli website
  191. * Encoded (unsolved and solved), the strings are these:
  192. * 7x7:6002002030603030000010230420200000305010404003003
  193. * 7x7:6662232336663232331311235422255544325413434443313
  194. */
  195. static char *board_to_string(int *board, int w, int h) {
  196. const int sz = w * h;
  197. const int chw = (4*w + 2); /* +2 for trailing '+' and '\n' */
  198. const int chh = (2*h + 1); /* +1: n fence segments, n+1 posts */
  199. const int chlen = chw * chh;
  200. char *repr = snewn(chlen + 1, char);
  201. int i;
  202. assert(board);
  203. /* build the first line ("^(\+---){n}\+$") */
  204. for (i = 0; i < w; ++i) {
  205. repr[4*i + 0] = '+';
  206. repr[4*i + 1] = '-';
  207. repr[4*i + 2] = '-';
  208. repr[4*i + 3] = '-';
  209. }
  210. repr[4*i + 0] = '+';
  211. repr[4*i + 1] = '\n';
  212. /* ... and copy it onto the odd-numbered lines */
  213. for (i = 0; i < h; ++i) memcpy(repr + (2*i + 2) * chw, repr, chw);
  214. /* build the second line ("^(\|\t){n}\|$") */
  215. for (i = 0; i < w; ++i) {
  216. repr[chw + 4*i + 0] = '|';
  217. repr[chw + 4*i + 1] = ' ';
  218. repr[chw + 4*i + 2] = ' ';
  219. repr[chw + 4*i + 3] = ' ';
  220. }
  221. repr[chw + 4*i + 0] = '|';
  222. repr[chw + 4*i + 1] = '\n';
  223. /* ... and copy it onto the even-numbered lines */
  224. for (i = 1; i < h; ++i) memcpy(repr + (2*i + 1) * chw, repr + chw, chw);
  225. /* fill in the numbers */
  226. for (i = 0; i < sz; ++i) {
  227. const int x = i % w;
  228. const int y = i / w;
  229. if (board[i] == EMPTY) continue;
  230. repr[chw*(2*y + 1) + (4*x + 2)] = board[i] + '0';
  231. }
  232. repr[chlen] = '\0';
  233. return repr;
  234. }
  235. static bool game_can_format_as_text_now(const game_params *params)
  236. {
  237. return true;
  238. }
  239. static char *game_text_format(const game_state *state)
  240. {
  241. const int w = state->shared->params.w;
  242. const int h = state->shared->params.h;
  243. return board_to_string(state->board, w, h);
  244. }
  245. /*****************************************************************************
  246. * GAME GENERATION AND SOLVER *
  247. *****************************************************************************/
  248. static const int dx[4] = {-1, 1, 0, 0};
  249. static const int dy[4] = {0, 0, -1, 1};
  250. struct solver_state
  251. {
  252. DSF *dsf;
  253. int *board;
  254. int *connected;
  255. int nempty;
  256. /* Used internally by learn_bitmap_deductions; kept here to avoid
  257. * mallocing/freeing them every time that function is called. */
  258. int *bm, *bmminsize;
  259. DSF *bmdsf;
  260. };
  261. static void print_board(int *board, int w, int h) {
  262. if (verbose) {
  263. char *repr = board_to_string(board, w, h);
  264. printv("%s\n", repr);
  265. free(repr);
  266. }
  267. }
  268. static game_state *new_game(midend *, const game_params *, const char *);
  269. static void free_game(game_state *);
  270. #define SENTINEL (sz+1)
  271. static bool mark_region(int *board, int w, int h, int i, int n, int m) {
  272. int j;
  273. board[i] = -1;
  274. for (j = 0; j < 4; ++j) {
  275. const int x = (i % w) + dx[j], y = (i / w) + dy[j], ii = w*y + x;
  276. if (x < 0 || x >= w || y < 0 || y >= h) continue;
  277. if (board[ii] == m) return false;
  278. if (board[ii] != n) continue;
  279. if (!mark_region(board, w, h, ii, n, m)) return false;
  280. }
  281. return true;
  282. }
  283. static int region_size(int *board, int w, int h, int i) {
  284. const int sz = w * h;
  285. int j, size, copy;
  286. if (board[i] == 0) return 0;
  287. copy = board[i];
  288. mark_region(board, w, h, i, board[i], SENTINEL);
  289. for (size = j = 0; j < sz; ++j) {
  290. if (board[j] != -1) continue;
  291. ++size;
  292. board[j] = copy;
  293. }
  294. return size;
  295. }
  296. static void merge_ones(int *board, int w, int h)
  297. {
  298. const int sz = w * h;
  299. const int maxsize = min(max(max(w, h), 3), 9);
  300. int i, j, k;
  301. bool change;
  302. do {
  303. change = false;
  304. for (i = 0; i < sz; ++i) {
  305. if (board[i] != 1) continue;
  306. for (j = 0; j < 4; ++j, board[i] = 1) {
  307. const int x = (i % w) + dx[j], y = (i / w) + dy[j];
  308. int oldsize, newsize, ii = w*y + x;
  309. bool ok;
  310. if (x < 0 || x >= w || y < 0 || y >= h) continue;
  311. if (board[ii] == maxsize) continue;
  312. oldsize = board[ii];
  313. board[i] = oldsize;
  314. newsize = region_size(board, w, h, i);
  315. if (newsize > maxsize) continue;
  316. ok = mark_region(board, w, h, i, oldsize, newsize);
  317. for (k = 0; k < sz; ++k)
  318. if (board[k] == -1)
  319. board[k] = ok ? newsize : oldsize;
  320. if (ok) break;
  321. }
  322. if (j < 4) change = true;
  323. }
  324. } while (change);
  325. }
  326. /* generate a random valid board; uses validate_board. */
  327. static void make_board(int *board, int w, int h, random_state *rs) {
  328. const int sz = w * h;
  329. /* w=h=2 is a special case which requires a number > max(w, h) */
  330. /* TODO prove that this is the case ONLY for w=h=2. */
  331. const int maxsize = min(max(max(w, h), 3), 9);
  332. /* Note that if 1 in {w, h} then it's impossible to have a region
  333. * of size > w*h, so the special case only affects w=h=2. */
  334. int i;
  335. DSF *dsf;
  336. bool change;
  337. assert(w >= 1);
  338. assert(h >= 1);
  339. assert(board);
  340. /* I abuse the board variable: when generating the puzzle, it
  341. * contains a shuffled list of numbers {0, ..., sz-1}. */
  342. for (i = 0; i < sz; ++i) board[i] = i;
  343. dsf = dsf_new(sz);
  344. retry:
  345. dsf_reinit(dsf);
  346. shuffle(board, sz, sizeof (int), rs);
  347. do {
  348. change = false; /* as long as the board potentially has errors */
  349. for (i = 0; i < sz; ++i) {
  350. const int square = dsf_canonify(dsf, board[i]);
  351. const int size = dsf_size(dsf, square);
  352. int merge = SENTINEL, min = maxsize - size + 1;
  353. bool error = false;
  354. int neighbour, neighbour_size, j;
  355. int directions[4];
  356. for (j = 0; j < 4; ++j)
  357. directions[j] = j;
  358. shuffle(directions, 4, sizeof(int), rs);
  359. for (j = 0; j < 4; ++j) {
  360. const int x = (board[i] % w) + dx[directions[j]];
  361. const int y = (board[i] / w) + dy[directions[j]];
  362. if (x < 0 || x >= w || y < 0 || y >= h) continue;
  363. neighbour = dsf_canonify(dsf, w*y + x);
  364. if (square == neighbour) continue;
  365. neighbour_size = dsf_size(dsf, neighbour);
  366. if (size == neighbour_size) error = true;
  367. /* find the smallest neighbour to merge with, which
  368. * wouldn't make the region too large. (This is
  369. * guaranteed by the initial value of `min'.) */
  370. if (neighbour_size < min && random_upto(rs, 10)) {
  371. min = neighbour_size;
  372. merge = neighbour;
  373. }
  374. }
  375. /* if this square is not in error, leave it be */
  376. if (!error) continue;
  377. /* if it is, but we can't fix it, retry the whole board.
  378. * Maybe we could fix it by merging the conflicting
  379. * neighbouring region(s) into some of their neighbours,
  380. * but just restarting works out fine. */
  381. if (merge == SENTINEL) goto retry;
  382. /* merge with the smallest neighbouring workable region. */
  383. dsf_merge(dsf, square, merge);
  384. change = true;
  385. }
  386. } while (change);
  387. for (i = 0; i < sz; ++i) board[i] = dsf_size(dsf, i);
  388. merge_ones(board, w, h);
  389. dsf_free(dsf);
  390. }
  391. static void merge(DSF *dsf, int *connected, int a, int b) {
  392. int c;
  393. assert(dsf);
  394. assert(connected);
  395. a = dsf_canonify(dsf, a);
  396. b = dsf_canonify(dsf, b);
  397. if (a == b) return;
  398. dsf_merge(dsf, a, b);
  399. c = connected[a];
  400. connected[a] = connected[b];
  401. connected[b] = c;
  402. }
  403. static void *memdup(const void *ptr, size_t len, size_t esz) {
  404. void *dup = smalloc(len * esz);
  405. assert(ptr);
  406. memcpy(dup, ptr, len * esz);
  407. return dup;
  408. }
  409. static void expand(struct solver_state *s, int w, int h, int t, int f) {
  410. int j;
  411. assert(s);
  412. assert(s->board[t] == EMPTY); /* expand to empty square */
  413. assert(s->board[f] != EMPTY); /* expand from non-empty square */
  414. printv(
  415. "learn: expanding %d from (%d, %d) into (%d, %d)\n",
  416. s->board[f], f % w, f / w, t % w, t / w);
  417. s->board[t] = s->board[f];
  418. for (j = 0; j < 4; ++j) {
  419. const int x = (t % w) + dx[j];
  420. const int y = (t / w) + dy[j];
  421. const int idx = w*y + x;
  422. if (x < 0 || x >= w || y < 0 || y >= h) continue;
  423. if (s->board[idx] != s->board[t]) continue;
  424. merge(s->dsf, s->connected, t, idx);
  425. }
  426. --s->nempty;
  427. }
  428. static void clear_count(int *board, int sz) {
  429. int i;
  430. for (i = 0; i < sz; ++i) {
  431. if (board[i] >= 0) continue;
  432. else if (board[i] == -SENTINEL) board[i] = EMPTY;
  433. else board[i] = -board[i];
  434. }
  435. }
  436. static void flood_count(int *board, int w, int h, int i, int n, int *c) {
  437. const int sz = w * h;
  438. int k;
  439. if (board[i] == EMPTY) board[i] = -SENTINEL;
  440. else if (board[i] == n) board[i] = -board[i];
  441. else return;
  442. if (--*c == 0) return;
  443. for (k = 0; k < 4; ++k) {
  444. const int x = (i % w) + dx[k];
  445. const int y = (i / w) + dy[k];
  446. const int idx = w*y + x;
  447. if (x < 0 || x >= w || y < 0 || y >= h) continue;
  448. flood_count(board, w, h, idx, n, c);
  449. if (*c == 0) return;
  450. }
  451. }
  452. static bool check_capacity(int *board, int w, int h, int i) {
  453. int n = board[i];
  454. flood_count(board, w, h, i, board[i], &n);
  455. clear_count(board, w * h);
  456. return n == 0;
  457. }
  458. static int expandsize(const int *board, DSF *dsf, int w, int h, int i, int n) {
  459. int j;
  460. int nhits = 0;
  461. int hits[4];
  462. int size = 1;
  463. for (j = 0; j < 4; ++j) {
  464. const int x = (i % w) + dx[j];
  465. const int y = (i / w) + dy[j];
  466. const int idx = w*y + x;
  467. int root;
  468. int m;
  469. if (x < 0 || x >= w || y < 0 || y >= h) continue;
  470. if (board[idx] != n) continue;
  471. root = dsf_canonify(dsf, idx);
  472. for (m = 0; m < nhits && root != hits[m]; ++m);
  473. if (m < nhits) continue;
  474. printv("\t (%d, %d) contrib %d to size\n", x, y, dsf_size(dsf, root));
  475. size += dsf_size(dsf, root);
  476. assert(dsf_size(dsf, root) >= 1);
  477. hits[nhits++] = root;
  478. }
  479. return size;
  480. }
  481. /*
  482. * +---+---+---+---+---+---+---+
  483. * | 6 | | | 2 | | | 2 |
  484. * +---+---+---+---+---+---+---+
  485. * | | 3 | | 6 | | 3 | |
  486. * +---+---+---+---+---+---+---+
  487. * | 3 | | | | | | 1 |
  488. * +---+---+---+---+---+---+---+
  489. * | | 2 | 3 | | 4 | 2 | |
  490. * +---+---+---+---+---+---+---+
  491. * | 2 | | | | | | 3 |
  492. * +---+---+---+---+---+---+---+
  493. * | | 5 | | 1 | | 4 | |
  494. * +---+---+---+---+---+---+---+
  495. * | 4 | | | 3 | | | 3 |
  496. * +---+---+---+---+---+---+---+
  497. */
  498. /* Solving techniques:
  499. *
  500. * CONNECTED COMPONENT FORCED EXPANSION (too big):
  501. * When a CC can only be expanded in one direction, because all the
  502. * other ones would make the CC too big.
  503. * +---+---+---+---+---+
  504. * | 2 | 2 | | 2 | _ |
  505. * +---+---+---+---+---+
  506. *
  507. * CONNECTED COMPONENT FORCED EXPANSION (too small):
  508. * When a CC must include a particular square, because otherwise there
  509. * would not be enough room to complete it. This includes squares not
  510. * adjacent to the CC through learn_critical_square.
  511. * +---+---+
  512. * | 2 | _ |
  513. * +---+---+
  514. *
  515. * DROPPING IN A ONE:
  516. * When an empty square has no neighbouring empty squares and only a 1
  517. * will go into the square (or other CCs would be too big).
  518. * +---+---+---+
  519. * | 2 | 2 | _ |
  520. * +---+---+---+
  521. *
  522. * TODO: generalise DROPPING IN A ONE: find the size of the CC of
  523. * empty squares and a list of all adjacent numbers. See if only one
  524. * number in {1, ..., size} u {all adjacent numbers} is possible.
  525. * Probably this is only effective for a CC size < n for some n (4?)
  526. *
  527. * TODO: backtracking.
  528. */
  529. static void filled_square(struct solver_state *s, int w, int h, int i) {
  530. int j;
  531. for (j = 0; j < 4; ++j) {
  532. const int x = (i % w) + dx[j];
  533. const int y = (i / w) + dy[j];
  534. const int idx = w*y + x;
  535. if (x < 0 || x >= w || y < 0 || y >= h) continue;
  536. if (s->board[i] == s->board[idx])
  537. merge(s->dsf, s->connected, i, idx);
  538. }
  539. }
  540. static void init_solver_state(struct solver_state *s, int w, int h) {
  541. const int sz = w * h;
  542. int i;
  543. assert(s);
  544. s->nempty = 0;
  545. for (i = 0; i < sz; ++i) s->connected[i] = i;
  546. for (i = 0; i < sz; ++i)
  547. if (s->board[i] == EMPTY) ++s->nempty;
  548. else filled_square(s, w, h, i);
  549. }
  550. static bool learn_expand_or_one(struct solver_state *s, int w, int h) {
  551. const int sz = w * h;
  552. int i;
  553. bool learn = false;
  554. assert(s);
  555. for (i = 0; i < sz; ++i) {
  556. int j;
  557. bool one = true;
  558. if (s->board[i] != EMPTY) continue;
  559. for (j = 0; j < 4; ++j) {
  560. const int x = (i % w) + dx[j];
  561. const int y = (i / w) + dy[j];
  562. const int idx = w*y + x;
  563. if (x < 0 || x >= w || y < 0 || y >= h) continue;
  564. if (s->board[idx] == EMPTY) {
  565. one = false;
  566. continue;
  567. }
  568. if (one &&
  569. (s->board[idx] == 1 ||
  570. (s->board[idx] >= expandsize(s->board, s->dsf, w, h,
  571. i, s->board[idx]))))
  572. one = false;
  573. if (dsf_size(s->dsf, idx) == s->board[idx]) continue;
  574. assert(s->board[i] == EMPTY);
  575. s->board[i] = -SENTINEL;
  576. if (check_capacity(s->board, w, h, idx)) continue;
  577. assert(s->board[i] == EMPTY);
  578. printv("learn: expanding in one\n");
  579. expand(s, w, h, i, idx);
  580. learn = true;
  581. break;
  582. }
  583. if (j == 4 && one) {
  584. printv("learn: one at (%d, %d)\n", i % w, i / w);
  585. assert(s->board[i] == EMPTY);
  586. s->board[i] = 1;
  587. assert(s->nempty);
  588. --s->nempty;
  589. learn = true;
  590. }
  591. }
  592. return learn;
  593. }
  594. static bool learn_blocked_expansion(struct solver_state *s, int w, int h) {
  595. const int sz = w * h;
  596. int i;
  597. bool learn = false;
  598. assert(s);
  599. /* for every connected component */
  600. for (i = 0; i < sz; ++i) {
  601. int exp = SENTINEL;
  602. int j;
  603. if (s->board[i] == EMPTY) continue;
  604. j = dsf_canonify(s->dsf, i);
  605. /* (but only for each connected component) */
  606. if (i != j) continue;
  607. /* (and not if it's already complete) */
  608. if (dsf_size(s->dsf, j) == s->board[j]) continue;
  609. /* for each square j _in_ the connected component */
  610. do {
  611. int k;
  612. printv(" looking at (%d, %d)\n", j % w, j / w);
  613. /* for each neighbouring square (idx) */
  614. for (k = 0; k < 4; ++k) {
  615. const int x = (j % w) + dx[k];
  616. const int y = (j / w) + dy[k];
  617. const int idx = w*y + x;
  618. int size;
  619. /* int l;
  620. int nhits = 0;
  621. int hits[4]; */
  622. if (x < 0 || x >= w || y < 0 || y >= h) continue;
  623. if (s->board[idx] != EMPTY) continue;
  624. if (exp == idx) continue;
  625. printv("\ttrying to expand onto (%d, %d)\n", x, y);
  626. /* find out the would-be size of the new connected
  627. * component if we actually expanded into idx */
  628. /*
  629. size = 1;
  630. for (l = 0; l < 4; ++l) {
  631. const int lx = x + dx[l];
  632. const int ly = y + dy[l];
  633. const int idxl = w*ly + lx;
  634. int root;
  635. int m;
  636. if (lx < 0 || lx >= w || ly < 0 || ly >= h) continue;
  637. if (board[idxl] != board[j]) continue;
  638. root = dsf_canonify(dsf, idxl);
  639. for (m = 0; m < nhits && root != hits[m]; ++m);
  640. if (m != nhits) continue;
  641. // printv("\t (%d, %d) contributed %d to size\n", lx, ly, dsf[root] >> 2);
  642. size += dsf_size(dsf, root);
  643. assert(dsf_size(dsf, root) >= 1);
  644. hits[nhits++] = root;
  645. }
  646. */
  647. size = expandsize(s->board, s->dsf, w, h, idx, s->board[j]);
  648. /* ... and see if that size is too big, or if we
  649. * have other expansion candidates. Otherwise
  650. * remember the (so far) only candidate. */
  651. printv("\tthat would give a size of %d\n", size);
  652. if (size > s->board[j]) continue;
  653. /* printv("\tnow knowing %d expansions\n", nexpand + 1); */
  654. if (exp != SENTINEL) goto next_i;
  655. assert(exp != idx);
  656. exp = idx;
  657. }
  658. j = s->connected[j]; /* next square in the same CC */
  659. assert(s->board[i] == s->board[j]);
  660. } while (j != i);
  661. /* end: for each square j _in_ the connected component */
  662. if (exp == SENTINEL) continue;
  663. printv("learning to expand\n");
  664. expand(s, w, h, exp, i);
  665. learn = true;
  666. next_i:
  667. ;
  668. }
  669. /* end: for each connected component */
  670. return learn;
  671. }
  672. static bool learn_critical_square(struct solver_state *s, int w, int h) {
  673. const int sz = w * h;
  674. int i;
  675. bool learn = false;
  676. assert(s);
  677. /* for each connected component */
  678. for (i = 0; i < sz; ++i) {
  679. int j, slack;
  680. if (s->board[i] == EMPTY) continue;
  681. if (i != dsf_canonify(s->dsf, i)) continue;
  682. slack = s->board[i] - dsf_size(s->dsf, i);
  683. if (slack == 0) continue;
  684. assert(s->board[i] != 1);
  685. /* for each empty square */
  686. for (j = 0; j < sz; ++j) {
  687. if (s->board[j] == EMPTY) {
  688. /* if it's too far away from the CC, don't bother */
  689. int k = i, jx = j % w, jy = j / w;
  690. do {
  691. int kx = k % w, ky = k / w;
  692. if (abs(kx - jx) + abs(ky - jy) <= slack) break;
  693. k = s->connected[k];
  694. } while (i != k);
  695. if (i == k) continue; /* not within range */
  696. } else continue;
  697. s->board[j] = -SENTINEL;
  698. if (check_capacity(s->board, w, h, i)) continue;
  699. /* if not expanding s->board[i] to s->board[j] implies
  700. * that s->board[i] can't reach its full size, ... */
  701. assert(s->nempty);
  702. printv(
  703. "learn: ds %d at (%d, %d) blocking (%d, %d)\n",
  704. s->board[i], j % w, j / w, i % w, i / w);
  705. --s->nempty;
  706. s->board[j] = s->board[i];
  707. filled_square(s, w, h, j);
  708. learn = true;
  709. }
  710. }
  711. return learn;
  712. }
  713. #if 0
  714. static void print_bitmap(int *bitmap, int w, int h) {
  715. if (verbose) {
  716. int x, y;
  717. for (y = 0; y < h; y++) {
  718. for (x = 0; x < w; x++) {
  719. printv(" %03x", bm[y*w+x]);
  720. }
  721. printv("\n");
  722. }
  723. }
  724. }
  725. #endif
  726. static bool learn_bitmap_deductions(struct solver_state *s, int w, int h)
  727. {
  728. const int sz = w * h;
  729. int *bm = s->bm;
  730. DSF *dsf = s->bmdsf;
  731. int *minsize = s->bmminsize;
  732. int x, y, i, j, n;
  733. bool learn = false;
  734. /*
  735. * This function does deductions based on building up a bitmap
  736. * which indicates the possible numbers that can appear in each
  737. * grid square. If we can rule out all but one possibility for a
  738. * particular square, then we've found out the value of that
  739. * square. In particular, this is one of the few forms of
  740. * deduction capable of inferring the existence of a 'ghost
  741. * region', i.e. a region which has none of its squares filled in
  742. * at all.
  743. *
  744. * The reasoning goes like this. A currently unfilled square S can
  745. * turn out to contain digit n in exactly two ways: either S is
  746. * part of an n-region which also includes some currently known
  747. * connected component of squares with n in, or S is part of an
  748. * n-region separate from _all_ currently known connected
  749. * components. If we can rule out both possibilities, then square
  750. * S can't contain digit n at all.
  751. *
  752. * The former possibility: if there's a region of size n
  753. * containing both S and some existing component C, then that
  754. * means the distance from S to C must be small enough that C
  755. * could be extended to include S without becoming too big. So we
  756. * can do a breadth-first search out from all existing components
  757. * with n in them, to identify all the squares which could be
  758. * joined to any of them.
  759. *
  760. * The latter possibility: if there's a region of size n that
  761. * doesn't contain _any_ existing component, then it also can't
  762. * contain any square adjacent to an existing component either. So
  763. * we can identify all the EMPTY squares not adjacent to any
  764. * existing square with n in, and group them into connected
  765. * components; then any component of size less than n is ruled
  766. * out, because there wouldn't be room to create a completely new
  767. * n-region in it.
  768. *
  769. * In fact we process these possibilities in the other order.
  770. * First we find all the squares not adjacent to an existing
  771. * square with n in; then we winnow those by removing too-small
  772. * connected components, to get the set of squares which could
  773. * possibly be part of a brand new n-region; and finally we do the
  774. * breadth-first search to add in the set of squares which could
  775. * possibly be added to some existing n-region.
  776. */
  777. /*
  778. * Start by initialising our bitmap to 'all numbers possible in
  779. * all squares'.
  780. */
  781. for (y = 0; y < h; y++)
  782. for (x = 0; x < w; x++)
  783. bm[y*w+x] = (1 << 10) - (1 << 1); /* bits 1,2,...,9 now set */
  784. #if 0
  785. printv("initial bitmap:\n");
  786. print_bitmap(bm, w, h);
  787. #endif
  788. /*
  789. * Now completely zero out the bitmap for squares that are already
  790. * filled in (we aren't interested in those anyway). Also, for any
  791. * filled square, eliminate its number from all its neighbours
  792. * (because, as discussed above, the neighbours couldn't be part
  793. * of a _new_ region with that number in it, and that's the case
  794. * we consider first).
  795. */
  796. for (y = 0; y < h; y++) {
  797. for (x = 0; x < w; x++) {
  798. i = y*w+x;
  799. n = s->board[i];
  800. if (n != EMPTY) {
  801. bm[i] = 0;
  802. if (x > 0)
  803. bm[i-1] &= ~(1 << n);
  804. if (x+1 < w)
  805. bm[i+1] &= ~(1 << n);
  806. if (y > 0)
  807. bm[i-w] &= ~(1 << n);
  808. if (y+1 < h)
  809. bm[i+w] &= ~(1 << n);
  810. }
  811. }
  812. }
  813. #if 0
  814. printv("bitmap after filled squares:\n");
  815. print_bitmap(bm, w, h);
  816. #endif
  817. /*
  818. * Now, for each n, we separately find the connected components of
  819. * squares for which n is still a possibility. Then discard any
  820. * component of size < n, because that component is too small to
  821. * have a completely new n-region in it.
  822. */
  823. for (n = 1; n <= 9; n++) {
  824. dsf_reinit(dsf);
  825. /* Build the dsf */
  826. for (y = 0; y < h; y++)
  827. for (x = 0; x+1 < w; x++)
  828. if (bm[y*w+x] & bm[y*w+(x+1)] & (1 << n))
  829. dsf_merge(dsf, y*w+x, y*w+(x+1));
  830. for (y = 0; y+1 < h; y++)
  831. for (x = 0; x < w; x++)
  832. if (bm[y*w+x] & bm[(y+1)*w+x] & (1 << n))
  833. dsf_merge(dsf, y*w+x, (y+1)*w+x);
  834. /* Query the dsf */
  835. for (i = 0; i < sz; i++)
  836. if ((bm[i] & (1 << n)) && dsf_size(dsf, i) < n)
  837. bm[i] &= ~(1 << n);
  838. }
  839. #if 0
  840. printv("bitmap after winnowing small components:\n");
  841. print_bitmap(bm, w, h);
  842. #endif
  843. /*
  844. * Now our bitmap includes every square which could be part of a
  845. * completely new region, of any size. Extend it to include
  846. * squares which could be part of an existing region.
  847. */
  848. for (n = 1; n <= 9; n++) {
  849. /*
  850. * We're going to do a breadth-first search starting from
  851. * existing connected components with cell value n, to find
  852. * all cells they might possibly extend into.
  853. *
  854. * The quantity we compute, for each square, is 'minimum size
  855. * that any existing CC would have to have if extended to
  856. * include this square'. So squares already _in_ an existing
  857. * CC are initialised to the size of that CC; then we search
  858. * outwards using the rule that if a square's score is j, then
  859. * its neighbours can't score more than j+1.
  860. *
  861. * Scores are capped at n+1, because if a square scores more
  862. * than n then that's enough to know it can't possibly be
  863. * reached by extending an existing region - we don't need to
  864. * know exactly _how far_ out of reach it is.
  865. */
  866. for (i = 0; i < sz; i++) {
  867. if (s->board[i] == n) {
  868. /* Square is part of an existing CC. */
  869. minsize[i] = dsf_size(s->dsf, i);
  870. } else {
  871. /* Otherwise, initialise to the maximum score n+1;
  872. * we'll reduce this later if we find a neighbouring
  873. * square with a lower score. */
  874. minsize[i] = n+1;
  875. }
  876. }
  877. for (j = 1; j < n; j++) {
  878. /*
  879. * Find neighbours of cells scoring j, and set their score
  880. * to at most j+1.
  881. *
  882. * Doing the BFS this way means we need n passes over the
  883. * grid, which isn't entirely optimal but it seems to be
  884. * fast enough for the moment. This could probably be
  885. * improved by keeping a linked-list queue of cells in
  886. * some way, but I think you'd have to be a bit careful to
  887. * insert things into the right place in the queue; this
  888. * way is easier not to get wrong.
  889. */
  890. for (y = 0; y < h; y++) {
  891. for (x = 0; x < w; x++) {
  892. i = y*w+x;
  893. if (minsize[i] == j) {
  894. if (x > 0 && minsize[i-1] > j+1)
  895. minsize[i-1] = j+1;
  896. if (x+1 < w && minsize[i+1] > j+1)
  897. minsize[i+1] = j+1;
  898. if (y > 0 && minsize[i-w] > j+1)
  899. minsize[i-w] = j+1;
  900. if (y+1 < h && minsize[i+w] > j+1)
  901. minsize[i+w] = j+1;
  902. }
  903. }
  904. }
  905. }
  906. /*
  907. * Now, every cell scoring at most n should have its 1<<n bit
  908. * in the bitmap reinstated, because we've found that it's
  909. * potentially reachable by extending an existing CC.
  910. */
  911. for (i = 0; i < sz; i++)
  912. if (minsize[i] <= n)
  913. bm[i] |= 1<<n;
  914. }
  915. #if 0
  916. printv("bitmap after bfs:\n");
  917. print_bitmap(bm, w, h);
  918. #endif
  919. /*
  920. * Now our bitmap is complete. Look for entries with only one bit
  921. * set; those are squares with only one possible number, in which
  922. * case we can fill that number in.
  923. */
  924. for (i = 0; i < sz; i++) {
  925. if (bm[i] && !(bm[i] & (bm[i]-1))) { /* is bm[i] a power of two? */
  926. int val = bm[i];
  927. /* Integer log2, by simple binary search. */
  928. n = 0;
  929. if (val >> 8) { val >>= 8; n += 8; }
  930. if (val >> 4) { val >>= 4; n += 4; }
  931. if (val >> 2) { val >>= 2; n += 2; }
  932. if (val >> 1) { val >>= 1; n += 1; }
  933. /* Double-check that we ended up with a sensible
  934. * answer. */
  935. assert(1 <= n);
  936. assert(n <= 9);
  937. assert(bm[i] == (1 << n));
  938. if (s->board[i] == EMPTY) {
  939. printv("learn: %d is only possibility at (%d, %d)\n",
  940. n, i % w, i / w);
  941. s->board[i] = n;
  942. filled_square(s, w, h, i);
  943. assert(s->nempty);
  944. --s->nempty;
  945. learn = true;
  946. }
  947. }
  948. }
  949. return learn;
  950. }
  951. static bool solver(const int *orig, int w, int h, char **solution) {
  952. const int sz = w * h;
  953. struct solver_state ss;
  954. ss.board = memdup(orig, sz, sizeof (int));
  955. ss.dsf = dsf_new(sz); /* eqv classes: connected components */
  956. ss.connected = snewn(sz, int); /* connected[n] := n.next; */
  957. /* cyclic disjoint singly linked lists, same partitioning as dsf.
  958. * The lists lets you iterate over a partition given any member */
  959. ss.bm = snewn(sz, int);
  960. ss.bmdsf = dsf_new(sz);
  961. ss.bmminsize = snewn(sz, int);
  962. printv("trying to solve this:\n");
  963. print_board(ss.board, w, h);
  964. init_solver_state(&ss, w, h);
  965. do {
  966. if (learn_blocked_expansion(&ss, w, h)) continue;
  967. if (learn_expand_or_one(&ss, w, h)) continue;
  968. if (learn_critical_square(&ss, w, h)) continue;
  969. if (learn_bitmap_deductions(&ss, w, h)) continue;
  970. break;
  971. } while (ss.nempty);
  972. printv("best guess:\n");
  973. print_board(ss.board, w, h);
  974. if (solution) {
  975. int i;
  976. *solution = snewn(sz + 2, char);
  977. **solution = 's';
  978. for (i = 0; i < sz; ++i) (*solution)[i + 1] = ss.board[i] + '0';
  979. (*solution)[sz + 1] = '\0';
  980. }
  981. dsf_free(ss.dsf);
  982. sfree(ss.board);
  983. sfree(ss.connected);
  984. sfree(ss.bm);
  985. dsf_free(ss.bmdsf);
  986. sfree(ss.bmminsize);
  987. return !ss.nempty;
  988. }
  989. static DSF *make_dsf(DSF *dsf, int *board, const int w, const int h) {
  990. const int sz = w * h;
  991. int i;
  992. if (!dsf)
  993. dsf = dsf_new_min(w * h);
  994. else
  995. dsf_reinit(dsf);
  996. for (i = 0; i < sz; ++i) {
  997. int j;
  998. for (j = 0; j < 4; ++j) {
  999. const int x = (i % w) + dx[j];
  1000. const int y = (i / w) + dy[j];
  1001. const int k = w*y + x;
  1002. if (x < 0 || x >= w || y < 0 || y >= h) continue;
  1003. if (board[i] == board[k]) dsf_merge(dsf, i, k);
  1004. }
  1005. }
  1006. return dsf;
  1007. }
  1008. static void minimize_clue_set(int *board, int w, int h, random_state *rs)
  1009. {
  1010. const int sz = w * h;
  1011. int *shuf = snewn(sz, int), i;
  1012. DSF *dsf;
  1013. int *next;
  1014. for (i = 0; i < sz; ++i) shuf[i] = i;
  1015. shuffle(shuf, sz, sizeof (int), rs);
  1016. /*
  1017. * First, try to eliminate an entire region at a time if possible,
  1018. * because inferring the existence of a completely unclued region
  1019. * is a particularly good aspect of this puzzle type and we want
  1020. * to encourage it to happen.
  1021. *
  1022. * Begin by identifying the regions as linked lists of cells using
  1023. * the 'next' array.
  1024. */
  1025. dsf = make_dsf(NULL, board, w, h);
  1026. next = snewn(sz, int);
  1027. for (i = 0; i < sz; ++i) {
  1028. int j = dsf_minimal(dsf, i);
  1029. if (i == j) {
  1030. /* First cell of a region; set next[i] = -1 to indicate
  1031. * end-of-list. */
  1032. next[i] = -1;
  1033. } else {
  1034. /* Add this cell to a region which already has a
  1035. * linked-list head, by pointing the minimal element j
  1036. * at this one, and pointing this one in turn at wherever
  1037. * j previously pointed. (This should end up with the
  1038. * elements linked in the order 1,n,n-1,n-2,...,2, which
  1039. * is a bit weird-looking, but any order is fine.)
  1040. */
  1041. assert(j < i);
  1042. next[i] = next[j];
  1043. next[j] = i;
  1044. }
  1045. }
  1046. /*
  1047. * Now loop over the grid cells in our shuffled order, and each
  1048. * time we encounter a region for the first time, try to remove it
  1049. * all. Then we set next[canonical index] to -2 rather than -1, to
  1050. * mark it as already tried.
  1051. *
  1052. * Doing this in a loop over _cells_, rather than extracting and
  1053. * shuffling a list of _regions_, is intended to skew the
  1054. * probabilities towards trying to remove larger regions first
  1055. * (but without anything as crudely predictable as enforcing that
  1056. * we _always_ process regions in descending size order). Region
  1057. * removals might well be mutually exclusive, and larger ghost
  1058. * regions are more interesting, so we want to bias towards them
  1059. * if we can.
  1060. */
  1061. for (i = 0; i < sz; ++i) {
  1062. int j = dsf_minimal(dsf, shuf[i]);
  1063. if (next[j] != -2) {
  1064. int tmp = board[j];
  1065. int k;
  1066. /* Blank out the whole thing. */
  1067. for (k = j; k >= 0; k = next[k])
  1068. board[k] = EMPTY;
  1069. if (!solver(board, w, h, NULL)) {
  1070. /* Wasn't still solvable; reinstate it all */
  1071. for (k = j; k >= 0; k = next[k])
  1072. board[k] = tmp;
  1073. }
  1074. /* Either way, don't try this region again. */
  1075. next[j] = -2;
  1076. }
  1077. }
  1078. sfree(next);
  1079. dsf_free(dsf);
  1080. /*
  1081. * Now go through individual cells, in the same shuffled order,
  1082. * and try to remove each one by itself.
  1083. */
  1084. for (i = 0; i < sz; ++i) {
  1085. int tmp = board[shuf[i]];
  1086. board[shuf[i]] = EMPTY;
  1087. if (!solver(board, w, h, NULL)) board[shuf[i]] = tmp;
  1088. }
  1089. sfree(shuf);
  1090. }
  1091. static int encode_run(char *buffer, int run)
  1092. {
  1093. int i = 0;
  1094. for (; run > 26; run -= 26)
  1095. buffer[i++] = 'z';
  1096. if (run)
  1097. buffer[i++] = 'a' - 1 + run;
  1098. return i;
  1099. }
  1100. static char *new_game_desc(const game_params *params, random_state *rs,
  1101. char **aux, bool interactive)
  1102. {
  1103. const int w = params->w, h = params->h, sz = w * h;
  1104. int *board = snewn(sz, int), i, j, run;
  1105. char *description = snewn(sz + 1, char);
  1106. make_board(board, w, h, rs);
  1107. minimize_clue_set(board, w, h, rs);
  1108. for (run = j = i = 0; i < sz; ++i) {
  1109. assert(board[i] >= 0);
  1110. assert(board[i] < 10);
  1111. if (board[i] == 0) {
  1112. ++run;
  1113. } else {
  1114. j += encode_run(description + j, run);
  1115. run = 0;
  1116. description[j++] = board[i] + '0';
  1117. }
  1118. }
  1119. j += encode_run(description + j, run);
  1120. description[j++] = '\0';
  1121. sfree(board);
  1122. return sresize(description, j, char);
  1123. }
  1124. static const char *validate_desc(const game_params *params, const char *desc)
  1125. {
  1126. const int sz = params->w * params->h;
  1127. const char m = '0' + max(max(params->w, params->h), 3);
  1128. int area;
  1129. for (area = 0; *desc; ++desc) {
  1130. if (*desc >= 'a' && *desc <= 'z') area += *desc - 'a' + 1;
  1131. else if (*desc >= '0' && *desc <= m) ++area;
  1132. else {
  1133. static char s[] = "Invalid character '%""' in game description";
  1134. int n = sprintf(s, "Invalid character '%1c' in game description",
  1135. *desc);
  1136. assert(n + 1 <= lenof(s)); /* +1 for the terminating NUL */
  1137. return s;
  1138. }
  1139. if (area > sz) return "Too much data to fit in grid";
  1140. }
  1141. return (area < sz) ? "Not enough data to fill grid" : NULL;
  1142. }
  1143. static key_label *game_request_keys(const game_params *params, int *nkeys)
  1144. {
  1145. int i;
  1146. key_label *keys = snewn(11, key_label);
  1147. *nkeys = 11;
  1148. for(i = 0; i < 10; ++i)
  1149. {
  1150. keys[i].button = '0' + i;
  1151. keys[i].label = NULL;
  1152. }
  1153. keys[10].button = '\b';
  1154. keys[10].label = NULL;
  1155. return keys;
  1156. }
  1157. static game_state *new_game(midend *me, const game_params *params,
  1158. const char *desc)
  1159. {
  1160. game_state *state = snew(game_state);
  1161. int sz = params->w * params->h;
  1162. int i;
  1163. state->cheated = false;
  1164. state->completed = false;
  1165. state->shared = snew(struct shared_state);
  1166. state->shared->refcnt = 1;
  1167. state->shared->params = *params; /* struct copy */
  1168. state->shared->clues = snewn(sz, int);
  1169. for (i = 0; *desc; ++desc) {
  1170. if (*desc >= 'a' && *desc <= 'z') {
  1171. int j = *desc - 'a' + 1;
  1172. assert(i + j <= sz);
  1173. for (; j; --j) state->shared->clues[i++] = 0;
  1174. } else state->shared->clues[i++] = *desc - '0';
  1175. }
  1176. state->board = memdup(state->shared->clues, sz, sizeof (int));
  1177. return state;
  1178. }
  1179. static game_state *dup_game(const game_state *state)
  1180. {
  1181. const int sz = state->shared->params.w * state->shared->params.h;
  1182. game_state *ret = snew(game_state);
  1183. ret->board = memdup(state->board, sz, sizeof (int));
  1184. ret->shared = state->shared;
  1185. ret->cheated = state->cheated;
  1186. ret->completed = state->completed;
  1187. ++ret->shared->refcnt;
  1188. return ret;
  1189. }
  1190. static void free_game(game_state *state)
  1191. {
  1192. assert(state);
  1193. sfree(state->board);
  1194. if (--state->shared->refcnt == 0) {
  1195. sfree(state->shared->clues);
  1196. sfree(state->shared);
  1197. }
  1198. sfree(state);
  1199. }
  1200. static char *solve_game(const game_state *state, const game_state *currstate,
  1201. const char *aux, const char **error)
  1202. {
  1203. if (aux == NULL) {
  1204. const int w = state->shared->params.w;
  1205. const int h = state->shared->params.h;
  1206. char *new_aux;
  1207. if (!solver(state->board, w, h, &new_aux))
  1208. *error = "Sorry, I couldn't find a solution";
  1209. return new_aux;
  1210. }
  1211. return dupstr(aux);
  1212. }
  1213. /*****************************************************************************
  1214. * USER INTERFACE STATE AND ACTION *
  1215. *****************************************************************************/
  1216. struct game_ui {
  1217. bool *sel; /* w*h highlighted squares, or NULL */
  1218. int cur_x, cur_y;
  1219. bool cur_visible, keydragging;
  1220. };
  1221. static game_ui *new_ui(const game_state *state)
  1222. {
  1223. game_ui *ui = snew(game_ui);
  1224. ui->sel = NULL;
  1225. ui->cur_x = ui->cur_y = 0;
  1226. ui->cur_visible = getenv_bool("PUZZLES_SHOW_CURSOR", false);
  1227. ui->keydragging = false;
  1228. return ui;
  1229. }
  1230. static void free_ui(game_ui *ui)
  1231. {
  1232. if (ui->sel)
  1233. sfree(ui->sel);
  1234. sfree(ui);
  1235. }
  1236. static void game_changed_state(game_ui *ui, const game_state *oldstate,
  1237. const game_state *newstate)
  1238. {
  1239. /* Clear any selection */
  1240. if (ui->sel) {
  1241. sfree(ui->sel);
  1242. ui->sel = NULL;
  1243. }
  1244. ui->keydragging = false;
  1245. }
  1246. static const char *current_key_label(const game_ui *ui,
  1247. const game_state *state, int button)
  1248. {
  1249. const int w = state->shared->params.w;
  1250. if (IS_CURSOR_SELECT(button) && ui->cur_visible) {
  1251. if (button == CURSOR_SELECT) {
  1252. if (ui->keydragging) return "Stop";
  1253. return "Multiselect";
  1254. }
  1255. if (button == CURSOR_SELECT2 &&
  1256. !state->shared->clues[w*ui->cur_y + ui->cur_x])
  1257. return (ui->sel[w*ui->cur_y + ui->cur_x]) ? "Deselect" : "Select";
  1258. }
  1259. return "";
  1260. }
  1261. #define PREFERRED_TILE_SIZE 32
  1262. #define TILE_SIZE (ds->tilesize)
  1263. #define BORDER (TILE_SIZE / 2)
  1264. #define BORDER_WIDTH (max(TILE_SIZE / 32, 1))
  1265. struct game_drawstate {
  1266. struct game_params params;
  1267. int tilesize;
  1268. bool started;
  1269. int *v, *flags;
  1270. DSF *dsf_scratch;
  1271. int *border_scratch;
  1272. };
  1273. static char *interpret_move(const game_state *state, game_ui *ui,
  1274. const game_drawstate *ds,
  1275. int x, int y, int button)
  1276. {
  1277. const int w = state->shared->params.w;
  1278. const int h = state->shared->params.h;
  1279. const int tx = (x + TILE_SIZE - BORDER) / TILE_SIZE - 1;
  1280. const int ty = (y + TILE_SIZE - BORDER) / TILE_SIZE - 1;
  1281. char *move = NULL;
  1282. int i;
  1283. assert(ui);
  1284. assert(ds);
  1285. button &= ~MOD_MASK;
  1286. if (button == LEFT_BUTTON || button == LEFT_DRAG) {
  1287. /* A left-click anywhere will clear the current selection. */
  1288. if (button == LEFT_BUTTON) {
  1289. if (ui->sel) {
  1290. sfree(ui->sel);
  1291. ui->sel = NULL;
  1292. }
  1293. }
  1294. if (tx >= 0 && tx < w && ty >= 0 && ty < h) {
  1295. if (!ui->sel) {
  1296. ui->sel = snewn(w*h, bool);
  1297. memset(ui->sel, 0, w*h*sizeof(bool));
  1298. }
  1299. if (!state->shared->clues[w*ty+tx])
  1300. ui->sel[w*ty+tx] = true;
  1301. }
  1302. ui->cur_visible = false;
  1303. return MOVE_UI_UPDATE;
  1304. }
  1305. if (IS_CURSOR_MOVE(button)) {
  1306. ui->cur_visible = true;
  1307. move_cursor(button, &ui->cur_x, &ui->cur_y, w, h, false);
  1308. if (ui->keydragging) goto select_square;
  1309. return MOVE_UI_UPDATE;
  1310. }
  1311. if (button == CURSOR_SELECT) {
  1312. if (!ui->cur_visible) {
  1313. ui->cur_visible = true;
  1314. return MOVE_UI_UPDATE;
  1315. }
  1316. ui->keydragging = !ui->keydragging;
  1317. if (!ui->keydragging) return MOVE_UI_UPDATE;
  1318. select_square:
  1319. if (!ui->sel) {
  1320. ui->sel = snewn(w*h, bool);
  1321. memset(ui->sel, 0, w*h*sizeof(bool));
  1322. }
  1323. if (!state->shared->clues[w*ui->cur_y + ui->cur_x])
  1324. ui->sel[w*ui->cur_y + ui->cur_x] = true;
  1325. return MOVE_UI_UPDATE;
  1326. }
  1327. if (button == CURSOR_SELECT2) {
  1328. if (!ui->cur_visible) {
  1329. ui->cur_visible = true;
  1330. return MOVE_UI_UPDATE;
  1331. }
  1332. if (!ui->sel) {
  1333. ui->sel = snewn(w*h, bool);
  1334. memset(ui->sel, 0, w*h*sizeof(bool));
  1335. }
  1336. ui->keydragging = false;
  1337. if (!state->shared->clues[w*ui->cur_y + ui->cur_x])
  1338. ui->sel[w*ui->cur_y + ui->cur_x] ^= 1;
  1339. for (i = 0; i < w*h && !ui->sel[i]; i++);
  1340. if (i == w*h) {
  1341. sfree(ui->sel);
  1342. ui->sel = NULL;
  1343. }
  1344. return MOVE_UI_UPDATE;
  1345. }
  1346. if (button == '\b' || button == 27) {
  1347. sfree(ui->sel);
  1348. ui->sel = NULL;
  1349. ui->keydragging = false;
  1350. return MOVE_UI_UPDATE;
  1351. }
  1352. if (button < '0' || button > '9') return MOVE_UNUSED;
  1353. button -= '0';
  1354. if (button > (w == 2 && h == 2 ? 3 : max(w, h))) return MOVE_UNUSED;
  1355. ui->keydragging = false;
  1356. for (i = 0; i < w*h; i++) {
  1357. char buf[32];
  1358. if ((ui->sel && ui->sel[i]) ||
  1359. (!ui->sel && ui->cur_visible && (w*ui->cur_y+ui->cur_x) == i)) {
  1360. if (state->shared->clues[i] != 0) continue; /* in case cursor is on clue */
  1361. if (state->board[i] != button) {
  1362. sprintf(buf, "%s%d", move ? "," : "", i);
  1363. if (move) {
  1364. move = srealloc(move, strlen(move)+strlen(buf)+1);
  1365. strcat(move, buf);
  1366. } else {
  1367. move = smalloc(strlen(buf)+1);
  1368. strcpy(move, buf);
  1369. }
  1370. }
  1371. }
  1372. }
  1373. if (move) {
  1374. char buf[32];
  1375. sprintf(buf, "_%d", button);
  1376. move = srealloc(move, strlen(move)+strlen(buf)+1);
  1377. strcat(move, buf);
  1378. }
  1379. if (!ui->sel) return move ? move : MOVE_NO_EFFECT;
  1380. sfree(ui->sel);
  1381. ui->sel = NULL;
  1382. /* Need to update UI at least, as we cleared the selection */
  1383. return move ? move : MOVE_UI_UPDATE;
  1384. }
  1385. static game_state *execute_move(const game_state *state, const char *move)
  1386. {
  1387. game_state *new_state = NULL;
  1388. const int sz = state->shared->params.w * state->shared->params.h;
  1389. if (*move == 's') {
  1390. int i = 0;
  1391. if (strlen(move) != sz + 1) return NULL;
  1392. new_state = dup_game(state);
  1393. for (++move; i < sz; ++i) new_state->board[i] = move[i] - '0';
  1394. new_state->cheated = true;
  1395. } else {
  1396. int value;
  1397. char *endptr, *delim = strchr(move, '_');
  1398. if (!delim) goto err;
  1399. value = strtol(delim+1, &endptr, 0);
  1400. if (*endptr || endptr == delim+1) goto err;
  1401. if (value < 0 || value > 9) goto err;
  1402. new_state = dup_game(state);
  1403. while (*move) {
  1404. const int i = strtol(move, &endptr, 0);
  1405. if (endptr == move) goto err;
  1406. if (i < 0 || i >= sz) goto err;
  1407. new_state->board[i] = value;
  1408. if (*endptr == '_') break;
  1409. if (*endptr != ',') goto err;
  1410. move = endptr + 1;
  1411. }
  1412. }
  1413. /*
  1414. * Check for completion.
  1415. */
  1416. if (!new_state->completed) {
  1417. const int w = new_state->shared->params.w;
  1418. const int h = new_state->shared->params.h;
  1419. const int sz = w * h;
  1420. DSF *dsf = make_dsf(NULL, new_state->board, w, h);
  1421. int i;
  1422. for (i = 0; i < sz && new_state->board[i] == dsf_size(dsf, i); ++i);
  1423. dsf_free(dsf);
  1424. if (i == sz)
  1425. new_state->completed = true;
  1426. }
  1427. return new_state;
  1428. err:
  1429. if (new_state) free_game(new_state);
  1430. return NULL;
  1431. }
  1432. /* ----------------------------------------------------------------------
  1433. * Drawing routines.
  1434. */
  1435. #define FLASH_TIME 0.4F
  1436. #define COL_CLUE COL_GRID
  1437. enum {
  1438. COL_BACKGROUND,
  1439. COL_GRID,
  1440. COL_HIGHLIGHT,
  1441. COL_CORRECT,
  1442. COL_ERROR,
  1443. COL_USER,
  1444. COL_CURSOR,
  1445. NCOLOURS
  1446. };
  1447. static void game_compute_size(const game_params *params, int tilesize,
  1448. const game_ui *ui, int *x, int *y)
  1449. {
  1450. *x = (params->w + 1) * tilesize;
  1451. *y = (params->h + 1) * tilesize;
  1452. }
  1453. static void game_set_size(drawing *dr, game_drawstate *ds,
  1454. const game_params *params, int tilesize)
  1455. {
  1456. ds->tilesize = tilesize;
  1457. }
  1458. static float *game_colours(frontend *fe, int *ncolours)
  1459. {
  1460. float *ret = snewn(3 * NCOLOURS, float);
  1461. frontend_default_colour(fe, &ret[COL_BACKGROUND * 3]);
  1462. ret[COL_GRID * 3 + 0] = 0.0F;
  1463. ret[COL_GRID * 3 + 1] = 0.0F;
  1464. ret[COL_GRID * 3 + 2] = 0.0F;
  1465. ret[COL_HIGHLIGHT * 3 + 0] = 0.7F * ret[COL_BACKGROUND * 3 + 0];
  1466. ret[COL_HIGHLIGHT * 3 + 1] = 0.7F * ret[COL_BACKGROUND * 3 + 1];
  1467. ret[COL_HIGHLIGHT * 3 + 2] = 0.7F * ret[COL_BACKGROUND * 3 + 2];
  1468. ret[COL_CORRECT * 3 + 0] = 0.9F * ret[COL_BACKGROUND * 3 + 0];
  1469. ret[COL_CORRECT * 3 + 1] = 0.9F * ret[COL_BACKGROUND * 3 + 1];
  1470. ret[COL_CORRECT * 3 + 2] = 0.9F * ret[COL_BACKGROUND * 3 + 2];
  1471. ret[COL_CURSOR * 3 + 0] = 0.5F * ret[COL_BACKGROUND * 3 + 0];
  1472. ret[COL_CURSOR * 3 + 1] = 0.5F * ret[COL_BACKGROUND * 3 + 1];
  1473. ret[COL_CURSOR * 3 + 2] = 0.5F * ret[COL_BACKGROUND * 3 + 2];
  1474. ret[COL_ERROR * 3 + 0] = 1.0F;
  1475. ret[COL_ERROR * 3 + 1] = 0.85F * ret[COL_BACKGROUND * 3 + 1];
  1476. ret[COL_ERROR * 3 + 2] = 0.85F * ret[COL_BACKGROUND * 3 + 2];
  1477. ret[COL_USER * 3 + 0] = 0.0F;
  1478. ret[COL_USER * 3 + 1] = 0.6F * ret[COL_BACKGROUND * 3 + 1];
  1479. ret[COL_USER * 3 + 2] = 0.0F;
  1480. *ncolours = NCOLOURS;
  1481. return ret;
  1482. }
  1483. static game_drawstate *game_new_drawstate(drawing *dr, const game_state *state)
  1484. {
  1485. struct game_drawstate *ds = snew(struct game_drawstate);
  1486. int i;
  1487. ds->tilesize = PREFERRED_TILE_SIZE;
  1488. ds->started = false;
  1489. ds->params = state->shared->params;
  1490. ds->v = snewn(ds->params.w * ds->params.h, int);
  1491. ds->flags = snewn(ds->params.w * ds->params.h, int);
  1492. for (i = 0; i < ds->params.w * ds->params.h; i++)
  1493. ds->v[i] = ds->flags[i] = -1;
  1494. ds->border_scratch = snewn(ds->params.w * ds->params.h, int);
  1495. ds->dsf_scratch = NULL;
  1496. return ds;
  1497. }
  1498. static void game_free_drawstate(drawing *dr, game_drawstate *ds)
  1499. {
  1500. sfree(ds->v);
  1501. sfree(ds->flags);
  1502. sfree(ds->border_scratch);
  1503. dsf_free(ds->dsf_scratch);
  1504. sfree(ds);
  1505. }
  1506. #define BORDER_U 0x001
  1507. #define BORDER_D 0x002
  1508. #define BORDER_L 0x004
  1509. #define BORDER_R 0x008
  1510. #define BORDER_UR 0x010
  1511. #define BORDER_DR 0x020
  1512. #define BORDER_UL 0x040
  1513. #define BORDER_DL 0x080
  1514. #define HIGH_BG 0x100
  1515. #define CORRECT_BG 0x200
  1516. #define ERROR_BG 0x400
  1517. #define USER_COL 0x800
  1518. #define CURSOR_SQ 0x1000
  1519. static void draw_square(drawing *dr, game_drawstate *ds, int x, int y,
  1520. int n, int flags)
  1521. {
  1522. assert(dr);
  1523. assert(ds);
  1524. /*
  1525. * Clip to the grid square.
  1526. */
  1527. clip(dr, BORDER + x*TILE_SIZE, BORDER + y*TILE_SIZE,
  1528. TILE_SIZE, TILE_SIZE);
  1529. /*
  1530. * Clear the square.
  1531. */
  1532. draw_rect(dr,
  1533. BORDER + x*TILE_SIZE,
  1534. BORDER + y*TILE_SIZE,
  1535. TILE_SIZE,
  1536. TILE_SIZE,
  1537. (flags & HIGH_BG ? COL_HIGHLIGHT :
  1538. flags & ERROR_BG ? COL_ERROR :
  1539. flags & CORRECT_BG ? COL_CORRECT : COL_BACKGROUND));
  1540. /*
  1541. * Draw the grid lines.
  1542. */
  1543. draw_line(dr, BORDER + x*TILE_SIZE, BORDER + y*TILE_SIZE,
  1544. BORDER + (x+1)*TILE_SIZE, BORDER + y*TILE_SIZE, COL_GRID);
  1545. draw_line(dr, BORDER + x*TILE_SIZE, BORDER + y*TILE_SIZE,
  1546. BORDER + x*TILE_SIZE, BORDER + (y+1)*TILE_SIZE, COL_GRID);
  1547. /*
  1548. * Draw the number.
  1549. */
  1550. if (n) {
  1551. char buf[2];
  1552. buf[0] = n + '0';
  1553. buf[1] = '\0';
  1554. draw_text(dr,
  1555. (x + 1) * TILE_SIZE,
  1556. (y + 1) * TILE_SIZE,
  1557. FONT_VARIABLE,
  1558. TILE_SIZE / 2,
  1559. ALIGN_VCENTRE | ALIGN_HCENTRE,
  1560. flags & USER_COL ? COL_USER : COL_CLUE,
  1561. buf);
  1562. }
  1563. /*
  1564. * Draw bold lines around the borders.
  1565. */
  1566. if (flags & BORDER_L)
  1567. draw_rect(dr,
  1568. BORDER + x*TILE_SIZE + 1,
  1569. BORDER + y*TILE_SIZE + 1,
  1570. BORDER_WIDTH,
  1571. TILE_SIZE - 1,
  1572. COL_GRID);
  1573. if (flags & BORDER_U)
  1574. draw_rect(dr,
  1575. BORDER + x*TILE_SIZE + 1,
  1576. BORDER + y*TILE_SIZE + 1,
  1577. TILE_SIZE - 1,
  1578. BORDER_WIDTH,
  1579. COL_GRID);
  1580. if (flags & BORDER_R)
  1581. draw_rect(dr,
  1582. BORDER + (x+1)*TILE_SIZE - BORDER_WIDTH,
  1583. BORDER + y*TILE_SIZE + 1,
  1584. BORDER_WIDTH,
  1585. TILE_SIZE - 1,
  1586. COL_GRID);
  1587. if (flags & BORDER_D)
  1588. draw_rect(dr,
  1589. BORDER + x*TILE_SIZE + 1,
  1590. BORDER + (y+1)*TILE_SIZE - BORDER_WIDTH,
  1591. TILE_SIZE - 1,
  1592. BORDER_WIDTH,
  1593. COL_GRID);
  1594. if (flags & BORDER_UL)
  1595. draw_rect(dr,
  1596. BORDER + x*TILE_SIZE + 1,
  1597. BORDER + y*TILE_SIZE + 1,
  1598. BORDER_WIDTH,
  1599. BORDER_WIDTH,
  1600. COL_GRID);
  1601. if (flags & BORDER_UR)
  1602. draw_rect(dr,
  1603. BORDER + (x+1)*TILE_SIZE - BORDER_WIDTH,
  1604. BORDER + y*TILE_SIZE + 1,
  1605. BORDER_WIDTH,
  1606. BORDER_WIDTH,
  1607. COL_GRID);
  1608. if (flags & BORDER_DL)
  1609. draw_rect(dr,
  1610. BORDER + x*TILE_SIZE + 1,
  1611. BORDER + (y+1)*TILE_SIZE - BORDER_WIDTH,
  1612. BORDER_WIDTH,
  1613. BORDER_WIDTH,
  1614. COL_GRID);
  1615. if (flags & BORDER_DR)
  1616. draw_rect(dr,
  1617. BORDER + (x+1)*TILE_SIZE - BORDER_WIDTH,
  1618. BORDER + (y+1)*TILE_SIZE - BORDER_WIDTH,
  1619. BORDER_WIDTH,
  1620. BORDER_WIDTH,
  1621. COL_GRID);
  1622. if (flags & CURSOR_SQ) {
  1623. int coff = TILE_SIZE/8;
  1624. draw_rect_outline(dr,
  1625. BORDER + x*TILE_SIZE + coff,
  1626. BORDER + y*TILE_SIZE + coff,
  1627. TILE_SIZE - coff*2,
  1628. TILE_SIZE - coff*2,
  1629. COL_CURSOR);
  1630. }
  1631. unclip(dr);
  1632. draw_update(dr,
  1633. BORDER + x*TILE_SIZE,
  1634. BORDER + y*TILE_SIZE,
  1635. TILE_SIZE,
  1636. TILE_SIZE);
  1637. }
  1638. static void draw_grid(
  1639. drawing *dr, game_drawstate *ds, const game_state *state,
  1640. const game_ui *ui, bool flashy, bool borders, bool shading)
  1641. {
  1642. const int w = state->shared->params.w;
  1643. const int h = state->shared->params.h;
  1644. int x;
  1645. int y;
  1646. /*
  1647. * Build a dsf for the board in its current state, to use for
  1648. * highlights and hints.
  1649. */
  1650. ds->dsf_scratch = make_dsf(ds->dsf_scratch, state->board, w, h);
  1651. /*
  1652. * Work out where we're putting borders between the cells.
  1653. */
  1654. for (y = 0; y < w*h; y++)
  1655. ds->border_scratch[y] = 0;
  1656. for (y = 0; y < h; y++)
  1657. for (x = 0; x < w; x++) {
  1658. int dx, dy;
  1659. int v1, s1, v2, s2;
  1660. for (dx = 0; dx <= 1; dx++) {
  1661. bool border = false;
  1662. dy = 1 - dx;
  1663. if (x+dx >= w || y+dy >= h)
  1664. continue;
  1665. v1 = state->board[y*w+x];
  1666. v2 = state->board[(y+dy)*w+(x+dx)];
  1667. s1 = dsf_size(ds->dsf_scratch, y*w+x);
  1668. s2 = dsf_size(ds->dsf_scratch, (y+dy)*w+(x+dx));
  1669. /*
  1670. * We only ever draw a border between two cells if
  1671. * they don't have the same contents.
  1672. */
  1673. if (v1 != v2) {
  1674. /*
  1675. * But in that situation, we don't always draw
  1676. * a border. We do if the two cells both
  1677. * contain actual numbers...
  1678. */
  1679. if (v1 && v2)
  1680. border = true;
  1681. /*
  1682. * ... or if at least one of them is a
  1683. * completed or overfull omino.
  1684. */
  1685. if (v1 && s1 >= v1)
  1686. border = true;
  1687. if (v2 && s2 >= v2)
  1688. border = true;
  1689. }
  1690. if (border)
  1691. ds->border_scratch[y*w+x] |= (dx ? 1 : 2);
  1692. }
  1693. }
  1694. /*
  1695. * Actually do the drawing.
  1696. */
  1697. for (y = 0; y < h; ++y)
  1698. for (x = 0; x < w; ++x) {
  1699. /*
  1700. * Determine what we need to draw in this square.
  1701. */
  1702. int i = y*w+x, v = state->board[i];
  1703. int flags = 0;
  1704. if (flashy || !shading) {
  1705. /* clear all background flags */
  1706. } else if (ui && ui->sel && ui->sel[i]) {
  1707. flags |= HIGH_BG;
  1708. } else if (v) {
  1709. int size = dsf_size(ds->dsf_scratch, i);
  1710. if (size == v)
  1711. flags |= CORRECT_BG;
  1712. else if (size > v)
  1713. flags |= ERROR_BG;
  1714. else {
  1715. int rt = dsf_canonify(ds->dsf_scratch, i), j;
  1716. for (j = 0; j < w*h; ++j) {
  1717. int k;
  1718. if (dsf_canonify(ds->dsf_scratch, j) != rt) continue;
  1719. for (k = 0; k < 4; ++k) {
  1720. const int xx = j % w + dx[k], yy = j / w + dy[k];
  1721. if (xx >= 0 && xx < w && yy >= 0 && yy < h &&
  1722. state->board[yy*w + xx] == EMPTY)
  1723. goto noflag;
  1724. }
  1725. }
  1726. flags |= ERROR_BG;
  1727. noflag:
  1728. ;
  1729. }
  1730. }
  1731. if (ui && ui->cur_visible && x == ui->cur_x && y == ui->cur_y)
  1732. flags |= CURSOR_SQ;
  1733. /*
  1734. * Borders at the very edges of the grid are
  1735. * independent of the `borders' flag.
  1736. */
  1737. if (x == 0)
  1738. flags |= BORDER_L;
  1739. if (y == 0)
  1740. flags |= BORDER_U;
  1741. if (x == w-1)
  1742. flags |= BORDER_R;
  1743. if (y == h-1)
  1744. flags |= BORDER_D;
  1745. if (borders) {
  1746. if (x == 0 || (ds->border_scratch[y*w+(x-1)] & 1))
  1747. flags |= BORDER_L;
  1748. if (y == 0 || (ds->border_scratch[(y-1)*w+x] & 2))
  1749. flags |= BORDER_U;
  1750. if (x == w-1 || (ds->border_scratch[y*w+x] & 1))
  1751. flags |= BORDER_R;
  1752. if (y == h-1 || (ds->border_scratch[y*w+x] & 2))
  1753. flags |= BORDER_D;
  1754. if (y > 0 && x > 0 && (ds->border_scratch[(y-1)*w+(x-1)]))
  1755. flags |= BORDER_UL;
  1756. if (y > 0 && x < w-1 &&
  1757. ((ds->border_scratch[(y-1)*w+x] & 1) ||
  1758. (ds->border_scratch[(y-1)*w+(x+1)] & 2)))
  1759. flags |= BORDER_UR;
  1760. if (y < h-1 && x > 0 &&
  1761. ((ds->border_scratch[y*w+(x-1)] & 2) ||
  1762. (ds->border_scratch[(y+1)*w+(x-1)] & 1)))
  1763. flags |= BORDER_DL;
  1764. if (y < h-1 && x < w-1 &&
  1765. ((ds->border_scratch[y*w+(x+1)] & 2) ||
  1766. (ds->border_scratch[(y+1)*w+x] & 1)))
  1767. flags |= BORDER_DR;
  1768. }
  1769. if (!state->shared->clues[y*w+x])
  1770. flags |= USER_COL;
  1771. if (ds->v[y*w+x] != v || ds->flags[y*w+x] != flags) {
  1772. draw_square(dr, ds, x, y, v, flags);
  1773. ds->v[y*w+x] = v;
  1774. ds->flags[y*w+x] = flags;
  1775. }
  1776. }
  1777. }
  1778. static void game_redraw(drawing *dr, game_drawstate *ds,
  1779. const game_state *oldstate, const game_state *state,
  1780. int dir, const game_ui *ui,
  1781. float animtime, float flashtime)
  1782. {
  1783. const int w = state->shared->params.w;
  1784. const int h = state->shared->params.h;
  1785. const bool flashy =
  1786. flashtime > 0 &&
  1787. (flashtime <= FLASH_TIME/3 || flashtime >= FLASH_TIME*2/3);
  1788. if (!ds->started) {
  1789. /*
  1790. * Black rectangle which is the main grid.
  1791. */
  1792. draw_rect(dr, BORDER - BORDER_WIDTH, BORDER - BORDER_WIDTH,
  1793. w*TILE_SIZE + 2*BORDER_WIDTH + 1,
  1794. h*TILE_SIZE + 2*BORDER_WIDTH + 1,
  1795. COL_GRID);
  1796. draw_update(dr, 0, 0, w*TILE_SIZE + 2*BORDER, h*TILE_SIZE + 2*BORDER);
  1797. ds->started = true;
  1798. }
  1799. draw_grid(dr, ds, state, ui, flashy, true, true);
  1800. }
  1801. static float game_anim_length(const game_state *oldstate,
  1802. const game_state *newstate, int dir, game_ui *ui)
  1803. {
  1804. return 0.0F;
  1805. }
  1806. static float game_flash_length(const game_state *oldstate,
  1807. const game_state *newstate, int dir, game_ui *ui)
  1808. {
  1809. assert(oldstate);
  1810. assert(newstate);
  1811. assert(newstate->shared);
  1812. assert(oldstate->shared == newstate->shared);
  1813. if (!oldstate->completed && newstate->completed &&
  1814. !oldstate->cheated && !newstate->cheated)
  1815. return FLASH_TIME;
  1816. return 0.0F;
  1817. }
  1818. static void game_get_cursor_location(const game_ui *ui,
  1819. const game_drawstate *ds,
  1820. const game_state *state,
  1821. const game_params *params,
  1822. int *x, int *y, int *w, int *h)
  1823. {
  1824. if(ui->cur_visible)
  1825. {
  1826. *x = BORDER + ui->cur_x * TILE_SIZE;
  1827. *y = BORDER + ui->cur_y * TILE_SIZE;
  1828. *w = *h = TILE_SIZE;
  1829. }
  1830. }
  1831. static int game_status(const game_state *state)
  1832. {
  1833. return state->completed ? +1 : 0;
  1834. }
  1835. static void game_print_size(const game_params *params, const game_ui *ui,
  1836. float *x, float *y)
  1837. {
  1838. int pw, ph;
  1839. /*
  1840. * I'll use 6mm squares by default.
  1841. */
  1842. game_compute_size(params, 600, ui, &pw, &ph);
  1843. *x = pw / 100.0F;
  1844. *y = ph / 100.0F;
  1845. }
  1846. static void game_print(drawing *dr, const game_state *state, const game_ui *ui,
  1847. int tilesize)
  1848. {
  1849. const int w = state->shared->params.w;
  1850. const int h = state->shared->params.h;
  1851. int c, i;
  1852. bool borders;
  1853. /* Ick: fake up `ds->tilesize' for macro expansion purposes */
  1854. game_drawstate *ds = game_new_drawstate(dr, state);
  1855. game_set_size(dr, ds, NULL, tilesize);
  1856. c = print_mono_colour(dr, 1); assert(c == COL_BACKGROUND);
  1857. c = print_mono_colour(dr, 0); assert(c == COL_GRID);
  1858. c = print_mono_colour(dr, 1); assert(c == COL_HIGHLIGHT);
  1859. c = print_mono_colour(dr, 1); assert(c == COL_CORRECT);
  1860. c = print_mono_colour(dr, 1); assert(c == COL_ERROR);
  1861. c = print_mono_colour(dr, 0); assert(c == COL_USER);
  1862. /*
  1863. * Border.
  1864. */
  1865. draw_rect(dr, BORDER - BORDER_WIDTH, BORDER - BORDER_WIDTH,
  1866. w*TILE_SIZE + 2*BORDER_WIDTH + 1,
  1867. h*TILE_SIZE + 2*BORDER_WIDTH + 1,
  1868. COL_GRID);
  1869. /*
  1870. * We'll draw borders between the ominoes iff the grid is not
  1871. * pristine. So scan it to see if it is.
  1872. */
  1873. borders = false;
  1874. for (i = 0; i < w*h; i++)
  1875. if (state->board[i] && !state->shared->clues[i])
  1876. borders = true;
  1877. /*
  1878. * Draw grid.
  1879. */
  1880. print_line_width(dr, TILE_SIZE / 64);
  1881. draw_grid(dr, ds, state, NULL, false, borders, false);
  1882. /*
  1883. * Clean up.
  1884. */
  1885. game_free_drawstate(dr, ds);
  1886. }
  1887. #ifdef COMBINED
  1888. #define thegame filling
  1889. #endif
  1890. const struct game thegame = {
  1891. "Filling", "games.filling", "filling",
  1892. default_params,
  1893. game_fetch_preset, NULL,
  1894. decode_params,
  1895. encode_params,
  1896. free_params,
  1897. dup_params,
  1898. true, game_configure, custom_params,
  1899. validate_params,
  1900. new_game_desc,
  1901. validate_desc,
  1902. new_game,
  1903. dup_game,
  1904. free_game,
  1905. true, solve_game,
  1906. true, game_can_format_as_text_now, game_text_format,
  1907. NULL, NULL, /* get_prefs, set_prefs */
  1908. new_ui,
  1909. free_ui,
  1910. NULL, /* encode_ui */
  1911. NULL, /* decode_ui */
  1912. game_request_keys,
  1913. game_changed_state,
  1914. current_key_label,
  1915. interpret_move,
  1916. execute_move,
  1917. PREFERRED_TILE_SIZE, game_compute_size, game_set_size,
  1918. game_colours,
  1919. game_new_drawstate,
  1920. game_free_drawstate,
  1921. game_redraw,
  1922. game_anim_length,
  1923. game_flash_length,
  1924. game_get_cursor_location,
  1925. game_status,
  1926. true, false, game_print_size, game_print,
  1927. false, /* wants_statusbar */
  1928. false, NULL, /* timing_state */
  1929. REQUIRE_NUMPAD, /* flags */
  1930. };
  1931. #ifdef STANDALONE_SOLVER /* solver? hah! */
  1932. int main(int argc, char **argv) {
  1933. while (*++argv) {
  1934. game_params *params;
  1935. game_state *state;
  1936. char *par;
  1937. char *desc;
  1938. for (par = desc = *argv; *desc != '\0' && *desc != ':'; ++desc);
  1939. if (*desc == '\0') {
  1940. fprintf(stderr, "bad puzzle id: %s", par);
  1941. continue;
  1942. }
  1943. *desc++ = '\0';
  1944. params = snew(game_params);
  1945. decode_params(params, par);
  1946. state = new_game(NULL, params, desc);
  1947. if (solver(state->board, params->w, params->h, NULL))
  1948. printf("%s:%s: solvable\n", par, desc);
  1949. else
  1950. printf("%s:%s: not solvable\n", par, desc);
  1951. }
  1952. return 0;
  1953. }
  1954. #endif
  1955. /* vim: set shiftwidth=4 tabstop=8: */