rect.c 93 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024
  1. /*
  2. * rect.c: Puzzle from nikoli.co.jp. You have a square grid with
  3. * numbers in some squares; you must divide the square grid up into
  4. * variously sized rectangles, such that every rectangle contains
  5. * exactly one numbered square and the area of each rectangle is
  6. * equal to the number contained in it.
  7. */
  8. /*
  9. * TODO:
  10. *
  11. * - Improve singleton removal.
  12. * + It would be nice to limit the size of the generated
  13. * rectangles in accordance with existing constraints such as
  14. * the maximum rectangle size and the one about not
  15. * generating a rectangle the full width or height of the
  16. * grid.
  17. * + This could be achieved by making a less random choice
  18. * about which of the available options to use.
  19. * + Alternatively, we could create our rectangle and then
  20. * split it up.
  21. */
  22. #include <stdio.h>
  23. #include <stdlib.h>
  24. #include <string.h>
  25. #include <assert.h>
  26. #include <ctype.h>
  27. #ifdef NO_TGMATH_H
  28. # include <math.h>
  29. #else
  30. # include <tgmath.h>
  31. #endif
  32. #include "puzzles.h"
  33. enum {
  34. COL_BACKGROUND,
  35. COL_CORRECT,
  36. COL_LINE,
  37. COL_TEXT,
  38. COL_GRID,
  39. COL_DRAG, COL_DRAGERASE,
  40. COL_CURSOR,
  41. NCOLOURS
  42. };
  43. struct game_params {
  44. int w, h;
  45. float expandfactor;
  46. bool unique;
  47. };
  48. #define INDEX(state, x, y) (((y) * (state)->w) + (x))
  49. #define index(state, a, x, y) ((a) [ INDEX(state,x,y) ])
  50. #define grid(state,x,y) index(state, (state)->grid, x, y)
  51. #define vedge(state,x,y) index(state, (state)->vedge, x, y)
  52. #define hedge(state,x,y) index(state, (state)->hedge, x, y)
  53. #define CRANGE(state,x,y,dx,dy) ( (x) >= dx && (x) < (state)->w && \
  54. (y) >= dy && (y) < (state)->h )
  55. #define RANGE(state,x,y) CRANGE(state,x,y,0,0)
  56. #define HRANGE(state,x,y) CRANGE(state,x,y,0,1)
  57. #define VRANGE(state,x,y) CRANGE(state,x,y,1,0)
  58. #define PREFERRED_TILE_SIZE 24
  59. #define TILE_SIZE (ds->tilesize)
  60. #ifdef SMALL_SCREEN
  61. #define BORDER (2)
  62. #else
  63. #define BORDER (TILE_SIZE * 3 / 4)
  64. #endif
  65. #define CORNER_TOLERANCE 0.15F
  66. #define CENTRE_TOLERANCE 0.15F
  67. #define FLASH_TIME 0.13F
  68. #define COORD(x) ( (x) * TILE_SIZE + BORDER )
  69. #define FROMCOORD(x) ( ((x) - BORDER) / TILE_SIZE )
  70. struct game_state {
  71. int w, h;
  72. int *grid; /* contains the numbers */
  73. unsigned char *vedge; /* (w+1) x h */
  74. unsigned char *hedge; /* w x (h+1) */
  75. bool completed, cheated;
  76. unsigned char *correct;
  77. };
  78. static game_params *default_params(void)
  79. {
  80. game_params *ret = snew(game_params);
  81. ret->w = ret->h = 7;
  82. ret->expandfactor = 0.0F;
  83. ret->unique = true;
  84. return ret;
  85. }
  86. static bool game_fetch_preset(int i, char **name, game_params **params)
  87. {
  88. game_params *ret;
  89. int w, h;
  90. char buf[80];
  91. switch (i) {
  92. case 0: w = 7, h = 7; break;
  93. case 1: w = 9, h = 9; break;
  94. case 2: w = 11, h = 11; break;
  95. case 3: w = 13, h = 13; break;
  96. case 4: w = 15, h = 15; break;
  97. #ifndef SMALL_SCREEN
  98. case 5: w = 17, h = 17; break;
  99. case 6: w = 19, h = 19; break;
  100. #endif
  101. default: return false;
  102. }
  103. sprintf(buf, "%dx%d", w, h);
  104. *name = dupstr(buf);
  105. *params = ret = snew(game_params);
  106. ret->w = w;
  107. ret->h = h;
  108. ret->expandfactor = 0.0F;
  109. ret->unique = true;
  110. return true;
  111. }
  112. static void free_params(game_params *params)
  113. {
  114. sfree(params);
  115. }
  116. static game_params *dup_params(const game_params *params)
  117. {
  118. game_params *ret = snew(game_params);
  119. *ret = *params; /* structure copy */
  120. return ret;
  121. }
  122. static void decode_params(game_params *ret, char const *string)
  123. {
  124. ret->w = ret->h = atoi(string);
  125. while (*string && isdigit((unsigned char)*string)) string++;
  126. if (*string == 'x') {
  127. string++;
  128. ret->h = atoi(string);
  129. while (*string && isdigit((unsigned char)*string)) string++;
  130. }
  131. if (*string == 'e') {
  132. string++;
  133. ret->expandfactor = (float)atof(string);
  134. while (*string &&
  135. (*string == '.' || isdigit((unsigned char)*string))) string++;
  136. }
  137. if (*string == 'a') {
  138. string++;
  139. ret->unique = false;
  140. }
  141. }
  142. static char *encode_params(const game_params *params, bool full)
  143. {
  144. char data[256];
  145. sprintf(data, "%dx%d", params->w, params->h);
  146. if (full && params->expandfactor)
  147. sprintf(data + strlen(data), "e%g", params->expandfactor);
  148. if (full && !params->unique)
  149. strcat(data, "a");
  150. return dupstr(data);
  151. }
  152. static config_item *game_configure(const game_params *params)
  153. {
  154. config_item *ret;
  155. char buf[80];
  156. ret = snewn(5, config_item);
  157. ret[0].name = "Width";
  158. ret[0].type = C_STRING;
  159. sprintf(buf, "%d", params->w);
  160. ret[0].u.string.sval = dupstr(buf);
  161. ret[1].name = "Height";
  162. ret[1].type = C_STRING;
  163. sprintf(buf, "%d", params->h);
  164. ret[1].u.string.sval = dupstr(buf);
  165. ret[2].name = "Expansion factor";
  166. ret[2].type = C_STRING;
  167. sprintf(buf, "%g", params->expandfactor);
  168. ret[2].u.string.sval = dupstr(buf);
  169. ret[3].name = "Ensure unique solution";
  170. ret[3].type = C_BOOLEAN;
  171. ret[3].u.boolean.bval = params->unique;
  172. ret[4].name = NULL;
  173. ret[4].type = C_END;
  174. return ret;
  175. }
  176. static game_params *custom_params(const config_item *cfg)
  177. {
  178. game_params *ret = snew(game_params);
  179. ret->w = atoi(cfg[0].u.string.sval);
  180. ret->h = atoi(cfg[1].u.string.sval);
  181. ret->expandfactor = (float)atof(cfg[2].u.string.sval);
  182. ret->unique = cfg[3].u.boolean.bval;
  183. return ret;
  184. }
  185. static const char *validate_params(const game_params *params, bool full)
  186. {
  187. if (params->w <= 0 || params->h <= 0)
  188. return "Width and height must both be greater than zero";
  189. if (params->w > INT_MAX / params->h)
  190. return "Width times height must not be unreasonably large";
  191. if (params->w*params->h < 2)
  192. return "Grid area must be greater than one";
  193. if (params->expandfactor < 0.0F)
  194. return "Expansion factor may not be negative";
  195. return NULL;
  196. }
  197. struct point {
  198. int x, y;
  199. };
  200. struct rect {
  201. int x, y;
  202. int w, h;
  203. };
  204. struct rectlist {
  205. struct rect *rects;
  206. int n;
  207. };
  208. struct numberdata {
  209. int area;
  210. int npoints;
  211. struct point *points;
  212. };
  213. /* ----------------------------------------------------------------------
  214. * Solver for Rectangles games.
  215. *
  216. * This solver is souped up beyond the needs of actually _solving_
  217. * a puzzle. It is also designed to cope with uncertainty about
  218. * where the numbers have been placed. This is because I run it on
  219. * my generated grids _before_ placing the numbers, and have it
  220. * tell me where I need to place the numbers to ensure a unique
  221. * solution.
  222. */
  223. static void remove_rect_placement(int w, int h,
  224. struct rectlist *rectpositions,
  225. int *overlaps,
  226. int rectnum, int placement)
  227. {
  228. int x, y, xx, yy;
  229. #ifdef SOLVER_DIAGNOSTICS
  230. printf("ruling out rect %d placement at %d,%d w=%d h=%d\n", rectnum,
  231. rectpositions[rectnum].rects[placement].x,
  232. rectpositions[rectnum].rects[placement].y,
  233. rectpositions[rectnum].rects[placement].w,
  234. rectpositions[rectnum].rects[placement].h);
  235. #endif
  236. /*
  237. * Decrement each entry in the overlaps array to reflect the
  238. * removal of this rectangle placement.
  239. */
  240. for (yy = 0; yy < rectpositions[rectnum].rects[placement].h; yy++) {
  241. y = yy + rectpositions[rectnum].rects[placement].y;
  242. for (xx = 0; xx < rectpositions[rectnum].rects[placement].w; xx++) {
  243. x = xx + rectpositions[rectnum].rects[placement].x;
  244. assert(overlaps[(rectnum * h + y) * w + x] != 0);
  245. if (overlaps[(rectnum * h + y) * w + x] > 0)
  246. overlaps[(rectnum * h + y) * w + x]--;
  247. }
  248. }
  249. /*
  250. * Remove the placement from the list of positions for that
  251. * rectangle, by interchanging it with the one on the end.
  252. */
  253. if (placement < rectpositions[rectnum].n - 1) {
  254. struct rect t;
  255. t = rectpositions[rectnum].rects[rectpositions[rectnum].n - 1];
  256. rectpositions[rectnum].rects[rectpositions[rectnum].n - 1] =
  257. rectpositions[rectnum].rects[placement];
  258. rectpositions[rectnum].rects[placement] = t;
  259. }
  260. rectpositions[rectnum].n--;
  261. }
  262. static void remove_number_placement(int w, int h, struct numberdata *number,
  263. int index, int *rectbyplace)
  264. {
  265. /*
  266. * Remove the entry from the rectbyplace array.
  267. */
  268. rectbyplace[number->points[index].y * w + number->points[index].x] = -1;
  269. /*
  270. * Remove the placement from the list of candidates for that
  271. * number, by interchanging it with the one on the end.
  272. */
  273. if (index < number->npoints - 1) {
  274. struct point t;
  275. t = number->points[number->npoints - 1];
  276. number->points[number->npoints - 1] = number->points[index];
  277. number->points[index] = t;
  278. }
  279. number->npoints--;
  280. }
  281. /*
  282. * Returns 0 for failure to solve due to inconsistency; 1 for
  283. * success; 2 for failure to complete a solution due to either
  284. * ambiguity or it being too difficult.
  285. */
  286. static int rect_solver(int w, int h, int nrects, struct numberdata *numbers,
  287. unsigned char *hedge, unsigned char *vedge,
  288. random_state *rs)
  289. {
  290. struct rectlist *rectpositions;
  291. int *overlaps, *rectbyplace, *workspace;
  292. int i, ret;
  293. /*
  294. * Start by setting up a list of candidate positions for each
  295. * rectangle.
  296. */
  297. rectpositions = snewn(nrects, struct rectlist);
  298. for (i = 0; i < nrects; i++) {
  299. int rw, rh, area = numbers[i].area;
  300. int j, minx, miny, maxx, maxy;
  301. struct rect *rlist;
  302. int rlistn, rlistsize;
  303. /*
  304. * For each rectangle, begin by finding the bounding
  305. * rectangle of its candidate number placements.
  306. */
  307. maxx = maxy = -1;
  308. minx = w;
  309. miny = h;
  310. for (j = 0; j < numbers[i].npoints; j++) {
  311. if (minx > numbers[i].points[j].x) minx = numbers[i].points[j].x;
  312. if (miny > numbers[i].points[j].y) miny = numbers[i].points[j].y;
  313. if (maxx < numbers[i].points[j].x) maxx = numbers[i].points[j].x;
  314. if (maxy < numbers[i].points[j].y) maxy = numbers[i].points[j].y;
  315. }
  316. /*
  317. * Now loop over all possible rectangle placements
  318. * overlapping a point within that bounding rectangle;
  319. * ensure each one actually contains a candidate number
  320. * placement, and add it to the list.
  321. */
  322. rlist = NULL;
  323. rlistn = rlistsize = 0;
  324. for (rw = 1; rw <= area && rw <= w; rw++) {
  325. int x, y;
  326. if (area % rw)
  327. continue;
  328. rh = area / rw;
  329. if (rh > h)
  330. continue;
  331. for (y = miny - rh + 1; y <= maxy; y++) {
  332. if (y < 0 || y+rh > h)
  333. continue;
  334. for (x = minx - rw + 1; x <= maxx; x++) {
  335. if (x < 0 || x+rw > w)
  336. continue;
  337. /*
  338. * See if we can find a candidate number
  339. * placement within this rectangle.
  340. */
  341. for (j = 0; j < numbers[i].npoints; j++)
  342. if (numbers[i].points[j].x >= x &&
  343. numbers[i].points[j].x < x+rw &&
  344. numbers[i].points[j].y >= y &&
  345. numbers[i].points[j].y < y+rh)
  346. break;
  347. if (j < numbers[i].npoints) {
  348. /*
  349. * Add this to the list of candidate
  350. * placements for this rectangle.
  351. */
  352. if (rlistn >= rlistsize) {
  353. rlistsize = rlistn + 32;
  354. rlist = sresize(rlist, rlistsize, struct rect);
  355. }
  356. rlist[rlistn].x = x;
  357. rlist[rlistn].y = y;
  358. rlist[rlistn].w = rw;
  359. rlist[rlistn].h = rh;
  360. #ifdef SOLVER_DIAGNOSTICS
  361. printf("rect %d [area %d]: candidate position at"
  362. " %d,%d w=%d h=%d\n",
  363. i, area, x, y, rw, rh);
  364. #endif
  365. rlistn++;
  366. }
  367. }
  368. }
  369. }
  370. rectpositions[i].rects = rlist;
  371. rectpositions[i].n = rlistn;
  372. }
  373. /*
  374. * Next, construct a multidimensional array tracking how many
  375. * candidate positions for each rectangle overlap each square.
  376. *
  377. * Indexing of this array is by the formula
  378. *
  379. * overlaps[(rectindex * h + y) * w + x]
  380. *
  381. * A positive or zero value indicates what it sounds as if it
  382. * should; -1 indicates that this square _cannot_ be part of
  383. * this rectangle; and -2 indicates that it _definitely_ is
  384. * (which is distinct from 1, because one might very well know
  385. * that _if_ square S is part of rectangle R then it must be
  386. * because R is placed in a certain position without knowing
  387. * that it definitely _is_).
  388. */
  389. overlaps = snewn(nrects * w * h, int);
  390. memset(overlaps, 0, nrects * w * h * sizeof(int));
  391. for (i = 0; i < nrects; i++) {
  392. int j;
  393. for (j = 0; j < rectpositions[i].n; j++) {
  394. int xx, yy;
  395. for (yy = 0; yy < rectpositions[i].rects[j].h; yy++)
  396. for (xx = 0; xx < rectpositions[i].rects[j].w; xx++)
  397. overlaps[(i * h + yy+rectpositions[i].rects[j].y) * w +
  398. xx+rectpositions[i].rects[j].x]++;
  399. }
  400. }
  401. /*
  402. * Also we want an array covering the grid once, to make it
  403. * easy to figure out which squares are candidate number
  404. * placements for which rectangles. (The existence of this
  405. * single array assumes that no square starts off as a
  406. * candidate number placement for more than one rectangle. This
  407. * assumption is justified, because this solver is _either_
  408. * used to solve real problems - in which case there is a
  409. * single placement for every number - _or_ used to decide on
  410. * number placements for a new puzzle, in which case each
  411. * number's placements are confined to the intended position of
  412. * the rectangle containing that number.)
  413. */
  414. rectbyplace = snewn(w * h, int);
  415. for (i = 0; i < w*h; i++)
  416. rectbyplace[i] = -1;
  417. for (i = 0; i < nrects; i++) {
  418. int j;
  419. for (j = 0; j < numbers[i].npoints; j++) {
  420. int x = numbers[i].points[j].x;
  421. int y = numbers[i].points[j].y;
  422. assert(rectbyplace[y * w + x] == -1);
  423. rectbyplace[y * w + x] = i;
  424. }
  425. }
  426. workspace = snewn(nrects, int);
  427. /*
  428. * Now run the actual deduction loop.
  429. */
  430. while (1) {
  431. bool done_something = false;
  432. #ifdef SOLVER_DIAGNOSTICS
  433. printf("starting deduction loop\n");
  434. for (i = 0; i < nrects; i++) {
  435. printf("rect %d overlaps:\n", i);
  436. {
  437. int x, y;
  438. for (y = 0; y < h; y++) {
  439. for (x = 0; x < w; x++) {
  440. printf("%3d", overlaps[(i * h + y) * w + x]);
  441. }
  442. printf("\n");
  443. }
  444. }
  445. }
  446. printf("rectbyplace:\n");
  447. {
  448. int x, y;
  449. for (y = 0; y < h; y++) {
  450. for (x = 0; x < w; x++) {
  451. printf("%3d", rectbyplace[y * w + x]);
  452. }
  453. printf("\n");
  454. }
  455. }
  456. #endif
  457. /*
  458. * Housekeeping. Look for rectangles whose number has only
  459. * one candidate position left, and mark that square as
  460. * known if it isn't already.
  461. */
  462. for (i = 0; i < nrects; i++) {
  463. if (numbers[i].npoints == 1) {
  464. int x = numbers[i].points[0].x;
  465. int y = numbers[i].points[0].y;
  466. if (overlaps[(i * h + y) * w + x] >= -1) {
  467. int j;
  468. if (overlaps[(i * h + y) * w + x] <= 0) {
  469. ret = 0; /* inconsistency */
  470. goto cleanup;
  471. }
  472. #ifdef SOLVER_DIAGNOSTICS
  473. printf("marking %d,%d as known for rect %d"
  474. " (sole remaining number position)\n", x, y, i);
  475. #endif
  476. for (j = 0; j < nrects; j++)
  477. overlaps[(j * h + y) * w + x] = -1;
  478. overlaps[(i * h + y) * w + x] = -2;
  479. }
  480. }
  481. }
  482. /*
  483. * Now look at the intersection of all possible placements
  484. * for each rectangle, and mark all squares in that
  485. * intersection as known for that rectangle if they aren't
  486. * already.
  487. */
  488. for (i = 0; i < nrects; i++) {
  489. int minx, miny, maxx, maxy, xx, yy, j;
  490. minx = miny = 0;
  491. maxx = w;
  492. maxy = h;
  493. for (j = 0; j < rectpositions[i].n; j++) {
  494. int x = rectpositions[i].rects[j].x;
  495. int y = rectpositions[i].rects[j].y;
  496. int w = rectpositions[i].rects[j].w;
  497. int h = rectpositions[i].rects[j].h;
  498. if (minx < x) minx = x;
  499. if (miny < y) miny = y;
  500. if (maxx > x+w) maxx = x+w;
  501. if (maxy > y+h) maxy = y+h;
  502. }
  503. for (yy = miny; yy < maxy; yy++)
  504. for (xx = minx; xx < maxx; xx++)
  505. if (overlaps[(i * h + yy) * w + xx] >= -1) {
  506. if (overlaps[(i * h + yy) * w + xx] <= 0) {
  507. ret = 0; /* inconsistency */
  508. goto cleanup;
  509. }
  510. #ifdef SOLVER_DIAGNOSTICS
  511. printf("marking %d,%d as known for rect %d"
  512. " (intersection of all placements)\n",
  513. xx, yy, i);
  514. #endif
  515. for (j = 0; j < nrects; j++)
  516. overlaps[(j * h + yy) * w + xx] = -1;
  517. overlaps[(i * h + yy) * w + xx] = -2;
  518. }
  519. }
  520. /*
  521. * Rectangle-focused deduction. Look at each rectangle in
  522. * turn and try to rule out some of its candidate
  523. * placements.
  524. */
  525. for (i = 0; i < nrects; i++) {
  526. int j;
  527. for (j = 0; j < rectpositions[i].n; j++) {
  528. int xx, yy, k;
  529. bool del = false;
  530. for (k = 0; k < nrects; k++)
  531. workspace[k] = 0;
  532. for (yy = 0; yy < rectpositions[i].rects[j].h; yy++) {
  533. int y = yy + rectpositions[i].rects[j].y;
  534. for (xx = 0; xx < rectpositions[i].rects[j].w; xx++) {
  535. int x = xx + rectpositions[i].rects[j].x;
  536. if (overlaps[(i * h + y) * w + x] == -1) {
  537. /*
  538. * This placement overlaps a square
  539. * which is _known_ to be part of
  540. * another rectangle. Therefore we must
  541. * rule it out.
  542. */
  543. #ifdef SOLVER_DIAGNOSTICS
  544. printf("rect %d placement at %d,%d w=%d h=%d "
  545. "contains %d,%d which is known-other\n", i,
  546. rectpositions[i].rects[j].x,
  547. rectpositions[i].rects[j].y,
  548. rectpositions[i].rects[j].w,
  549. rectpositions[i].rects[j].h,
  550. x, y);
  551. #endif
  552. del = true;
  553. }
  554. if (rectbyplace[y * w + x] != -1) {
  555. /*
  556. * This placement overlaps one of the
  557. * candidate number placements for some
  558. * rectangle. Count it.
  559. */
  560. workspace[rectbyplace[y * w + x]]++;
  561. }
  562. }
  563. }
  564. if (!del) {
  565. /*
  566. * If we haven't ruled this placement out
  567. * already, see if it overlaps _all_ of the
  568. * candidate number placements for any
  569. * rectangle. If so, we can rule it out.
  570. */
  571. for (k = 0; k < nrects; k++)
  572. if (k != i && workspace[k] == numbers[k].npoints) {
  573. #ifdef SOLVER_DIAGNOSTICS
  574. printf("rect %d placement at %d,%d w=%d h=%d "
  575. "contains all number points for rect %d\n",
  576. i,
  577. rectpositions[i].rects[j].x,
  578. rectpositions[i].rects[j].y,
  579. rectpositions[i].rects[j].w,
  580. rectpositions[i].rects[j].h,
  581. k);
  582. #endif
  583. del = true;
  584. break;
  585. }
  586. /*
  587. * Failing that, see if it overlaps at least
  588. * one of the candidate number placements for
  589. * itself! (This might not be the case if one
  590. * of those number placements has been removed
  591. * recently.).
  592. */
  593. if (!del && workspace[i] == 0) {
  594. #ifdef SOLVER_DIAGNOSTICS
  595. printf("rect %d placement at %d,%d w=%d h=%d "
  596. "contains none of its own number points\n",
  597. i,
  598. rectpositions[i].rects[j].x,
  599. rectpositions[i].rects[j].y,
  600. rectpositions[i].rects[j].w,
  601. rectpositions[i].rects[j].h);
  602. #endif
  603. del = true;
  604. }
  605. }
  606. if (del) {
  607. remove_rect_placement(w, h, rectpositions, overlaps, i, j);
  608. j--; /* don't skip over next placement */
  609. done_something = true;
  610. }
  611. }
  612. }
  613. /*
  614. * Square-focused deduction. Look at each square not marked
  615. * as known, and see if there are any which can only be
  616. * part of a single rectangle.
  617. */
  618. {
  619. int x, y, n, index;
  620. for (y = 0; y < h; y++) for (x = 0; x < w; x++) {
  621. /* Known squares are marked as <0 everywhere, so we only need
  622. * to check the overlaps entry for rect 0. */
  623. if (overlaps[y * w + x] < 0)
  624. continue; /* known already */
  625. n = 0;
  626. index = -1;
  627. for (i = 0; i < nrects; i++)
  628. if (overlaps[(i * h + y) * w + x] > 0)
  629. n++, index = i;
  630. if (n == 1) {
  631. int j;
  632. /*
  633. * Now we can rule out all placements for
  634. * rectangle `index' which _don't_ contain
  635. * square x,y.
  636. */
  637. #ifdef SOLVER_DIAGNOSTICS
  638. printf("square %d,%d can only be in rectangle %d\n",
  639. x, y, index);
  640. #endif
  641. for (j = 0; j < rectpositions[index].n; j++) {
  642. struct rect *r = &rectpositions[index].rects[j];
  643. if (x >= r->x && x < r->x + r->w &&
  644. y >= r->y && y < r->y + r->h)
  645. continue; /* this one is OK */
  646. remove_rect_placement(w, h, rectpositions, overlaps,
  647. index, j);
  648. j--; /* don't skip over next placement */
  649. done_something = true;
  650. }
  651. }
  652. }
  653. }
  654. /*
  655. * If we've managed to deduce anything by normal means,
  656. * loop round again and see if there's more to be done.
  657. * Only if normal deduction has completely failed us should
  658. * we now move on to narrowing down the possible number
  659. * placements.
  660. */
  661. if (done_something)
  662. continue;
  663. /*
  664. * Now we have done everything we can with the current set
  665. * of number placements. So we need to winnow the number
  666. * placements so as to narrow down the possibilities. We do
  667. * this by searching for a candidate placement (of _any_
  668. * rectangle) which overlaps a candidate placement of the
  669. * number for some other rectangle.
  670. */
  671. if (rs) {
  672. struct rpn {
  673. int rect;
  674. int placement;
  675. int number;
  676. } *rpns = NULL;
  677. size_t nrpns = 0, rpnsize = 0;
  678. int j;
  679. for (i = 0; i < nrects; i++) {
  680. for (j = 0; j < rectpositions[i].n; j++) {
  681. int xx, yy;
  682. for (yy = 0; yy < rectpositions[i].rects[j].h; yy++) {
  683. int y = yy + rectpositions[i].rects[j].y;
  684. for (xx = 0; xx < rectpositions[i].rects[j].w; xx++) {
  685. int x = xx + rectpositions[i].rects[j].x;
  686. if (rectbyplace[y * w + x] >= 0 &&
  687. rectbyplace[y * w + x] != i) {
  688. /*
  689. * Add this to the list of
  690. * winnowing possibilities.
  691. */
  692. if (nrpns >= rpnsize) {
  693. rpnsize = rpnsize * 3 / 2 + 32;
  694. rpns = sresize(rpns, rpnsize, struct rpn);
  695. }
  696. rpns[nrpns].rect = i;
  697. rpns[nrpns].placement = j;
  698. rpns[nrpns].number = rectbyplace[y * w + x];
  699. nrpns++;
  700. }
  701. }
  702. }
  703. }
  704. }
  705. #ifdef SOLVER_DIAGNOSTICS
  706. printf("%d candidate rect placements we could eliminate\n", nrpns);
  707. #endif
  708. if (nrpns > 0) {
  709. /*
  710. * Now choose one of these unwanted rectangle
  711. * placements, and eliminate it.
  712. */
  713. int index = random_upto(rs, nrpns);
  714. int k, m;
  715. struct rpn rpn = rpns[index];
  716. struct rect r;
  717. sfree(rpns);
  718. i = rpn.rect;
  719. j = rpn.placement;
  720. k = rpn.number;
  721. r = rectpositions[i].rects[j];
  722. /*
  723. * We rule out placement j of rectangle i by means
  724. * of removing all of rectangle k's candidate
  725. * number placements which do _not_ overlap it.
  726. * This will ensure that it is eliminated during
  727. * the next pass of rectangle-focused deduction.
  728. */
  729. #ifdef SOLVER_DIAGNOSTICS
  730. printf("ensuring number for rect %d is within"
  731. " rect %d's placement at %d,%d w=%d h=%d\n",
  732. k, i, r.x, r.y, r.w, r.h);
  733. #endif
  734. for (m = 0; m < numbers[k].npoints; m++) {
  735. int x = numbers[k].points[m].x;
  736. int y = numbers[k].points[m].y;
  737. if (x < r.x || x >= r.x + r.w ||
  738. y < r.y || y >= r.y + r.h) {
  739. #ifdef SOLVER_DIAGNOSTICS
  740. printf("eliminating number for rect %d at %d,%d\n",
  741. k, x, y);
  742. #endif
  743. remove_number_placement(w, h, &numbers[k],
  744. m, rectbyplace);
  745. m--; /* don't skip the next one */
  746. done_something = true;
  747. }
  748. }
  749. }
  750. }
  751. if (!done_something) {
  752. #ifdef SOLVER_DIAGNOSTICS
  753. printf("terminating deduction loop\n");
  754. #endif
  755. break;
  756. }
  757. }
  758. cleanup:
  759. ret = 1;
  760. for (i = 0; i < nrects; i++) {
  761. #ifdef SOLVER_DIAGNOSTICS
  762. printf("rect %d has %d possible placements\n",
  763. i, rectpositions[i].n);
  764. #endif
  765. if (rectpositions[i].n <= 0) {
  766. ret = 0; /* inconsistency */
  767. } else if (rectpositions[i].n > 1) {
  768. ret = 2; /* remaining uncertainty */
  769. } else if (hedge && vedge) {
  770. /*
  771. * Place the rectangle in its only possible position.
  772. */
  773. int x, y;
  774. struct rect *r = &rectpositions[i].rects[0];
  775. for (y = 0; y < r->h; y++) {
  776. if (r->x > 0)
  777. vedge[(r->y+y) * w + r->x] = 1;
  778. if (r->x+r->w < w)
  779. vedge[(r->y+y) * w + r->x+r->w] = 1;
  780. }
  781. for (x = 0; x < r->w; x++) {
  782. if (r->y > 0)
  783. hedge[r->y * w + r->x+x] = 1;
  784. if (r->y+r->h < h)
  785. hedge[(r->y+r->h) * w + r->x+x] = 1;
  786. }
  787. }
  788. }
  789. /*
  790. * Free up all allocated storage.
  791. */
  792. sfree(workspace);
  793. sfree(rectbyplace);
  794. sfree(overlaps);
  795. for (i = 0; i < nrects; i++)
  796. sfree(rectpositions[i].rects);
  797. sfree(rectpositions);
  798. return ret;
  799. }
  800. /* ----------------------------------------------------------------------
  801. * Grid generation code.
  802. */
  803. /*
  804. * This function does one of two things. If passed r==NULL, it
  805. * counts the number of possible rectangles which cover the given
  806. * square, and returns it in *n. If passed r!=NULL then it _reads_
  807. * *n to find an index, counts the possible rectangles until it
  808. * reaches the nth, and writes it into r.
  809. *
  810. * `scratch' is expected to point to an array of 2 * params->w
  811. * ints, used internally as scratch space (and passed in like this
  812. * to avoid re-allocating and re-freeing it every time round a
  813. * tight loop).
  814. */
  815. static void enum_rects(game_params *params, int *grid, struct rect *r, int *n,
  816. int sx, int sy, int *scratch)
  817. {
  818. int rw, rh, mw, mh;
  819. int x, y, dx, dy;
  820. int maxarea, realmaxarea;
  821. int index = 0;
  822. int *top, *bottom;
  823. /*
  824. * Maximum rectangle area is 1/6 of total grid size, unless
  825. * this means we can't place any rectangles at all in which
  826. * case we set it to 2 at minimum.
  827. */
  828. maxarea = params->w * params->h / 6;
  829. if (maxarea < 2)
  830. maxarea = 2;
  831. /*
  832. * Scan the grid to find the limits of the region within which
  833. * any rectangle containing this point must fall. This will
  834. * save us trawling the inside of every rectangle later on to
  835. * see if it contains any used squares.
  836. */
  837. top = scratch;
  838. bottom = scratch + params->w;
  839. for (dy = -1; dy <= +1; dy += 2) {
  840. int *array = (dy == -1 ? top : bottom);
  841. for (dx = -1; dx <= +1; dx += 2) {
  842. for (x = sx; x >= 0 && x < params->w; x += dx) {
  843. array[x] = -2 * params->h * dy;
  844. for (y = sy; y >= 0 && y < params->h; y += dy) {
  845. if (index(params, grid, x, y) == -1 &&
  846. (x == sx || dy*y <= dy*array[x-dx]))
  847. array[x] = y;
  848. else
  849. break;
  850. }
  851. }
  852. }
  853. }
  854. /*
  855. * Now scan again to work out the largest rectangles we can fit
  856. * in the grid, so that we can terminate the following loops
  857. * early once we get down to not having much space left in the
  858. * grid.
  859. */
  860. realmaxarea = 0;
  861. for (x = 0; x < params->w; x++) {
  862. int x2;
  863. rh = bottom[x] - top[x] + 1;
  864. if (rh <= 0)
  865. continue; /* no rectangles can start here */
  866. dx = (x > sx ? -1 : +1);
  867. for (x2 = x; x2 >= 0 && x2 < params->w; x2 += dx)
  868. if (bottom[x2] < bottom[x] || top[x2] > top[x])
  869. break;
  870. rw = abs(x2 - x);
  871. if (realmaxarea < rw * rh)
  872. realmaxarea = rw * rh;
  873. }
  874. if (realmaxarea > maxarea)
  875. realmaxarea = maxarea;
  876. /*
  877. * Rectangles which go right the way across the grid are
  878. * boring, although they can't be helped in the case of
  879. * extremely small grids. (Also they might be generated later
  880. * on by the singleton-removal process; we can't help that.)
  881. */
  882. mw = params->w - 1;
  883. if (mw < 3) mw++;
  884. mh = params->h - 1;
  885. if (mh < 3) mh++;
  886. for (rw = 1; rw <= mw; rw++)
  887. for (rh = 1; rh <= mh; rh++) {
  888. if (rw * rh > realmaxarea)
  889. continue;
  890. if (rw * rh == 1)
  891. continue;
  892. for (x = max(sx - rw + 1, 0); x <= min(sx, params->w - rw); x++)
  893. for (y = max(sy - rh + 1, 0); y <= min(sy, params->h - rh);
  894. y++) {
  895. /*
  896. * Check this rectangle against the region we
  897. * defined above.
  898. */
  899. if (top[x] <= y && top[x+rw-1] <= y &&
  900. bottom[x] >= y+rh-1 && bottom[x+rw-1] >= y+rh-1) {
  901. if (r && index == *n) {
  902. r->x = x;
  903. r->y = y;
  904. r->w = rw;
  905. r->h = rh;
  906. return;
  907. }
  908. index++;
  909. }
  910. }
  911. }
  912. assert(!r);
  913. *n = index;
  914. }
  915. static void place_rect(game_params *params, int *grid, struct rect r)
  916. {
  917. int idx = INDEX(params, r.x, r.y);
  918. int x, y;
  919. for (x = r.x; x < r.x+r.w; x++)
  920. for (y = r.y; y < r.y+r.h; y++) {
  921. index(params, grid, x, y) = idx;
  922. }
  923. #ifdef GENERATION_DIAGNOSTICS
  924. printf(" placing rectangle at (%d,%d) size %d x %d\n",
  925. r.x, r.y, r.w, r.h);
  926. #endif
  927. }
  928. static struct rect find_rect(game_params *params, int *grid, int x, int y)
  929. {
  930. int idx, w, h;
  931. struct rect r;
  932. /*
  933. * Find the top left of the rectangle.
  934. */
  935. idx = index(params, grid, x, y);
  936. if (idx < 0) {
  937. r.x = x;
  938. r.y = y;
  939. r.w = r.h = 1;
  940. return r; /* 1x1 singleton here */
  941. }
  942. y = idx / params->w;
  943. x = idx % params->w;
  944. /*
  945. * Find the width and height of the rectangle.
  946. */
  947. for (w = 1;
  948. (x+w < params->w && index(params,grid,x+w,y)==idx);
  949. w++);
  950. for (h = 1;
  951. (y+h < params->h && index(params,grid,x,y+h)==idx);
  952. h++);
  953. r.x = x;
  954. r.y = y;
  955. r.w = w;
  956. r.h = h;
  957. return r;
  958. }
  959. #ifdef GENERATION_DIAGNOSTICS
  960. static void display_grid(game_params *params, int *grid, int *numbers, int all)
  961. {
  962. unsigned char *egrid = snewn((params->w*2+3) * (params->h*2+3),
  963. unsigned char);
  964. int x, y;
  965. int r = (params->w*2+3);
  966. memset(egrid, 0, (params->w*2+3) * (params->h*2+3));
  967. for (x = 0; x < params->w; x++)
  968. for (y = 0; y < params->h; y++) {
  969. int i = index(params, grid, x, y);
  970. if (x == 0 || index(params, grid, x-1, y) != i)
  971. egrid[(2*y+2) * r + (2*x+1)] = 1;
  972. if (x == params->w-1 || index(params, grid, x+1, y) != i)
  973. egrid[(2*y+2) * r + (2*x+3)] = 1;
  974. if (y == 0 || index(params, grid, x, y-1) != i)
  975. egrid[(2*y+1) * r + (2*x+2)] = 1;
  976. if (y == params->h-1 || index(params, grid, x, y+1) != i)
  977. egrid[(2*y+3) * r + (2*x+2)] = 1;
  978. }
  979. for (y = 1; y < 2*params->h+2; y++) {
  980. for (x = 1; x < 2*params->w+2; x++) {
  981. if (!((y|x)&1)) {
  982. int k = numbers ? index(params, numbers, x/2-1, y/2-1) : 0;
  983. if (k || (all && numbers)) printf("%2d", k); else printf(" ");
  984. } else if (!((y&x)&1)) {
  985. int v = egrid[y*r+x];
  986. if ((y&1) && v) v = '-';
  987. if ((x&1) && v) v = '|';
  988. if (!v) v = ' ';
  989. putchar(v);
  990. if (!(x&1)) putchar(v);
  991. } else {
  992. int c, d = 0;
  993. if (egrid[y*r+(x+1)]) d |= 1;
  994. if (egrid[(y-1)*r+x]) d |= 2;
  995. if (egrid[y*r+(x-1)]) d |= 4;
  996. if (egrid[(y+1)*r+x]) d |= 8;
  997. c = " ??+?-++?+|+++++"[d];
  998. putchar(c);
  999. if (!(x&1)) putchar(c);
  1000. }
  1001. }
  1002. putchar('\n');
  1003. }
  1004. sfree(egrid);
  1005. }
  1006. #endif
  1007. static char *new_game_desc(const game_params *params_in, random_state *rs,
  1008. char **aux, bool interactive)
  1009. {
  1010. game_params params_copy = *params_in; /* structure copy */
  1011. game_params *params = &params_copy;
  1012. int *grid, *numbers = NULL;
  1013. int x, y, y2, y2last, yx, run, i, nsquares;
  1014. char *desc, *p;
  1015. int *enum_rects_scratch;
  1016. game_params params2real, *params2 = &params2real;
  1017. while (1) {
  1018. /*
  1019. * Set up the smaller width and height which we will use to
  1020. * generate the base grid.
  1021. */
  1022. params2->w = (int)((float)params->w / (1.0F + params->expandfactor));
  1023. if (params2->w < 2 && params->w >= 2) params2->w = 2;
  1024. params2->h = (int)((float)params->h / (1.0F + params->expandfactor));
  1025. if (params2->h < 2 && params->h >= 2) params2->h = 2;
  1026. grid = snewn(params2->w * params2->h, int);
  1027. enum_rects_scratch = snewn(2 * params2->w, int);
  1028. nsquares = 0;
  1029. for (y = 0; y < params2->h; y++)
  1030. for (x = 0; x < params2->w; x++) {
  1031. index(params2, grid, x, y) = -1;
  1032. nsquares++;
  1033. }
  1034. /*
  1035. * Place rectangles until we can't any more. We do this by
  1036. * finding a square we haven't yet covered, and randomly
  1037. * choosing a rectangle to cover it.
  1038. */
  1039. while (nsquares > 0) {
  1040. int square = random_upto(rs, nsquares);
  1041. int n;
  1042. struct rect r;
  1043. x = params2->w;
  1044. y = params2->h;
  1045. for (y = 0; y < params2->h; y++) {
  1046. for (x = 0; x < params2->w; x++) {
  1047. if (index(params2, grid, x, y) == -1 && square-- == 0)
  1048. break;
  1049. }
  1050. if (x < params2->w)
  1051. break;
  1052. }
  1053. assert(x < params2->w && y < params2->h);
  1054. /*
  1055. * Now see how many rectangles fit around this one.
  1056. */
  1057. enum_rects(params2, grid, NULL, &n, x, y, enum_rects_scratch);
  1058. if (!n) {
  1059. /*
  1060. * There are no possible rectangles covering this
  1061. * square, meaning it must be a singleton. Mark it
  1062. * -2 so we know not to keep trying.
  1063. */
  1064. index(params2, grid, x, y) = -2;
  1065. nsquares--;
  1066. } else {
  1067. /*
  1068. * Pick one at random.
  1069. */
  1070. n = random_upto(rs, n);
  1071. enum_rects(params2, grid, &r, &n, x, y, enum_rects_scratch);
  1072. /*
  1073. * Place it.
  1074. */
  1075. place_rect(params2, grid, r);
  1076. nsquares -= r.w * r.h;
  1077. }
  1078. }
  1079. sfree(enum_rects_scratch);
  1080. /*
  1081. * Deal with singleton spaces remaining in the grid, one by
  1082. * one.
  1083. *
  1084. * We do this by making a local change to the layout. There are
  1085. * several possibilities:
  1086. *
  1087. * +-----+-----+ Here, we can remove the singleton by
  1088. * | | | extending the 1x2 rectangle below it
  1089. * +--+--+-----+ into a 1x3.
  1090. * | | | |
  1091. * | +--+ |
  1092. * | | | |
  1093. * | | | |
  1094. * | | | |
  1095. * +--+--+-----+
  1096. *
  1097. * +--+--+--+ Here, that trick doesn't work: there's no
  1098. * | | | 1 x n rectangle with the singleton at one
  1099. * | | | end. Instead, we extend a 1 x n rectangle
  1100. * | | | _out_ from the singleton, shaving a layer
  1101. * +--+--+ | off the end of another rectangle. So if we
  1102. * | | | | extended up, we'd make our singleton part
  1103. * | +--+--+ of a 1x3 and generate a 1x2 where the 2x2
  1104. * | | | used to be; or we could extend right into
  1105. * +--+-----+ a 2x1, turning the 1x3 into a 1x2.
  1106. *
  1107. * +-----+--+ Here, we can't even do _that_, since any
  1108. * | | | direction we choose to extend the singleton
  1109. * +--+--+ | will produce a new singleton as a result of
  1110. * | | | | truncating one of the size-2 rectangles.
  1111. * | +--+--+ Fortunately, this case can _only_ occur when
  1112. * | | | a singleton is surrounded by four size-2s
  1113. * +--+-----+ in this fashion; so instead we can simply
  1114. * replace the whole section with a single 3x3.
  1115. */
  1116. for (x = 0; x < params2->w; x++) {
  1117. for (y = 0; y < params2->h; y++) {
  1118. if (index(params2, grid, x, y) < 0) {
  1119. int dirs[4], ndirs;
  1120. #ifdef GENERATION_DIAGNOSTICS
  1121. display_grid(params2, grid, NULL, false);
  1122. printf("singleton at %d,%d\n", x, y);
  1123. #endif
  1124. /*
  1125. * Check in which directions we can feasibly extend
  1126. * the singleton. We can extend in a particular
  1127. * direction iff either:
  1128. *
  1129. * - the rectangle on that side of the singleton
  1130. * is not 2x1, and we are at one end of the edge
  1131. * of it we are touching
  1132. *
  1133. * - it is 2x1 but we are on its short side.
  1134. *
  1135. * FIXME: we could plausibly choose between these
  1136. * based on the sizes of the rectangles they would
  1137. * create?
  1138. */
  1139. ndirs = 0;
  1140. if (x < params2->w-1) {
  1141. struct rect r = find_rect(params2, grid, x+1, y);
  1142. if ((r.w * r.h > 2 && (r.y==y || r.y+r.h-1==y)) || r.h==1)
  1143. dirs[ndirs++] = 1; /* right */
  1144. }
  1145. if (y > 0) {
  1146. struct rect r = find_rect(params2, grid, x, y-1);
  1147. if ((r.w * r.h > 2 && (r.x==x || r.x+r.w-1==x)) || r.w==1)
  1148. dirs[ndirs++] = 2; /* up */
  1149. }
  1150. if (x > 0) {
  1151. struct rect r = find_rect(params2, grid, x-1, y);
  1152. if ((r.w * r.h > 2 && (r.y==y || r.y+r.h-1==y)) || r.h==1)
  1153. dirs[ndirs++] = 4; /* left */
  1154. }
  1155. if (y < params2->h-1) {
  1156. struct rect r = find_rect(params2, grid, x, y+1);
  1157. if ((r.w * r.h > 2 && (r.x==x || r.x+r.w-1==x)) || r.w==1)
  1158. dirs[ndirs++] = 8; /* down */
  1159. }
  1160. if (ndirs > 0) {
  1161. int which, dir;
  1162. struct rect r1, r2;
  1163. memset(&r1, 0, sizeof(struct rect));
  1164. memset(&r2, 0, sizeof(struct rect));
  1165. which = random_upto(rs, ndirs);
  1166. dir = dirs[which];
  1167. switch (dir) {
  1168. case 1: /* right */
  1169. assert(x < params2->w+1);
  1170. #ifdef GENERATION_DIAGNOSTICS
  1171. printf("extending right\n");
  1172. #endif
  1173. r1 = find_rect(params2, grid, x+1, y);
  1174. r2.x = x;
  1175. r2.y = y;
  1176. r2.w = 1 + r1.w;
  1177. r2.h = 1;
  1178. if (r1.y == y)
  1179. r1.y++;
  1180. r1.h--;
  1181. break;
  1182. case 2: /* up */
  1183. assert(y > 0);
  1184. #ifdef GENERATION_DIAGNOSTICS
  1185. printf("extending up\n");
  1186. #endif
  1187. r1 = find_rect(params2, grid, x, y-1);
  1188. r2.x = x;
  1189. r2.y = r1.y;
  1190. r2.w = 1;
  1191. r2.h = 1 + r1.h;
  1192. if (r1.x == x)
  1193. r1.x++;
  1194. r1.w--;
  1195. break;
  1196. case 4: /* left */
  1197. assert(x > 0);
  1198. #ifdef GENERATION_DIAGNOSTICS
  1199. printf("extending left\n");
  1200. #endif
  1201. r1 = find_rect(params2, grid, x-1, y);
  1202. r2.x = r1.x;
  1203. r2.y = y;
  1204. r2.w = 1 + r1.w;
  1205. r2.h = 1;
  1206. if (r1.y == y)
  1207. r1.y++;
  1208. r1.h--;
  1209. break;
  1210. case 8: /* down */
  1211. assert(y < params2->h+1);
  1212. #ifdef GENERATION_DIAGNOSTICS
  1213. printf("extending down\n");
  1214. #endif
  1215. r1 = find_rect(params2, grid, x, y+1);
  1216. r2.x = x;
  1217. r2.y = y;
  1218. r2.w = 1;
  1219. r2.h = 1 + r1.h;
  1220. if (r1.x == x)
  1221. r1.x++;
  1222. r1.w--;
  1223. break;
  1224. default: /* should never happen */
  1225. assert(!"invalid direction");
  1226. }
  1227. if (r1.h > 0 && r1.w > 0)
  1228. place_rect(params2, grid, r1);
  1229. place_rect(params2, grid, r2);
  1230. } else {
  1231. #ifndef NDEBUG
  1232. /*
  1233. * Sanity-check that there really is a 3x3
  1234. * rectangle surrounding this singleton and it
  1235. * contains absolutely everything we could
  1236. * possibly need.
  1237. */
  1238. {
  1239. int xx, yy;
  1240. assert(x > 0 && x < params2->w-1);
  1241. assert(y > 0 && y < params2->h-1);
  1242. for (xx = x-1; xx <= x+1; xx++)
  1243. for (yy = y-1; yy <= y+1; yy++) {
  1244. struct rect r = find_rect(params2,grid,xx,yy);
  1245. assert(r.x >= x-1);
  1246. assert(r.y >= y-1);
  1247. assert(r.x+r.w-1 <= x+1);
  1248. assert(r.y+r.h-1 <= y+1);
  1249. }
  1250. }
  1251. #endif
  1252. #ifdef GENERATION_DIAGNOSTICS
  1253. printf("need the 3x3 trick\n");
  1254. #endif
  1255. /*
  1256. * FIXME: If the maximum rectangle area for
  1257. * this grid is less than 9, we ought to
  1258. * subdivide the 3x3 in some fashion. There are
  1259. * five other possibilities:
  1260. *
  1261. * - a 6 and a 3
  1262. * - a 4, a 3 and a 2
  1263. * - three 3s
  1264. * - a 3 and three 2s (two different arrangements).
  1265. */
  1266. {
  1267. struct rect r;
  1268. r.x = x-1;
  1269. r.y = y-1;
  1270. r.w = r.h = 3;
  1271. place_rect(params2, grid, r);
  1272. }
  1273. }
  1274. }
  1275. }
  1276. }
  1277. /*
  1278. * We have now constructed a grid of the size specified in
  1279. * params2. Now we extend it into a grid of the size specified
  1280. * in params. We do this in two passes: we extend it vertically
  1281. * until it's the right height, then we transpose it, then
  1282. * extend it vertically again (getting it effectively the right
  1283. * width), then finally transpose again.
  1284. */
  1285. for (i = 0; i < 2; i++) {
  1286. int *grid2, *expand, *where;
  1287. game_params params3real, *params3 = &params3real;
  1288. #ifdef GENERATION_DIAGNOSTICS
  1289. printf("before expansion:\n");
  1290. display_grid(params2, grid, NULL, true);
  1291. #endif
  1292. /*
  1293. * Set up the new grid.
  1294. */
  1295. grid2 = snewn(params2->w * params->h, int);
  1296. expand = snewn(params2->h-1, int);
  1297. where = snewn(params2->w, int);
  1298. params3->w = params2->w;
  1299. params3->h = params->h;
  1300. /*
  1301. * Decide which horizontal edges are going to get expanded,
  1302. * and by how much.
  1303. */
  1304. for (y = 0; y < params2->h-1; y++)
  1305. expand[y] = 0;
  1306. for (y = params2->h; y < params->h; y++) {
  1307. x = random_upto(rs, params2->h-1);
  1308. expand[x]++;
  1309. }
  1310. #ifdef GENERATION_DIAGNOSTICS
  1311. printf("expand[] = {");
  1312. for (y = 0; y < params2->h-1; y++)
  1313. printf(" %d", expand[y]);
  1314. printf(" }\n");
  1315. #endif
  1316. /*
  1317. * Perform the expansion. The way this works is that we
  1318. * alternately:
  1319. *
  1320. * - copy a row from grid into grid2
  1321. *
  1322. * - invent some number of additional rows in grid2 where
  1323. * there was previously only a horizontal line between
  1324. * rows in grid, and make random decisions about where
  1325. * among these to place each rectangle edge that ran
  1326. * along this line.
  1327. */
  1328. for (y = y2 = y2last = 0; y < params2->h; y++) {
  1329. /*
  1330. * Copy a single line from row y of grid into row y2 of
  1331. * grid2.
  1332. */
  1333. for (x = 0; x < params2->w; x++) {
  1334. int val = index(params2, grid, x, y);
  1335. if (val / params2->w == y && /* rect starts on this line */
  1336. (y2 == 0 || /* we're at the very top, or... */
  1337. index(params3, grid2, x, y2-1) / params3->w < y2last
  1338. /* this rect isn't already started */))
  1339. index(params3, grid2, x, y2) =
  1340. INDEX(params3, val % params2->w, y2);
  1341. else
  1342. index(params3, grid2, x, y2) =
  1343. index(params3, grid2, x, y2-1);
  1344. }
  1345. /*
  1346. * If that was the last line, terminate the loop early.
  1347. */
  1348. if (++y2 == params3->h)
  1349. break;
  1350. y2last = y2;
  1351. /*
  1352. * Invent some number of additional lines. First walk
  1353. * along this line working out where to put all the
  1354. * edges that coincide with it.
  1355. */
  1356. yx = -1;
  1357. for (x = 0; x < params2->w; x++) {
  1358. if (index(params2, grid, x, y) !=
  1359. index(params2, grid, x, y+1)) {
  1360. /*
  1361. * This is a horizontal edge, so it needs
  1362. * placing.
  1363. */
  1364. if (x == 0 ||
  1365. (index(params2, grid, x-1, y) !=
  1366. index(params2, grid, x, y) &&
  1367. index(params2, grid, x-1, y+1) !=
  1368. index(params2, grid, x, y+1))) {
  1369. /*
  1370. * Here we have the chance to make a new
  1371. * decision.
  1372. */
  1373. yx = random_upto(rs, expand[y]+1);
  1374. } else {
  1375. /*
  1376. * Here we just reuse the previous value of
  1377. * yx.
  1378. */
  1379. }
  1380. } else
  1381. yx = -1;
  1382. where[x] = yx;
  1383. }
  1384. for (yx = 0; yx < expand[y]; yx++) {
  1385. /*
  1386. * Invent a single row. For each square in the row,
  1387. * we copy the grid entry from the square above it,
  1388. * unless we're starting the new rectangle here.
  1389. */
  1390. for (x = 0; x < params2->w; x++) {
  1391. if (yx == where[x]) {
  1392. int val = index(params2, grid, x, y+1);
  1393. val %= params2->w;
  1394. val = INDEX(params3, val, y2);
  1395. index(params3, grid2, x, y2) = val;
  1396. } else
  1397. index(params3, grid2, x, y2) =
  1398. index(params3, grid2, x, y2-1);
  1399. }
  1400. y2++;
  1401. }
  1402. }
  1403. sfree(expand);
  1404. sfree(where);
  1405. #ifdef GENERATION_DIAGNOSTICS
  1406. printf("after expansion:\n");
  1407. display_grid(params3, grid2, NULL, true);
  1408. #endif
  1409. /*
  1410. * Transpose.
  1411. */
  1412. params2->w = params3->h;
  1413. params2->h = params3->w;
  1414. sfree(grid);
  1415. grid = snewn(params2->w * params2->h, int);
  1416. for (x = 0; x < params2->w; x++)
  1417. for (y = 0; y < params2->h; y++) {
  1418. int idx1 = INDEX(params2, x, y);
  1419. int idx2 = INDEX(params3, y, x);
  1420. int tmp;
  1421. tmp = grid2[idx2];
  1422. tmp = (tmp % params3->w) * params2->w + (tmp / params3->w);
  1423. grid[idx1] = tmp;
  1424. }
  1425. sfree(grid2);
  1426. {
  1427. int tmp;
  1428. tmp = params->w;
  1429. params->w = params->h;
  1430. params->h = tmp;
  1431. }
  1432. #ifdef GENERATION_DIAGNOSTICS
  1433. printf("after transposition:\n");
  1434. display_grid(params2, grid, NULL, true);
  1435. #endif
  1436. }
  1437. /*
  1438. * Run the solver to narrow down the possible number
  1439. * placements.
  1440. */
  1441. {
  1442. struct numberdata *nd;
  1443. int nnumbers, i, ret;
  1444. /* Count the rectangles. */
  1445. nnumbers = 0;
  1446. for (y = 0; y < params->h; y++) {
  1447. for (x = 0; x < params->w; x++) {
  1448. int idx = INDEX(params, x, y);
  1449. if (index(params, grid, x, y) == idx)
  1450. nnumbers++;
  1451. }
  1452. }
  1453. nd = snewn(nnumbers, struct numberdata);
  1454. /* Now set up each number's candidate position list. */
  1455. i = 0;
  1456. for (y = 0; y < params->h; y++) {
  1457. for (x = 0; x < params->w; x++) {
  1458. int idx = INDEX(params, x, y);
  1459. if (index(params, grid, x, y) == idx) {
  1460. struct rect r = find_rect(params, grid, x, y);
  1461. int j, k, m;
  1462. nd[i].area = r.w * r.h;
  1463. nd[i].npoints = nd[i].area;
  1464. nd[i].points = snewn(nd[i].npoints, struct point);
  1465. m = 0;
  1466. for (j = 0; j < r.h; j++)
  1467. for (k = 0; k < r.w; k++) {
  1468. nd[i].points[m].x = k + r.x;
  1469. nd[i].points[m].y = j + r.y;
  1470. m++;
  1471. }
  1472. assert(m == nd[i].npoints);
  1473. i++;
  1474. }
  1475. }
  1476. }
  1477. if (params->unique)
  1478. ret = rect_solver(params->w, params->h, nnumbers, nd,
  1479. NULL, NULL, rs);
  1480. else
  1481. ret = 1; /* allow any number placement at all */
  1482. if (ret == 1) {
  1483. /*
  1484. * Now place the numbers according to the solver's
  1485. * recommendations.
  1486. */
  1487. numbers = snewn(params->w * params->h, int);
  1488. for (y = 0; y < params->h; y++)
  1489. for (x = 0; x < params->w; x++) {
  1490. index(params, numbers, x, y) = 0;
  1491. }
  1492. for (i = 0; i < nnumbers; i++) {
  1493. int idx = random_upto(rs, nd[i].npoints);
  1494. int x = nd[i].points[idx].x;
  1495. int y = nd[i].points[idx].y;
  1496. index(params,numbers,x,y) = nd[i].area;
  1497. }
  1498. }
  1499. /*
  1500. * Clean up.
  1501. */
  1502. for (i = 0; i < nnumbers; i++)
  1503. sfree(nd[i].points);
  1504. sfree(nd);
  1505. /*
  1506. * If we've succeeded, then terminate the loop.
  1507. */
  1508. if (ret == 1)
  1509. break;
  1510. }
  1511. /*
  1512. * Give up and go round again.
  1513. */
  1514. sfree(grid);
  1515. }
  1516. /*
  1517. * Store the solution in aux.
  1518. */
  1519. {
  1520. char *ai;
  1521. int len;
  1522. len = 2 + (params->w-1)*params->h + (params->h-1)*params->w;
  1523. ai = snewn(len, char);
  1524. ai[0] = 'S';
  1525. p = ai+1;
  1526. for (y = 0; y < params->h; y++)
  1527. for (x = 1; x < params->w; x++)
  1528. *p++ = (index(params, grid, x, y) !=
  1529. index(params, grid, x-1, y) ? '1' : '0');
  1530. for (y = 1; y < params->h; y++)
  1531. for (x = 0; x < params->w; x++)
  1532. *p++ = (index(params, grid, x, y) !=
  1533. index(params, grid, x, y-1) ? '1' : '0');
  1534. assert(p - ai == len-1);
  1535. *p = '\0';
  1536. *aux = ai;
  1537. }
  1538. #ifdef GENERATION_DIAGNOSTICS
  1539. display_grid(params, grid, numbers, false);
  1540. #endif
  1541. desc = snewn(11 * params->w * params->h, char);
  1542. p = desc;
  1543. run = 0;
  1544. for (i = 0; i <= params->w * params->h; i++) {
  1545. int n = (i < params->w * params->h ? numbers[i] : -1);
  1546. if (!n)
  1547. run++;
  1548. else {
  1549. if (run) {
  1550. while (run > 0) {
  1551. int c = 'a' - 1 + run;
  1552. if (run > 26)
  1553. c = 'z';
  1554. *p++ = c;
  1555. run -= c - ('a' - 1);
  1556. }
  1557. } else {
  1558. /*
  1559. * If there's a number in the very top left or
  1560. * bottom right, there's no point putting an
  1561. * unnecessary _ before or after it.
  1562. */
  1563. if (p > desc && n > 0)
  1564. *p++ = '_';
  1565. }
  1566. if (n > 0)
  1567. p += sprintf(p, "%d", n);
  1568. run = 0;
  1569. }
  1570. }
  1571. *p = '\0';
  1572. sfree(grid);
  1573. sfree(numbers);
  1574. return desc;
  1575. }
  1576. static const char *validate_desc(const game_params *params, const char *desc)
  1577. {
  1578. int area = params->w * params->h;
  1579. int squares = 0;
  1580. while (*desc) {
  1581. int n = *desc++;
  1582. if (n >= 'a' && n <= 'z') {
  1583. squares += n - 'a' + 1;
  1584. } else if (n == '_') {
  1585. /* do nothing */;
  1586. } else if (n > '0' && n <= '9') {
  1587. squares++;
  1588. while (*desc >= '0' && *desc <= '9')
  1589. desc++;
  1590. } else
  1591. return "Invalid character in game description";
  1592. }
  1593. if (squares < area)
  1594. return "Not enough data to fill grid";
  1595. if (squares > area)
  1596. return "Too much data to fit in grid";
  1597. return NULL;
  1598. }
  1599. static unsigned char *get_correct(game_state *state)
  1600. {
  1601. unsigned char *ret;
  1602. int x, y;
  1603. ret = snewn(state->w * state->h, unsigned char);
  1604. memset(ret, 0xFF, state->w * state->h);
  1605. for (x = 0; x < state->w; x++)
  1606. for (y = 0; y < state->h; y++)
  1607. if (index(state,ret,x,y) == 0xFF) {
  1608. int rw, rh;
  1609. int xx, yy;
  1610. int num, area;
  1611. bool valid;
  1612. /*
  1613. * Find a rectangle starting at this point.
  1614. */
  1615. rw = 1;
  1616. while (x+rw < state->w && !vedge(state,x+rw,y))
  1617. rw++;
  1618. rh = 1;
  1619. while (y+rh < state->h && !hedge(state,x,y+rh))
  1620. rh++;
  1621. /*
  1622. * We know what the dimensions of the rectangle
  1623. * should be if it's there at all. Find out if we
  1624. * really have a valid rectangle.
  1625. */
  1626. valid = true;
  1627. /* Check the horizontal edges. */
  1628. for (xx = x; xx < x+rw; xx++) {
  1629. for (yy = y; yy <= y+rh; yy++) {
  1630. int e = !HRANGE(state,xx,yy) || hedge(state,xx,yy);
  1631. int ec = (yy == y || yy == y+rh);
  1632. if (e != ec)
  1633. valid = false;
  1634. }
  1635. }
  1636. /* Check the vertical edges. */
  1637. for (yy = y; yy < y+rh; yy++) {
  1638. for (xx = x; xx <= x+rw; xx++) {
  1639. int e = !VRANGE(state,xx,yy) || vedge(state,xx,yy);
  1640. int ec = (xx == x || xx == x+rw);
  1641. if (e != ec)
  1642. valid = false;
  1643. }
  1644. }
  1645. /*
  1646. * If this is not a valid rectangle with no other
  1647. * edges inside it, we just mark this square as not
  1648. * complete and proceed to the next square.
  1649. */
  1650. if (!valid) {
  1651. index(state, ret, x, y) = 0;
  1652. continue;
  1653. }
  1654. /*
  1655. * We have a rectangle. Now see what its area is,
  1656. * and how many numbers are in it.
  1657. */
  1658. num = 0;
  1659. area = 0;
  1660. for (xx = x; xx < x+rw; xx++) {
  1661. for (yy = y; yy < y+rh; yy++) {
  1662. area++;
  1663. if (grid(state,xx,yy)) {
  1664. if (num > 0)
  1665. valid = false; /* two numbers */
  1666. num = grid(state,xx,yy);
  1667. }
  1668. }
  1669. }
  1670. if (num != area)
  1671. valid = false;
  1672. /*
  1673. * Now fill in the whole rectangle based on the
  1674. * value of `valid'.
  1675. */
  1676. for (xx = x; xx < x+rw; xx++) {
  1677. for (yy = y; yy < y+rh; yy++) {
  1678. index(state, ret, xx, yy) = valid;
  1679. }
  1680. }
  1681. }
  1682. return ret;
  1683. }
  1684. static game_state *new_game(midend *me, const game_params *params,
  1685. const char *desc)
  1686. {
  1687. game_state *state = snew(game_state);
  1688. int x, y, i, area;
  1689. state->w = params->w;
  1690. state->h = params->h;
  1691. area = state->w * state->h;
  1692. state->grid = snewn(area, int);
  1693. state->vedge = snewn(area, unsigned char);
  1694. state->hedge = snewn(area, unsigned char);
  1695. state->completed = false;
  1696. state->cheated = false;
  1697. i = 0;
  1698. while (*desc) {
  1699. int n = *desc++;
  1700. if (n >= 'a' && n <= 'z') {
  1701. int run = n - 'a' + 1;
  1702. assert(i + run <= area);
  1703. while (run-- > 0)
  1704. state->grid[i++] = 0;
  1705. } else if (n == '_') {
  1706. /* do nothing */;
  1707. } else if (n > '0' && n <= '9') {
  1708. assert(i < area);
  1709. state->grid[i++] = atoi(desc-1);
  1710. while (*desc >= '0' && *desc <= '9')
  1711. desc++;
  1712. } else {
  1713. assert(!"We can't get here");
  1714. }
  1715. }
  1716. assert(i == area);
  1717. for (y = 0; y < state->h; y++)
  1718. for (x = 0; x < state->w; x++)
  1719. vedge(state,x,y) = hedge(state,x,y) = 0;
  1720. state->correct = get_correct(state);
  1721. return state;
  1722. }
  1723. static game_state *dup_game(const game_state *state)
  1724. {
  1725. game_state *ret = snew(game_state);
  1726. ret->w = state->w;
  1727. ret->h = state->h;
  1728. ret->vedge = snewn(state->w * state->h, unsigned char);
  1729. ret->hedge = snewn(state->w * state->h, unsigned char);
  1730. ret->grid = snewn(state->w * state->h, int);
  1731. ret->correct = snewn(ret->w * ret->h, unsigned char);
  1732. ret->completed = state->completed;
  1733. ret->cheated = state->cheated;
  1734. memcpy(ret->grid, state->grid, state->w * state->h * sizeof(int));
  1735. memcpy(ret->vedge, state->vedge, state->w*state->h*sizeof(unsigned char));
  1736. memcpy(ret->hedge, state->hedge, state->w*state->h*sizeof(unsigned char));
  1737. memcpy(ret->correct, state->correct, state->w*state->h*sizeof(unsigned char));
  1738. return ret;
  1739. }
  1740. static void free_game(game_state *state)
  1741. {
  1742. sfree(state->grid);
  1743. sfree(state->vedge);
  1744. sfree(state->hedge);
  1745. sfree(state->correct);
  1746. sfree(state);
  1747. }
  1748. static char *solve_game(const game_state *state, const game_state *currstate,
  1749. const char *ai, const char **error)
  1750. {
  1751. unsigned char *vedge, *hedge;
  1752. int x, y, len;
  1753. char *ret, *p;
  1754. int i, j, n;
  1755. struct numberdata *nd;
  1756. if (ai)
  1757. return dupstr(ai);
  1758. /*
  1759. * Attempt the in-built solver.
  1760. */
  1761. /* Set up each number's (very short) candidate position list. */
  1762. for (i = n = 0; i < state->h * state->w; i++)
  1763. if (state->grid[i])
  1764. n++;
  1765. nd = snewn(n, struct numberdata);
  1766. for (i = j = 0; i < state->h * state->w; i++)
  1767. if (state->grid[i]) {
  1768. nd[j].area = state->grid[i];
  1769. nd[j].npoints = 1;
  1770. nd[j].points = snewn(1, struct point);
  1771. nd[j].points[0].x = i % state->w;
  1772. nd[j].points[0].y = i / state->w;
  1773. j++;
  1774. }
  1775. assert(j == n);
  1776. vedge = snewn(state->w * state->h, unsigned char);
  1777. hedge = snewn(state->w * state->h, unsigned char);
  1778. memset(vedge, 0, state->w * state->h);
  1779. memset(hedge, 0, state->w * state->h);
  1780. rect_solver(state->w, state->h, n, nd, hedge, vedge, NULL);
  1781. /*
  1782. * Clean up.
  1783. */
  1784. for (i = 0; i < n; i++)
  1785. sfree(nd[i].points);
  1786. sfree(nd);
  1787. len = 2 + (state->w-1)*state->h + (state->h-1)*state->w;
  1788. ret = snewn(len, char);
  1789. p = ret;
  1790. *p++ = 'S';
  1791. for (y = 0; y < state->h; y++)
  1792. for (x = 1; x < state->w; x++)
  1793. *p++ = vedge[y*state->w+x] ? '1' : '0';
  1794. for (y = 1; y < state->h; y++)
  1795. for (x = 0; x < state->w; x++)
  1796. *p++ = hedge[y*state->w+x] ? '1' : '0';
  1797. *p++ = '\0';
  1798. assert(p - ret == len);
  1799. sfree(vedge);
  1800. sfree(hedge);
  1801. return ret;
  1802. }
  1803. static bool game_can_format_as_text_now(const game_params *params)
  1804. {
  1805. return true;
  1806. }
  1807. static char *game_text_format(const game_state *state)
  1808. {
  1809. char *ret, *p, buf[80];
  1810. int i, x, y, col, maxlen;
  1811. /*
  1812. * First determine the number of spaces required to display a
  1813. * number. We'll use at least two, because one looks a bit
  1814. * silly.
  1815. */
  1816. col = 2;
  1817. for (i = 0; i < state->w * state->h; i++) {
  1818. x = sprintf(buf, "%d", state->grid[i]);
  1819. if (col < x) col = x;
  1820. }
  1821. /*
  1822. * Now we know the exact total size of the grid we're going to
  1823. * produce: it's got 2*h+1 rows, each containing w lots of col,
  1824. * w+1 boundary characters and a trailing newline.
  1825. */
  1826. maxlen = (2*state->h+1) * (state->w * (col+1) + 2);
  1827. ret = snewn(maxlen+1, char);
  1828. p = ret;
  1829. for (y = 0; y <= 2*state->h; y++) {
  1830. for (x = 0; x <= 2*state->w; x++) {
  1831. if (x & y & 1) {
  1832. /*
  1833. * Display a number.
  1834. */
  1835. int v = grid(state, x/2, y/2);
  1836. if (v)
  1837. sprintf(buf, "%*d", col, v);
  1838. else
  1839. sprintf(buf, "%*s", col, "");
  1840. memcpy(p, buf, col);
  1841. p += col;
  1842. } else if (x & 1) {
  1843. /*
  1844. * Display a horizontal edge or nothing.
  1845. */
  1846. int h = (y==0 || y==2*state->h ? 1 :
  1847. HRANGE(state, x/2, y/2) && hedge(state, x/2, y/2));
  1848. int i;
  1849. if (h)
  1850. h = '-';
  1851. else
  1852. h = ' ';
  1853. for (i = 0; i < col; i++)
  1854. *p++ = h;
  1855. } else if (y & 1) {
  1856. /*
  1857. * Display a vertical edge or nothing.
  1858. */
  1859. int v = (x==0 || x==2*state->w ? 1 :
  1860. VRANGE(state, x/2, y/2) && vedge(state, x/2, y/2));
  1861. if (v)
  1862. *p++ = '|';
  1863. else
  1864. *p++ = ' ';
  1865. } else {
  1866. /*
  1867. * Display a corner, or a vertical edge, or a
  1868. * horizontal edge, or nothing.
  1869. */
  1870. int hl = (y==0 || y==2*state->h ? 1 :
  1871. HRANGE(state, (x-1)/2, y/2) && hedge(state, (x-1)/2, y/2));
  1872. int hr = (y==0 || y==2*state->h ? 1 :
  1873. HRANGE(state, (x+1)/2, y/2) && hedge(state, (x+1)/2, y/2));
  1874. int vu = (x==0 || x==2*state->w ? 1 :
  1875. VRANGE(state, x/2, (y-1)/2) && vedge(state, x/2, (y-1)/2));
  1876. int vd = (x==0 || x==2*state->w ? 1 :
  1877. VRANGE(state, x/2, (y+1)/2) && vedge(state, x/2, (y+1)/2));
  1878. if (!hl && !hr && !vu && !vd)
  1879. *p++ = ' ';
  1880. else if (hl && hr && !vu && !vd)
  1881. *p++ = '-';
  1882. else if (!hl && !hr && vu && vd)
  1883. *p++ = '|';
  1884. else
  1885. *p++ = '+';
  1886. }
  1887. }
  1888. *p++ = '\n';
  1889. }
  1890. assert(p - ret == maxlen);
  1891. *p = '\0';
  1892. return ret;
  1893. }
  1894. struct game_ui {
  1895. /*
  1896. * These coordinates are 2 times the obvious grid coordinates.
  1897. * Hence, the top left of the grid is (0,0), the grid point to
  1898. * the right of that is (2,0), the one _below that_ is (2,2)
  1899. * and so on. This is so that we can specify a drag start point
  1900. * on an edge (one odd coordinate) or in the middle of a square
  1901. * (two odd coordinates) rather than always at a corner.
  1902. *
  1903. * -1,-1 means no drag is in progress.
  1904. */
  1905. int drag_start_x;
  1906. int drag_start_y;
  1907. int drag_end_x;
  1908. int drag_end_y;
  1909. /*
  1910. * This flag is set as soon as a dragging action moves the
  1911. * mouse pointer away from its starting point, so that even if
  1912. * the pointer _returns_ to its starting point the action is
  1913. * treated as a small drag rather than a click.
  1914. */
  1915. bool dragged;
  1916. /* This flag is set if we're doing an erase operation (i.e.
  1917. * removing edges in the centre of the rectangle without altering
  1918. * the outlines).
  1919. */
  1920. bool erasing;
  1921. /*
  1922. * These are the co-ordinates of the top-left and bottom-right squares
  1923. * in the drag box, respectively, or -1 otherwise.
  1924. */
  1925. int x1;
  1926. int y1;
  1927. int x2;
  1928. int y2;
  1929. /*
  1930. * These are the coordinates of a cursor, whether it's visible, and
  1931. * whether it was used to start a drag.
  1932. */
  1933. int cur_x, cur_y;
  1934. bool cur_visible, cur_dragging;
  1935. };
  1936. static void reset_ui(game_ui *ui)
  1937. {
  1938. ui->drag_start_x = -1;
  1939. ui->drag_start_y = -1;
  1940. ui->drag_end_x = -1;
  1941. ui->drag_end_y = -1;
  1942. ui->x1 = -1;
  1943. ui->y1 = -1;
  1944. ui->x2 = -1;
  1945. ui->y2 = -1;
  1946. ui->dragged = false;
  1947. }
  1948. static game_ui *new_ui(const game_state *state)
  1949. {
  1950. game_ui *ui = snew(game_ui);
  1951. reset_ui(ui);
  1952. ui->erasing = false;
  1953. ui->cur_x = ui->cur_y = 0;
  1954. ui->cur_visible = getenv_bool("PUZZLES_SHOW_CURSOR", false);
  1955. ui->cur_dragging = false;
  1956. return ui;
  1957. }
  1958. static void free_ui(game_ui *ui)
  1959. {
  1960. sfree(ui);
  1961. }
  1962. static void coord_round(float x, float y, int *xr, int *yr)
  1963. {
  1964. float xs, ys, xv, yv, dx, dy, dist;
  1965. /*
  1966. * Find the nearest square-centre.
  1967. */
  1968. xs = (float)floor(x) + 0.5F;
  1969. ys = (float)floor(y) + 0.5F;
  1970. /*
  1971. * And find the nearest grid vertex.
  1972. */
  1973. xv = (float)floor(x + 0.5F);
  1974. yv = (float)floor(y + 0.5F);
  1975. /*
  1976. * We allocate clicks in parts of the grid square to either
  1977. * corners, edges or square centres, as follows:
  1978. *
  1979. * +--+--------+--+
  1980. * | | | |
  1981. * +--+ +--+
  1982. * | `. ,' |
  1983. * | +--+ |
  1984. * | | | |
  1985. * | +--+ |
  1986. * | ,' `. |
  1987. * +--+ +--+
  1988. * | | | |
  1989. * +--+--------+--+
  1990. *
  1991. * (Not to scale!)
  1992. *
  1993. * In other words: we measure the square distance (i.e.
  1994. * max(dx,dy)) from the click to the nearest corner, and if
  1995. * it's within CORNER_TOLERANCE then we return a corner click.
  1996. * We measure the square distance from the click to the nearest
  1997. * centre, and if that's within CENTRE_TOLERANCE we return a
  1998. * centre click. Failing that, we find which of the two edge
  1999. * centres is nearer to the click and return that edge.
  2000. */
  2001. /*
  2002. * Check for corner click.
  2003. */
  2004. dx = (float)fabs(x - xv);
  2005. dy = (float)fabs(y - yv);
  2006. dist = (dx > dy ? dx : dy);
  2007. if (dist < CORNER_TOLERANCE) {
  2008. *xr = 2 * (int)xv;
  2009. *yr = 2 * (int)yv;
  2010. } else {
  2011. /*
  2012. * Check for centre click.
  2013. */
  2014. dx = (float)fabs(x - xs);
  2015. dy = (float)fabs(y - ys);
  2016. dist = (dx > dy ? dx : dy);
  2017. if (dist < CENTRE_TOLERANCE) {
  2018. *xr = 1 + 2 * (int)xs;
  2019. *yr = 1 + 2 * (int)ys;
  2020. } else {
  2021. /*
  2022. * Failing both of those, see which edge we're closer to.
  2023. * Conveniently, this is simply done by testing the relative
  2024. * magnitude of dx and dy (which are currently distances from
  2025. * the square centre).
  2026. */
  2027. if (dx > dy) {
  2028. /* Vertical edge: x-coord of corner,
  2029. * y-coord of square centre. */
  2030. *xr = 2 * (int)xv;
  2031. *yr = 1 + 2 * (int)floor(ys);
  2032. } else {
  2033. /* Horizontal edge: x-coord of square centre,
  2034. * y-coord of corner. */
  2035. *xr = 1 + 2 * (int)floor(xs);
  2036. *yr = 2 * (int)yv;
  2037. }
  2038. }
  2039. }
  2040. }
  2041. /*
  2042. * Returns true if it has made any change to the grid.
  2043. */
  2044. static bool grid_draw_rect(const game_state *state,
  2045. unsigned char *hedge, unsigned char *vedge,
  2046. int c, bool really, bool outline,
  2047. int x1, int y1, int x2, int y2)
  2048. {
  2049. int x, y;
  2050. bool changed = false;
  2051. /*
  2052. * Draw horizontal edges of rectangles.
  2053. */
  2054. for (x = x1; x < x2; x++)
  2055. for (y = y1; y <= y2; y++)
  2056. if (HRANGE(state,x,y)) {
  2057. int val = index(state,hedge,x,y);
  2058. if (y == y1 || y == y2) {
  2059. if (!outline) continue;
  2060. val = c;
  2061. } else if (c == 1)
  2062. val = 0;
  2063. changed = changed || (index(state,hedge,x,y) != val);
  2064. if (really)
  2065. index(state,hedge,x,y) = val;
  2066. }
  2067. /*
  2068. * Draw vertical edges of rectangles.
  2069. */
  2070. for (y = y1; y < y2; y++)
  2071. for (x = x1; x <= x2; x++)
  2072. if (VRANGE(state,x,y)) {
  2073. int val = index(state,vedge,x,y);
  2074. if (x == x1 || x == x2) {
  2075. if (!outline) continue;
  2076. val = c;
  2077. } else if (c == 1)
  2078. val = 0;
  2079. changed = changed || (index(state,vedge,x,y) != val);
  2080. if (really)
  2081. index(state,vedge,x,y) = val;
  2082. }
  2083. return changed;
  2084. }
  2085. static bool ui_draw_rect(const game_state *state, const game_ui *ui,
  2086. unsigned char *hedge, unsigned char *vedge, int c,
  2087. bool really, bool outline)
  2088. {
  2089. return grid_draw_rect(state, hedge, vedge, c, really, outline,
  2090. ui->x1, ui->y1, ui->x2, ui->y2);
  2091. }
  2092. static void game_changed_state(game_ui *ui, const game_state *oldstate,
  2093. const game_state *newstate)
  2094. {
  2095. }
  2096. struct game_drawstate {
  2097. bool started;
  2098. int w, h, tilesize;
  2099. unsigned long *visible;
  2100. };
  2101. static const char *current_key_label(const game_ui *ui,
  2102. const game_state *state, int button)
  2103. {
  2104. if (IS_CURSOR_SELECT(button) && ui->cur_visible &&
  2105. !(ui->drag_start_x >= 0 && !ui->cur_dragging)) {
  2106. if (ui->cur_dragging) {
  2107. if (!ui->dragged) return "Cancel";
  2108. if ((button == CURSOR_SELECT2) == ui->erasing) return "Done";
  2109. return "Cancel";
  2110. }
  2111. return button == CURSOR_SELECT ? "Mark" : "Erase";
  2112. }
  2113. return "";
  2114. }
  2115. static char *interpret_move(const game_state *from, game_ui *ui,
  2116. const game_drawstate *ds,
  2117. int x, int y, int button)
  2118. {
  2119. int xc, yc;
  2120. bool startdrag = false, enddrag = false, active = false, erasing = false;
  2121. char buf[80], *ret;
  2122. button &= ~MOD_MASK;
  2123. coord_round(FROMCOORD((float)x), FROMCOORD((float)y), &xc, &yc);
  2124. if (button == LEFT_BUTTON || button == RIGHT_BUTTON) {
  2125. if (ui->drag_start_x >= 0 && ui->cur_dragging)
  2126. reset_ui(ui); /* cancel keyboard dragging */
  2127. startdrag = true;
  2128. ui->cur_visible = ui->cur_dragging = false;
  2129. active = true;
  2130. erasing = (button == RIGHT_BUTTON);
  2131. } else if (button == LEFT_RELEASE || button == RIGHT_RELEASE) {
  2132. /* We assert we should have had a LEFT_BUTTON first. */
  2133. if (ui->cur_visible) {
  2134. ui->cur_visible = false;
  2135. active = true;
  2136. }
  2137. assert(!ui->cur_dragging);
  2138. enddrag = true;
  2139. erasing = (button == RIGHT_RELEASE);
  2140. } else if (IS_CURSOR_MOVE(button)) {
  2141. move_cursor(button, &ui->cur_x, &ui->cur_y, from->w, from->h, false);
  2142. ui->cur_visible = true;
  2143. active = true;
  2144. if (!ui->cur_dragging) return MOVE_UI_UPDATE;
  2145. coord_round((float)ui->cur_x + 0.5F, (float)ui->cur_y + 0.5F, &xc, &yc);
  2146. } else if (IS_CURSOR_SELECT(button)) {
  2147. if (ui->drag_start_x >= 0 && !ui->cur_dragging) {
  2148. /*
  2149. * If a mouse drag is in progress, ignore attempts to
  2150. * start a keyboard one.
  2151. */
  2152. return NULL;
  2153. }
  2154. if (!ui->cur_visible) {
  2155. assert(!ui->cur_dragging);
  2156. ui->cur_visible = true;
  2157. return MOVE_UI_UPDATE;
  2158. }
  2159. coord_round((float)ui->cur_x + 0.5F, (float)ui->cur_y + 0.5F, &xc, &yc);
  2160. erasing = (button == CURSOR_SELECT2);
  2161. if (ui->cur_dragging) {
  2162. ui->cur_dragging = false;
  2163. enddrag = true;
  2164. active = true;
  2165. } else {
  2166. ui->cur_dragging = true;
  2167. startdrag = true;
  2168. active = true;
  2169. }
  2170. } else if (button == '\b' || button == 27) {
  2171. if (!ui->cur_dragging) {
  2172. ui->cur_visible = false;
  2173. } else {
  2174. assert(ui->cur_visible);
  2175. reset_ui(ui); /* cancel keyboard dragging */
  2176. ui->cur_dragging = false;
  2177. }
  2178. return MOVE_UI_UPDATE;
  2179. } else if (button != LEFT_DRAG && button != RIGHT_DRAG) {
  2180. return NULL;
  2181. }
  2182. if (startdrag &&
  2183. xc >= 0 && xc <= 2*from->w &&
  2184. yc >= 0 && yc <= 2*from->h) {
  2185. ui->drag_start_x = xc;
  2186. ui->drag_start_y = yc;
  2187. ui->drag_end_x = -1;
  2188. ui->drag_end_y = -1;
  2189. ui->dragged = false;
  2190. ui->erasing = erasing;
  2191. active = true;
  2192. }
  2193. if (ui->drag_start_x >= 0 &&
  2194. (xc != ui->drag_end_x || yc != ui->drag_end_y)) {
  2195. int t;
  2196. if (ui->drag_end_x != -1 && ui->drag_end_y != -1)
  2197. ui->dragged = true;
  2198. ui->drag_end_x = xc;
  2199. ui->drag_end_y = yc;
  2200. active = true;
  2201. if (xc >= 0 && xc <= 2*from->w &&
  2202. yc >= 0 && yc <= 2*from->h) {
  2203. ui->x1 = ui->drag_start_x;
  2204. ui->x2 = ui->drag_end_x;
  2205. if (ui->x2 < ui->x1) { t = ui->x1; ui->x1 = ui->x2; ui->x2 = t; }
  2206. ui->y1 = ui->drag_start_y;
  2207. ui->y2 = ui->drag_end_y;
  2208. if (ui->y2 < ui->y1) { t = ui->y1; ui->y1 = ui->y2; ui->y2 = t; }
  2209. ui->x1 = ui->x1 / 2; /* rounds down */
  2210. ui->x2 = (ui->x2+1) / 2; /* rounds up */
  2211. ui->y1 = ui->y1 / 2; /* rounds down */
  2212. ui->y2 = (ui->y2+1) / 2; /* rounds up */
  2213. } else {
  2214. ui->x1 = -1;
  2215. ui->y1 = -1;
  2216. ui->x2 = -1;
  2217. ui->y2 = -1;
  2218. }
  2219. }
  2220. ret = NULL;
  2221. if (enddrag && (ui->drag_start_x >= 0)) {
  2222. if (xc >= 0 && xc <= 2*from->w &&
  2223. yc >= 0 && yc <= 2*from->h &&
  2224. erasing == ui->erasing) {
  2225. if (ui->dragged) {
  2226. if (ui_draw_rect(from, ui, from->hedge,
  2227. from->vedge, 1, false, !ui->erasing)) {
  2228. sprintf(buf, "%c%d,%d,%d,%d",
  2229. (int)(ui->erasing ? 'E' : 'R'),
  2230. ui->x1, ui->y1, ui->x2 - ui->x1, ui->y2 - ui->y1);
  2231. ret = dupstr(buf);
  2232. }
  2233. } else {
  2234. if ((xc & 1) && !(yc & 1) && HRANGE(from,xc/2,yc/2)) {
  2235. sprintf(buf, "H%d,%d", xc/2, yc/2);
  2236. ret = dupstr(buf);
  2237. }
  2238. if ((yc & 1) && !(xc & 1) && VRANGE(from,xc/2,yc/2)) {
  2239. sprintf(buf, "V%d,%d", xc/2, yc/2);
  2240. ret = dupstr(buf);
  2241. }
  2242. }
  2243. }
  2244. reset_ui(ui);
  2245. active = true;
  2246. }
  2247. if (ret)
  2248. return ret; /* a move has been made */
  2249. else if (active)
  2250. return MOVE_UI_UPDATE;
  2251. else
  2252. return NULL;
  2253. }
  2254. static game_state *execute_move(const game_state *from, const char *move)
  2255. {
  2256. game_state *ret;
  2257. int x1, y1, x2, y2, mode;
  2258. if (move[0] == 'S') {
  2259. const char *p = move+1;
  2260. int x, y;
  2261. ret = dup_game(from);
  2262. ret->cheated = true;
  2263. for (y = 0; y < ret->h; y++)
  2264. for (x = 1; x < ret->w; x++) {
  2265. vedge(ret, x, y) = (*p == '1');
  2266. if (*p) p++;
  2267. }
  2268. for (y = 1; y < ret->h; y++)
  2269. for (x = 0; x < ret->w; x++) {
  2270. hedge(ret, x, y) = (*p == '1');
  2271. if (*p) p++;
  2272. }
  2273. sfree(ret->correct);
  2274. ret->correct = get_correct(ret);
  2275. return ret;
  2276. } else if ((move[0] == 'R' || move[0] == 'E') &&
  2277. sscanf(move+1, "%d,%d,%d,%d", &x1, &y1, &x2, &y2) == 4 &&
  2278. x1 >= 0 && x2 >= 0 && x1+x2 <= from->w &&
  2279. y1 >= 0 && y2 >= 0 && y1+y2 <= from->h) {
  2280. x2 += x1;
  2281. y2 += y1;
  2282. mode = move[0];
  2283. } else if ((move[0] == 'H' || move[0] == 'V') &&
  2284. sscanf(move+1, "%d,%d", &x1, &y1) == 2 &&
  2285. (move[0] == 'H' ? HRANGE(from, x1, y1) :
  2286. VRANGE(from, x1, y1))) {
  2287. mode = move[0];
  2288. } else
  2289. return NULL; /* can't parse move string */
  2290. ret = dup_game(from);
  2291. if (mode == 'R' || mode == 'E') {
  2292. grid_draw_rect(ret, ret->hedge, ret->vedge, 1, true,
  2293. mode == 'R', x1, y1, x2, y2);
  2294. } else if (mode == 'H') {
  2295. hedge(ret,x1,y1) = !hedge(ret,x1,y1);
  2296. } else if (mode == 'V') {
  2297. vedge(ret,x1,y1) = !vedge(ret,x1,y1);
  2298. }
  2299. sfree(ret->correct);
  2300. ret->correct = get_correct(ret);
  2301. /*
  2302. * We've made a real change to the grid. Check to see
  2303. * if the game has been completed.
  2304. */
  2305. if (!ret->completed) {
  2306. int x, y;
  2307. bool ok;
  2308. ok = true;
  2309. for (x = 0; x < ret->w; x++)
  2310. for (y = 0; y < ret->h; y++)
  2311. if (!index(ret, ret->correct, x, y))
  2312. ok = false;
  2313. if (ok)
  2314. ret->completed = true;
  2315. }
  2316. return ret;
  2317. }
  2318. /* ----------------------------------------------------------------------
  2319. * Drawing routines.
  2320. */
  2321. #define CORRECT (1L<<16)
  2322. #define CURSOR (1L<<17)
  2323. #define COLOUR(k) ( (k)==1 ? COL_LINE : (k)==2 ? COL_DRAG : COL_DRAGERASE )
  2324. #define MAX4(x,y,z,w) ( max(max(x,y),max(z,w)) )
  2325. static void game_compute_size(const game_params *params, int tilesize,
  2326. const game_ui *ui, int *x, int *y)
  2327. {
  2328. /* Ick: fake up `ds->tilesize' for macro expansion purposes */
  2329. struct { int tilesize; } ads, *ds = &ads;
  2330. ads.tilesize = tilesize;
  2331. *x = params->w * TILE_SIZE + 2*BORDER + 1;
  2332. *y = params->h * TILE_SIZE + 2*BORDER + 1;
  2333. }
  2334. static void game_set_size(drawing *dr, game_drawstate *ds,
  2335. const game_params *params, int tilesize)
  2336. {
  2337. ds->tilesize = tilesize;
  2338. }
  2339. static float *game_colours(frontend *fe, int *ncolours)
  2340. {
  2341. float *ret = snewn(3 * NCOLOURS, float);
  2342. frontend_default_colour(fe, &ret[COL_BACKGROUND * 3]);
  2343. ret[COL_GRID * 3 + 0] = 0.5F * ret[COL_BACKGROUND * 3 + 0];
  2344. ret[COL_GRID * 3 + 1] = 0.5F * ret[COL_BACKGROUND * 3 + 1];
  2345. ret[COL_GRID * 3 + 2] = 0.5F * ret[COL_BACKGROUND * 3 + 2];
  2346. ret[COL_DRAG * 3 + 0] = 1.0F;
  2347. ret[COL_DRAG * 3 + 1] = 0.0F;
  2348. ret[COL_DRAG * 3 + 2] = 0.0F;
  2349. ret[COL_DRAGERASE * 3 + 0] = 0.2F;
  2350. ret[COL_DRAGERASE * 3 + 1] = 0.2F;
  2351. ret[COL_DRAGERASE * 3 + 2] = 1.0F;
  2352. ret[COL_CORRECT * 3 + 0] = 0.75F * ret[COL_BACKGROUND * 3 + 0];
  2353. ret[COL_CORRECT * 3 + 1] = 0.75F * ret[COL_BACKGROUND * 3 + 1];
  2354. ret[COL_CORRECT * 3 + 2] = 0.75F * ret[COL_BACKGROUND * 3 + 2];
  2355. ret[COL_LINE * 3 + 0] = 0.0F;
  2356. ret[COL_LINE * 3 + 1] = 0.0F;
  2357. ret[COL_LINE * 3 + 2] = 0.0F;
  2358. ret[COL_TEXT * 3 + 0] = 0.0F;
  2359. ret[COL_TEXT * 3 + 1] = 0.0F;
  2360. ret[COL_TEXT * 3 + 2] = 0.0F;
  2361. ret[COL_CURSOR * 3 + 0] = 1.0F;
  2362. ret[COL_CURSOR * 3 + 1] = 0.5F;
  2363. ret[COL_CURSOR * 3 + 2] = 0.5F;
  2364. *ncolours = NCOLOURS;
  2365. return ret;
  2366. }
  2367. static game_drawstate *game_new_drawstate(drawing *dr, const game_state *state)
  2368. {
  2369. struct game_drawstate *ds = snew(struct game_drawstate);
  2370. int i;
  2371. ds->started = false;
  2372. ds->w = state->w;
  2373. ds->h = state->h;
  2374. ds->visible = snewn(ds->w * ds->h, unsigned long);
  2375. ds->tilesize = 0; /* not decided yet */
  2376. for (i = 0; i < ds->w * ds->h; i++)
  2377. ds->visible[i] = 0xFFFF;
  2378. return ds;
  2379. }
  2380. static void game_free_drawstate(drawing *dr, game_drawstate *ds)
  2381. {
  2382. sfree(ds->visible);
  2383. sfree(ds);
  2384. }
  2385. static void draw_tile(drawing *dr, game_drawstate *ds, const game_state *state,
  2386. int x, int y, unsigned char *hedge, unsigned char *vedge,
  2387. unsigned char *corners, unsigned long bgflags)
  2388. {
  2389. int cx = COORD(x), cy = COORD(y);
  2390. char str[80];
  2391. draw_rect(dr, cx, cy, TILE_SIZE+1, TILE_SIZE+1, COL_GRID);
  2392. draw_rect(dr, cx+1, cy+1, TILE_SIZE-1, TILE_SIZE-1,
  2393. (bgflags & CURSOR) ? COL_CURSOR :
  2394. (bgflags & CORRECT) ? COL_CORRECT : COL_BACKGROUND);
  2395. if (grid(state,x,y)) {
  2396. sprintf(str, "%d", grid(state,x,y));
  2397. draw_text(dr, cx+TILE_SIZE/2, cy+TILE_SIZE/2, FONT_VARIABLE,
  2398. TILE_SIZE/2, ALIGN_HCENTRE | ALIGN_VCENTRE, COL_TEXT, str);
  2399. }
  2400. /*
  2401. * Draw edges.
  2402. */
  2403. if (!HRANGE(state,x,y) || index(state,hedge,x,y))
  2404. draw_rect(dr, cx, cy, TILE_SIZE+1, 2,
  2405. HRANGE(state,x,y) ? COLOUR(index(state,hedge,x,y)) :
  2406. COL_LINE);
  2407. if (!HRANGE(state,x,y+1) || index(state,hedge,x,y+1))
  2408. draw_rect(dr, cx, cy+TILE_SIZE-1, TILE_SIZE+1, 2,
  2409. HRANGE(state,x,y+1) ? COLOUR(index(state,hedge,x,y+1)) :
  2410. COL_LINE);
  2411. if (!VRANGE(state,x,y) || index(state,vedge,x,y))
  2412. draw_rect(dr, cx, cy, 2, TILE_SIZE+1,
  2413. VRANGE(state,x,y) ? COLOUR(index(state,vedge,x,y)) :
  2414. COL_LINE);
  2415. if (!VRANGE(state,x+1,y) || index(state,vedge,x+1,y))
  2416. draw_rect(dr, cx+TILE_SIZE-1, cy, 2, TILE_SIZE+1,
  2417. VRANGE(state,x+1,y) ? COLOUR(index(state,vedge,x+1,y)) :
  2418. COL_LINE);
  2419. /*
  2420. * Draw corners.
  2421. */
  2422. if (index(state,corners,x,y))
  2423. draw_rect(dr, cx, cy, 2, 2,
  2424. COLOUR(index(state,corners,x,y)));
  2425. if (x+1 < state->w && index(state,corners,x+1,y))
  2426. draw_rect(dr, cx+TILE_SIZE-1, cy, 2, 2,
  2427. COLOUR(index(state,corners,x+1,y)));
  2428. if (y+1 < state->h && index(state,corners,x,y+1))
  2429. draw_rect(dr, cx, cy+TILE_SIZE-1, 2, 2,
  2430. COLOUR(index(state,corners,x,y+1)));
  2431. if (x+1 < state->w && y+1 < state->h && index(state,corners,x+1,y+1))
  2432. draw_rect(dr, cx+TILE_SIZE-1, cy+TILE_SIZE-1, 2, 2,
  2433. COLOUR(index(state,corners,x+1,y+1)));
  2434. draw_update(dr, cx, cy, TILE_SIZE+1, TILE_SIZE+1);
  2435. }
  2436. static void game_redraw(drawing *dr, game_drawstate *ds,
  2437. const game_state *oldstate, const game_state *state,
  2438. int dir, const game_ui *ui,
  2439. float animtime, float flashtime)
  2440. {
  2441. int x, y;
  2442. unsigned char *hedge, *vedge, *corners;
  2443. if (ui->dragged) {
  2444. hedge = snewn(state->w*state->h, unsigned char);
  2445. vedge = snewn(state->w*state->h, unsigned char);
  2446. memcpy(hedge, state->hedge, state->w*state->h);
  2447. memcpy(vedge, state->vedge, state->w*state->h);
  2448. ui_draw_rect(state, ui, hedge, vedge, ui->erasing ? 3 : 2, true, true);
  2449. } else {
  2450. hedge = state->hedge;
  2451. vedge = state->vedge;
  2452. }
  2453. corners = snewn(state->w * state->h, unsigned char);
  2454. memset(corners, 0, state->w * state->h);
  2455. for (x = 0; x < state->w; x++)
  2456. for (y = 0; y < state->h; y++) {
  2457. if (x > 0) {
  2458. int e = index(state, vedge, x, y);
  2459. if (index(state,corners,x,y) < e)
  2460. index(state,corners,x,y) = e;
  2461. if (y+1 < state->h &&
  2462. index(state,corners,x,y+1) < e)
  2463. index(state,corners,x,y+1) = e;
  2464. }
  2465. if (y > 0) {
  2466. int e = index(state, hedge, x, y);
  2467. if (index(state,corners,x,y) < e)
  2468. index(state,corners,x,y) = e;
  2469. if (x+1 < state->w &&
  2470. index(state,corners,x+1,y) < e)
  2471. index(state,corners,x+1,y) = e;
  2472. }
  2473. }
  2474. if (!ds->started) {
  2475. draw_rect(dr, COORD(0)-1, COORD(0)-1,
  2476. ds->w*TILE_SIZE+3, ds->h*TILE_SIZE+3, COL_LINE);
  2477. ds->started = true;
  2478. draw_update(dr, 0, 0,
  2479. state->w * TILE_SIZE + 2*BORDER + 1,
  2480. state->h * TILE_SIZE + 2*BORDER + 1);
  2481. }
  2482. for (x = 0; x < state->w; x++)
  2483. for (y = 0; y < state->h; y++) {
  2484. unsigned long c = 0;
  2485. if (HRANGE(state,x,y))
  2486. c |= index(state,hedge,x,y);
  2487. if (HRANGE(state,x,y+1))
  2488. c |= index(state,hedge,x,y+1) << 2;
  2489. if (VRANGE(state,x,y))
  2490. c |= index(state,vedge,x,y) << 4;
  2491. if (VRANGE(state,x+1,y))
  2492. c |= index(state,vedge,x+1,y) << 6;
  2493. c |= index(state,corners,x,y) << 8;
  2494. if (x+1 < state->w)
  2495. c |= index(state,corners,x+1,y) << 10;
  2496. if (y+1 < state->h)
  2497. c |= index(state,corners,x,y+1) << 12;
  2498. if (x+1 < state->w && y+1 < state->h)
  2499. /* cast to prevent 2<<14 sign-extending on promotion to long */
  2500. c |= (unsigned long)index(state,corners,x+1,y+1) << 14;
  2501. if (index(state, state->correct, x, y) && !flashtime)
  2502. c |= CORRECT;
  2503. if (ui->cur_visible && ui->cur_x == x && ui->cur_y == y)
  2504. c |= CURSOR;
  2505. if (index(ds,ds->visible,x,y) != c) {
  2506. draw_tile(dr, ds, state, x, y, hedge, vedge, corners,
  2507. (c & (CORRECT|CURSOR)) );
  2508. index(ds,ds->visible,x,y) = c;
  2509. }
  2510. }
  2511. {
  2512. char buf[256];
  2513. if (ui->dragged &&
  2514. ui->x1 >= 0 && ui->y1 >= 0 &&
  2515. ui->x2 >= 0 && ui->y2 >= 0) {
  2516. sprintf(buf, "%dx%d ",
  2517. ui->x2-ui->x1,
  2518. ui->y2-ui->y1);
  2519. } else {
  2520. buf[0] = '\0';
  2521. }
  2522. if (state->cheated)
  2523. strcat(buf, "Auto-solved.");
  2524. else if (state->completed)
  2525. strcat(buf, "COMPLETED!");
  2526. status_bar(dr, buf);
  2527. }
  2528. if (hedge != state->hedge) {
  2529. sfree(hedge);
  2530. sfree(vedge);
  2531. }
  2532. sfree(corners);
  2533. }
  2534. static float game_anim_length(const game_state *oldstate,
  2535. const game_state *newstate, int dir, game_ui *ui)
  2536. {
  2537. return 0.0F;
  2538. }
  2539. static float game_flash_length(const game_state *oldstate,
  2540. const game_state *newstate, int dir, game_ui *ui)
  2541. {
  2542. if (!oldstate->completed && newstate->completed &&
  2543. !oldstate->cheated && !newstate->cheated)
  2544. return FLASH_TIME;
  2545. return 0.0F;
  2546. }
  2547. static void game_get_cursor_location(const game_ui *ui,
  2548. const game_drawstate *ds,
  2549. const game_state *state,
  2550. const game_params *params,
  2551. int *x, int *y, int *w, int *h)
  2552. {
  2553. if(ui->cur_visible) {
  2554. *x = COORD(ui->cur_x);
  2555. *y = COORD(ui->cur_y);
  2556. *w = *h = TILE_SIZE;
  2557. }
  2558. }
  2559. static int game_status(const game_state *state)
  2560. {
  2561. return state->completed ? +1 : 0;
  2562. }
  2563. static void game_print_size(const game_params *params, const game_ui *ui,
  2564. float *x, float *y)
  2565. {
  2566. int pw, ph;
  2567. /*
  2568. * I'll use 5mm squares by default.
  2569. */
  2570. game_compute_size(params, 500, ui, &pw, &ph);
  2571. *x = pw / 100.0F;
  2572. *y = ph / 100.0F;
  2573. }
  2574. static void game_print(drawing *dr, const game_state *state, const game_ui *ui,
  2575. int tilesize)
  2576. {
  2577. int w = state->w, h = state->h;
  2578. int ink = print_mono_colour(dr, 0);
  2579. int x, y;
  2580. /* Ick: fake up `ds->tilesize' for macro expansion purposes */
  2581. game_drawstate ads, *ds = &ads;
  2582. game_set_size(dr, ds, NULL, tilesize);
  2583. /*
  2584. * Border.
  2585. */
  2586. print_line_width(dr, TILE_SIZE / 10);
  2587. draw_rect_outline(dr, COORD(0), COORD(0), w*TILE_SIZE, h*TILE_SIZE, ink);
  2588. /*
  2589. * Grid. We have to make the grid lines particularly thin,
  2590. * because users will be drawing lines _along_ them and we want
  2591. * those lines to be visible.
  2592. */
  2593. print_line_width(dr, TILE_SIZE / 256);
  2594. for (x = 1; x < w; x++)
  2595. draw_line(dr, COORD(x), COORD(0), COORD(x), COORD(h), ink);
  2596. for (y = 1; y < h; y++)
  2597. draw_line(dr, COORD(0), COORD(y), COORD(w), COORD(y), ink);
  2598. /*
  2599. * Solution.
  2600. */
  2601. print_line_width(dr, TILE_SIZE / 10);
  2602. for (y = 0; y <= h; y++)
  2603. for (x = 0; x <= w; x++) {
  2604. if (HRANGE(state,x,y) && hedge(state,x,y))
  2605. draw_line(dr, COORD(x), COORD(y), COORD(x+1), COORD(y), ink);
  2606. if (VRANGE(state,x,y) && vedge(state,x,y))
  2607. draw_line(dr, COORD(x), COORD(y), COORD(x), COORD(y+1), ink);
  2608. }
  2609. /*
  2610. * Clues.
  2611. */
  2612. for (y = 0; y < h; y++)
  2613. for (x = 0; x < w; x++)
  2614. if (grid(state,x,y)) {
  2615. char str[80];
  2616. sprintf(str, "%d", grid(state,x,y));
  2617. draw_text(dr, COORD(x)+TILE_SIZE/2, COORD(y)+TILE_SIZE/2,
  2618. FONT_VARIABLE, TILE_SIZE/2,
  2619. ALIGN_HCENTRE | ALIGN_VCENTRE, ink, str);
  2620. }
  2621. }
  2622. #ifdef COMBINED
  2623. #define thegame rect
  2624. #endif
  2625. const struct game thegame = {
  2626. "Rectangles", "games.rectangles", "rect",
  2627. default_params,
  2628. game_fetch_preset, NULL,
  2629. decode_params,
  2630. encode_params,
  2631. free_params,
  2632. dup_params,
  2633. true, game_configure, custom_params,
  2634. validate_params,
  2635. new_game_desc,
  2636. validate_desc,
  2637. new_game,
  2638. dup_game,
  2639. free_game,
  2640. true, solve_game,
  2641. true, game_can_format_as_text_now, game_text_format,
  2642. NULL, NULL, /* get_prefs, set_prefs */
  2643. new_ui,
  2644. free_ui,
  2645. NULL, /* encode_ui */
  2646. NULL, /* decode_ui */
  2647. NULL, /* game_request_keys */
  2648. game_changed_state,
  2649. current_key_label,
  2650. interpret_move,
  2651. execute_move,
  2652. PREFERRED_TILE_SIZE, game_compute_size, game_set_size,
  2653. game_colours,
  2654. game_new_drawstate,
  2655. game_free_drawstate,
  2656. game_redraw,
  2657. game_anim_length,
  2658. game_flash_length,
  2659. game_get_cursor_location,
  2660. game_status,
  2661. true, false, game_print_size, game_print,
  2662. true, /* wants_statusbar */
  2663. false, NULL, /* timing_state */
  2664. 0, /* flags */
  2665. };
  2666. /* vim: set shiftwidth=4 tabstop=8: */