bridges.c 107 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341
  1. /*
  2. * bridges.c: Implementation of the Nikoli game 'Bridges'.
  3. *
  4. * Things still to do:
  5. *
  6. * - The solver's algorithmic design is not really ideal. It makes
  7. * use of the same data representation as gameplay uses, which
  8. * often looks like a tempting reuse of code but isn't always a
  9. * good idea. In this case, it's unpleasant that each edge of the
  10. * graph ends up represented as multiple squares on a grid, with
  11. * flags indicating when edges and non-edges cross; that's useful
  12. * when the result can be directly translated into positions of
  13. * graphics on the display, but in purely internal work it makes
  14. * even simple manipulations during solving more painful than they
  15. * should be, and complex ones have no choice but to modify the
  16. * data structures temporarily, test things, and put them back. I
  17. * envisage a complete solver rewrite along the following lines:
  18. * + We have a collection of vertices (islands) and edges
  19. * (potential bridge locations, i.e. pairs of horizontal or
  20. * vertical islands with no other island in between).
  21. * + Each edge has an associated list of edges that cross it, and
  22. * hence with which it is mutually exclusive.
  23. * + For each edge, we track the min and max number of bridges we
  24. * currently think possible.
  25. * + For each vertex, we track the number of _liberties_ it has,
  26. * i.e. its clue number minus the min bridge count for each edge
  27. * out of it.
  28. * + We also maintain a dsf that identifies sets of vertices which
  29. * are connected components of the puzzle so far, and for each
  30. * equivalence class we track the total number of liberties for
  31. * that component. (The dsf mechanism will also already track
  32. * the size of each component, i.e. number of islands.)
  33. * + So incrementing the min for an edge requires processing along
  34. * the lines of:
  35. * - set the max for all edges crossing that one to zero
  36. * - decrement the liberty count for the vertex at each end,
  37. * and also for each vertex's equivalence class (NB they may
  38. * be the same class)
  39. * - unify the two equivalence classes if they're not already,
  40. * and if so, set the liberty count for the new class to be
  41. * the sum of the previous two.
  42. * + Decrementing the max is much easier, however.
  43. * + With this data structure the really fiddly stuff in stage3()
  44. * becomes more or less trivial, because it's now a quick job to
  45. * find out whether an island would form an isolated subgraph if
  46. * connected to a given subset of its neighbours:
  47. * - identify the connected components containing the test
  48. * vertex and its putative new neighbours (but be careful not
  49. * to count a component more than once if two or more of the
  50. * vertices involved are already in the same one)
  51. * - find the sum of those components' liberty counts, and also
  52. * the total number of islands involved
  53. * - if the total liberty count of the connected components is
  54. * exactly equal to twice the number of edges we'd be adding
  55. * (of course each edge destroys two liberties, one at each
  56. * end) then these components would become a subgraph with
  57. * zero liberties if connected together.
  58. * - therefore, if that subgraph also contains fewer than the
  59. * total number of islands, it's disallowed.
  60. * - As mentioned in stage3(), once we've identified such a
  61. * disallowed pattern, we have two choices for what to do
  62. * with it: if the candidate set of neighbours has size 1 we
  63. * can reduce the max for the edge to that one neighbour,
  64. * whereas if its complement has size 1 we can increase the
  65. * min for the edge to the _omitted_ neighbour.
  66. *
  67. * - write a recursive solver?
  68. */
  69. #include <stdio.h>
  70. #include <stdlib.h>
  71. #include <string.h>
  72. #include <assert.h>
  73. #include <ctype.h>
  74. #include <limits.h>
  75. #ifdef NO_TGMATH_H
  76. # include <math.h>
  77. #else
  78. # include <tgmath.h>
  79. #endif
  80. #include "puzzles.h"
  81. #undef DRAW_GRID
  82. /* --- structures for params, state, etc. --- */
  83. #define MAX_BRIDGES 4
  84. #define PREFERRED_TILE_SIZE 24
  85. #define TILE_SIZE (ds->tilesize)
  86. #define BORDER (TILE_SIZE / 2)
  87. #define COORD(x) ( (x) * TILE_SIZE + BORDER )
  88. #define FROMCOORD(x) ( ((x) - BORDER + TILE_SIZE) / TILE_SIZE - 1 )
  89. #define FLASH_TIME 0.50F
  90. enum {
  91. COL_BACKGROUND,
  92. COL_FOREGROUND,
  93. COL_HIGHLIGHT, COL_LOWLIGHT,
  94. COL_SELECTED, COL_MARK,
  95. COL_HINT, COL_GRID,
  96. COL_WARNING,
  97. COL_CURSOR,
  98. NCOLOURS
  99. };
  100. struct game_params {
  101. int w, h, maxb;
  102. int islands, expansion; /* %age of island squares, %age chance of expansion */
  103. bool allowloops;
  104. int difficulty;
  105. };
  106. /* general flags used by all structs */
  107. #define G_ISLAND 0x0001
  108. #define G_LINEV 0x0002 /* contains a vert. line */
  109. #define G_LINEH 0x0004 /* contains a horiz. line (mutex with LINEV) */
  110. #define G_LINE (G_LINEV|G_LINEH)
  111. #define G_MARKV 0x0008
  112. #define G_MARKH 0x0010
  113. #define G_MARK (G_MARKV|G_MARKH)
  114. #define G_NOLINEV 0x0020
  115. #define G_NOLINEH 0x0040
  116. #define G_NOLINE (G_NOLINEV|G_NOLINEH)
  117. /* flags used by the error checker */
  118. #define G_WARN 0x0080
  119. /* flags used by the solver etc. */
  120. #define G_SWEEP 0x1000
  121. #define G_FLAGSH (G_LINEH|G_MARKH|G_NOLINEH)
  122. #define G_FLAGSV (G_LINEV|G_MARKV|G_NOLINEV)
  123. typedef unsigned int grid_type; /* change me later if we invent > 16 bits of flags. */
  124. struct solver_state {
  125. DSF *dsf, *tmpdsf;
  126. int *comptspaces, *tmpcompspaces;
  127. int refcount;
  128. };
  129. /* state->gridi is an optimisation; it stores the pointer to the island
  130. * structs indexed by (x,y). It's not strictly necessary (we could use
  131. * find234 instead), but Purify showed that board generation (mostly the solver)
  132. * was spending 60% of its time in find234. */
  133. struct surrounds { /* cloned from lightup.c */
  134. struct { int x, y, dx, dy, off; } points[4];
  135. int npoints, nislands;
  136. };
  137. struct island {
  138. game_state *state;
  139. int x, y, count;
  140. struct surrounds adj;
  141. };
  142. struct game_state {
  143. int w, h, maxb;
  144. bool completed, solved;
  145. bool allowloops;
  146. grid_type *grid;
  147. struct island *islands;
  148. int n_islands, n_islands_alloc;
  149. game_params params; /* used by the aux solver. */
  150. #define N_WH_ARRAYS 5
  151. char *wha, *possv, *possh, *lines, *maxv, *maxh;
  152. struct island **gridi;
  153. struct solver_state *solver; /* refcounted */
  154. };
  155. #define GRIDSZ(s) ((s)->w * (s)->h * sizeof(grid_type))
  156. #define INGRID(s,x,y) ((x) >= 0 && (x) < (s)->w && (y) >= 0 && (y) < (s)->h)
  157. #define DINDEX(x,y) ((y)*state->w + (x))
  158. #define INDEX(s,g,x,y) ((s)->g[(y)*((s)->w) + (x)])
  159. #define IDX(s,g,i) ((s)->g[(i)])
  160. #define GRID(s,x,y) INDEX(s,grid,x,y)
  161. #define POSSIBLES(s,dx,x,y) ((dx) ? (INDEX(s,possh,x,y)) : (INDEX(s,possv,x,y)))
  162. #define MAXIMUM(s,dx,x,y) ((dx) ? (INDEX(s,maxh,x,y)) : (INDEX(s,maxv,x,y)))
  163. #define GRIDCOUNT(s,x,y,f) ((GRID(s,x,y) & (f)) ? (INDEX(s,lines,x,y)) : 0)
  164. #define WITHIN2(x,min,max) ((x) >= (min) && (x) <= (max))
  165. #define WITHIN(x,min,max) ((min) > (max) ? \
  166. WITHIN2(x,max,min) : WITHIN2(x,min,max))
  167. /* --- island struct and tree support functions --- */
  168. #define ISLAND_ORTH(is,j,f,df) \
  169. (is->f + (is->adj.points[(j)].off*is->adj.points[(j)].df))
  170. #define ISLAND_ORTHX(is,j) ISLAND_ORTH(is,j,x,dx)
  171. #define ISLAND_ORTHY(is,j) ISLAND_ORTH(is,j,y,dy)
  172. static void fixup_islands_for_realloc(game_state *state)
  173. {
  174. int i;
  175. for (i = 0; i < state->w*state->h; i++) state->gridi[i] = NULL;
  176. for (i = 0; i < state->n_islands; i++) {
  177. struct island *is = &state->islands[i];
  178. is->state = state;
  179. INDEX(state, gridi, is->x, is->y) = is;
  180. }
  181. }
  182. static bool game_can_format_as_text_now(const game_params *params)
  183. {
  184. return true;
  185. }
  186. static char *game_text_format(const game_state *state)
  187. {
  188. int x, y, len, nl;
  189. char *ret, *p;
  190. struct island *is;
  191. grid_type grid;
  192. len = (state->h) * (state->w+1) + 1;
  193. ret = snewn(len, char);
  194. p = ret;
  195. for (y = 0; y < state->h; y++) {
  196. for (x = 0; x < state->w; x++) {
  197. grid = GRID(state,x,y);
  198. nl = INDEX(state,lines,x,y);
  199. is = INDEX(state, gridi, x, y);
  200. if (is) {
  201. *p++ = '0' + is->count;
  202. } else if (grid & G_LINEV) {
  203. *p++ = (nl > 1) ? '"' : (nl == 1) ? '|' : '!'; /* gaah, want a double-bar. */
  204. } else if (grid & G_LINEH) {
  205. *p++ = (nl > 1) ? '=' : (nl == 1) ? '-' : '~';
  206. } else {
  207. *p++ = '.';
  208. }
  209. }
  210. *p++ = '\n';
  211. }
  212. *p++ = '\0';
  213. assert(p - ret == len);
  214. return ret;
  215. }
  216. static void debug_state(game_state *state)
  217. {
  218. char *textversion = game_text_format(state);
  219. debug(("%s", textversion));
  220. sfree(textversion);
  221. }
  222. /*static void debug_possibles(game_state *state)
  223. {
  224. int x, y;
  225. debug(("possh followed by possv\n"));
  226. for (y = 0; y < state->h; y++) {
  227. for (x = 0; x < state->w; x++) {
  228. debug(("%d", POSSIBLES(state, 1, x, y)));
  229. }
  230. debug((" "));
  231. for (x = 0; x < state->w; x++) {
  232. debug(("%d", POSSIBLES(state, 0, x, y)));
  233. }
  234. debug(("\n"));
  235. }
  236. debug(("\n"));
  237. for (y = 0; y < state->h; y++) {
  238. for (x = 0; x < state->w; x++) {
  239. debug(("%d", MAXIMUM(state, 1, x, y)));
  240. }
  241. debug((" "));
  242. for (x = 0; x < state->w; x++) {
  243. debug(("%d", MAXIMUM(state, 0, x, y)));
  244. }
  245. debug(("\n"));
  246. }
  247. debug(("\n"));
  248. }*/
  249. static void island_set_surrounds(struct island *is)
  250. {
  251. assert(INGRID(is->state,is->x,is->y));
  252. is->adj.npoints = is->adj.nislands = 0;
  253. #define ADDPOINT(cond,ddx,ddy) do {\
  254. if (cond) { \
  255. is->adj.points[is->adj.npoints].x = is->x+(ddx); \
  256. is->adj.points[is->adj.npoints].y = is->y+(ddy); \
  257. is->adj.points[is->adj.npoints].dx = (ddx); \
  258. is->adj.points[is->adj.npoints].dy = (ddy); \
  259. is->adj.points[is->adj.npoints].off = 0; \
  260. is->adj.npoints++; \
  261. } } while(0)
  262. ADDPOINT(is->x > 0, -1, 0);
  263. ADDPOINT(is->x < (is->state->w-1), +1, 0);
  264. ADDPOINT(is->y > 0, 0, -1);
  265. ADDPOINT(is->y < (is->state->h-1), 0, +1);
  266. }
  267. static void island_find_orthogonal(struct island *is)
  268. {
  269. /* fills in the rest of the 'surrounds' structure, assuming
  270. * all other islands are now in place. */
  271. int i, x, y, dx, dy, off;
  272. is->adj.nislands = 0;
  273. for (i = 0; i < is->adj.npoints; i++) {
  274. dx = is->adj.points[i].dx;
  275. dy = is->adj.points[i].dy;
  276. x = is->x + dx;
  277. y = is->y + dy;
  278. off = 1;
  279. is->adj.points[i].off = 0;
  280. while (INGRID(is->state, x, y)) {
  281. if (GRID(is->state, x, y) & G_ISLAND) {
  282. is->adj.points[i].off = off;
  283. is->adj.nislands++;
  284. /*debug(("island (%d,%d) has orth is. %d*(%d,%d) away at (%d,%d).\n",
  285. is->x, is->y, off, dx, dy,
  286. ISLAND_ORTHX(is,i), ISLAND_ORTHY(is,i)));*/
  287. goto foundisland;
  288. }
  289. off++; x += dx; y += dy;
  290. }
  291. foundisland:
  292. ;
  293. }
  294. }
  295. static bool island_hasbridge(struct island *is, int direction)
  296. {
  297. int x = is->adj.points[direction].x;
  298. int y = is->adj.points[direction].y;
  299. grid_type gline = is->adj.points[direction].dx ? G_LINEH : G_LINEV;
  300. if (GRID(is->state, x, y) & gline) return true;
  301. return false;
  302. }
  303. static struct island *island_find_connection(struct island *is, int adjpt)
  304. {
  305. struct island *is_r;
  306. assert(adjpt < is->adj.npoints);
  307. if (!is->adj.points[adjpt].off) return NULL;
  308. if (!island_hasbridge(is, adjpt)) return NULL;
  309. is_r = INDEX(is->state, gridi,
  310. ISLAND_ORTHX(is, adjpt), ISLAND_ORTHY(is, adjpt));
  311. assert(is_r);
  312. return is_r;
  313. }
  314. static struct island *island_add(game_state *state, int x, int y, int count)
  315. {
  316. struct island *is;
  317. bool realloced = false;
  318. assert(!(GRID(state,x,y) & G_ISLAND));
  319. GRID(state,x,y) |= G_ISLAND;
  320. state->n_islands++;
  321. if (state->n_islands > state->n_islands_alloc) {
  322. state->n_islands_alloc = state->n_islands * 2;
  323. state->islands =
  324. sresize(state->islands, state->n_islands_alloc, struct island);
  325. realloced = true;
  326. }
  327. is = &state->islands[state->n_islands-1];
  328. memset(is, 0, sizeof(struct island));
  329. is->state = state;
  330. is->x = x;
  331. is->y = y;
  332. is->count = count;
  333. island_set_surrounds(is);
  334. if (realloced)
  335. fixup_islands_for_realloc(state);
  336. else
  337. INDEX(state, gridi, x, y) = is;
  338. return is;
  339. }
  340. /* n = -1 means 'flip NOLINE flags [and set line to 0].' */
  341. static void island_join(struct island *i1, struct island *i2, int n, bool is_max)
  342. {
  343. game_state *state = i1->state;
  344. int s, e, x, y;
  345. assert(i1->state == i2->state);
  346. assert(n >= -1 && n <= i1->state->maxb);
  347. if (i1->x == i2->x) {
  348. x = i1->x;
  349. if (i1->y < i2->y) {
  350. s = i1->y+1; e = i2->y-1;
  351. } else {
  352. s = i2->y+1; e = i1->y-1;
  353. }
  354. for (y = s; y <= e; y++) {
  355. if (is_max) {
  356. INDEX(state,maxv,x,y) = n;
  357. } else {
  358. if (n < 0) {
  359. GRID(state,x,y) ^= G_NOLINEV;
  360. } else if (n == 0) {
  361. GRID(state,x,y) &= ~G_LINEV;
  362. } else {
  363. GRID(state,x,y) |= G_LINEV;
  364. INDEX(state,lines,x,y) = n;
  365. }
  366. }
  367. }
  368. } else if (i1->y == i2->y) {
  369. y = i1->y;
  370. if (i1->x < i2->x) {
  371. s = i1->x+1; e = i2->x-1;
  372. } else {
  373. s = i2->x+1; e = i1->x-1;
  374. }
  375. for (x = s; x <= e; x++) {
  376. if (is_max) {
  377. INDEX(state,maxh,x,y) = n;
  378. } else {
  379. if (n < 0) {
  380. GRID(state,x,y) ^= G_NOLINEH;
  381. } else if (n == 0) {
  382. GRID(state,x,y) &= ~G_LINEH;
  383. } else {
  384. GRID(state,x,y) |= G_LINEH;
  385. INDEX(state,lines,x,y) = n;
  386. }
  387. }
  388. }
  389. } else {
  390. assert(!"island_join: islands not orthogonal.");
  391. }
  392. }
  393. /* Counts the number of bridges currently attached to the island. */
  394. static int island_countbridges(struct island *is)
  395. {
  396. int i, c = 0;
  397. for (i = 0; i < is->adj.npoints; i++) {
  398. c += GRIDCOUNT(is->state,
  399. is->adj.points[i].x, is->adj.points[i].y,
  400. is->adj.points[i].dx ? G_LINEH : G_LINEV);
  401. }
  402. /*debug(("island count for (%d,%d) is %d.\n", is->x, is->y, c));*/
  403. return c;
  404. }
  405. static int island_adjspace(struct island *is, bool marks, int missing,
  406. int direction)
  407. {
  408. int x, y, poss, curr, dx;
  409. grid_type gline, mline;
  410. x = is->adj.points[direction].x;
  411. y = is->adj.points[direction].y;
  412. dx = is->adj.points[direction].dx;
  413. gline = dx ? G_LINEH : G_LINEV;
  414. if (marks) {
  415. mline = dx ? G_MARKH : G_MARKV;
  416. if (GRID(is->state,x,y) & mline) return 0;
  417. }
  418. poss = POSSIBLES(is->state, dx, x, y);
  419. poss = min(poss, missing);
  420. curr = GRIDCOUNT(is->state, x, y, gline);
  421. poss = min(poss, MAXIMUM(is->state, dx, x, y) - curr);
  422. return poss;
  423. }
  424. /* Counts the number of bridge spaces left around the island;
  425. * expects the possibles to be up-to-date. */
  426. static int island_countspaces(struct island *is, bool marks)
  427. {
  428. int i, c = 0, missing;
  429. missing = is->count - island_countbridges(is);
  430. if (missing < 0) return 0;
  431. for (i = 0; i < is->adj.npoints; i++) {
  432. c += island_adjspace(is, marks, missing, i);
  433. }
  434. return c;
  435. }
  436. /* Returns a bridge count rather than a boolean */
  437. static int island_isadj(struct island *is, int direction)
  438. {
  439. int x, y;
  440. grid_type gline, mline;
  441. x = is->adj.points[direction].x;
  442. y = is->adj.points[direction].y;
  443. mline = is->adj.points[direction].dx ? G_MARKH : G_MARKV;
  444. gline = is->adj.points[direction].dx ? G_LINEH : G_LINEV;
  445. if (GRID(is->state, x, y) & mline) {
  446. /* If we're marked (i.e. the thing to attach to is complete)
  447. * only count an adjacency if we're already attached. */
  448. return GRIDCOUNT(is->state, x, y, gline);
  449. } else {
  450. /* If we're unmarked, count possible adjacency iff it's
  451. * flagged as POSSIBLE. */
  452. return POSSIBLES(is->state, is->adj.points[direction].dx, x, y);
  453. }
  454. return 0;
  455. }
  456. /* Counts the no. of possible adjacent islands (including islands
  457. * we're already connected to). */
  458. static int island_countadj(struct island *is)
  459. {
  460. int i, nadj = 0;
  461. for (i = 0; i < is->adj.npoints; i++) {
  462. if (island_isadj(is, i)) nadj++;
  463. }
  464. return nadj;
  465. }
  466. static void island_togglemark(struct island *is)
  467. {
  468. int i, j, x, y, o;
  469. struct island *is_loop;
  470. /* mark the island... */
  471. GRID(is->state, is->x, is->y) ^= G_MARK;
  472. /* ...remove all marks on non-island squares... */
  473. for (x = 0; x < is->state->w; x++) {
  474. for (y = 0; y < is->state->h; y++) {
  475. if (!(GRID(is->state, x, y) & G_ISLAND))
  476. GRID(is->state, x, y) &= ~G_MARK;
  477. }
  478. }
  479. /* ...and add marks to squares around marked islands. */
  480. for (i = 0; i < is->state->n_islands; i++) {
  481. is_loop = &is->state->islands[i];
  482. if (!(GRID(is_loop->state, is_loop->x, is_loop->y) & G_MARK))
  483. continue;
  484. for (j = 0; j < is_loop->adj.npoints; j++) {
  485. /* if this direction takes us to another island, mark all
  486. * squares between the two islands. */
  487. if (!is_loop->adj.points[j].off) continue;
  488. assert(is_loop->adj.points[j].off > 1);
  489. for (o = 1; o < is_loop->adj.points[j].off; o++) {
  490. GRID(is_loop->state,
  491. is_loop->x + is_loop->adj.points[j].dx*o,
  492. is_loop->y + is_loop->adj.points[j].dy*o) |=
  493. is_loop->adj.points[j].dy ? G_MARKV : G_MARKH;
  494. }
  495. }
  496. }
  497. }
  498. static bool island_impossible(struct island *is, bool strict)
  499. {
  500. int curr = island_countbridges(is), nspc = is->count - curr, nsurrspc;
  501. int i, poss;
  502. struct island *is_orth;
  503. if (nspc < 0) {
  504. debug(("island at (%d,%d) impossible because full.\n", is->x, is->y));
  505. return true; /* too many bridges */
  506. } else if ((curr + island_countspaces(is, false)) < is->count) {
  507. debug(("island at (%d,%d) impossible because not enough spaces.\n", is->x, is->y));
  508. return true; /* impossible to create enough bridges */
  509. } else if (strict && curr < is->count) {
  510. debug(("island at (%d,%d) impossible because locked.\n", is->x, is->y));
  511. return true; /* not enough bridges and island is locked */
  512. }
  513. /* Count spaces in surrounding islands. */
  514. nsurrspc = 0;
  515. for (i = 0; i < is->adj.npoints; i++) {
  516. int ifree, dx = is->adj.points[i].dx;
  517. if (!is->adj.points[i].off) continue;
  518. poss = POSSIBLES(is->state, dx,
  519. is->adj.points[i].x, is->adj.points[i].y);
  520. if (poss == 0) continue;
  521. is_orth = INDEX(is->state, gridi,
  522. ISLAND_ORTHX(is,i), ISLAND_ORTHY(is,i));
  523. assert(is_orth);
  524. ifree = is_orth->count - island_countbridges(is_orth);
  525. if (ifree > 0) {
  526. /*
  527. * ifree is the number of bridges unfilled in the other
  528. * island, which is clearly an upper bound on the number
  529. * of extra bridges this island may run to it.
  530. *
  531. * Another upper bound is the number of bridges unfilled
  532. * on the specific line between here and there. We must
  533. * take the minimum of both.
  534. */
  535. int bmax = MAXIMUM(is->state, dx,
  536. is->adj.points[i].x, is->adj.points[i].y);
  537. int bcurr = GRIDCOUNT(is->state,
  538. is->adj.points[i].x, is->adj.points[i].y,
  539. dx ? G_LINEH : G_LINEV);
  540. assert(bcurr <= bmax);
  541. nsurrspc += min(ifree, bmax - bcurr);
  542. }
  543. }
  544. if (nsurrspc < nspc) {
  545. debug(("island at (%d,%d) impossible: surr. islands %d spc, need %d.\n",
  546. is->x, is->y, nsurrspc, nspc));
  547. return true; /* not enough spaces around surrounding islands to fill this one. */
  548. }
  549. return false;
  550. }
  551. /* --- Game parameter functions --- */
  552. #define DEFAULT_PRESET 0
  553. static const struct game_params bridges_presets[] = {
  554. { 7, 7, 2, 30, 10, 1, 0 },
  555. { 7, 7, 2, 30, 10, 1, 1 },
  556. { 7, 7, 2, 30, 10, 1, 2 },
  557. { 10, 10, 2, 30, 10, 1, 0 },
  558. { 10, 10, 2, 30, 10, 1, 1 },
  559. { 10, 10, 2, 30, 10, 1, 2 },
  560. { 15, 15, 2, 30, 10, 1, 0 },
  561. { 15, 15, 2, 30, 10, 1, 1 },
  562. { 15, 15, 2, 30, 10, 1, 2 },
  563. };
  564. static game_params *default_params(void)
  565. {
  566. game_params *ret = snew(game_params);
  567. *ret = bridges_presets[DEFAULT_PRESET];
  568. return ret;
  569. }
  570. static bool game_fetch_preset(int i, char **name, game_params **params)
  571. {
  572. game_params *ret;
  573. char buf[80];
  574. if (i < 0 || i >= lenof(bridges_presets))
  575. return false;
  576. ret = default_params();
  577. *ret = bridges_presets[i];
  578. *params = ret;
  579. sprintf(buf, "%dx%d %s", ret->w, ret->h,
  580. ret->difficulty == 0 ? "easy" :
  581. ret->difficulty == 1 ? "medium" : "hard");
  582. *name = dupstr(buf);
  583. return true;
  584. }
  585. static void free_params(game_params *params)
  586. {
  587. sfree(params);
  588. }
  589. static game_params *dup_params(const game_params *params)
  590. {
  591. game_params *ret = snew(game_params);
  592. *ret = *params; /* structure copy */
  593. return ret;
  594. }
  595. #define EATNUM(x) do { \
  596. (x) = atoi(string); \
  597. while (*string && isdigit((unsigned char)*string)) string++; \
  598. } while(0)
  599. static void decode_params(game_params *params, char const *string)
  600. {
  601. EATNUM(params->w);
  602. params->h = params->w;
  603. if (*string == 'x') {
  604. string++;
  605. EATNUM(params->h);
  606. }
  607. if (*string == 'i') {
  608. string++;
  609. EATNUM(params->islands);
  610. }
  611. if (*string == 'e') {
  612. string++;
  613. EATNUM(params->expansion);
  614. }
  615. if (*string == 'm') {
  616. string++;
  617. EATNUM(params->maxb);
  618. }
  619. params->allowloops = true;
  620. if (*string == 'L') {
  621. string++;
  622. params->allowloops = false;
  623. }
  624. if (*string == 'd') {
  625. string++;
  626. EATNUM(params->difficulty);
  627. }
  628. }
  629. static char *encode_params(const game_params *params, bool full)
  630. {
  631. char buf[80];
  632. if (full) {
  633. sprintf(buf, "%dx%di%de%dm%d%sd%d",
  634. params->w, params->h, params->islands, params->expansion,
  635. params->maxb, params->allowloops ? "" : "L",
  636. params->difficulty);
  637. } else {
  638. sprintf(buf, "%dx%dm%d%s", params->w, params->h,
  639. params->maxb, params->allowloops ? "" : "L");
  640. }
  641. return dupstr(buf);
  642. }
  643. static config_item *game_configure(const game_params *params)
  644. {
  645. config_item *ret;
  646. char buf[80];
  647. ret = snewn(8, config_item);
  648. ret[0].name = "Width";
  649. ret[0].type = C_STRING;
  650. sprintf(buf, "%d", params->w);
  651. ret[0].u.string.sval = dupstr(buf);
  652. ret[1].name = "Height";
  653. ret[1].type = C_STRING;
  654. sprintf(buf, "%d", params->h);
  655. ret[1].u.string.sval = dupstr(buf);
  656. ret[2].name = "Difficulty";
  657. ret[2].type = C_CHOICES;
  658. ret[2].u.choices.choicenames = ":Easy:Medium:Hard";
  659. ret[2].u.choices.selected = params->difficulty;
  660. ret[3].name = "Allow loops";
  661. ret[3].type = C_BOOLEAN;
  662. ret[3].u.boolean.bval = params->allowloops;
  663. ret[4].name = "Max. bridges per direction";
  664. ret[4].type = C_CHOICES;
  665. ret[4].u.choices.choicenames = ":1:2:3:4"; /* keep up-to-date with
  666. * MAX_BRIDGES */
  667. ret[4].u.choices.selected = params->maxb - 1;
  668. ret[5].name = "%age of island squares";
  669. ret[5].type = C_CHOICES;
  670. ret[5].u.choices.choicenames = ":5%:10%:15%:20%:25%:30%";
  671. ret[5].u.choices.selected = (params->islands / 5)-1;
  672. ret[6].name = "Expansion factor (%age)";
  673. ret[6].type = C_CHOICES;
  674. ret[6].u.choices.choicenames = ":0%:10%:20%:30%:40%:50%:60%:70%:80%:90%:100%";
  675. ret[6].u.choices.selected = params->expansion / 10;
  676. ret[7].name = NULL;
  677. ret[7].type = C_END;
  678. return ret;
  679. }
  680. static game_params *custom_params(const config_item *cfg)
  681. {
  682. game_params *ret = snew(game_params);
  683. ret->w = atoi(cfg[0].u.string.sval);
  684. ret->h = atoi(cfg[1].u.string.sval);
  685. ret->difficulty = cfg[2].u.choices.selected;
  686. ret->allowloops = cfg[3].u.boolean.bval;
  687. ret->maxb = cfg[4].u.choices.selected + 1;
  688. ret->islands = (cfg[5].u.choices.selected + 1) * 5;
  689. ret->expansion = cfg[6].u.choices.selected * 10;
  690. return ret;
  691. }
  692. static const char *validate_params(const game_params *params, bool full)
  693. {
  694. if (params->w < 3 || params->h < 3)
  695. return "Width and height must be at least 3";
  696. if (params->w > INT_MAX / params->h)
  697. return "Width times height must not be unreasonably large";
  698. if (params->maxb < 1 || params->maxb > MAX_BRIDGES)
  699. return "Too many bridges.";
  700. if (full) {
  701. if (params->islands <= 0 || params->islands > 30)
  702. return "%age of island squares must be between 1% and 30%";
  703. if (params->expansion < 0 || params->expansion > 100)
  704. return "Expansion factor must be between 0 and 100";
  705. }
  706. return NULL;
  707. }
  708. /* --- Game encoding and differences --- */
  709. static char *encode_game(game_state *state)
  710. {
  711. char *ret, *p;
  712. int wh = state->w*state->h, run, x, y;
  713. struct island *is;
  714. ret = snewn(wh + 1, char);
  715. p = ret;
  716. run = 0;
  717. for (y = 0; y < state->h; y++) {
  718. for (x = 0; x < state->w; x++) {
  719. is = INDEX(state, gridi, x, y);
  720. if (is) {
  721. if (run) {
  722. *p++ = ('a'-1) + run;
  723. run = 0;
  724. }
  725. if (is->count < 10)
  726. *p++ = '0' + is->count;
  727. else
  728. *p++ = 'A' + (is->count - 10);
  729. } else {
  730. if (run == 26) {
  731. *p++ = ('a'-1) + run;
  732. run = 0;
  733. }
  734. run++;
  735. }
  736. }
  737. }
  738. if (run) {
  739. *p++ = ('a'-1) + run;
  740. run = 0;
  741. }
  742. *p = '\0';
  743. assert(p - ret <= wh);
  744. return ret;
  745. }
  746. static char *game_state_diff(const game_state *src, const game_state *dest)
  747. {
  748. int movesize = 256, movelen = 0;
  749. char *move = snewn(movesize, char), buf[80];
  750. int i, d, x, y, len;
  751. grid_type gline, nline;
  752. struct island *is_s, *is_d, *is_orth;
  753. #define APPEND do { \
  754. if (movelen + len >= movesize) { \
  755. movesize = movelen + len + 256; \
  756. move = sresize(move, movesize, char); \
  757. } \
  758. strcpy(move + movelen, buf); \
  759. movelen += len; \
  760. } while(0)
  761. move[movelen++] = 'S';
  762. move[movelen] = '\0';
  763. assert(src->n_islands == dest->n_islands);
  764. for (i = 0; i < src->n_islands; i++) {
  765. is_s = &src->islands[i];
  766. is_d = &dest->islands[i];
  767. assert(is_s->x == is_d->x);
  768. assert(is_s->y == is_d->y);
  769. assert(is_s->adj.npoints == is_d->adj.npoints); /* more paranoia */
  770. for (d = 0; d < is_s->adj.npoints; d++) {
  771. if (is_s->adj.points[d].dx == -1 ||
  772. is_s->adj.points[d].dy == -1) continue;
  773. x = is_s->adj.points[d].x;
  774. y = is_s->adj.points[d].y;
  775. gline = is_s->adj.points[d].dx ? G_LINEH : G_LINEV;
  776. nline = is_s->adj.points[d].dx ? G_NOLINEH : G_NOLINEV;
  777. is_orth = INDEX(dest, gridi,
  778. ISLAND_ORTHX(is_d, d), ISLAND_ORTHY(is_d, d));
  779. if (GRIDCOUNT(src, x, y, gline) != GRIDCOUNT(dest, x, y, gline)) {
  780. assert(is_orth);
  781. len = sprintf(buf, ";L%d,%d,%d,%d,%d",
  782. is_s->x, is_s->y, is_orth->x, is_orth->y,
  783. GRIDCOUNT(dest, x, y, gline));
  784. APPEND;
  785. }
  786. if ((GRID(src,x,y) & nline) != (GRID(dest, x, y) & nline)) {
  787. assert(is_orth);
  788. len = sprintf(buf, ";N%d,%d,%d,%d",
  789. is_s->x, is_s->y, is_orth->x, is_orth->y);
  790. APPEND;
  791. }
  792. }
  793. if ((GRID(src, is_s->x, is_s->y) & G_MARK) !=
  794. (GRID(dest, is_d->x, is_d->y) & G_MARK)) {
  795. len = sprintf(buf, ";M%d,%d", is_s->x, is_s->y);
  796. APPEND;
  797. }
  798. }
  799. return move;
  800. }
  801. /* --- Game setup and solving utilities --- */
  802. /* This function is optimised; a Quantify showed that lots of grid-generation time
  803. * (>50%) was spent in here. Hence the IDX() stuff. */
  804. static void map_update_possibles(game_state *state)
  805. {
  806. int x, y, s, e, i, np, maxb, w = state->w, idx;
  807. bool bl;
  808. struct island *is_s = NULL, *is_f = NULL;
  809. /* Run down vertical stripes [un]setting possv... */
  810. for (x = 0; x < state->w; x++) {
  811. idx = x;
  812. s = e = -1;
  813. bl = false;
  814. maxb = state->params.maxb; /* placate optimiser */
  815. /* Unset possible flags until we find an island. */
  816. for (y = 0; y < state->h; y++) {
  817. is_s = IDX(state, gridi, idx);
  818. if (is_s) {
  819. maxb = is_s->count;
  820. break;
  821. }
  822. IDX(state, possv, idx) = 0;
  823. idx += w;
  824. }
  825. for (; y < state->h; y++) {
  826. maxb = min(maxb, IDX(state, maxv, idx));
  827. is_f = IDX(state, gridi, idx);
  828. if (is_f) {
  829. assert(is_s);
  830. np = min(maxb, is_f->count);
  831. if (s != -1) {
  832. for (i = s; i <= e; i++) {
  833. INDEX(state, possv, x, i) = bl ? 0 : np;
  834. }
  835. }
  836. s = y+1;
  837. bl = false;
  838. is_s = is_f;
  839. maxb = is_s->count;
  840. } else {
  841. e = y;
  842. if (IDX(state,grid,idx) & (G_LINEH|G_NOLINEV)) bl = true;
  843. }
  844. idx += w;
  845. }
  846. if (s != -1) {
  847. for (i = s; i <= e; i++)
  848. INDEX(state, possv, x, i) = 0;
  849. }
  850. }
  851. /* ...and now do horizontal stripes [un]setting possh. */
  852. /* can we lose this clone'n'hack? */
  853. for (y = 0; y < state->h; y++) {
  854. idx = y*w;
  855. s = e = -1;
  856. bl = false;
  857. maxb = state->params.maxb; /* placate optimiser */
  858. for (x = 0; x < state->w; x++) {
  859. is_s = IDX(state, gridi, idx);
  860. if (is_s) {
  861. maxb = is_s->count;
  862. break;
  863. }
  864. IDX(state, possh, idx) = 0;
  865. idx += 1;
  866. }
  867. for (; x < state->w; x++) {
  868. maxb = min(maxb, IDX(state, maxh, idx));
  869. is_f = IDX(state, gridi, idx);
  870. if (is_f) {
  871. assert(is_s);
  872. np = min(maxb, is_f->count);
  873. if (s != -1) {
  874. for (i = s; i <= e; i++) {
  875. INDEX(state, possh, i, y) = bl ? 0 : np;
  876. }
  877. }
  878. s = x+1;
  879. bl = false;
  880. is_s = is_f;
  881. maxb = is_s->count;
  882. } else {
  883. e = x;
  884. if (IDX(state,grid,idx) & (G_LINEV|G_NOLINEH)) bl = true;
  885. }
  886. idx += 1;
  887. }
  888. if (s != -1) {
  889. for (i = s; i <= e; i++)
  890. INDEX(state, possh, i, y) = 0;
  891. }
  892. }
  893. }
  894. static void map_count(game_state *state)
  895. {
  896. int i, n, ax, ay;
  897. grid_type flag, grid;
  898. struct island *is;
  899. for (i = 0; i < state->n_islands; i++) {
  900. is = &state->islands[i];
  901. is->count = 0;
  902. for (n = 0; n < is->adj.npoints; n++) {
  903. ax = is->adj.points[n].x;
  904. ay = is->adj.points[n].y;
  905. flag = (ax == is->x) ? G_LINEV : G_LINEH;
  906. grid = GRID(state,ax,ay);
  907. if (grid & flag) {
  908. is->count += INDEX(state,lines,ax,ay);
  909. }
  910. }
  911. }
  912. }
  913. static void map_find_orthogonal(game_state *state)
  914. {
  915. int i;
  916. for (i = 0; i < state->n_islands; i++) {
  917. island_find_orthogonal(&state->islands[i]);
  918. }
  919. }
  920. struct bridges_neighbour_ctx {
  921. game_state *state;
  922. int i, n, neighbours[4];
  923. };
  924. static int bridges_neighbour(int vertex, void *vctx)
  925. {
  926. struct bridges_neighbour_ctx *ctx = (struct bridges_neighbour_ctx *)vctx;
  927. if (vertex >= 0) {
  928. game_state *state = ctx->state;
  929. int w = state->w, x = vertex % w, y = vertex / w;
  930. grid_type grid = GRID(state, x, y), gline = grid & G_LINE;
  931. struct island *is;
  932. int x1, y1, x2, y2, i;
  933. ctx->i = ctx->n = 0;
  934. is = INDEX(state, gridi, x, y);
  935. if (is) {
  936. for (i = 0; i < is->adj.npoints; i++) {
  937. gline = is->adj.points[i].dx ? G_LINEH : G_LINEV;
  938. if (GRID(state, is->adj.points[i].x,
  939. is->adj.points[i].y) & gline) {
  940. ctx->neighbours[ctx->n++] =
  941. (is->adj.points[i].y * w + is->adj.points[i].x);
  942. }
  943. }
  944. } else if (gline) {
  945. if (gline & G_LINEV) {
  946. x1 = x2 = x;
  947. y1 = y-1; y2 = y+1;
  948. } else {
  949. x1 = x-1; x2 = x+1;
  950. y1 = y2 = y;
  951. }
  952. /* Non-island squares with edges in should never be
  953. * pointing off the edge of the grid. */
  954. assert(INGRID(state, x1, y1));
  955. assert(INGRID(state, x2, y2));
  956. if (GRID(state, x1, y1) & (gline | G_ISLAND))
  957. ctx->neighbours[ctx->n++] = y1 * w + x1;
  958. if (GRID(state, x2, y2) & (gline | G_ISLAND))
  959. ctx->neighbours[ctx->n++] = y2 * w + x2;
  960. }
  961. }
  962. if (ctx->i < ctx->n)
  963. return ctx->neighbours[ctx->i++];
  964. else
  965. return -1;
  966. }
  967. static bool map_hasloops(game_state *state, bool mark)
  968. {
  969. int x, y;
  970. struct findloopstate *fls;
  971. struct bridges_neighbour_ctx ctx;
  972. bool ret;
  973. fls = findloop_new_state(state->w * state->h);
  974. ctx.state = state;
  975. ret = findloop_run(fls, state->w * state->h, bridges_neighbour, &ctx);
  976. if (mark) {
  977. for (y = 0; y < state->h; y++) {
  978. for (x = 0; x < state->w; x++) {
  979. int u, v;
  980. u = y * state->w + x;
  981. for (v = bridges_neighbour(u, &ctx); v >= 0;
  982. v = bridges_neighbour(-1, &ctx))
  983. if (findloop_is_loop_edge(fls, u, v))
  984. GRID(state,x,y) |= G_WARN;
  985. }
  986. }
  987. }
  988. findloop_free_state(fls);
  989. return ret;
  990. }
  991. static void map_group(game_state *state)
  992. {
  993. int i, d1, d2;
  994. int x, y, x2, y2;
  995. DSF *dsf = state->solver->dsf;
  996. struct island *is, *is_join;
  997. /* Initialise dsf. */
  998. dsf_reinit(dsf);
  999. /* For each island, find connected islands right or down
  1000. * and merge the dsf for the island squares as well as the
  1001. * bridge squares. */
  1002. for (x = 0; x < state->w; x++) {
  1003. for (y = 0; y < state->h; y++) {
  1004. GRID(state,x,y) &= ~(G_SWEEP|G_WARN); /* for group_full. */
  1005. is = INDEX(state, gridi, x, y);
  1006. if (!is) continue;
  1007. d1 = DINDEX(x,y);
  1008. for (i = 0; i < is->adj.npoints; i++) {
  1009. /* only want right/down */
  1010. if (is->adj.points[i].dx == -1 ||
  1011. is->adj.points[i].dy == -1) continue;
  1012. is_join = island_find_connection(is, i);
  1013. if (!is_join) continue;
  1014. d2 = DINDEX(is_join->x, is_join->y);
  1015. if (dsf_equivalent(dsf, d1, d2)) {
  1016. ; /* we have a loop. See comment in map_hasloops. */
  1017. /* However, we still want to merge all squares joining
  1018. * this side-that-makes-a-loop. */
  1019. }
  1020. /* merge all squares between island 1 and island 2. */
  1021. for (x2 = x; x2 <= is_join->x; x2++) {
  1022. for (y2 = y; y2 <= is_join->y; y2++) {
  1023. d2 = DINDEX(x2,y2);
  1024. if (d1 != d2) dsf_merge(dsf,d1,d2);
  1025. }
  1026. }
  1027. }
  1028. }
  1029. }
  1030. }
  1031. static bool map_group_check(game_state *state, int canon, bool warn,
  1032. int *nislands_r)
  1033. {
  1034. DSF *dsf = state->solver->dsf;
  1035. int nislands = 0;
  1036. int x, y, i;
  1037. bool allfull = true;
  1038. struct island *is;
  1039. for (i = 0; i < state->n_islands; i++) {
  1040. is = &state->islands[i];
  1041. if (dsf_canonify(dsf, DINDEX(is->x,is->y)) != canon) continue;
  1042. GRID(state, is->x, is->y) |= G_SWEEP;
  1043. nislands++;
  1044. if (island_countbridges(is) != is->count)
  1045. allfull = false;
  1046. }
  1047. if (warn && allfull && nislands != state->n_islands) {
  1048. /* we're full and this island group isn't the whole set.
  1049. * Mark all squares with this dsf canon as ERR. */
  1050. for (x = 0; x < state->w; x++) {
  1051. for (y = 0; y < state->h; y++) {
  1052. if (dsf_canonify(dsf, DINDEX(x,y)) == canon) {
  1053. GRID(state,x,y) |= G_WARN;
  1054. }
  1055. }
  1056. }
  1057. }
  1058. if (nislands_r) *nislands_r = nislands;
  1059. return allfull;
  1060. }
  1061. static bool map_group_full(game_state *state, int *ngroups_r)
  1062. {
  1063. DSF *dsf = state->solver->dsf;
  1064. int ngroups = 0;
  1065. int i;
  1066. bool anyfull = false;
  1067. struct island *is;
  1068. /* NB this assumes map_group (or sth else) has cleared G_SWEEP. */
  1069. for (i = 0; i < state->n_islands; i++) {
  1070. is = &state->islands[i];
  1071. if (GRID(state,is->x,is->y) & G_SWEEP) continue;
  1072. ngroups++;
  1073. if (map_group_check(state, dsf_canonify(dsf, DINDEX(is->x,is->y)),
  1074. true, NULL))
  1075. anyfull = true;
  1076. }
  1077. *ngroups_r = ngroups;
  1078. return anyfull;
  1079. }
  1080. static bool map_check(game_state *state)
  1081. {
  1082. int ngroups;
  1083. /* Check for loops, if necessary. */
  1084. if (!state->allowloops) {
  1085. if (map_hasloops(state, true))
  1086. return false;
  1087. }
  1088. /* Place islands into island groups and check for early
  1089. * satisfied-groups. */
  1090. map_group(state); /* clears WARN and SWEEP */
  1091. if (map_group_full(state, &ngroups)) {
  1092. if (ngroups == 1) return true;
  1093. }
  1094. return false;
  1095. }
  1096. static void map_clear(game_state *state)
  1097. {
  1098. int x, y;
  1099. for (x = 0; x < state->w; x++) {
  1100. for (y = 0; y < state->h; y++) {
  1101. /* clear most flags; might want to be slightly more careful here. */
  1102. GRID(state,x,y) &= G_ISLAND;
  1103. }
  1104. }
  1105. }
  1106. static void solve_join(struct island *is, int direction, int n, bool is_max)
  1107. {
  1108. struct island *is_orth;
  1109. int d1, d2;
  1110. DSF *dsf = is->state->solver->dsf;
  1111. game_state *state = is->state; /* for DINDEX */
  1112. is_orth = INDEX(is->state, gridi,
  1113. ISLAND_ORTHX(is, direction),
  1114. ISLAND_ORTHY(is, direction));
  1115. assert(is_orth);
  1116. /*debug(("...joining (%d,%d) to (%d,%d) with %d bridge(s).\n",
  1117. is->x, is->y, is_orth->x, is_orth->y, n));*/
  1118. island_join(is, is_orth, n, is_max);
  1119. if (n > 0 && !is_max) {
  1120. d1 = DINDEX(is->x, is->y);
  1121. d2 = DINDEX(is_orth->x, is_orth->y);
  1122. if (!dsf_equivalent(dsf, d1, d2))
  1123. dsf_merge(dsf, d1, d2);
  1124. }
  1125. }
  1126. static int solve_fillone(struct island *is)
  1127. {
  1128. int i, nadded = 0;
  1129. debug(("solve_fillone for island (%d,%d).\n", is->x, is->y));
  1130. for (i = 0; i < is->adj.npoints; i++) {
  1131. if (island_isadj(is, i)) {
  1132. if (island_hasbridge(is, i)) {
  1133. /* already attached; do nothing. */;
  1134. } else {
  1135. solve_join(is, i, 1, false);
  1136. nadded++;
  1137. }
  1138. }
  1139. }
  1140. return nadded;
  1141. }
  1142. static int solve_fill(struct island *is)
  1143. {
  1144. /* for each unmarked adjacent, make sure we convert every possible bridge
  1145. * to a real one, and then work out the possibles afresh. */
  1146. int i, nnew, ncurr, nadded = 0, missing;
  1147. debug(("solve_fill for island (%d,%d).\n", is->x, is->y));
  1148. missing = is->count - island_countbridges(is);
  1149. if (missing < 0) return 0;
  1150. /* very like island_countspaces. */
  1151. for (i = 0; i < is->adj.npoints; i++) {
  1152. nnew = island_adjspace(is, true, missing, i);
  1153. if (nnew) {
  1154. ncurr = GRIDCOUNT(is->state,
  1155. is->adj.points[i].x, is->adj.points[i].y,
  1156. is->adj.points[i].dx ? G_LINEH : G_LINEV);
  1157. solve_join(is, i, nnew + ncurr, false);
  1158. nadded += nnew;
  1159. }
  1160. }
  1161. return nadded;
  1162. }
  1163. static bool solve_island_stage1(struct island *is, bool *didsth_r)
  1164. {
  1165. int bridges = island_countbridges(is);
  1166. int nspaces = island_countspaces(is, true);
  1167. int nadj = island_countadj(is);
  1168. bool didsth = false;
  1169. assert(didsth_r);
  1170. /*debug(("island at (%d,%d) filled %d/%d (%d spc) nadj %d\n",
  1171. is->x, is->y, bridges, is->count, nspaces, nadj));*/
  1172. if (bridges > is->count) {
  1173. /* We only ever add bridges when we're sure they fit, or that's
  1174. * the only place they can go. If we've added bridges such that
  1175. * another island has become wrong, the puzzle must not have had
  1176. * a solution. */
  1177. debug(("...island at (%d,%d) is overpopulated!\n", is->x, is->y));
  1178. return false;
  1179. } else if (bridges == is->count) {
  1180. /* This island is full. Make sure it's marked (and update
  1181. * possibles if we did). */
  1182. if (!(GRID(is->state, is->x, is->y) & G_MARK)) {
  1183. debug(("...marking island (%d,%d) as full.\n", is->x, is->y));
  1184. island_togglemark(is);
  1185. didsth = true;
  1186. }
  1187. } else if (GRID(is->state, is->x, is->y) & G_MARK) {
  1188. debug(("...island (%d,%d) is marked but unfinished!\n",
  1189. is->x, is->y));
  1190. return false; /* island has been marked unfinished; no solution from here. */
  1191. } else {
  1192. /* This is the interesting bit; we try and fill in more information
  1193. * about this island. */
  1194. if (is->count == bridges + nspaces) {
  1195. if (solve_fill(is) > 0) didsth = true;
  1196. } else if (is->count > ((nadj-1) * is->state->maxb)) {
  1197. /* must have at least one bridge in each possible direction. */
  1198. if (solve_fillone(is) > 0) didsth = true;
  1199. }
  1200. }
  1201. if (didsth) {
  1202. map_update_possibles(is->state);
  1203. *didsth_r = true;
  1204. }
  1205. return true;
  1206. }
  1207. /* returns true if a new line here would cause a loop. */
  1208. static bool solve_island_checkloop(struct island *is, int direction)
  1209. {
  1210. struct island *is_orth;
  1211. DSF *dsf = is->state->solver->dsf;
  1212. int d1, d2;
  1213. game_state *state = is->state;
  1214. if (is->state->allowloops)
  1215. return false; /* don't care anyway */
  1216. if (island_hasbridge(is, direction))
  1217. return false; /* already has a bridge */
  1218. if (island_isadj(is, direction) == 0)
  1219. return false; /* no adj island */
  1220. is_orth = INDEX(is->state, gridi,
  1221. ISLAND_ORTHX(is,direction),
  1222. ISLAND_ORTHY(is,direction));
  1223. if (!is_orth) return false;
  1224. d1 = DINDEX(is->x, is->y);
  1225. d2 = DINDEX(is_orth->x, is_orth->y);
  1226. if (dsf_equivalent(dsf, d1, d2)) {
  1227. /* two islands are connected already; don't join them. */
  1228. return true;
  1229. }
  1230. return false;
  1231. }
  1232. static bool solve_island_stage2(struct island *is, bool *didsth_r)
  1233. {
  1234. int navail = 0, nadj, i;
  1235. bool added = false, removed = false;
  1236. assert(didsth_r);
  1237. for (i = 0; i < is->adj.npoints; i++) {
  1238. if (solve_island_checkloop(is, i)) {
  1239. debug(("removing possible loop at (%d,%d) direction %d.\n",
  1240. is->x, is->y, i));
  1241. solve_join(is, i, -1, false);
  1242. map_update_possibles(is->state);
  1243. removed = true;
  1244. } else {
  1245. navail += island_isadj(is, i);
  1246. /*debug(("stage2: navail for (%d,%d) direction (%d,%d) is %d.\n",
  1247. is->x, is->y,
  1248. is->adj.points[i].dx, is->adj.points[i].dy,
  1249. island_isadj(is, i)));*/
  1250. }
  1251. }
  1252. /*debug(("island at (%d,%d) navail %d: checking...\n", is->x, is->y, navail));*/
  1253. for (i = 0; i < is->adj.npoints; i++) {
  1254. if (!island_hasbridge(is, i)) {
  1255. nadj = island_isadj(is, i);
  1256. if (nadj > 0 && (navail - nadj) < is->count) {
  1257. /* we couldn't now complete the island without at
  1258. * least one bridge here; put it in. */
  1259. /*debug(("nadj %d, navail %d, is->count %d.\n",
  1260. nadj, navail, is->count));*/
  1261. debug(("island at (%d,%d) direction (%d,%d) must have 1 bridge\n",
  1262. is->x, is->y,
  1263. is->adj.points[i].dx, is->adj.points[i].dy));
  1264. solve_join(is, i, 1, false);
  1265. added = true;
  1266. /*debug_state(is->state);
  1267. debug_possibles(is->state);*/
  1268. }
  1269. }
  1270. }
  1271. if (added) map_update_possibles(is->state);
  1272. if (added || removed) *didsth_r = true;
  1273. return true;
  1274. }
  1275. static bool solve_island_subgroup(struct island *is, int direction)
  1276. {
  1277. struct island *is_join;
  1278. int nislands;
  1279. DSF *dsf = is->state->solver->dsf;
  1280. game_state *state = is->state;
  1281. debug(("..checking subgroups.\n"));
  1282. /* if is isn't full, return 0. */
  1283. if (island_countbridges(is) < is->count) {
  1284. debug(("...orig island (%d,%d) not full.\n", is->x, is->y));
  1285. return false;
  1286. }
  1287. if (direction >= 0) {
  1288. is_join = INDEX(state, gridi,
  1289. ISLAND_ORTHX(is, direction),
  1290. ISLAND_ORTHY(is, direction));
  1291. assert(is_join);
  1292. /* if is_join isn't full, return 0. */
  1293. if (island_countbridges(is_join) < is_join->count) {
  1294. debug(("...dest island (%d,%d) not full.\n",
  1295. is_join->x, is_join->y));
  1296. return false;
  1297. }
  1298. }
  1299. /* Check group membership for is->dsf; if it's full return 1. */
  1300. if (map_group_check(state, dsf_canonify(dsf, DINDEX(is->x,is->y)),
  1301. false, &nislands)) {
  1302. if (nislands < state->n_islands) {
  1303. /* we have a full subgroup that isn't the whole set.
  1304. * This isn't allowed. */
  1305. debug(("island at (%d,%d) makes full subgroup, disallowing.\n",
  1306. is->x, is->y));
  1307. return true;
  1308. } else {
  1309. debug(("...has finished puzzle.\n"));
  1310. }
  1311. }
  1312. return false;
  1313. }
  1314. static bool solve_island_impossible(game_state *state)
  1315. {
  1316. struct island *is;
  1317. int i;
  1318. /* If any islands are impossible, return 1. */
  1319. for (i = 0; i < state->n_islands; i++) {
  1320. is = &state->islands[i];
  1321. if (island_impossible(is, false)) {
  1322. debug(("island at (%d,%d) has become impossible, disallowing.\n",
  1323. is->x, is->y));
  1324. return true;
  1325. }
  1326. }
  1327. return false;
  1328. }
  1329. /* Bear in mind that this function is really rather inefficient. */
  1330. static bool solve_island_stage3(struct island *is, bool *didsth_r)
  1331. {
  1332. int i, n, x, y, missing, spc, curr, maxb;
  1333. bool didsth = false;
  1334. struct solver_state *ss = is->state->solver;
  1335. assert(didsth_r);
  1336. missing = is->count - island_countbridges(is);
  1337. if (missing <= 0) return true;
  1338. for (i = 0; i < is->adj.npoints; i++) {
  1339. x = is->adj.points[i].x;
  1340. y = is->adj.points[i].y;
  1341. spc = island_adjspace(is, true, missing, i);
  1342. if (spc == 0) continue;
  1343. curr = GRIDCOUNT(is->state, x, y,
  1344. is->adj.points[i].dx ? G_LINEH : G_LINEV);
  1345. debug(("island at (%d,%d) s3, trying %d - %d bridges.\n",
  1346. is->x, is->y, curr+1, curr+spc));
  1347. /* Now we know that this island could have more bridges,
  1348. * to bring the total from curr+1 to curr+spc. */
  1349. maxb = -1;
  1350. /* We have to squirrel the dsf away and restore it afterwards;
  1351. * it is additive only, and can't be removed from. */
  1352. dsf_copy(ss->tmpdsf, ss->dsf);
  1353. for (n = curr+1; n <= curr+spc; n++) {
  1354. solve_join(is, i, n, false);
  1355. map_update_possibles(is->state);
  1356. if (solve_island_subgroup(is, i) ||
  1357. solve_island_impossible(is->state)) {
  1358. maxb = n-1;
  1359. debug(("island at (%d,%d) d(%d,%d) new max of %d bridges:\n",
  1360. is->x, is->y,
  1361. is->adj.points[i].dx, is->adj.points[i].dy,
  1362. maxb));
  1363. break;
  1364. }
  1365. }
  1366. solve_join(is, i, curr, false); /* put back to before. */
  1367. dsf_copy(ss->dsf, ss->tmpdsf);
  1368. if (maxb != -1) {
  1369. /*debug_state(is->state);*/
  1370. if (maxb == 0) {
  1371. debug(("...adding NOLINE.\n"));
  1372. solve_join(is, i, -1, false); /* we can't have any bridges here. */
  1373. } else {
  1374. debug(("...setting maximum\n"));
  1375. solve_join(is, i, maxb, true);
  1376. }
  1377. didsth = true;
  1378. }
  1379. map_update_possibles(is->state);
  1380. }
  1381. for (i = 0; i < is->adj.npoints; i++) {
  1382. /*
  1383. * Now check to see if any currently empty direction must have
  1384. * at least one bridge in order to avoid forming an isolated
  1385. * subgraph. This differs from the check above in that it
  1386. * considers multiple target islands. For example:
  1387. *
  1388. * 2 2 4
  1389. * 1 3 2
  1390. * 3
  1391. * 4
  1392. *
  1393. * The example on the left can be handled by the above loop:
  1394. * it will observe that connecting the central 2 twice to the
  1395. * left would form an isolated subgraph, and hence it will
  1396. * restrict that 2 to at most one bridge in that direction.
  1397. * But the example on the right won't be handled by that loop,
  1398. * because the deduction requires us to imagine connecting the
  1399. * 3 to _both_ the 1 and 2 at once to form an isolated
  1400. * subgraph.
  1401. *
  1402. * This pass is necessary _as well_ as the above one, because
  1403. * neither can do the other's job. In the left one,
  1404. * restricting the direction which _would_ cause trouble can
  1405. * be done even if it's not yet clear which of the remaining
  1406. * directions has to have a compensatory bridge; whereas the
  1407. * pass below that can handle the right-hand example does need
  1408. * to know what direction to point the necessary bridge in.
  1409. *
  1410. * Neither pass can handle the most general case, in which we
  1411. * observe that an arbitrary subset of an island's neighbours
  1412. * would form an isolated subgraph with it if it connected
  1413. * maximally to them, and hence that at least one bridge must
  1414. * point to some neighbour outside that subset but we don't
  1415. * know which neighbour. To handle that, we'd have to have a
  1416. * richer data format for the solver, which could cope with
  1417. * recording the idea that at least one of two edges must have
  1418. * a bridge.
  1419. */
  1420. bool got = false;
  1421. int before[4];
  1422. int j;
  1423. spc = island_adjspace(is, true, missing, i);
  1424. if (spc == 0) continue;
  1425. for (j = 0; j < is->adj.npoints; j++)
  1426. before[j] = GRIDCOUNT(is->state,
  1427. is->adj.points[j].x,
  1428. is->adj.points[j].y,
  1429. is->adj.points[j].dx ? G_LINEH : G_LINEV);
  1430. if (before[i] != 0) continue; /* this idea is pointless otherwise */
  1431. dsf_copy(ss->tmpdsf, ss->dsf);
  1432. for (j = 0; j < is->adj.npoints; j++) {
  1433. spc = island_adjspace(is, true, missing, j);
  1434. if (spc == 0) continue;
  1435. if (j == i) continue;
  1436. solve_join(is, j, before[j] + spc, false);
  1437. }
  1438. map_update_possibles(is->state);
  1439. if (solve_island_subgroup(is, -1))
  1440. got = true;
  1441. for (j = 0; j < is->adj.npoints; j++)
  1442. solve_join(is, j, before[j], false);
  1443. dsf_copy(ss->dsf, ss->tmpdsf);
  1444. if (got) {
  1445. debug(("island at (%d,%d) must connect in direction (%d,%d) to"
  1446. " avoid full subgroup.\n",
  1447. is->x, is->y, is->adj.points[i].dx, is->adj.points[i].dy));
  1448. solve_join(is, i, 1, false);
  1449. didsth = true;
  1450. }
  1451. map_update_possibles(is->state);
  1452. }
  1453. if (didsth) *didsth_r = didsth;
  1454. return true;
  1455. }
  1456. #define CONTINUE_IF_FULL do { \
  1457. if (GRID(state, is->x, is->y) & G_MARK) { \
  1458. /* island full, don't try fixing it */ \
  1459. continue; \
  1460. } } while(0)
  1461. static int solve_sub(game_state *state, int difficulty, int depth)
  1462. {
  1463. struct island *is;
  1464. int i;
  1465. while (1) {
  1466. bool didsth = false;
  1467. /* First island iteration: things we can work out by looking at
  1468. * properties of the island as a whole. */
  1469. for (i = 0; i < state->n_islands; i++) {
  1470. is = &state->islands[i];
  1471. if (!solve_island_stage1(is, &didsth)) return 0;
  1472. }
  1473. if (didsth) continue;
  1474. else if (difficulty < 1) break;
  1475. /* Second island iteration: thing we can work out by looking at
  1476. * properties of individual island connections. */
  1477. for (i = 0; i < state->n_islands; i++) {
  1478. is = &state->islands[i];
  1479. CONTINUE_IF_FULL;
  1480. if (!solve_island_stage2(is, &didsth)) return 0;
  1481. }
  1482. if (didsth) continue;
  1483. else if (difficulty < 2) break;
  1484. /* Third island iteration: things we can only work out by looking
  1485. * at groups of islands. */
  1486. for (i = 0; i < state->n_islands; i++) {
  1487. is = &state->islands[i];
  1488. if (!solve_island_stage3(is, &didsth)) return 0;
  1489. }
  1490. if (didsth) continue;
  1491. else if (difficulty < 3) break;
  1492. /* If we can be bothered, write a recursive solver to finish here. */
  1493. break;
  1494. }
  1495. if (map_check(state)) return 1; /* solved it */
  1496. return 0;
  1497. }
  1498. static void solve_for_hint(game_state *state)
  1499. {
  1500. map_group(state);
  1501. solve_sub(state, 10, 0);
  1502. }
  1503. static int solve_from_scratch(game_state *state, int difficulty)
  1504. {
  1505. map_clear(state);
  1506. map_group(state);
  1507. map_update_possibles(state);
  1508. return solve_sub(state, difficulty, 0);
  1509. }
  1510. /* --- New game functions --- */
  1511. static game_state *new_state(const game_params *params)
  1512. {
  1513. game_state *ret = snew(game_state);
  1514. int wh = params->w * params->h, i;
  1515. ret->w = params->w;
  1516. ret->h = params->h;
  1517. ret->allowloops = params->allowloops;
  1518. ret->maxb = params->maxb;
  1519. ret->params = *params;
  1520. ret->grid = snewn(wh, grid_type);
  1521. memset(ret->grid, 0, GRIDSZ(ret));
  1522. ret->wha = snewn(wh*N_WH_ARRAYS, char);
  1523. memset(ret->wha, 0, wh*N_WH_ARRAYS*sizeof(char));
  1524. ret->possv = ret->wha;
  1525. ret->possh = ret->wha + wh;
  1526. ret->lines = ret->wha + wh*2;
  1527. ret->maxv = ret->wha + wh*3;
  1528. ret->maxh = ret->wha + wh*4;
  1529. memset(ret->maxv, ret->maxb, wh*sizeof(char));
  1530. memset(ret->maxh, ret->maxb, wh*sizeof(char));
  1531. ret->islands = NULL;
  1532. ret->n_islands = 0;
  1533. ret->n_islands_alloc = 0;
  1534. ret->gridi = snewn(wh, struct island *);
  1535. for (i = 0; i < wh; i++) ret->gridi[i] = NULL;
  1536. ret->solved = false;
  1537. ret->completed = false;
  1538. ret->solver = snew(struct solver_state);
  1539. ret->solver->dsf = dsf_new(wh);
  1540. ret->solver->tmpdsf = dsf_new(wh);
  1541. ret->solver->refcount = 1;
  1542. return ret;
  1543. }
  1544. static game_state *dup_game(const game_state *state)
  1545. {
  1546. game_state *ret = snew(game_state);
  1547. int wh = state->w*state->h;
  1548. ret->w = state->w;
  1549. ret->h = state->h;
  1550. ret->allowloops = state->allowloops;
  1551. ret->maxb = state->maxb;
  1552. ret->params = state->params;
  1553. ret->grid = snewn(wh, grid_type);
  1554. memcpy(ret->grid, state->grid, GRIDSZ(ret));
  1555. ret->wha = snewn(wh*N_WH_ARRAYS, char);
  1556. memcpy(ret->wha, state->wha, wh*N_WH_ARRAYS*sizeof(char));
  1557. ret->possv = ret->wha;
  1558. ret->possh = ret->wha + wh;
  1559. ret->lines = ret->wha + wh*2;
  1560. ret->maxv = ret->wha + wh*3;
  1561. ret->maxh = ret->wha + wh*4;
  1562. ret->islands = snewn(state->n_islands, struct island);
  1563. memcpy(ret->islands, state->islands, state->n_islands * sizeof(struct island));
  1564. ret->n_islands = ret->n_islands_alloc = state->n_islands;
  1565. ret->gridi = snewn(wh, struct island *);
  1566. fixup_islands_for_realloc(ret);
  1567. ret->solved = state->solved;
  1568. ret->completed = state->completed;
  1569. ret->solver = state->solver;
  1570. ret->solver->refcount++;
  1571. return ret;
  1572. }
  1573. static void free_game(game_state *state)
  1574. {
  1575. if (--state->solver->refcount <= 0) {
  1576. dsf_free(state->solver->dsf);
  1577. dsf_free(state->solver->tmpdsf);
  1578. sfree(state->solver);
  1579. }
  1580. sfree(state->islands);
  1581. sfree(state->gridi);
  1582. sfree(state->wha);
  1583. sfree(state->grid);
  1584. sfree(state);
  1585. }
  1586. #define MAX_NEWISLAND_TRIES 50
  1587. #define MIN_SENSIBLE_ISLANDS 3
  1588. #define ORDER(a,b) do { if (a < b) { int tmp=a; int a=b; int b=tmp; } } while(0)
  1589. static char *new_game_desc(const game_params *params, random_state *rs,
  1590. char **aux, bool interactive)
  1591. {
  1592. game_state *tobuild = NULL;
  1593. int i, j, wh = params->w * params->h, x, y, dx, dy;
  1594. int minx, miny, maxx, maxy, joinx, joiny, newx, newy, diffx, diffy;
  1595. int ni_req = max((params->islands * wh) / 100, MIN_SENSIBLE_ISLANDS), ni_curr, ni_bad;
  1596. struct island *is, *is2;
  1597. char *ret;
  1598. unsigned int echeck;
  1599. /* pick a first island position randomly. */
  1600. generate:
  1601. if (tobuild) free_game(tobuild);
  1602. tobuild = new_state(params);
  1603. x = random_upto(rs, params->w);
  1604. y = random_upto(rs, params->h);
  1605. island_add(tobuild, x, y, 0);
  1606. ni_curr = 1;
  1607. ni_bad = 0;
  1608. debug(("Created initial island at (%d,%d).\n", x, y));
  1609. while (ni_curr < ni_req) {
  1610. /* Pick a random island to try and extend from. */
  1611. i = random_upto(rs, tobuild->n_islands);
  1612. is = &tobuild->islands[i];
  1613. /* Pick a random direction to extend in. */
  1614. j = random_upto(rs, is->adj.npoints);
  1615. dx = is->adj.points[j].x - is->x;
  1616. dy = is->adj.points[j].y - is->y;
  1617. /* Find out limits of where we could put a new island. */
  1618. joinx = joiny = -1;
  1619. minx = is->x + 2*dx; miny = is->y + 2*dy; /* closest is 2 units away. */
  1620. x = is->x+dx; y = is->y+dy;
  1621. if (GRID(tobuild,x,y) & (G_LINEV|G_LINEH)) {
  1622. /* already a line next to the island, continue. */
  1623. goto bad;
  1624. }
  1625. while (1) {
  1626. if (x < 0 || x >= params->w || y < 0 || y >= params->h) {
  1627. /* got past the edge; put a possible at the island
  1628. * and exit. */
  1629. maxx = x-dx; maxy = y-dy;
  1630. goto foundmax;
  1631. }
  1632. if (GRID(tobuild,x,y) & G_ISLAND) {
  1633. /* could join up to an existing island... */
  1634. joinx = x; joiny = y;
  1635. /* ... or make a new one 2 spaces away. */
  1636. maxx = x - 2*dx; maxy = y - 2*dy;
  1637. goto foundmax;
  1638. } else if (GRID(tobuild,x,y) & (G_LINEV|G_LINEH)) {
  1639. /* could make a new one 1 space away from the line. */
  1640. maxx = x - dx; maxy = y - dy;
  1641. goto foundmax;
  1642. }
  1643. x += dx; y += dy;
  1644. }
  1645. foundmax:
  1646. debug(("Island at (%d,%d) with d(%d,%d) has new positions "
  1647. "(%d,%d) -> (%d,%d), join (%d,%d).\n",
  1648. is->x, is->y, dx, dy, minx, miny, maxx, maxy, joinx, joiny));
  1649. /* Now we know where we could either put a new island
  1650. * (between min and max), or (if loops are allowed) could join on
  1651. * to an existing island (at join). */
  1652. if (params->allowloops && joinx != -1 && joiny != -1) {
  1653. if (random_upto(rs, 100) < (unsigned long)params->expansion) {
  1654. is2 = INDEX(tobuild, gridi, joinx, joiny);
  1655. debug(("Joining island at (%d,%d) to (%d,%d).\n",
  1656. is->x, is->y, is2->x, is2->y));
  1657. goto join;
  1658. }
  1659. }
  1660. diffx = (maxx - minx) * dx;
  1661. diffy = (maxy - miny) * dy;
  1662. if (diffx < 0 || diffy < 0) goto bad;
  1663. if (random_upto(rs,100) < (unsigned long)params->expansion) {
  1664. newx = maxx; newy = maxy;
  1665. debug(("Creating new island at (%d,%d) (expanded).\n", newx, newy));
  1666. } else {
  1667. newx = minx + random_upto(rs,diffx+1)*dx;
  1668. newy = miny + random_upto(rs,diffy+1)*dy;
  1669. debug(("Creating new island at (%d,%d).\n", newx, newy));
  1670. }
  1671. /* check we're not next to island in the other orthogonal direction. */
  1672. if ((INGRID(tobuild,newx+dy,newy+dx) && (GRID(tobuild,newx+dy,newy+dx) & G_ISLAND)) ||
  1673. (INGRID(tobuild,newx-dy,newy-dx) && (GRID(tobuild,newx-dy,newy-dx) & G_ISLAND))) {
  1674. debug(("New location is adjacent to island, skipping.\n"));
  1675. goto bad;
  1676. }
  1677. is2 = island_add(tobuild, newx, newy, 0);
  1678. /* Must get is again at this point; the array might have
  1679. * been realloced by island_add... */
  1680. is = &tobuild->islands[i]; /* ...but order will not change. */
  1681. ni_curr++; ni_bad = 0;
  1682. join:
  1683. island_join(is, is2, random_upto(rs, tobuild->maxb)+1, false);
  1684. debug_state(tobuild);
  1685. continue;
  1686. bad:
  1687. ni_bad++;
  1688. if (ni_bad > MAX_NEWISLAND_TRIES) {
  1689. debug(("Unable to create any new islands after %d tries; "
  1690. "created %d [%d%%] (instead of %d [%d%%] requested).\n",
  1691. MAX_NEWISLAND_TRIES,
  1692. ni_curr, ni_curr * 100 / wh,
  1693. ni_req, ni_req * 100 / wh));
  1694. goto generated;
  1695. }
  1696. }
  1697. generated:
  1698. if (ni_curr == 1) {
  1699. debug(("Only generated one island (!), retrying.\n"));
  1700. goto generate;
  1701. }
  1702. /* Check we have at least one island on each extremity of the grid. */
  1703. echeck = 0;
  1704. for (x = 0; x < params->w; x++) {
  1705. if (INDEX(tobuild, gridi, x, 0)) echeck |= 1;
  1706. if (INDEX(tobuild, gridi, x, params->h-1)) echeck |= 2;
  1707. }
  1708. for (y = 0; y < params->h; y++) {
  1709. if (INDEX(tobuild, gridi, 0, y)) echeck |= 4;
  1710. if (INDEX(tobuild, gridi, params->w-1, y)) echeck |= 8;
  1711. }
  1712. if (echeck != 15) {
  1713. debug(("Generated grid doesn't fill to sides, retrying.\n"));
  1714. goto generate;
  1715. }
  1716. map_count(tobuild);
  1717. map_find_orthogonal(tobuild);
  1718. if (params->difficulty > 0) {
  1719. if ((ni_curr > MIN_SENSIBLE_ISLANDS) &&
  1720. (solve_from_scratch(tobuild, params->difficulty-1) > 0)) {
  1721. debug(("Grid is solvable at difficulty %d (too easy); retrying.\n",
  1722. params->difficulty-1));
  1723. goto generate;
  1724. }
  1725. }
  1726. if (solve_from_scratch(tobuild, params->difficulty) == 0) {
  1727. debug(("Grid not solvable at difficulty %d, (too hard); retrying.\n",
  1728. params->difficulty));
  1729. goto generate;
  1730. }
  1731. /* ... tobuild is now solved. We rely on this making the diff for aux. */
  1732. debug_state(tobuild);
  1733. ret = encode_game(tobuild);
  1734. {
  1735. game_state *clean = dup_game(tobuild);
  1736. map_clear(clean);
  1737. map_update_possibles(clean);
  1738. *aux = game_state_diff(clean, tobuild);
  1739. free_game(clean);
  1740. }
  1741. free_game(tobuild);
  1742. return ret;
  1743. }
  1744. static const char *validate_desc(const game_params *params, const char *desc)
  1745. {
  1746. int i, j, wh = params->w * params->h, nislands = 0;
  1747. bool *last_row = snewn(params->w, bool);
  1748. memset(last_row, 0, params->w * sizeof(bool));
  1749. for (i = 0; i < wh; i++) {
  1750. if ((*desc >= '1' && *desc <= '9') || (*desc >= 'A' && *desc <= 'G')) {
  1751. nislands++;
  1752. /* Look for other islands to the left and above. */
  1753. if ((i % params->w > 0 && last_row[i % params->w - 1]) ||
  1754. last_row[i % params->w]) {
  1755. sfree(last_row);
  1756. return "Game description contains joined islands";
  1757. }
  1758. last_row[i % params->w] = true;
  1759. } else if (*desc >= 'a' && *desc <= 'z') {
  1760. for (j = 0; j < *desc - 'a' + 1; j++)
  1761. last_row[(i + j) % params->w] = false;
  1762. i += *desc - 'a'; /* plus the i++ */
  1763. } else if (!*desc) {
  1764. sfree(last_row);
  1765. return "Game description shorter than expected";
  1766. } else {
  1767. sfree(last_row);
  1768. return "Game description contains unexpected character";
  1769. }
  1770. desc++;
  1771. }
  1772. sfree(last_row);
  1773. if (*desc || i > wh)
  1774. return "Game description longer than expected";
  1775. if (nislands < 2)
  1776. return "Game description has too few islands";
  1777. return NULL;
  1778. }
  1779. static game_state *new_game_sub(const game_params *params, const char *desc)
  1780. {
  1781. game_state *state = new_state(params);
  1782. int x, y, run = 0;
  1783. debug(("new_game[_sub]: desc = '%s'.\n", desc));
  1784. for (y = 0; y < params->h; y++) {
  1785. for (x = 0; x < params->w; x++) {
  1786. char c = '\0';
  1787. if (run == 0) {
  1788. c = *desc++;
  1789. assert(c != 'S');
  1790. if (c >= 'a' && c <= 'z')
  1791. run = c - 'a' + 1;
  1792. }
  1793. if (run > 0) {
  1794. c = 'S';
  1795. run--;
  1796. }
  1797. switch (c) {
  1798. case '1': case '2': case '3': case '4':
  1799. case '5': case '6': case '7': case '8': case '9':
  1800. island_add(state, x, y, (c - '0'));
  1801. break;
  1802. case 'A': case 'B': case 'C': case 'D':
  1803. case 'E': case 'F': case 'G':
  1804. island_add(state, x, y, (c - 'A') + 10);
  1805. break;
  1806. case 'S':
  1807. /* empty square */
  1808. break;
  1809. default:
  1810. assert(!"Malformed desc.");
  1811. break;
  1812. }
  1813. }
  1814. }
  1815. if (*desc) assert(!"Over-long desc.");
  1816. map_find_orthogonal(state);
  1817. map_update_possibles(state);
  1818. return state;
  1819. }
  1820. static game_state *new_game(midend *me, const game_params *params,
  1821. const char *desc)
  1822. {
  1823. return new_game_sub(params, desc);
  1824. }
  1825. struct game_ui {
  1826. int dragx_src, dragy_src; /* source; -1 means no drag */
  1827. int dragx_dst, dragy_dst; /* src's closest orth island. */
  1828. grid_type todraw;
  1829. bool dragging, drag_is_noline;
  1830. int nlines;
  1831. int cur_x, cur_y; /* cursor position */
  1832. bool cur_visible;
  1833. bool show_hints;
  1834. };
  1835. static char *ui_cancel_drag(game_ui *ui)
  1836. {
  1837. ui->dragx_src = ui->dragy_src = -1;
  1838. ui->dragx_dst = ui->dragy_dst = -1;
  1839. ui->dragging = false;
  1840. return MOVE_UI_UPDATE;
  1841. }
  1842. static game_ui *new_ui(const game_state *state)
  1843. {
  1844. game_ui *ui = snew(game_ui);
  1845. ui_cancel_drag(ui);
  1846. if (state != NULL) {
  1847. ui->cur_x = state->islands[0].x;
  1848. ui->cur_y = state->islands[0].y;
  1849. }
  1850. ui->cur_visible = getenv_bool("PUZZLES_SHOW_CURSOR", false);
  1851. ui->show_hints = false;
  1852. return ui;
  1853. }
  1854. static config_item *get_prefs(game_ui *ui)
  1855. {
  1856. config_item *ret;
  1857. ret = snewn(2, config_item);
  1858. ret[0].name = "Show possible bridge locations";
  1859. ret[0].kw = "show-hints";
  1860. ret[0].type = C_BOOLEAN;
  1861. ret[0].u.boolean.bval = ui->show_hints;
  1862. ret[1].name = NULL;
  1863. ret[1].type = C_END;
  1864. return ret;
  1865. }
  1866. static void set_prefs(game_ui *ui, const config_item *cfg)
  1867. {
  1868. ui->show_hints = cfg[0].u.boolean.bval;
  1869. }
  1870. static void free_ui(game_ui *ui)
  1871. {
  1872. sfree(ui);
  1873. }
  1874. static void game_changed_state(game_ui *ui, const game_state *oldstate,
  1875. const game_state *newstate)
  1876. {
  1877. }
  1878. static const char *current_key_label(const game_ui *ui,
  1879. const game_state *state, int button)
  1880. {
  1881. if (IS_CURSOR_SELECT(button)) {
  1882. if (!ui->cur_visible)
  1883. return ""; /* Actually shows cursor. */
  1884. if (ui->dragging || button == CURSOR_SELECT2)
  1885. return "Finished";
  1886. if (GRID(state, ui->cur_x, ui->cur_y) & G_ISLAND)
  1887. return "Select";
  1888. }
  1889. return "";
  1890. }
  1891. struct game_drawstate {
  1892. int tilesize;
  1893. int w, h;
  1894. unsigned long *grid, *newgrid;
  1895. int *lv, *lh;
  1896. bool started, dragging;
  1897. };
  1898. static void game_get_cursor_location(const game_ui *ui,
  1899. const game_drawstate *ds,
  1900. const game_state *state,
  1901. const game_params *params,
  1902. int *x, int *y, int *w, int *h)
  1903. {
  1904. if(ui->cur_visible) {
  1905. *x = COORD(ui->cur_x);
  1906. *y = COORD(ui->cur_y);
  1907. *w = *h = TILE_SIZE;
  1908. }
  1909. }
  1910. /*
  1911. * The contents of ds->grid are complicated, because of the circular
  1912. * islands which overlap their own grid square into neighbouring
  1913. * squares. An island square can contain pieces of the bridges in all
  1914. * directions, and conversely a bridge square can be intruded on by
  1915. * islands from any direction.
  1916. *
  1917. * So we define one group of flags describing what's important about
  1918. * an island, and another describing a bridge. Island squares' entries
  1919. * in ds->grid contain one of the former and four of the latter; bridge
  1920. * squares, four of the former and _two_ of the latter - because a
  1921. * horizontal and vertical 'bridge' can cross, when one of them is a
  1922. * 'no bridge here' pencil mark.
  1923. *
  1924. * Bridge flags need to indicate 0-4 actual bridges (3 bits), a 'no
  1925. * bridge' row of crosses, or a grey hint line; that's 7
  1926. * possibilities, so 3 bits suffice. But then we also need to vary the
  1927. * colours: the bridges can turn COL_WARNING if they're part of a loop
  1928. * in no-loops mode, COL_HIGHLIGHT during a victory flash, or
  1929. * COL_SELECTED if they're the bridge the user is currently dragging,
  1930. * so that's 2 more bits for foreground colour. Also bridges can be
  1931. * backed by COL_MARK if they're locked by the user, so that's one
  1932. * more bit, making 6 bits per bridge direction.
  1933. *
  1934. * Island flags omit the actual island clue (it never changes during
  1935. * the game, so doesn't have to be stored in ds->grid to check against
  1936. * the previous version), so they just need to include 2 bits for
  1937. * foreground colour (an island can be normal, COL_HIGHLIGHT during
  1938. * victory, COL_WARNING if its clue is unsatisfiable, or COL_SELECTED
  1939. * if it's part of the user's drag) and 2 bits for background (normal,
  1940. * COL_MARK for a locked island, COL_CURSOR for the keyboard cursor).
  1941. * That's 4 bits per island direction. We must also indicate whether
  1942. * no island is present at all (in the case where the island is
  1943. * potentially intruding into the side of a line square), which we do
  1944. * using the unused 4th value of the background field.
  1945. *
  1946. * So an island square needs 4 + 4*6 = 28 bits, while a bridge square
  1947. * needs 4*4 + 2*6 = 28 bits too. Both only just fit in 32 bits, which
  1948. * is handy, because otherwise we'd have to faff around forever with
  1949. * little structs!
  1950. */
  1951. /* Flags for line data */
  1952. #define DL_COUNTMASK 0x07
  1953. #define DL_COUNT_CROSS 0x06
  1954. #define DL_COUNT_HINT 0x07
  1955. #define DL_COLMASK 0x18
  1956. #define DL_COL_NORMAL 0x00
  1957. #define DL_COL_WARNING 0x08
  1958. #define DL_COL_FLASH 0x10
  1959. #define DL_COL_SELECTED 0x18
  1960. #define DL_LOCK 0x20
  1961. #define DL_MASK 0x3F
  1962. /* Flags for island data */
  1963. #define DI_COLMASK 0x03
  1964. #define DI_COL_NORMAL 0x00
  1965. #define DI_COL_FLASH 0x01
  1966. #define DI_COL_WARNING 0x02
  1967. #define DI_COL_SELECTED 0x03
  1968. #define DI_BGMASK 0x0C
  1969. #define DI_BG_NO_ISLAND 0x00
  1970. #define DI_BG_NORMAL 0x04
  1971. #define DI_BG_MARK 0x08
  1972. #define DI_BG_CURSOR 0x0C
  1973. #define DI_MASK 0x0F
  1974. /* Shift counts for the format of a 32-bit word in an island square */
  1975. #define D_I_ISLAND_SHIFT 0
  1976. #define D_I_LINE_SHIFT_L 4
  1977. #define D_I_LINE_SHIFT_R 10
  1978. #define D_I_LINE_SHIFT_U 16
  1979. #define D_I_LINE_SHIFT_D 24
  1980. /* Shift counts for the format of a 32-bit word in a line square */
  1981. #define D_L_ISLAND_SHIFT_L 0
  1982. #define D_L_ISLAND_SHIFT_R 4
  1983. #define D_L_ISLAND_SHIFT_U 8
  1984. #define D_L_ISLAND_SHIFT_D 12
  1985. #define D_L_LINE_SHIFT_H 16
  1986. #define D_L_LINE_SHIFT_V 22
  1987. static char *update_drag_dst(const game_state *state, game_ui *ui,
  1988. const game_drawstate *ds, int nx, int ny)
  1989. {
  1990. int ox, oy, dx, dy, i, currl, maxb;
  1991. struct island *is;
  1992. grid_type gtype, ntype, mtype, curr;
  1993. if (ui->dragx_src == -1 || ui->dragy_src == -1) return NULL;
  1994. ui->dragx_dst = -1;
  1995. ui->dragy_dst = -1;
  1996. /* work out which of the four directions we're closest to... */
  1997. ox = COORD(ui->dragx_src) + TILE_SIZE/2;
  1998. oy = COORD(ui->dragy_src) + TILE_SIZE/2;
  1999. if (abs(nx-ox) < abs(ny-oy)) {
  2000. dx = 0;
  2001. dy = (ny-oy) < 0 ? -1 : 1;
  2002. gtype = G_LINEV; ntype = G_NOLINEV; mtype = G_MARKV;
  2003. maxb = INDEX(state, maxv, ui->dragx_src+dx, ui->dragy_src+dy);
  2004. } else {
  2005. dy = 0;
  2006. dx = (nx-ox) < 0 ? -1 : 1;
  2007. gtype = G_LINEH; ntype = G_NOLINEH; mtype = G_MARKH;
  2008. maxb = INDEX(state, maxh, ui->dragx_src+dx, ui->dragy_src+dy);
  2009. }
  2010. if (ui->drag_is_noline) {
  2011. ui->todraw = ntype;
  2012. } else {
  2013. curr = GRID(state, ui->dragx_src+dx, ui->dragy_src+dy);
  2014. currl = INDEX(state, lines, ui->dragx_src+dx, ui->dragy_src+dy);
  2015. if (curr & gtype) {
  2016. if (currl == maxb) {
  2017. ui->todraw = 0;
  2018. ui->nlines = 0;
  2019. } else {
  2020. ui->todraw = gtype;
  2021. ui->nlines = currl + 1;
  2022. }
  2023. } else {
  2024. ui->todraw = gtype;
  2025. ui->nlines = 1;
  2026. }
  2027. }
  2028. /* ... and see if there's an island off in that direction. */
  2029. is = INDEX(state, gridi, ui->dragx_src, ui->dragy_src);
  2030. for (i = 0; i < is->adj.npoints; i++) {
  2031. if (is->adj.points[i].off == 0) continue;
  2032. curr = GRID(state, is->x+dx, is->y+dy);
  2033. if (curr & mtype) continue; /* don't allow changes to marked lines. */
  2034. if (ui->drag_is_noline) {
  2035. if (curr & gtype) continue; /* no no-line where already a line */
  2036. } else {
  2037. if (POSSIBLES(state, dx, is->x+dx, is->y+dy) == 0) continue; /* no line if !possible. */
  2038. if (curr & ntype) continue; /* can't have a bridge where there's a no-line. */
  2039. }
  2040. if (is->adj.points[i].dx == dx &&
  2041. is->adj.points[i].dy == dy) {
  2042. ui->dragx_dst = ISLAND_ORTHX(is,i);
  2043. ui->dragy_dst = ISLAND_ORTHY(is,i);
  2044. }
  2045. }
  2046. /*debug(("update_drag src (%d,%d) d(%d,%d) dst (%d,%d)\n",
  2047. ui->dragx_src, ui->dragy_src, dx, dy,
  2048. ui->dragx_dst, ui->dragy_dst));*/
  2049. return MOVE_UI_UPDATE;
  2050. }
  2051. static char *finish_drag(const game_state *state, game_ui *ui)
  2052. {
  2053. char buf[80];
  2054. if (ui->dragx_src == -1 || ui->dragy_src == -1)
  2055. return NULL;
  2056. if (ui->dragx_dst == -1 || ui->dragy_dst == -1)
  2057. return ui_cancel_drag(ui);
  2058. if (ui->drag_is_noline) {
  2059. sprintf(buf, "N%d,%d,%d,%d",
  2060. ui->dragx_src, ui->dragy_src,
  2061. ui->dragx_dst, ui->dragy_dst);
  2062. } else {
  2063. sprintf(buf, "L%d,%d,%d,%d,%d",
  2064. ui->dragx_src, ui->dragy_src,
  2065. ui->dragx_dst, ui->dragy_dst, ui->nlines);
  2066. }
  2067. ui_cancel_drag(ui);
  2068. return dupstr(buf);
  2069. }
  2070. static char *interpret_move(const game_state *state, game_ui *ui,
  2071. const game_drawstate *ds,
  2072. int x, int y, int button)
  2073. {
  2074. int gx = FROMCOORD(x), gy = FROMCOORD(y);
  2075. char buf[80], *ret;
  2076. grid_type ggrid = INGRID(state,gx,gy) ? GRID(state,gx,gy) : 0;
  2077. bool shift = button & MOD_SHFT, control = button & MOD_CTRL;
  2078. button &= ~MOD_MASK;
  2079. if (button == LEFT_BUTTON || button == RIGHT_BUTTON) {
  2080. if (!INGRID(state, gx, gy)) return MOVE_UNUSED;
  2081. ui->cur_visible = false;
  2082. if (ggrid & G_ISLAND) {
  2083. ui->dragx_src = gx;
  2084. ui->dragy_src = gy;
  2085. return MOVE_UI_UPDATE;
  2086. } else
  2087. return ui_cancel_drag(ui);
  2088. } else if (button == LEFT_DRAG || button == RIGHT_DRAG) {
  2089. if (INGRID(state, ui->dragx_src, ui->dragy_src)
  2090. && (gx != ui->dragx_src || gy != ui->dragy_src)
  2091. && !(GRID(state,ui->dragx_src,ui->dragy_src) & G_MARK)) {
  2092. ui->dragging = true;
  2093. ui->drag_is_noline = (button == RIGHT_DRAG);
  2094. return update_drag_dst(state, ui, ds, x, y);
  2095. } else {
  2096. /* cancel a drag when we go back to the starting point */
  2097. ui->dragx_dst = -1;
  2098. ui->dragy_dst = -1;
  2099. return MOVE_UI_UPDATE;
  2100. }
  2101. } else if (button == LEFT_RELEASE || button == RIGHT_RELEASE) {
  2102. if (ui->dragging) {
  2103. return finish_drag(state, ui);
  2104. } else {
  2105. if (!INGRID(state, ui->dragx_src, ui->dragy_src)
  2106. || gx != ui->dragx_src || gy != ui->dragy_src) {
  2107. return ui_cancel_drag(ui);
  2108. }
  2109. ui_cancel_drag(ui);
  2110. if (!INGRID(state, gx, gy)) return MOVE_UNUSED;
  2111. if (!(GRID(state, gx, gy) & G_ISLAND)) return MOVE_NO_EFFECT;
  2112. sprintf(buf, "M%d,%d", gx, gy);
  2113. return dupstr(buf);
  2114. }
  2115. } else if (button == 'h' || button == 'H') {
  2116. game_state *solved = dup_game(state);
  2117. solve_for_hint(solved);
  2118. ret = game_state_diff(state, solved);
  2119. free_game(solved);
  2120. return ret;
  2121. } else if (IS_CURSOR_MOVE(button)) {
  2122. ui->cur_visible = true;
  2123. if (control || shift) {
  2124. ui->dragx_src = ui->cur_x;
  2125. ui->dragy_src = ui->cur_y;
  2126. ui->dragging = true;
  2127. ui->drag_is_noline = !control;
  2128. }
  2129. if (ui->dragging) {
  2130. int nx = ui->cur_x, ny = ui->cur_y;
  2131. move_cursor(button, &nx, &ny, state->w, state->h, false);
  2132. if (nx == ui->cur_x && ny == ui->cur_y)
  2133. return MOVE_NO_EFFECT;
  2134. update_drag_dst(state, ui, ds,
  2135. COORD(nx)+TILE_SIZE/2,
  2136. COORD(ny)+TILE_SIZE/2);
  2137. return finish_drag(state, ui);
  2138. } else {
  2139. int dx = (button == CURSOR_RIGHT) ? +1 : (button == CURSOR_LEFT) ? -1 : 0;
  2140. int dy = (button == CURSOR_DOWN) ? +1 : (button == CURSOR_UP) ? -1 : 0;
  2141. int dorthx = 1 - abs(dx), dorthy = 1 - abs(dy);
  2142. int dir, orth, nx = x, ny = y;
  2143. /* 'orthorder' is a tweak to ensure that if you press RIGHT and
  2144. * happen to move upwards, when you press LEFT you then tend
  2145. * downwards (rather than upwards again). */
  2146. int orthorder = (button == CURSOR_LEFT || button == CURSOR_UP) ? 1 : -1;
  2147. /* This attempts to find an island in the direction you're
  2148. * asking for, broadly speaking. If you ask to go right, for
  2149. * example, it'll look for islands to the right and slightly
  2150. * above or below your current horiz. position, allowing
  2151. * further above/below the further away it searches. */
  2152. assert(GRID(state, ui->cur_x, ui->cur_y) & G_ISLAND);
  2153. /* currently this is depth-first (so orthogonally-adjacent
  2154. * islands across the other side of the grid will be moved to
  2155. * before closer islands slightly offset). Swap the order of
  2156. * these two loops to change to breadth-first search. */
  2157. for (orth = 0; ; orth++) {
  2158. bool oingrid = false;
  2159. for (dir = 1; ; dir++) {
  2160. bool dingrid = false;
  2161. if (orth > dir) continue; /* only search in cone outwards. */
  2162. nx = ui->cur_x + dir*dx + orth*dorthx*orthorder;
  2163. ny = ui->cur_y + dir*dy + orth*dorthy*orthorder;
  2164. if (INGRID(state, nx, ny)) {
  2165. dingrid = true;
  2166. oingrid = true;
  2167. if (GRID(state, nx, ny) & G_ISLAND) goto found;
  2168. }
  2169. nx = ui->cur_x + dir*dx - orth*dorthx*orthorder;
  2170. ny = ui->cur_y + dir*dy - orth*dorthy*orthorder;
  2171. if (INGRID(state, nx, ny)) {
  2172. dingrid = true;
  2173. oingrid = true;
  2174. if (GRID(state, nx, ny) & G_ISLAND) goto found;
  2175. }
  2176. if (!dingrid) break;
  2177. }
  2178. if (!oingrid) return MOVE_UI_UPDATE;
  2179. }
  2180. /* not reached */
  2181. found:
  2182. ui->cur_x = nx;
  2183. ui->cur_y = ny;
  2184. return MOVE_UI_UPDATE;
  2185. }
  2186. } else if (IS_CURSOR_SELECT(button)) {
  2187. if (!ui->cur_visible) {
  2188. ui->cur_visible = true;
  2189. return MOVE_UI_UPDATE;
  2190. }
  2191. if (ui->dragging || button == CURSOR_SELECT2) {
  2192. ui_cancel_drag(ui);
  2193. if (ui->dragx_dst == -1 && ui->dragy_dst == -1) {
  2194. sprintf(buf, "M%d,%d", ui->cur_x, ui->cur_y);
  2195. return dupstr(buf);
  2196. } else
  2197. return MOVE_UI_UPDATE;
  2198. } else {
  2199. grid_type v = GRID(state, ui->cur_x, ui->cur_y);
  2200. if (v & G_ISLAND) {
  2201. ui->dragging = true;
  2202. ui->dragx_src = ui->cur_x;
  2203. ui->dragy_src = ui->cur_y;
  2204. ui->dragx_dst = ui->dragy_dst = -1;
  2205. ui->drag_is_noline = (button == CURSOR_SELECT2);
  2206. return MOVE_UI_UPDATE;
  2207. }
  2208. }
  2209. } else if ((button >= '0' && button <= '9') ||
  2210. (button >= 'a' && button <= 'f') ||
  2211. (button >= 'A' && button <= 'F')) {
  2212. /* jump to island with .count == number closest to cur_{x,y} */
  2213. int best_x = -1, best_y = -1, best_sqdist = -1, number = -1, i;
  2214. if (button >= '0' && button <= '9')
  2215. number = (button == '0' ? 16 : button - '0');
  2216. else if (button >= 'a' && button <= 'f')
  2217. number = 10 + button - 'a';
  2218. else if (button >= 'A' && button <= 'F')
  2219. number = 10 + button - 'A';
  2220. if (!ui->cur_visible) {
  2221. ui->cur_visible = true;
  2222. return MOVE_UI_UPDATE;
  2223. }
  2224. for (i = 0; i < state->n_islands; ++i) {
  2225. int x = state->islands[i].x, y = state->islands[i].y;
  2226. int dx = x - ui->cur_x, dy = y - ui->cur_y;
  2227. int sqdist = dx*dx + dy*dy;
  2228. if (state->islands[i].count != number)
  2229. continue;
  2230. if (x == ui->cur_x && y == ui->cur_y)
  2231. continue;
  2232. /* new_game() reads the islands in row-major order, so by
  2233. * breaking ties in favor of `first in state->islands' we
  2234. * also break ties by `lexicographically smallest (y, x)'.
  2235. * Thus, there's a stable pattern to how ties are broken
  2236. * which the user can learn and use to navigate faster. */
  2237. if (best_sqdist == -1 || sqdist < best_sqdist) {
  2238. best_x = x;
  2239. best_y = y;
  2240. best_sqdist = sqdist;
  2241. }
  2242. }
  2243. if (best_x != -1 && best_y != -1) {
  2244. ui->cur_x = best_x;
  2245. ui->cur_y = best_y;
  2246. return MOVE_UI_UPDATE;
  2247. } else
  2248. return MOVE_NO_EFFECT;
  2249. } else if (button == 'g' || button == 'G') {
  2250. ui->show_hints = !ui->show_hints;
  2251. return MOVE_UI_UPDATE;
  2252. }
  2253. return MOVE_UNUSED;
  2254. }
  2255. static game_state *execute_move(const game_state *state, const char *move)
  2256. {
  2257. game_state *ret = dup_game(state);
  2258. int x1, y1, x2, y2, nl, n;
  2259. struct island *is1, *is2;
  2260. char c;
  2261. debug(("execute_move: %s\n", move));
  2262. if (!*move) goto badmove;
  2263. while (*move) {
  2264. c = *move++;
  2265. if (c == 'S') {
  2266. ret->solved = true;
  2267. n = 0;
  2268. } else if (c == 'L') {
  2269. if (sscanf(move, "%d,%d,%d,%d,%d%n",
  2270. &x1, &y1, &x2, &y2, &nl, &n) != 5)
  2271. goto badmove;
  2272. if (!INGRID(ret, x1, y1) || !INGRID(ret, x2, y2))
  2273. goto badmove;
  2274. /* Precisely one co-ordinate must differ between islands. */
  2275. if ((x1 != x2) + (y1 != y2) != 1) goto badmove;
  2276. is1 = INDEX(ret, gridi, x1, y1);
  2277. is2 = INDEX(ret, gridi, x2, y2);
  2278. if (!is1 || !is2) goto badmove;
  2279. if (nl < 0 || nl > state->maxb) goto badmove;
  2280. island_join(is1, is2, nl, false);
  2281. } else if (c == 'N') {
  2282. if (sscanf(move, "%d,%d,%d,%d%n",
  2283. &x1, &y1, &x2, &y2, &n) != 4)
  2284. goto badmove;
  2285. if (!INGRID(ret, x1, y1) || !INGRID(ret, x2, y2))
  2286. goto badmove;
  2287. if ((x1 != x2) + (y1 != y2) != 1) goto badmove;
  2288. is1 = INDEX(ret, gridi, x1, y1);
  2289. is2 = INDEX(ret, gridi, x2, y2);
  2290. if (!is1 || !is2) goto badmove;
  2291. island_join(is1, is2, -1, false);
  2292. } else if (c == 'M') {
  2293. if (sscanf(move, "%d,%d%n",
  2294. &x1, &y1, &n) != 2)
  2295. goto badmove;
  2296. if (!INGRID(ret, x1, y1))
  2297. goto badmove;
  2298. is1 = INDEX(ret, gridi, x1, y1);
  2299. if (!is1) goto badmove;
  2300. island_togglemark(is1);
  2301. } else
  2302. goto badmove;
  2303. move += n;
  2304. if (*move == ';')
  2305. move++;
  2306. else if (*move) goto badmove;
  2307. }
  2308. map_update_possibles(ret);
  2309. if (map_check(ret)) {
  2310. debug(("Game completed.\n"));
  2311. ret->completed = true;
  2312. }
  2313. return ret;
  2314. badmove:
  2315. debug(("%s: unrecognised move.\n", move));
  2316. free_game(ret);
  2317. return NULL;
  2318. }
  2319. static char *solve_game(const game_state *state, const game_state *currstate,
  2320. const char *aux, const char **error)
  2321. {
  2322. char *ret;
  2323. game_state *solved;
  2324. if (aux) {
  2325. debug(("solve_game: aux = %s\n", aux));
  2326. solved = execute_move(state, aux);
  2327. if (!solved) {
  2328. *error = "Generated aux string is not a valid move (!).";
  2329. return NULL;
  2330. }
  2331. } else {
  2332. solved = dup_game(state);
  2333. /* solve with max strength... */
  2334. if (solve_from_scratch(solved, 10) == 0) {
  2335. free_game(solved);
  2336. *error = "Game does not have a (non-recursive) solution.";
  2337. return NULL;
  2338. }
  2339. }
  2340. ret = game_state_diff(currstate, solved);
  2341. free_game(solved);
  2342. debug(("solve_game: ret = %s\n", ret));
  2343. return ret;
  2344. }
  2345. /* ----------------------------------------------------------------------
  2346. * Drawing routines.
  2347. */
  2348. static void game_compute_size(const game_params *params, int tilesize,
  2349. const game_ui *ui, int *x, int *y)
  2350. {
  2351. /* Ick: fake up `ds->tilesize' for macro expansion purposes */
  2352. struct { int tilesize; } ads, *ds = &ads;
  2353. ads.tilesize = tilesize;
  2354. *x = TILE_SIZE * params->w + 2 * BORDER;
  2355. *y = TILE_SIZE * params->h + 2 * BORDER;
  2356. }
  2357. static void game_set_size(drawing *dr, game_drawstate *ds,
  2358. const game_params *params, int tilesize)
  2359. {
  2360. ds->tilesize = tilesize;
  2361. }
  2362. static float *game_colours(frontend *fe, int *ncolours)
  2363. {
  2364. float *ret = snewn(3 * NCOLOURS, float);
  2365. int i;
  2366. game_mkhighlight(fe, ret, COL_BACKGROUND, COL_HIGHLIGHT, COL_LOWLIGHT);
  2367. for (i = 0; i < 3; i++) {
  2368. ret[COL_FOREGROUND * 3 + i] = 0.0F;
  2369. ret[COL_HINT * 3 + i] = ret[COL_LOWLIGHT * 3 + i];
  2370. ret[COL_GRID * 3 + i] =
  2371. (ret[COL_HINT * 3 + i] + ret[COL_BACKGROUND * 3 + i]) * 0.5F;
  2372. ret[COL_MARK * 3 + i] = ret[COL_HIGHLIGHT * 3 + i];
  2373. }
  2374. ret[COL_WARNING * 3 + 0] = 1.0F;
  2375. ret[COL_WARNING * 3 + 1] = 0.25F;
  2376. ret[COL_WARNING * 3 + 2] = 0.25F;
  2377. ret[COL_SELECTED * 3 + 0] = 0.25F;
  2378. ret[COL_SELECTED * 3 + 1] = 1.00F;
  2379. ret[COL_SELECTED * 3 + 2] = 0.25F;
  2380. ret[COL_CURSOR * 3 + 0] = min(ret[COL_BACKGROUND * 3 + 0] * 1.4F, 1.0F);
  2381. ret[COL_CURSOR * 3 + 1] = ret[COL_BACKGROUND * 3 + 1] * 0.8F;
  2382. ret[COL_CURSOR * 3 + 2] = ret[COL_BACKGROUND * 3 + 2] * 0.8F;
  2383. *ncolours = NCOLOURS;
  2384. return ret;
  2385. }
  2386. static game_drawstate *game_new_drawstate(drawing *dr, const game_state *state)
  2387. {
  2388. struct game_drawstate *ds = snew(struct game_drawstate);
  2389. int wh = state->w*state->h;
  2390. int i;
  2391. ds->tilesize = 0;
  2392. ds->w = state->w;
  2393. ds->h = state->h;
  2394. ds->started = false;
  2395. ds->dragging = false;
  2396. ds->grid = snewn(wh, unsigned long);
  2397. for (i = 0; i < wh; i++)
  2398. ds->grid[i] = ~0UL;
  2399. ds->newgrid = snewn(wh, unsigned long);
  2400. ds->lv = snewn(wh, int);
  2401. ds->lh = snewn(wh, int);
  2402. memset(ds->lv, 0, wh*sizeof(int));
  2403. memset(ds->lh, 0, wh*sizeof(int));
  2404. return ds;
  2405. }
  2406. static void game_free_drawstate(drawing *dr, game_drawstate *ds)
  2407. {
  2408. sfree(ds->lv);
  2409. sfree(ds->lh);
  2410. sfree(ds->newgrid);
  2411. sfree(ds->grid);
  2412. sfree(ds);
  2413. }
  2414. #define LINE_WIDTH (TILE_SIZE/8)
  2415. #define TS8(x) (((x)*TILE_SIZE)/8)
  2416. #define OFFSET(thing) ((TILE_SIZE/2) - ((thing)/2))
  2417. static bool between_island(const game_state *state, int sx, int sy,
  2418. int dx, int dy)
  2419. {
  2420. int x = sx - dx, y = sy - dy;
  2421. while (INGRID(state, x, y)) {
  2422. if (GRID(state, x, y) & G_ISLAND) goto found;
  2423. x -= dx; y -= dy;
  2424. }
  2425. return false;
  2426. found:
  2427. x = sx + dx, y = sy + dy;
  2428. while (INGRID(state, x, y)) {
  2429. if (GRID(state, x, y) & G_ISLAND) return true;
  2430. x += dx; y += dy;
  2431. }
  2432. return false;
  2433. }
  2434. static void lines_lvlh(const game_state *state, const game_ui *ui,
  2435. int x, int y, grid_type v, int *lv_r, int *lh_r)
  2436. {
  2437. int lh = 0, lv = 0;
  2438. if (v & G_LINEV) lv = INDEX(state,lines,x,y);
  2439. if (v & G_LINEH) lh = INDEX(state,lines,x,y);
  2440. if (ui->show_hints) {
  2441. if (between_island(state, x, y, 0, 1) && !lv) lv = 1;
  2442. if (between_island(state, x, y, 1, 0) && !lh) lh = 1;
  2443. }
  2444. /*debug(("lvlh: (%d,%d) v 0x%x lv %d lh %d.\n", x, y, v, lv, lh));*/
  2445. *lv_r = lv; *lh_r = lh;
  2446. }
  2447. static void draw_cross(drawing *dr, game_drawstate *ds,
  2448. int ox, int oy, int col)
  2449. {
  2450. int off = TS8(2);
  2451. draw_line(dr, ox, oy, ox+off, oy+off, col);
  2452. draw_line(dr, ox+off, oy, ox, oy+off, col);
  2453. }
  2454. static void draw_general_line(drawing *dr, game_drawstate *ds,
  2455. int ox, int oy, int fx, int fy, int ax, int ay,
  2456. int len, unsigned long ldata, int which)
  2457. {
  2458. /*
  2459. * Draw one direction of lines in a square. To permit the same
  2460. * code to handle horizontal and vertical lines, fx,fy are the
  2461. * 'forward' direction (along the lines) and ax,ay are the
  2462. * 'across' direction.
  2463. *
  2464. * We draw the white background for a locked bridge if (which &
  2465. * 1), and draw the bridges themselves if (which & 2). This
  2466. * permits us to get two overlapping locked bridges right without
  2467. * one of them erasing part of the other.
  2468. */
  2469. int fg;
  2470. fg = ((ldata & DL_COUNTMASK) == DL_COUNT_HINT ? COL_HINT :
  2471. (ldata & DL_COLMASK) == DL_COL_SELECTED ? COL_SELECTED :
  2472. (ldata & DL_COLMASK) == DL_COL_FLASH ? COL_HIGHLIGHT :
  2473. (ldata & DL_COLMASK) == DL_COL_WARNING ? COL_WARNING :
  2474. COL_FOREGROUND);
  2475. if ((ldata & DL_COUNTMASK) == DL_COUNT_CROSS) {
  2476. draw_cross(dr, ds,
  2477. ox + TS8(1)*fx + TS8(3)*ax,
  2478. oy + TS8(1)*fy + TS8(3)*ay, fg);
  2479. draw_cross(dr, ds,
  2480. ox + TS8(5)*fx + TS8(3)*ax,
  2481. oy + TS8(5)*fy + TS8(3)*ay, fg);
  2482. } else if ((ldata & DL_COUNTMASK) != 0) {
  2483. int lh, lw, gw, bw, i, loff;
  2484. lh = (ldata & DL_COUNTMASK);
  2485. if (lh == DL_COUNT_HINT)
  2486. lh = 1;
  2487. lw = gw = LINE_WIDTH;
  2488. while ((bw = lw * lh + gw * (lh+1)) > TILE_SIZE)
  2489. gw--;
  2490. loff = OFFSET(bw);
  2491. if (which & 1) {
  2492. if ((ldata & DL_LOCK) && fg != COL_HINT)
  2493. draw_rect(dr, ox + loff*ax, oy + loff*ay,
  2494. len*fx+bw*ax, len*fy+bw*ay, COL_MARK);
  2495. }
  2496. if (which & 2) {
  2497. for (i = 0; i < lh; i++, loff += lw + gw)
  2498. draw_rect(dr, ox + (loff+gw)*ax, oy + (loff+gw)*ay,
  2499. len*fx+lw*ax, len*fy+lw*ay, fg);
  2500. }
  2501. }
  2502. }
  2503. static void draw_hline(drawing *dr, game_drawstate *ds,
  2504. int ox, int oy, int w, unsigned long vdata, int which)
  2505. {
  2506. draw_general_line(dr, ds, ox, oy, 1, 0, 0, 1, w, vdata, which);
  2507. }
  2508. static void draw_vline(drawing *dr, game_drawstate *ds,
  2509. int ox, int oy, int h, unsigned long vdata, int which)
  2510. {
  2511. draw_general_line(dr, ds, ox, oy, 0, 1, 1, 0, h, vdata, which);
  2512. }
  2513. #define ISLAND_RADIUS ((TILE_SIZE*12)/20)
  2514. #define ISLAND_NUMSIZE(clue) \
  2515. (((clue) < 10) ? (TILE_SIZE*7)/10 : (TILE_SIZE*5)/10)
  2516. static void draw_island(drawing *dr, game_drawstate *ds,
  2517. int ox, int oy, int clue, unsigned long idata)
  2518. {
  2519. int half, orad, irad, fg, bg;
  2520. if ((idata & DI_BGMASK) == DI_BG_NO_ISLAND)
  2521. return;
  2522. half = TILE_SIZE/2;
  2523. orad = ISLAND_RADIUS;
  2524. irad = orad - LINE_WIDTH;
  2525. fg = ((idata & DI_COLMASK) == DI_COL_SELECTED ? COL_SELECTED :
  2526. (idata & DI_COLMASK) == DI_COL_WARNING ? COL_WARNING :
  2527. (idata & DI_COLMASK) == DI_COL_FLASH ? COL_HIGHLIGHT :
  2528. COL_FOREGROUND);
  2529. bg = ((idata & DI_BGMASK) == DI_BG_CURSOR ? COL_CURSOR :
  2530. (idata & DI_BGMASK) == DI_BG_MARK ? COL_MARK :
  2531. COL_BACKGROUND);
  2532. /* draw a thick circle */
  2533. draw_circle(dr, ox+half, oy+half, orad, fg, fg);
  2534. draw_circle(dr, ox+half, oy+half, irad, bg, bg);
  2535. if (clue > 0) {
  2536. char str[32];
  2537. int textcolour = (fg == COL_SELECTED ? COL_FOREGROUND : fg);
  2538. sprintf(str, "%d", clue);
  2539. draw_text(dr, ox+half, oy+half, FONT_VARIABLE, ISLAND_NUMSIZE(clue),
  2540. ALIGN_VCENTRE | ALIGN_HCENTRE, textcolour, str);
  2541. }
  2542. }
  2543. static void draw_island_tile(drawing *dr, game_drawstate *ds,
  2544. int x, int y, int clue, unsigned long data)
  2545. {
  2546. int ox = COORD(x), oy = COORD(y);
  2547. int which;
  2548. clip(dr, ox, oy, TILE_SIZE, TILE_SIZE);
  2549. draw_rect(dr, ox, oy, TILE_SIZE, TILE_SIZE, COL_BACKGROUND);
  2550. /*
  2551. * Because of the possibility of incoming bridges just about
  2552. * meeting at one corner, we must split the line-drawing into
  2553. * background and foreground segments.
  2554. */
  2555. for (which = 1; which <= 2; which <<= 1) {
  2556. draw_hline(dr, ds, ox, oy, TILE_SIZE/2,
  2557. (data >> D_I_LINE_SHIFT_L) & DL_MASK, which);
  2558. draw_hline(dr, ds, ox + TILE_SIZE - TILE_SIZE/2, oy, TILE_SIZE/2,
  2559. (data >> D_I_LINE_SHIFT_R) & DL_MASK, which);
  2560. draw_vline(dr, ds, ox, oy, TILE_SIZE/2,
  2561. (data >> D_I_LINE_SHIFT_U) & DL_MASK, which);
  2562. draw_vline(dr, ds, ox, oy + TILE_SIZE - TILE_SIZE/2, TILE_SIZE/2,
  2563. (data >> D_I_LINE_SHIFT_D) & DL_MASK, which);
  2564. }
  2565. draw_island(dr, ds, ox, oy, clue, (data >> D_I_ISLAND_SHIFT) & DI_MASK);
  2566. unclip(dr);
  2567. draw_update(dr, ox, oy, TILE_SIZE, TILE_SIZE);
  2568. }
  2569. static void draw_line_tile(drawing *dr, game_drawstate *ds,
  2570. int x, int y, unsigned long data)
  2571. {
  2572. int ox = COORD(x), oy = COORD(y);
  2573. unsigned long hdata, vdata;
  2574. clip(dr, ox, oy, TILE_SIZE, TILE_SIZE);
  2575. draw_rect(dr, ox, oy, TILE_SIZE, TILE_SIZE, COL_BACKGROUND);
  2576. /*
  2577. * We have to think about which of the horizontal and vertical
  2578. * line to draw first, if both exist.
  2579. *
  2580. * The rule is that hint lines are drawn at the bottom, then
  2581. * NOLINE crosses, then actual bridges. The enumeration in the
  2582. * DL_COUNTMASK field is set up so that this drops out of a
  2583. * straight comparison between the two.
  2584. *
  2585. * Since lines crossing in this type of square cannot both be
  2586. * actual bridges, there's no need to pass a nontrivial 'which'
  2587. * parameter to draw_[hv]line.
  2588. */
  2589. hdata = (data >> D_L_LINE_SHIFT_H) & DL_MASK;
  2590. vdata = (data >> D_L_LINE_SHIFT_V) & DL_MASK;
  2591. if ((hdata & DL_COUNTMASK) > (vdata & DL_COUNTMASK)) {
  2592. draw_hline(dr, ds, ox, oy, TILE_SIZE, hdata, 3);
  2593. draw_vline(dr, ds, ox, oy, TILE_SIZE, vdata, 3);
  2594. } else {
  2595. draw_vline(dr, ds, ox, oy, TILE_SIZE, vdata, 3);
  2596. draw_hline(dr, ds, ox, oy, TILE_SIZE, hdata, 3);
  2597. }
  2598. /*
  2599. * The islands drawn at the edges of a line tile don't need clue
  2600. * numbers.
  2601. */
  2602. draw_island(dr, ds, ox - TILE_SIZE, oy, -1,
  2603. (data >> D_L_ISLAND_SHIFT_L) & DI_MASK);
  2604. draw_island(dr, ds, ox + TILE_SIZE, oy, -1,
  2605. (data >> D_L_ISLAND_SHIFT_R) & DI_MASK);
  2606. draw_island(dr, ds, ox, oy - TILE_SIZE, -1,
  2607. (data >> D_L_ISLAND_SHIFT_U) & DI_MASK);
  2608. draw_island(dr, ds, ox, oy + TILE_SIZE, -1,
  2609. (data >> D_L_ISLAND_SHIFT_D) & DI_MASK);
  2610. unclip(dr);
  2611. draw_update(dr, ox, oy, TILE_SIZE, TILE_SIZE);
  2612. }
  2613. static void draw_edge_tile(drawing *dr, game_drawstate *ds,
  2614. int x, int y, int dx, int dy, unsigned long data)
  2615. {
  2616. int ox = COORD(x), oy = COORD(y);
  2617. int cx = ox, cy = oy, cw = TILE_SIZE, ch = TILE_SIZE;
  2618. if (dy) {
  2619. if (dy > 0)
  2620. cy += TILE_SIZE/2;
  2621. ch -= TILE_SIZE/2;
  2622. } else {
  2623. if (dx > 0)
  2624. cx += TILE_SIZE/2;
  2625. cw -= TILE_SIZE/2;
  2626. }
  2627. clip(dr, cx, cy, cw, ch);
  2628. draw_rect(dr, cx, cy, cw, ch, COL_BACKGROUND);
  2629. draw_island(dr, ds, ox + TILE_SIZE*dx, oy + TILE_SIZE*dy, -1,
  2630. (data >> D_I_ISLAND_SHIFT) & DI_MASK);
  2631. unclip(dr);
  2632. draw_update(dr, cx, cy, cw, ch);
  2633. }
  2634. static void game_redraw(drawing *dr, game_drawstate *ds,
  2635. const game_state *oldstate, const game_state *state,
  2636. int dir, const game_ui *ui,
  2637. float animtime, float flashtime)
  2638. {
  2639. int x, y, lv, lh;
  2640. grid_type v;
  2641. bool flash = false;
  2642. struct island *is, *is_drag_src = NULL, *is_drag_dst = NULL;
  2643. if (flashtime) {
  2644. int f = (int)(flashtime * 5 / FLASH_TIME);
  2645. if (f == 1 || f == 3) flash = true;
  2646. }
  2647. /* Clear screen, if required. */
  2648. if (!ds->started) {
  2649. #ifdef DRAW_GRID
  2650. draw_rect_outline(dr,
  2651. COORD(0)-1, COORD(0)-1,
  2652. TILE_SIZE * ds->w + 2, TILE_SIZE * ds->h + 2,
  2653. COL_GRID);
  2654. #endif
  2655. draw_update(dr, 0, 0,
  2656. TILE_SIZE * ds->w + 2 * BORDER,
  2657. TILE_SIZE * ds->h + 2 * BORDER);
  2658. ds->started = true;
  2659. }
  2660. if (ui->dragx_src != -1 && ui->dragy_src != -1) {
  2661. ds->dragging = true;
  2662. is_drag_src = INDEX(state, gridi, ui->dragx_src, ui->dragy_src);
  2663. assert(is_drag_src);
  2664. if (ui->dragx_dst != -1 && ui->dragy_dst != -1) {
  2665. is_drag_dst = INDEX(state, gridi, ui->dragx_dst, ui->dragy_dst);
  2666. assert(is_drag_dst);
  2667. }
  2668. } else
  2669. ds->dragging = false;
  2670. /*
  2671. * Set up ds->newgrid with the current grid contents.
  2672. */
  2673. for (x = 0; x < ds->w; x++)
  2674. for (y = 0; y < ds->h; y++)
  2675. INDEX(ds,newgrid,x,y) = 0;
  2676. for (x = 0; x < ds->w; x++) {
  2677. for (y = 0; y < ds->h; y++) {
  2678. v = GRID(state, x, y);
  2679. if (v & G_ISLAND) {
  2680. /*
  2681. * An island square. Compute the drawing data for the
  2682. * island, and put it in this square and surrounding
  2683. * squares.
  2684. */
  2685. unsigned long idata = 0;
  2686. is = INDEX(state, gridi, x, y);
  2687. if (flash)
  2688. idata |= DI_COL_FLASH;
  2689. if (is_drag_src && (is == is_drag_src ||
  2690. (is_drag_dst && is == is_drag_dst)))
  2691. idata |= DI_COL_SELECTED;
  2692. else if (island_impossible(is, v & G_MARK) || (v & G_WARN))
  2693. idata |= DI_COL_WARNING;
  2694. else
  2695. idata |= DI_COL_NORMAL;
  2696. if (ui->cur_visible &&
  2697. ui->cur_x == is->x && ui->cur_y == is->y)
  2698. idata |= DI_BG_CURSOR;
  2699. else if (v & G_MARK)
  2700. idata |= DI_BG_MARK;
  2701. else
  2702. idata |= DI_BG_NORMAL;
  2703. INDEX(ds,newgrid,x,y) |= idata << D_I_ISLAND_SHIFT;
  2704. if (x > 0 && !(GRID(state,x-1,y) & G_ISLAND))
  2705. INDEX(ds,newgrid,x-1,y) |= idata << D_L_ISLAND_SHIFT_R;
  2706. if (x+1 < state->w && !(GRID(state,x+1,y) & G_ISLAND))
  2707. INDEX(ds,newgrid,x+1,y) |= idata << D_L_ISLAND_SHIFT_L;
  2708. if (y > 0 && !(GRID(state,x,y-1) & G_ISLAND))
  2709. INDEX(ds,newgrid,x,y-1) |= idata << D_L_ISLAND_SHIFT_D;
  2710. if (y+1 < state->h && !(GRID(state,x,y+1) & G_ISLAND))
  2711. INDEX(ds,newgrid,x,y+1) |= idata << D_L_ISLAND_SHIFT_U;
  2712. } else {
  2713. unsigned long hdata, vdata;
  2714. bool selh = false, selv = false;
  2715. /*
  2716. * A line (non-island) square. Compute the drawing
  2717. * data for any horizontal and vertical lines in the
  2718. * square, and put them in this square's entry and
  2719. * optionally those for neighbouring islands too.
  2720. */
  2721. if (is_drag_dst &&
  2722. WITHIN(x,is_drag_src->x, is_drag_dst->x) &&
  2723. WITHIN(y,is_drag_src->y, is_drag_dst->y)) {
  2724. if (is_drag_src->x != is_drag_dst->x)
  2725. selh = true;
  2726. else
  2727. selv = true;
  2728. }
  2729. lines_lvlh(state, ui, x, y, v, &lv, &lh);
  2730. hdata = (v & G_NOLINEH ? DL_COUNT_CROSS :
  2731. v & G_LINEH ? lh :
  2732. (ui->show_hints &&
  2733. between_island(state,x,y,1,0)) ? DL_COUNT_HINT : 0);
  2734. vdata = (v & G_NOLINEV ? DL_COUNT_CROSS :
  2735. v & G_LINEV ? lv :
  2736. (ui->show_hints &&
  2737. between_island(state,x,y,0,1)) ? DL_COUNT_HINT : 0);
  2738. hdata |= (flash ? DL_COL_FLASH :
  2739. v & G_WARN ? DL_COL_WARNING :
  2740. selh ? DL_COL_SELECTED :
  2741. DL_COL_NORMAL);
  2742. vdata |= (flash ? DL_COL_FLASH :
  2743. v & G_WARN ? DL_COL_WARNING :
  2744. selv ? DL_COL_SELECTED :
  2745. DL_COL_NORMAL);
  2746. if (v & G_MARKH)
  2747. hdata |= DL_LOCK;
  2748. if (v & G_MARKV)
  2749. vdata |= DL_LOCK;
  2750. INDEX(ds,newgrid,x,y) |= hdata << D_L_LINE_SHIFT_H;
  2751. INDEX(ds,newgrid,x,y) |= vdata << D_L_LINE_SHIFT_V;
  2752. if (x > 0 && (GRID(state,x-1,y) & G_ISLAND))
  2753. INDEX(ds,newgrid,x-1,y) |= hdata << D_I_LINE_SHIFT_R;
  2754. if (x+1 < state->w && (GRID(state,x+1,y) & G_ISLAND))
  2755. INDEX(ds,newgrid,x+1,y) |= hdata << D_I_LINE_SHIFT_L;
  2756. if (y > 0 && (GRID(state,x,y-1) & G_ISLAND))
  2757. INDEX(ds,newgrid,x,y-1) |= vdata << D_I_LINE_SHIFT_D;
  2758. if (y+1 < state->h && (GRID(state,x,y+1) & G_ISLAND))
  2759. INDEX(ds,newgrid,x,y+1) |= vdata << D_I_LINE_SHIFT_U;
  2760. }
  2761. }
  2762. }
  2763. /*
  2764. * Now go through and draw any changed grid square.
  2765. */
  2766. for (x = 0; x < ds->w; x++) {
  2767. for (y = 0; y < ds->h; y++) {
  2768. unsigned long newval = INDEX(ds,newgrid,x,y);
  2769. if (INDEX(ds,grid,x,y) != newval) {
  2770. v = GRID(state, x, y);
  2771. if (v & G_ISLAND) {
  2772. is = INDEX(state, gridi, x, y);
  2773. draw_island_tile(dr, ds, x, y, is->count, newval);
  2774. /*
  2775. * If this tile is right at the edge of the grid,
  2776. * we must also draw the part of the island that
  2777. * goes completely out of bounds. We don't bother
  2778. * keeping separate entries in ds->newgrid for
  2779. * these tiles; it's easier just to redraw them
  2780. * iff we redraw their parent island tile.
  2781. */
  2782. if (x == 0)
  2783. draw_edge_tile(dr, ds, x-1, y, +1, 0, newval);
  2784. if (y == 0)
  2785. draw_edge_tile(dr, ds, x, y-1, 0, +1, newval);
  2786. if (x == state->w-1)
  2787. draw_edge_tile(dr, ds, x+1, y, -1, 0, newval);
  2788. if (y == state->h-1)
  2789. draw_edge_tile(dr, ds, x, y+1, 0, -1, newval);
  2790. } else {
  2791. draw_line_tile(dr, ds, x, y, newval);
  2792. }
  2793. INDEX(ds,grid,x,y) = newval;
  2794. }
  2795. }
  2796. }
  2797. }
  2798. static float game_anim_length(const game_state *oldstate,
  2799. const game_state *newstate, int dir, game_ui *ui)
  2800. {
  2801. return 0.0F;
  2802. }
  2803. static float game_flash_length(const game_state *oldstate,
  2804. const game_state *newstate, int dir, game_ui *ui)
  2805. {
  2806. if (!oldstate->completed && newstate->completed &&
  2807. !oldstate->solved && !newstate->solved)
  2808. return FLASH_TIME;
  2809. return 0.0F;
  2810. }
  2811. static int game_status(const game_state *state)
  2812. {
  2813. return state->completed ? +1 : 0;
  2814. }
  2815. static void game_print_size(const game_params *params, const game_ui *ui,
  2816. float *x, float *y)
  2817. {
  2818. int pw, ph;
  2819. /* 10mm squares by default. */
  2820. game_compute_size(params, 1000, ui, &pw, &ph);
  2821. *x = pw / 100.0F;
  2822. *y = ph / 100.0F;
  2823. }
  2824. static void game_print(drawing *dr, const game_state *state, const game_ui *ui,
  2825. int ts)
  2826. {
  2827. int ink = print_mono_colour(dr, 0);
  2828. int paper = print_mono_colour(dr, 1);
  2829. int x, y, cx, cy, i, nl;
  2830. int loff;
  2831. grid_type grid;
  2832. /* Ick: fake up `ds->tilesize' for macro expansion purposes */
  2833. game_drawstate ads, *ds = &ads;
  2834. ads.tilesize = ts;
  2835. /* I don't think this wants a border. */
  2836. /* Bridges */
  2837. loff = ts / (8 * sqrt((state->params.maxb - 1)));
  2838. print_line_width(dr, ts / 12);
  2839. for (x = 0; x < state->w; x++) {
  2840. for (y = 0; y < state->h; y++) {
  2841. cx = COORD(x); cy = COORD(y);
  2842. grid = GRID(state,x,y);
  2843. nl = INDEX(state,lines,x,y);
  2844. if (grid & G_ISLAND) continue;
  2845. if (grid & G_LINEV) {
  2846. for (i = 0; i < nl; i++)
  2847. draw_line(dr, cx+ts/2+(2*i-nl+1)*loff, cy,
  2848. cx+ts/2+(2*i-nl+1)*loff, cy+ts, ink);
  2849. }
  2850. if (grid & G_LINEH) {
  2851. for (i = 0; i < nl; i++)
  2852. draw_line(dr, cx, cy+ts/2+(2*i-nl+1)*loff,
  2853. cx+ts, cy+ts/2+(2*i-nl+1)*loff, ink);
  2854. }
  2855. }
  2856. }
  2857. /* Islands */
  2858. for (i = 0; i < state->n_islands; i++) {
  2859. char str[32];
  2860. struct island *is = &state->islands[i];
  2861. grid = GRID(state, is->x, is->y);
  2862. cx = COORD(is->x) + ts/2;
  2863. cy = COORD(is->y) + ts/2;
  2864. draw_circle(dr, cx, cy, ISLAND_RADIUS, paper, ink);
  2865. sprintf(str, "%d", is->count);
  2866. draw_text(dr, cx, cy, FONT_VARIABLE, ISLAND_NUMSIZE(is->count),
  2867. ALIGN_VCENTRE | ALIGN_HCENTRE, ink, str);
  2868. }
  2869. }
  2870. #ifdef COMBINED
  2871. #define thegame bridges
  2872. #endif
  2873. const struct game thegame = {
  2874. "Bridges", "games.bridges", "bridges",
  2875. default_params,
  2876. game_fetch_preset, NULL,
  2877. decode_params,
  2878. encode_params,
  2879. free_params,
  2880. dup_params,
  2881. true, game_configure, custom_params,
  2882. validate_params,
  2883. new_game_desc,
  2884. validate_desc,
  2885. new_game,
  2886. dup_game,
  2887. free_game,
  2888. true, solve_game,
  2889. true, game_can_format_as_text_now, game_text_format,
  2890. get_prefs, set_prefs,
  2891. new_ui,
  2892. free_ui,
  2893. NULL, /* encode_ui */
  2894. NULL, /* decode_ui */
  2895. NULL, /* game_request_keys */
  2896. game_changed_state,
  2897. current_key_label,
  2898. interpret_move,
  2899. execute_move,
  2900. PREFERRED_TILE_SIZE, game_compute_size, game_set_size,
  2901. game_colours,
  2902. game_new_drawstate,
  2903. game_free_drawstate,
  2904. game_redraw,
  2905. game_anim_length,
  2906. game_flash_length,
  2907. game_get_cursor_location,
  2908. game_status,
  2909. true, false, game_print_size, game_print,
  2910. false, /* wants_statusbar */
  2911. false, NULL, /* timing_state */
  2912. REQUIRE_RBUTTON, /* flags */
  2913. };
  2914. /* vim: set shiftwidth=4 tabstop=8: */