loopy.c 127 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905
  1. /*
  2. * loopy.c:
  3. *
  4. * An implementation of the Nikoli game 'Loop the loop'.
  5. * (c) Mike Pinna, 2005, 2006
  6. * Substantially rewritten to allowing for more general types of grid.
  7. * (c) Lambros Lambrou 2008
  8. *
  9. * vim: set shiftwidth=4 :set textwidth=80:
  10. */
  11. /*
  12. * Possible future solver enhancements:
  13. *
  14. * - There's an interesting deductive technique which makes use
  15. * of topology rather than just graph theory. Each _face_ in
  16. * the grid is either inside or outside the loop; you can tell
  17. * that two faces are on the same side of the loop if they're
  18. * separated by a LINE_NO (or, more generally, by a path
  19. * crossing no LINE_UNKNOWNs and an even number of LINE_YESes),
  20. * and on the opposite side of the loop if they're separated by
  21. * a LINE_YES (or an odd number of LINE_YESes and no
  22. * LINE_UNKNOWNs). Oh, and any face separated from the outside
  23. * of the grid by a LINE_YES or a LINE_NO is on the inside or
  24. * outside respectively. So if you can track this for all
  25. * faces, you figure out the state of the line between a pair
  26. * once their relative insideness is known.
  27. * + The way I envisage this working is simply to keep a flip dsf
  28. * of all _faces_, which indicates whether they're on
  29. * opposite sides of the loop from one another. We also
  30. * include a special entry in the dsf for the infinite
  31. * exterior "face".
  32. * + So, the simple way to do this is to just go through the
  33. * edges: every time we see an edge in a state other than
  34. * LINE_UNKNOWN which separates two faces that aren't in the
  35. * same dsf class, we can rectify that by merging the
  36. * classes. Then, conversely, an edge in LINE_UNKNOWN state
  37. * which separates two faces that _are_ in the same dsf
  38. * class can immediately have its state determined.
  39. * + But you can go one better, if you're prepared to loop
  40. * over all _pairs_ of edges. Suppose we have edges A and B,
  41. * which respectively separate faces A1,A2 and B1,B2.
  42. * Suppose that A,B are in the same edge-dsf class and that
  43. * A1,B1 (wlog) are in the same face-dsf class; then we can
  44. * immediately place A2,B2 into the same face-dsf class (as
  45. * each other, not as A1 and A2) one way round or the other.
  46. * And conversely again, if A1,B1 are in the same face-dsf
  47. * class and so are A2,B2, then we can put A,B into the same
  48. * face-dsf class.
  49. * * Of course, this deduction requires a quadratic-time
  50. * loop over all pairs of edges in the grid, so it should
  51. * be reserved until there's nothing easier left to be
  52. * done.
  53. *
  54. * - The generalised grid support has made me (SGT) notice a
  55. * possible extension to the loop-avoidance code. When you have
  56. * a path of connected edges such that no other edges at all
  57. * are incident on any vertex in the middle of the path - or,
  58. * alternatively, such that any such edges are already known to
  59. * be LINE_NO - then you know those edges are either all
  60. * LINE_YES or all LINE_NO. Hence you can mentally merge the
  61. * entire path into a single long curly edge for the purposes
  62. * of loop avoidance, and look directly at whether or not the
  63. * extreme endpoints of the path are connected by some other
  64. * route. I find this coming up fairly often when I play on the
  65. * octagonal grid setting, so it might be worth implementing in
  66. * the solver.
  67. *
  68. * - (Just a speed optimisation.) Consider some todo list queue where every
  69. * time we modify something we mark it for consideration by other bits of
  70. * the solver, to save iteration over things that have already been done.
  71. */
  72. #include <stdio.h>
  73. #include <stdlib.h>
  74. #include <stddef.h>
  75. #include <string.h>
  76. #include <assert.h>
  77. #include <ctype.h>
  78. #ifdef NO_TGMATH_H
  79. # include <math.h>
  80. #else
  81. # include <tgmath.h>
  82. #endif
  83. #include "puzzles.h"
  84. #include "tree234.h"
  85. #include "grid.h"
  86. #include "loopgen.h"
  87. /* Debugging options */
  88. /*
  89. #define DEBUG_CACHES
  90. #define SHOW_WORKING
  91. #define DEBUG_DLINES
  92. */
  93. /* ----------------------------------------------------------------------
  94. * Struct, enum and function declarations
  95. */
  96. enum {
  97. COL_BACKGROUND,
  98. COL_FOREGROUND,
  99. COL_LINEUNKNOWN,
  100. COL_HIGHLIGHT,
  101. COL_MISTAKE,
  102. COL_SATISFIED,
  103. COL_FAINT,
  104. NCOLOURS
  105. };
  106. struct game_state {
  107. grid *game_grid; /* ref-counted (internally) */
  108. /* Put -1 in a face that doesn't get a clue */
  109. signed char *clues;
  110. /* Array of line states, to store whether each line is
  111. * YES, NO or UNKNOWN */
  112. char *lines;
  113. bool *line_errors;
  114. bool exactly_one_loop;
  115. bool solved;
  116. bool cheated;
  117. /* Used in game_text_format(), so that it knows what type of
  118. * grid it's trying to render as ASCII text. */
  119. int grid_type;
  120. };
  121. enum solver_status {
  122. SOLVER_SOLVED, /* This is the only solution the solver could find */
  123. SOLVER_MISTAKE, /* This is definitely not a solution */
  124. SOLVER_AMBIGUOUS, /* This _might_ be an ambiguous solution */
  125. SOLVER_INCOMPLETE /* This may be a partial solution */
  126. };
  127. /* ------ Solver state ------ */
  128. typedef struct solver_state {
  129. game_state *state;
  130. enum solver_status solver_status;
  131. /* NB looplen is the number of dots that are joined together at a point, ie a
  132. * looplen of 1 means there are no lines to a particular dot */
  133. int *looplen;
  134. /* Difficulty level of solver. Used by solver functions that want to
  135. * vary their behaviour depending on the requested difficulty level. */
  136. int diff;
  137. /* caches */
  138. char *dot_yes_count;
  139. char *dot_no_count;
  140. char *face_yes_count;
  141. char *face_no_count;
  142. bool *dot_solved, *face_solved;
  143. DSF *dotdsf;
  144. /* Information for Normal level deductions:
  145. * For each dline, store a bitmask for whether we know:
  146. * (bit 0) at least one is YES
  147. * (bit 1) at most one is YES */
  148. char *dlines;
  149. /* Hard level information */
  150. DSF *linedsf;
  151. } solver_state;
  152. /*
  153. * Difficulty levels. I do some macro ickery here to ensure that my
  154. * enum and the various forms of my name list always match up.
  155. */
  156. #define DIFFLIST(A) \
  157. A(EASY,Easy,e) \
  158. A(NORMAL,Normal,n) \
  159. A(TRICKY,Tricky,t) \
  160. A(HARD,Hard,h)
  161. #define ENUM(upper,title,lower) DIFF_ ## upper,
  162. #define TITLE(upper,title,lower) #title,
  163. #define ENCODE(upper,title,lower) #lower
  164. #define CONFIG(upper,title,lower) ":" #title
  165. enum { DIFFLIST(ENUM) DIFF_MAX };
  166. static char const *const diffnames[] = { DIFFLIST(TITLE) };
  167. static char const diffchars[] = DIFFLIST(ENCODE);
  168. #define DIFFCONFIG DIFFLIST(CONFIG)
  169. /*
  170. * Solver routines, sorted roughly in order of computational cost.
  171. * The solver will run the faster deductions first, and slower deductions are
  172. * only invoked when the faster deductions are unable to make progress.
  173. * Each function is associated with a difficulty level, so that the generated
  174. * puzzles are solvable by applying only the functions with the chosen
  175. * difficulty level or lower.
  176. */
  177. #define SOLVERLIST(A) \
  178. A(trivial_deductions, DIFF_EASY) \
  179. A(dline_deductions, DIFF_NORMAL) \
  180. A(linedsf_deductions, DIFF_HARD) \
  181. A(loop_deductions, DIFF_EASY)
  182. #define SOLVER_FN_DECL(fn,diff) static int fn(solver_state *);
  183. #define SOLVER_FN(fn,diff) &fn,
  184. #define SOLVER_DIFF(fn,diff) diff,
  185. SOLVERLIST(SOLVER_FN_DECL)
  186. static int (*(solver_fns[]))(solver_state *) = { SOLVERLIST(SOLVER_FN) };
  187. static int const solver_diffs[] = { SOLVERLIST(SOLVER_DIFF) };
  188. static const int NUM_SOLVERS = sizeof(solver_diffs)/sizeof(*solver_diffs);
  189. struct game_params {
  190. int w, h;
  191. int diff;
  192. int type;
  193. };
  194. /* line_drawstate is the same as line_state, but with the extra ERROR
  195. * possibility. The drawing code copies line_state to line_drawstate,
  196. * except in the case that the line is an error. */
  197. enum line_state { LINE_YES, LINE_UNKNOWN, LINE_NO };
  198. enum line_drawstate { DS_LINE_YES, DS_LINE_UNKNOWN,
  199. DS_LINE_NO, DS_LINE_ERROR };
  200. #define OPP(line_state) \
  201. (2 - line_state)
  202. struct game_drawstate {
  203. bool started;
  204. int tilesize;
  205. bool flashing;
  206. int *textx, *texty;
  207. char *lines;
  208. bool *clue_error;
  209. bool *clue_satisfied;
  210. };
  211. static const char *validate_desc(const game_params *params, const char *desc);
  212. static int dot_order(const game_state* state, int i, char line_type);
  213. static int face_order(const game_state* state, int i, char line_type);
  214. static solver_state *solve_game_rec(const solver_state *sstate);
  215. #ifdef DEBUG_CACHES
  216. static void check_caches(const solver_state* sstate);
  217. #else
  218. #define check_caches(s)
  219. #endif
  220. /*
  221. * Grid type config options available in Loopy.
  222. *
  223. * Annoyingly, we have to use an enum here which doesn't match up
  224. * exactly to the grid-type enum in grid.h. Values in params->types
  225. * are given by names such as LOOPY_GRID_SQUARE, which shouldn't be
  226. * confused with GRID_SQUARE which is the value you pass to grid_new()
  227. * and friends. So beware!
  228. *
  229. * (This is partly for historical reasons - Loopy's version of the
  230. * enum is encoded in game parameter strings, so we keep it for
  231. * backwards compatibility. But also, we need to store additional data
  232. * here alongside each enum value, such as names for the presets menu,
  233. * which isn't stored in grid.h; so we have to have our own list macro
  234. * here anyway, and C doesn't make it easy to enforce that that lines
  235. * up exactly with grid.h.)
  236. *
  237. * Do not add values to this list _except_ at the end, or old game ids
  238. * will stop working!
  239. */
  240. #define GRIDLIST(A) \
  241. A("Squares",SQUARE,3,3) \
  242. A("Triangular",TRIANGULAR,3,3) \
  243. A("Honeycomb",HONEYCOMB,3,3) \
  244. A("Snub-Square",SNUBSQUARE,3,3) \
  245. A("Cairo",CAIRO,3,4) \
  246. A("Great-Hexagonal",GREATHEXAGONAL,3,3) \
  247. A("Octagonal",OCTAGONAL,3,3) \
  248. A("Kites",KITE,3,3) \
  249. A("Floret",FLORET,1,2) \
  250. A("Dodecagonal",DODECAGONAL,2,2) \
  251. A("Great-Dodecagonal",GREATDODECAGONAL,2,2) \
  252. A("Penrose (kite/dart)",PENROSE_P2,3,3) \
  253. A("Penrose (rhombs)",PENROSE_P3,3,3) \
  254. A("Great-Great-Dodecagonal",GREATGREATDODECAGONAL,2,2) \
  255. A("Kagome",KAGOME,3,3) \
  256. A("Compass-Dodecagonal",COMPASSDODECAGONAL,2,2) \
  257. A("Hats",HATS,6,6) \
  258. A("Spectres",SPECTRES,6,6) \
  259. /* end of list */
  260. #define GRID_NAME(title,type,amin,omin) title,
  261. #define GRID_CONFIG(title,type,amin,omin) ":" title
  262. #define GRID_LOOPYTYPE(title,type,amin,omin) LOOPY_GRID_ ## type,
  263. #define GRID_GRIDTYPE(title,type,amin,omin) GRID_ ## type,
  264. #define GRID_SIZES(title,type,amin,omin) \
  265. {amin, omin, \
  266. "Width and height for this grid type must both be at least " #amin, \
  267. "At least one of width and height for this grid type must be at least " #omin,},
  268. enum { GRIDLIST(GRID_LOOPYTYPE) LOOPY_GRID_DUMMY_TERMINATOR };
  269. static char const *const gridnames[] = { GRIDLIST(GRID_NAME) };
  270. #define GRID_CONFIGS GRIDLIST(GRID_CONFIG)
  271. static grid_type grid_types[] = { GRIDLIST(GRID_GRIDTYPE) };
  272. #define NUM_GRID_TYPES (sizeof(grid_types) / sizeof(grid_types[0]))
  273. static const struct {
  274. int amin, omin;
  275. const char *aerr, *oerr;
  276. } grid_size_limits[] = { GRIDLIST(GRID_SIZES) };
  277. /* Generates a (dynamically allocated) new grid, according to the
  278. * type and size requested in params. Does nothing if the grid is already
  279. * generated. */
  280. static grid *loopy_generate_grid(const game_params *params,
  281. const char *grid_desc)
  282. {
  283. return grid_new(grid_types[params->type], params->w, params->h, grid_desc);
  284. }
  285. /* ----------------------------------------------------------------------
  286. * Preprocessor magic
  287. */
  288. /* General constants */
  289. #define PREFERRED_TILE_SIZE 32
  290. #define BORDER(tilesize) ((tilesize) / 2)
  291. #define FLASH_TIME 0.5F
  292. #define BIT_SET(field, bit) ((field) & (1<<(bit)))
  293. #define SET_BIT(field, bit) (BIT_SET(field, bit) ? false : \
  294. ((field) |= (1<<(bit)), true))
  295. #define CLEAR_BIT(field, bit) (BIT_SET(field, bit) ? \
  296. ((field) &= ~(1<<(bit)), true) : false)
  297. #define CLUE2CHAR(c) \
  298. ((c < 0) ? ' ' : c < 10 ? c + '0' : c - 10 + 'A')
  299. /* ----------------------------------------------------------------------
  300. * General struct manipulation and other straightforward code
  301. */
  302. static game_state *dup_game(const game_state *state)
  303. {
  304. game_state *ret = snew(game_state);
  305. ret->game_grid = state->game_grid;
  306. ret->game_grid->refcount++;
  307. ret->solved = state->solved;
  308. ret->cheated = state->cheated;
  309. ret->clues = snewn(state->game_grid->num_faces, signed char);
  310. memcpy(ret->clues, state->clues, state->game_grid->num_faces);
  311. ret->lines = snewn(state->game_grid->num_edges, char);
  312. memcpy(ret->lines, state->lines, state->game_grid->num_edges);
  313. ret->line_errors = snewn(state->game_grid->num_edges, bool);
  314. memcpy(ret->line_errors, state->line_errors,
  315. state->game_grid->num_edges * sizeof(bool));
  316. ret->exactly_one_loop = state->exactly_one_loop;
  317. ret->grid_type = state->grid_type;
  318. return ret;
  319. }
  320. static void free_game(game_state *state)
  321. {
  322. if (state) {
  323. grid_free(state->game_grid);
  324. sfree(state->clues);
  325. sfree(state->lines);
  326. sfree(state->line_errors);
  327. sfree(state);
  328. }
  329. }
  330. static solver_state *new_solver_state(const game_state *state, int diff) {
  331. int i;
  332. int num_dots = state->game_grid->num_dots;
  333. int num_faces = state->game_grid->num_faces;
  334. int num_edges = state->game_grid->num_edges;
  335. solver_state *ret = snew(solver_state);
  336. ret->state = dup_game(state);
  337. ret->solver_status = SOLVER_INCOMPLETE;
  338. ret->diff = diff;
  339. ret->dotdsf = dsf_new(num_dots);
  340. ret->looplen = snewn(num_dots, int);
  341. for (i = 0; i < num_dots; i++) {
  342. ret->looplen[i] = 1;
  343. }
  344. ret->dot_solved = snewn(num_dots, bool);
  345. ret->face_solved = snewn(num_faces, bool);
  346. memset(ret->dot_solved, 0, num_dots * sizeof(bool));
  347. memset(ret->face_solved, 0, num_faces * sizeof(bool));
  348. ret->dot_yes_count = snewn(num_dots, char);
  349. memset(ret->dot_yes_count, 0, num_dots);
  350. ret->dot_no_count = snewn(num_dots, char);
  351. memset(ret->dot_no_count, 0, num_dots);
  352. ret->face_yes_count = snewn(num_faces, char);
  353. memset(ret->face_yes_count, 0, num_faces);
  354. ret->face_no_count = snewn(num_faces, char);
  355. memset(ret->face_no_count, 0, num_faces);
  356. if (diff < DIFF_NORMAL) {
  357. ret->dlines = NULL;
  358. } else {
  359. ret->dlines = snewn(2*num_edges, char);
  360. memset(ret->dlines, 0, 2*num_edges);
  361. }
  362. if (diff < DIFF_HARD) {
  363. ret->linedsf = NULL;
  364. } else {
  365. ret->linedsf = dsf_new_flip(state->game_grid->num_edges);
  366. }
  367. return ret;
  368. }
  369. static void free_solver_state(solver_state *sstate) {
  370. if (sstate) {
  371. free_game(sstate->state);
  372. dsf_free(sstate->dotdsf);
  373. sfree(sstate->looplen);
  374. sfree(sstate->dot_solved);
  375. sfree(sstate->face_solved);
  376. sfree(sstate->dot_yes_count);
  377. sfree(sstate->dot_no_count);
  378. sfree(sstate->face_yes_count);
  379. sfree(sstate->face_no_count);
  380. /* OK, because sfree(NULL) is a no-op */
  381. sfree(sstate->dlines);
  382. dsf_free(sstate->linedsf);
  383. sfree(sstate);
  384. }
  385. }
  386. static solver_state *dup_solver_state(const solver_state *sstate) {
  387. game_state *state = sstate->state;
  388. int num_dots = state->game_grid->num_dots;
  389. int num_faces = state->game_grid->num_faces;
  390. int num_edges = state->game_grid->num_edges;
  391. solver_state *ret = snew(solver_state);
  392. ret->state = state = dup_game(sstate->state);
  393. ret->solver_status = sstate->solver_status;
  394. ret->diff = sstate->diff;
  395. ret->dotdsf = dsf_new(num_dots);
  396. ret->looplen = snewn(num_dots, int);
  397. dsf_copy(ret->dotdsf, sstate->dotdsf);
  398. memcpy(ret->looplen, sstate->looplen,
  399. num_dots * sizeof(int));
  400. ret->dot_solved = snewn(num_dots, bool);
  401. ret->face_solved = snewn(num_faces, bool);
  402. memcpy(ret->dot_solved, sstate->dot_solved, num_dots * sizeof(bool));
  403. memcpy(ret->face_solved, sstate->face_solved, num_faces * sizeof(bool));
  404. ret->dot_yes_count = snewn(num_dots, char);
  405. memcpy(ret->dot_yes_count, sstate->dot_yes_count, num_dots);
  406. ret->dot_no_count = snewn(num_dots, char);
  407. memcpy(ret->dot_no_count, sstate->dot_no_count, num_dots);
  408. ret->face_yes_count = snewn(num_faces, char);
  409. memcpy(ret->face_yes_count, sstate->face_yes_count, num_faces);
  410. ret->face_no_count = snewn(num_faces, char);
  411. memcpy(ret->face_no_count, sstate->face_no_count, num_faces);
  412. if (sstate->dlines) {
  413. ret->dlines = snewn(2*num_edges, char);
  414. memcpy(ret->dlines, sstate->dlines,
  415. 2*num_edges);
  416. } else {
  417. ret->dlines = NULL;
  418. }
  419. if (sstate->linedsf) {
  420. ret->linedsf = dsf_new_flip(num_edges);
  421. dsf_copy(ret->linedsf, sstate->linedsf);
  422. } else {
  423. ret->linedsf = NULL;
  424. }
  425. return ret;
  426. }
  427. static game_params *default_params(void)
  428. {
  429. game_params *ret = snew(game_params);
  430. #ifdef SLOW_SYSTEM
  431. ret->h = 7;
  432. ret->w = 7;
  433. #else
  434. ret->h = 10;
  435. ret->w = 10;
  436. #endif
  437. ret->diff = DIFF_EASY;
  438. ret->type = 0;
  439. return ret;
  440. }
  441. static game_params *dup_params(const game_params *params)
  442. {
  443. game_params *ret = snew(game_params);
  444. *ret = *params; /* structure copy */
  445. return ret;
  446. }
  447. static const game_params loopy_presets_top[] = {
  448. #ifdef SMALL_SCREEN
  449. { 7, 7, DIFF_EASY, LOOPY_GRID_SQUARE },
  450. { 7, 7, DIFF_NORMAL, LOOPY_GRID_SQUARE },
  451. { 7, 7, DIFF_HARD, LOOPY_GRID_SQUARE },
  452. { 7, 7, DIFF_HARD, LOOPY_GRID_TRIANGULAR },
  453. { 5, 5, DIFF_HARD, LOOPY_GRID_SNUBSQUARE },
  454. { 7, 7, DIFF_HARD, LOOPY_GRID_CAIRO },
  455. { 5, 5, DIFF_HARD, LOOPY_GRID_KITE },
  456. { 6, 6, DIFF_HARD, LOOPY_GRID_PENROSE_P2 },
  457. { 6, 6, DIFF_HARD, LOOPY_GRID_PENROSE_P3 },
  458. #else
  459. { 7, 7, DIFF_EASY, LOOPY_GRID_SQUARE },
  460. { 10, 10, DIFF_EASY, LOOPY_GRID_SQUARE },
  461. { 7, 7, DIFF_NORMAL, LOOPY_GRID_SQUARE },
  462. { 10, 10, DIFF_NORMAL, LOOPY_GRID_SQUARE },
  463. { 7, 7, DIFF_HARD, LOOPY_GRID_SQUARE },
  464. { 10, 10, DIFF_HARD, LOOPY_GRID_SQUARE },
  465. { 12, 10, DIFF_HARD, LOOPY_GRID_TRIANGULAR },
  466. { 7, 7, DIFF_HARD, LOOPY_GRID_SNUBSQUARE },
  467. { 9, 9, DIFF_HARD, LOOPY_GRID_CAIRO },
  468. { 5, 5, DIFF_HARD, LOOPY_GRID_KITE },
  469. { 10, 10, DIFF_HARD, LOOPY_GRID_PENROSE_P2 },
  470. { 10, 10, DIFF_HARD, LOOPY_GRID_PENROSE_P3 },
  471. #endif
  472. };
  473. static const game_params loopy_presets_more[] = {
  474. #ifdef SMALL_SCREEN
  475. { 7, 7, DIFF_HARD, LOOPY_GRID_HONEYCOMB },
  476. { 5, 4, DIFF_HARD, LOOPY_GRID_GREATHEXAGONAL },
  477. { 5, 4, DIFF_HARD, LOOPY_GRID_KAGOME },
  478. { 5, 5, DIFF_HARD, LOOPY_GRID_OCTAGONAL },
  479. { 3, 3, DIFF_HARD, LOOPY_GRID_FLORET },
  480. { 3, 3, DIFF_HARD, LOOPY_GRID_DODECAGONAL },
  481. { 3, 3, DIFF_HARD, LOOPY_GRID_GREATDODECAGONAL },
  482. { 3, 2, DIFF_HARD, LOOPY_GRID_GREATGREATDODECAGONAL },
  483. { 3, 3, DIFF_HARD, LOOPY_GRID_COMPASSDODECAGONAL },
  484. { 6, 6, DIFF_HARD, LOOPY_GRID_HATS },
  485. { 6, 6, DIFF_HARD, LOOPY_GRID_SPECTRES },
  486. #else
  487. { 10, 10, DIFF_HARD, LOOPY_GRID_HONEYCOMB },
  488. { 5, 4, DIFF_HARD, LOOPY_GRID_GREATHEXAGONAL },
  489. { 5, 4, DIFF_HARD, LOOPY_GRID_KAGOME },
  490. { 7, 7, DIFF_HARD, LOOPY_GRID_OCTAGONAL },
  491. { 5, 5, DIFF_HARD, LOOPY_GRID_FLORET },
  492. { 5, 4, DIFF_HARD, LOOPY_GRID_DODECAGONAL },
  493. { 5, 4, DIFF_HARD, LOOPY_GRID_GREATDODECAGONAL },
  494. { 5, 3, DIFF_HARD, LOOPY_GRID_GREATGREATDODECAGONAL },
  495. { 5, 4, DIFF_HARD, LOOPY_GRID_COMPASSDODECAGONAL },
  496. { 10, 10, DIFF_HARD, LOOPY_GRID_HATS },
  497. { 10, 10, DIFF_HARD, LOOPY_GRID_SPECTRES },
  498. #endif
  499. };
  500. static void preset_menu_add_preset_with_title(struct preset_menu *menu,
  501. const game_params *params)
  502. {
  503. char buf[80];
  504. game_params *dup_params;
  505. sprintf(buf, "%dx%d %s - %s", params->h, params->w,
  506. gridnames[params->type], diffnames[params->diff]);
  507. dup_params = snew(game_params);
  508. *dup_params = *params;
  509. preset_menu_add_preset(menu, dupstr(buf), dup_params);
  510. }
  511. static struct preset_menu *game_preset_menu(void)
  512. {
  513. struct preset_menu *top, *more;
  514. int i;
  515. top = preset_menu_new();
  516. for (i = 0; i < lenof(loopy_presets_top); i++)
  517. preset_menu_add_preset_with_title(top, &loopy_presets_top[i]);
  518. more = preset_menu_add_submenu(top, dupstr("More..."));
  519. for (i = 0; i < lenof(loopy_presets_more); i++)
  520. preset_menu_add_preset_with_title(more, &loopy_presets_more[i]);
  521. return top;
  522. }
  523. static void free_params(game_params *params)
  524. {
  525. sfree(params);
  526. }
  527. static void decode_params(game_params *params, char const *string)
  528. {
  529. params->h = params->w = atoi(string);
  530. params->diff = DIFF_EASY;
  531. while (*string && isdigit((unsigned char)*string)) string++;
  532. if (*string == 'x') {
  533. string++;
  534. params->h = atoi(string);
  535. while (*string && isdigit((unsigned char)*string)) string++;
  536. }
  537. if (*string == 't') {
  538. string++;
  539. params->type = atoi(string);
  540. while (*string && isdigit((unsigned char)*string)) string++;
  541. }
  542. if (*string == 'd') {
  543. int i;
  544. string++;
  545. for (i = 0; i < DIFF_MAX; i++)
  546. if (*string == diffchars[i])
  547. params->diff = i;
  548. if (*string) string++;
  549. }
  550. }
  551. static char *encode_params(const game_params *params, bool full)
  552. {
  553. char str[80];
  554. sprintf(str, "%dx%dt%d", params->w, params->h, params->type);
  555. if (full)
  556. sprintf(str + strlen(str), "d%c", diffchars[params->diff]);
  557. return dupstr(str);
  558. }
  559. static config_item *game_configure(const game_params *params)
  560. {
  561. config_item *ret;
  562. char buf[80];
  563. ret = snewn(5, config_item);
  564. ret[0].name = "Width";
  565. ret[0].type = C_STRING;
  566. sprintf(buf, "%d", params->w);
  567. ret[0].u.string.sval = dupstr(buf);
  568. ret[1].name = "Height";
  569. ret[1].type = C_STRING;
  570. sprintf(buf, "%d", params->h);
  571. ret[1].u.string.sval = dupstr(buf);
  572. ret[2].name = "Grid type";
  573. ret[2].type = C_CHOICES;
  574. ret[2].u.choices.choicenames = GRID_CONFIGS;
  575. ret[2].u.choices.selected = params->type;
  576. ret[3].name = "Difficulty";
  577. ret[3].type = C_CHOICES;
  578. ret[3].u.choices.choicenames = DIFFCONFIG;
  579. ret[3].u.choices.selected = params->diff;
  580. ret[4].name = NULL;
  581. ret[4].type = C_END;
  582. return ret;
  583. }
  584. static game_params *custom_params(const config_item *cfg)
  585. {
  586. game_params *ret = snew(game_params);
  587. ret->w = atoi(cfg[0].u.string.sval);
  588. ret->h = atoi(cfg[1].u.string.sval);
  589. ret->type = cfg[2].u.choices.selected;
  590. ret->diff = cfg[3].u.choices.selected;
  591. return ret;
  592. }
  593. static const char *validate_params(const game_params *params, bool full)
  594. {
  595. const char *err;
  596. if (params->type < 0 || params->type >= NUM_GRID_TYPES)
  597. return "Illegal grid type";
  598. if (params->w < grid_size_limits[params->type].amin ||
  599. params->h < grid_size_limits[params->type].amin)
  600. return grid_size_limits[params->type].aerr;
  601. if (params->w < grid_size_limits[params->type].omin &&
  602. params->h < grid_size_limits[params->type].omin)
  603. return grid_size_limits[params->type].oerr;
  604. err = grid_validate_params(grid_types[params->type], params->w, params->h);
  605. if (err != NULL) return err;
  606. /*
  607. * This shouldn't be able to happen at all, since decode_params
  608. * and custom_params will never generate anything that isn't
  609. * within range.
  610. */
  611. assert(params->diff < DIFF_MAX);
  612. return NULL;
  613. }
  614. /* Returns a newly allocated string describing the current puzzle */
  615. static char *state_to_text(const game_state *state)
  616. {
  617. grid *g = state->game_grid;
  618. char *retval;
  619. int num_faces = g->num_faces;
  620. char *description = snewn(num_faces + 1, char);
  621. char *dp = description;
  622. int empty_count = 0;
  623. int i;
  624. for (i = 0; i < num_faces; i++) {
  625. if (state->clues[i] < 0) {
  626. if (empty_count > 25) {
  627. dp += sprintf(dp, "%c", (int)(empty_count + 'a' - 1));
  628. empty_count = 0;
  629. }
  630. empty_count++;
  631. } else {
  632. if (empty_count) {
  633. dp += sprintf(dp, "%c", (int)(empty_count + 'a' - 1));
  634. empty_count = 0;
  635. }
  636. dp += sprintf(dp, "%c", (int)CLUE2CHAR(state->clues[i]));
  637. }
  638. }
  639. if (empty_count)
  640. dp += sprintf(dp, "%c", (int)(empty_count + 'a' - 1));
  641. retval = dupstr(description);
  642. sfree(description);
  643. return retval;
  644. }
  645. #define GRID_DESC_SEP '_'
  646. /* Splits up a (optional) grid_desc from the game desc. Returns the
  647. * grid_desc (which needs freeing) and updates the desc pointer to
  648. * start of real desc, or returns NULL if no desc. */
  649. static char *extract_grid_desc(const char **desc)
  650. {
  651. char *sep = strchr(*desc, GRID_DESC_SEP), *gd;
  652. int gd_len;
  653. if (!sep) return NULL;
  654. gd_len = sep - (*desc);
  655. gd = snewn(gd_len+1, char);
  656. memcpy(gd, *desc, gd_len);
  657. gd[gd_len] = '\0';
  658. *desc = sep+1;
  659. return gd;
  660. }
  661. /* We require that the params pass the test in validate_params and that the
  662. * description fills the entire game area */
  663. static const char *validate_desc(const game_params *params, const char *desc)
  664. {
  665. int count = 0;
  666. grid *g;
  667. char *grid_desc;
  668. const char *ret;
  669. /* It's pretty inefficient to do this just for validation. All we need to
  670. * know is the precise number of faces. */
  671. grid_desc = extract_grid_desc(&desc);
  672. ret = grid_validate_desc(grid_types[params->type], params->w, params->h, grid_desc);
  673. if (ret) {
  674. sfree(grid_desc);
  675. return ret;
  676. }
  677. g = loopy_generate_grid(params, grid_desc);
  678. sfree(grid_desc);
  679. for (; *desc; ++desc) {
  680. if ((*desc >= '0' && *desc <= '9') || (*desc >= 'A' && *desc <= 'Z')) {
  681. count++;
  682. continue;
  683. }
  684. if (*desc >= 'a') {
  685. count += *desc - 'a' + 1;
  686. continue;
  687. }
  688. grid_free(g);
  689. return "Unknown character in description";
  690. }
  691. if (count < g->num_faces) {
  692. grid_free(g);
  693. return "Description too short for board size";
  694. }
  695. if (count > g->num_faces) {
  696. grid_free(g);
  697. return "Description too long for board size";
  698. }
  699. grid_free(g);
  700. return NULL;
  701. }
  702. /* Sums the lengths of the numbers in range [0,n) */
  703. /* See equivalent function in solo.c for justification of this. */
  704. static int len_0_to_n(int n)
  705. {
  706. int len = 1; /* Counting 0 as a bit of a special case */
  707. int i;
  708. for (i = 1; i < n; i *= 10) {
  709. len += max(n - i, 0);
  710. }
  711. return len;
  712. }
  713. static char *encode_solve_move(const game_state *state)
  714. {
  715. int len;
  716. char *ret, *p;
  717. int i;
  718. int num_edges = state->game_grid->num_edges;
  719. /* This is going to return a string representing the moves needed to set
  720. * every line in a grid to be the same as the ones in 'state'. The exact
  721. * length of this string is predictable. */
  722. len = 1; /* Count the 'S' prefix */
  723. /* Numbers in all lines */
  724. len += len_0_to_n(num_edges);
  725. /* For each line we also have a letter */
  726. len += num_edges;
  727. ret = snewn(len + 1, char);
  728. p = ret;
  729. p += sprintf(p, "S");
  730. for (i = 0; i < num_edges; i++) {
  731. switch (state->lines[i]) {
  732. case LINE_YES:
  733. p += sprintf(p, "%dy", i);
  734. break;
  735. case LINE_NO:
  736. p += sprintf(p, "%dn", i);
  737. break;
  738. }
  739. }
  740. /* No point in doing sums like that if they're going to be wrong */
  741. assert(strlen(ret) <= (size_t)len);
  742. return ret;
  743. }
  744. struct game_ui {
  745. /*
  746. * User preference: should grid lines in LINE_NO state be drawn
  747. * very faintly so users can still see where they are, or should
  748. * they be completely invisible?
  749. */
  750. bool draw_faint_lines;
  751. /*
  752. * User preference: when clicking an edge that has only one
  753. * possible edge connecting to one (or both) of its ends, should
  754. * that edge also change to the same state as the edge we just
  755. * clicked?
  756. */
  757. enum {
  758. AF_OFF, /* no, all grid edges are independent in the UI */
  759. AF_FIXED, /* yes, but only based on the grid itself */
  760. AF_ADAPTIVE /* yes, and consider edges user has already set to NO */
  761. } autofollow;
  762. };
  763. static void legacy_prefs_override(struct game_ui *ui_out)
  764. {
  765. static bool initialised = false;
  766. static int draw_faint_lines = -1;
  767. static int autofollow = -1;
  768. if (!initialised) {
  769. char *env;
  770. initialised = true;
  771. draw_faint_lines = getenv_bool("LOOPY_FAINT_LINES", -1);
  772. if ((env = getenv("LOOPY_AUTOFOLLOW")) != NULL) {
  773. if (!strcmp(env, "off"))
  774. autofollow = AF_OFF;
  775. else if (!strcmp(env, "fixed"))
  776. autofollow = AF_FIXED;
  777. else if (!strcmp(env, "adaptive"))
  778. autofollow = AF_ADAPTIVE;
  779. }
  780. }
  781. if (draw_faint_lines != -1)
  782. ui_out->draw_faint_lines = draw_faint_lines;
  783. if (autofollow != -1)
  784. ui_out->autofollow = autofollow;
  785. }
  786. static game_ui *new_ui(const game_state *state)
  787. {
  788. game_ui *ui = snew(game_ui);
  789. ui->draw_faint_lines = true;
  790. ui->autofollow = AF_OFF;
  791. legacy_prefs_override(ui);
  792. return ui;
  793. }
  794. static void free_ui(game_ui *ui)
  795. {
  796. sfree(ui);
  797. }
  798. static config_item *get_prefs(game_ui *ui)
  799. {
  800. config_item *ret;
  801. ret = snewn(3, config_item);
  802. ret[0].name = "Draw excluded grid lines faintly";
  803. ret[0].kw = "draw-faint-lines";
  804. ret[0].type = C_BOOLEAN;
  805. ret[0].u.boolean.bval = ui->draw_faint_lines;
  806. ret[1].name = "Auto-follow unique paths of edges";
  807. ret[1].kw = "auto-follow";
  808. ret[1].type = C_CHOICES;
  809. ret[1].u.choices.choicenames =
  810. ":No:Based on grid only:Based on grid and game state";
  811. ret[1].u.choices.choicekws = ":off:fixed:adaptive";
  812. ret[1].u.choices.selected = ui->autofollow;
  813. ret[2].name = NULL;
  814. ret[2].type = C_END;
  815. return ret;
  816. }
  817. static void set_prefs(game_ui *ui, const config_item *cfg)
  818. {
  819. ui->draw_faint_lines = cfg[0].u.boolean.bval;
  820. ui->autofollow = cfg[1].u.choices.selected;
  821. }
  822. static void game_changed_state(game_ui *ui, const game_state *oldstate,
  823. const game_state *newstate)
  824. {
  825. }
  826. static void game_compute_size(const game_params *params, int tilesize,
  827. const game_ui *ui, int *x, int *y)
  828. {
  829. int grid_width, grid_height, rendered_width, rendered_height;
  830. int g_tilesize;
  831. grid_compute_size(grid_types[params->type], params->w, params->h,
  832. &g_tilesize, &grid_width, &grid_height);
  833. /* multiply first to minimise rounding error on integer division */
  834. rendered_width = grid_width * tilesize / g_tilesize;
  835. rendered_height = grid_height * tilesize / g_tilesize;
  836. *x = rendered_width + 2 * BORDER(tilesize) + 1;
  837. *y = rendered_height + 2 * BORDER(tilesize) + 1;
  838. }
  839. static void game_set_size(drawing *dr, game_drawstate *ds,
  840. const game_params *params, int tilesize)
  841. {
  842. ds->tilesize = tilesize;
  843. }
  844. static float *game_colours(frontend *fe, int *ncolours)
  845. {
  846. float *ret = snewn(3 * NCOLOURS, float);
  847. frontend_default_colour(fe, &ret[COL_BACKGROUND * 3]);
  848. ret[COL_FOREGROUND * 3 + 0] = 0.0F;
  849. ret[COL_FOREGROUND * 3 + 1] = 0.0F;
  850. ret[COL_FOREGROUND * 3 + 2] = 0.0F;
  851. /*
  852. * We want COL_LINEUNKNOWN to be a yellow which is a bit darker
  853. * than the background. (I previously set it to 0.8,0.8,0, but
  854. * found that this went badly with the 0.8,0.8,0.8 favoured as a
  855. * background by the Java frontend.)
  856. */
  857. ret[COL_LINEUNKNOWN * 3 + 0] = ret[COL_BACKGROUND * 3 + 0] * 0.9F;
  858. ret[COL_LINEUNKNOWN * 3 + 1] = ret[COL_BACKGROUND * 3 + 1] * 0.9F;
  859. ret[COL_LINEUNKNOWN * 3 + 2] = 0.0F;
  860. ret[COL_HIGHLIGHT * 3 + 0] = 1.0F;
  861. ret[COL_HIGHLIGHT * 3 + 1] = 1.0F;
  862. ret[COL_HIGHLIGHT * 3 + 2] = 1.0F;
  863. ret[COL_MISTAKE * 3 + 0] = 1.0F;
  864. ret[COL_MISTAKE * 3 + 1] = 0.0F;
  865. ret[COL_MISTAKE * 3 + 2] = 0.0F;
  866. ret[COL_SATISFIED * 3 + 0] = 0.0F;
  867. ret[COL_SATISFIED * 3 + 1] = 0.0F;
  868. ret[COL_SATISFIED * 3 + 2] = 0.0F;
  869. /* We want the faint lines to be a bit darker than the background.
  870. * Except if the background is pretty dark already; then it ought to be a
  871. * bit lighter. Oy vey.
  872. */
  873. ret[COL_FAINT * 3 + 0] = ret[COL_BACKGROUND * 3 + 0] * 0.9F;
  874. ret[COL_FAINT * 3 + 1] = ret[COL_BACKGROUND * 3 + 1] * 0.9F;
  875. ret[COL_FAINT * 3 + 2] = ret[COL_BACKGROUND * 3 + 2] * 0.9F;
  876. *ncolours = NCOLOURS;
  877. return ret;
  878. }
  879. static game_drawstate *game_new_drawstate(drawing *dr, const game_state *state)
  880. {
  881. struct game_drawstate *ds = snew(struct game_drawstate);
  882. int num_faces = state->game_grid->num_faces;
  883. int num_edges = state->game_grid->num_edges;
  884. int i;
  885. ds->tilesize = 0;
  886. ds->started = false;
  887. ds->lines = snewn(num_edges, char);
  888. ds->clue_error = snewn(num_faces, bool);
  889. ds->clue_satisfied = snewn(num_faces, bool);
  890. ds->textx = snewn(num_faces, int);
  891. ds->texty = snewn(num_faces, int);
  892. ds->flashing = false;
  893. memset(ds->lines, LINE_UNKNOWN, num_edges);
  894. memset(ds->clue_error, 0, num_faces * sizeof(bool));
  895. memset(ds->clue_satisfied, 0, num_faces * sizeof(bool));
  896. for (i = 0; i < num_faces; i++)
  897. ds->textx[i] = ds->texty[i] = -1;
  898. return ds;
  899. }
  900. static void game_free_drawstate(drawing *dr, game_drawstate *ds)
  901. {
  902. sfree(ds->textx);
  903. sfree(ds->texty);
  904. sfree(ds->clue_error);
  905. sfree(ds->clue_satisfied);
  906. sfree(ds->lines);
  907. sfree(ds);
  908. }
  909. static float game_anim_length(const game_state *oldstate,
  910. const game_state *newstate, int dir, game_ui *ui)
  911. {
  912. return 0.0F;
  913. }
  914. static bool game_can_format_as_text_now(const game_params *params)
  915. {
  916. if (params->type != 0)
  917. return false;
  918. return true;
  919. }
  920. static char *game_text_format(const game_state *state)
  921. {
  922. int w, h, W, H;
  923. int x, y, i;
  924. int cell_size;
  925. char *ret;
  926. grid *g = state->game_grid;
  927. grid_face *f;
  928. assert(state->grid_type == 0);
  929. /* Work out the basic size unit */
  930. f = g->faces[0]; /* first face */
  931. assert(f->order == 4);
  932. /* The dots are ordered clockwise, so the two opposite
  933. * corners are guaranteed to span the square */
  934. cell_size = abs(f->dots[0]->x - f->dots[2]->x);
  935. w = (g->highest_x - g->lowest_x) / cell_size;
  936. h = (g->highest_y - g->lowest_y) / cell_size;
  937. /* Create a blank "canvas" to "draw" on */
  938. W = 2 * w + 2;
  939. H = 2 * h + 1;
  940. ret = snewn(W * H + 1, char);
  941. for (y = 0; y < H; y++) {
  942. for (x = 0; x < W-1; x++) {
  943. ret[y*W + x] = ' ';
  944. }
  945. ret[y*W + W-1] = '\n';
  946. }
  947. ret[H*W] = '\0';
  948. /* Fill in edge info */
  949. for (i = 0; i < g->num_edges; i++) {
  950. grid_edge *e = g->edges[i];
  951. /* Cell coordinates, from (0,0) to (w-1,h-1) */
  952. int x1 = (e->dot1->x - g->lowest_x) / cell_size;
  953. int x2 = (e->dot2->x - g->lowest_x) / cell_size;
  954. int y1 = (e->dot1->y - g->lowest_y) / cell_size;
  955. int y2 = (e->dot2->y - g->lowest_y) / cell_size;
  956. /* Midpoint, in canvas coordinates (canvas coordinates are just twice
  957. * cell coordinates) */
  958. x = x1 + x2;
  959. y = y1 + y2;
  960. switch (state->lines[i]) {
  961. case LINE_YES:
  962. ret[y*W + x] = (y1 == y2) ? '-' : '|';
  963. break;
  964. case LINE_NO:
  965. ret[y*W + x] = 'x';
  966. break;
  967. case LINE_UNKNOWN:
  968. break; /* already a space */
  969. default:
  970. assert(!"Illegal line state");
  971. }
  972. }
  973. /* Fill in clues */
  974. for (i = 0; i < g->num_faces; i++) {
  975. int x1, x2, y1, y2;
  976. f = g->faces[i];
  977. assert(f->order == 4);
  978. /* Cell coordinates, from (0,0) to (w-1,h-1) */
  979. x1 = (f->dots[0]->x - g->lowest_x) / cell_size;
  980. x2 = (f->dots[2]->x - g->lowest_x) / cell_size;
  981. y1 = (f->dots[0]->y - g->lowest_y) / cell_size;
  982. y2 = (f->dots[2]->y - g->lowest_y) / cell_size;
  983. /* Midpoint, in canvas coordinates */
  984. x = x1 + x2;
  985. y = y1 + y2;
  986. ret[y*W + x] = CLUE2CHAR(state->clues[i]);
  987. }
  988. return ret;
  989. }
  990. /* ----------------------------------------------------------------------
  991. * Debug code
  992. */
  993. #ifdef DEBUG_CACHES
  994. static void check_caches(const solver_state* sstate)
  995. {
  996. int i;
  997. const game_state *state = sstate->state;
  998. const grid *g = state->game_grid;
  999. for (i = 0; i < g->num_dots; i++) {
  1000. assert(dot_order(state, i, LINE_YES) == sstate->dot_yes_count[i]);
  1001. assert(dot_order(state, i, LINE_NO) == sstate->dot_no_count[i]);
  1002. }
  1003. for (i = 0; i < g->num_faces; i++) {
  1004. assert(face_order(state, i, LINE_YES) == sstate->face_yes_count[i]);
  1005. assert(face_order(state, i, LINE_NO) == sstate->face_no_count[i]);
  1006. }
  1007. }
  1008. #if 0
  1009. #define check_caches(s) \
  1010. do { \
  1011. fprintf(stderr, "check_caches at line %d\n", __LINE__); \
  1012. check_caches(s); \
  1013. } while (0)
  1014. #endif
  1015. #endif /* DEBUG_CACHES */
  1016. /* ----------------------------------------------------------------------
  1017. * Solver utility functions
  1018. */
  1019. /* Sets the line (with index i) to the new state 'line_new', and updates
  1020. * the cached counts of any affected faces and dots.
  1021. * Returns true if this actually changed the line's state. */
  1022. static bool solver_set_line(solver_state *sstate, int i,
  1023. enum line_state line_new
  1024. #ifdef SHOW_WORKING
  1025. , const char *reason
  1026. #endif
  1027. )
  1028. {
  1029. game_state *state = sstate->state;
  1030. grid *g;
  1031. grid_edge *e;
  1032. assert(line_new != LINE_UNKNOWN);
  1033. check_caches(sstate);
  1034. if (state->lines[i] == line_new) {
  1035. return false; /* nothing changed */
  1036. }
  1037. state->lines[i] = line_new;
  1038. #ifdef SHOW_WORKING
  1039. fprintf(stderr, "solver: set line [%d] to %s (%s)\n",
  1040. i, line_new == LINE_YES ? "YES" : "NO",
  1041. reason);
  1042. #endif
  1043. g = state->game_grid;
  1044. e = g->edges[i];
  1045. /* Update the cache for both dots and both faces affected by this. */
  1046. if (line_new == LINE_YES) {
  1047. sstate->dot_yes_count[e->dot1->index]++;
  1048. sstate->dot_yes_count[e->dot2->index]++;
  1049. if (e->face1) {
  1050. sstate->face_yes_count[e->face1->index]++;
  1051. }
  1052. if (e->face2) {
  1053. sstate->face_yes_count[e->face2->index]++;
  1054. }
  1055. } else {
  1056. sstate->dot_no_count[e->dot1->index]++;
  1057. sstate->dot_no_count[e->dot2->index]++;
  1058. if (e->face1) {
  1059. sstate->face_no_count[e->face1->index]++;
  1060. }
  1061. if (e->face2) {
  1062. sstate->face_no_count[e->face2->index]++;
  1063. }
  1064. }
  1065. check_caches(sstate);
  1066. return true;
  1067. }
  1068. #ifdef SHOW_WORKING
  1069. #define solver_set_line(a, b, c) \
  1070. solver_set_line(a, b, c, __FUNCTION__)
  1071. #endif
  1072. /*
  1073. * Merge two dots due to the existence of an edge between them.
  1074. * Updates the dsf tracking equivalence classes, and keeps track of
  1075. * the length of path each dot is currently a part of.
  1076. * Returns true if the dots were already linked, ie if they are part of a
  1077. * closed loop, and false otherwise.
  1078. */
  1079. static bool merge_dots(solver_state *sstate, int edge_index)
  1080. {
  1081. int i, j, len;
  1082. grid *g = sstate->state->game_grid;
  1083. grid_edge *e = g->edges[edge_index];
  1084. i = e->dot1->index;
  1085. j = e->dot2->index;
  1086. i = dsf_canonify(sstate->dotdsf, i);
  1087. j = dsf_canonify(sstate->dotdsf, j);
  1088. if (i == j) {
  1089. return true;
  1090. } else {
  1091. len = sstate->looplen[i] + sstate->looplen[j];
  1092. dsf_merge(sstate->dotdsf, i, j);
  1093. i = dsf_canonify(sstate->dotdsf, i);
  1094. sstate->looplen[i] = len;
  1095. return false;
  1096. }
  1097. }
  1098. /* Merge two lines because the solver has deduced that they must be either
  1099. * identical or opposite. Returns true if this is new information, otherwise
  1100. * false. */
  1101. static bool merge_lines(solver_state *sstate, int i, int j, bool inverse
  1102. #ifdef SHOW_WORKING
  1103. , const char *reason
  1104. #endif
  1105. )
  1106. {
  1107. bool inv_tmp;
  1108. assert(i < sstate->state->game_grid->num_edges);
  1109. assert(j < sstate->state->game_grid->num_edges);
  1110. i = dsf_canonify_flip(sstate->linedsf, i, &inv_tmp);
  1111. inverse ^= inv_tmp;
  1112. j = dsf_canonify_flip(sstate->linedsf, j, &inv_tmp);
  1113. inverse ^= inv_tmp;
  1114. dsf_merge_flip(sstate->linedsf, i, j, inverse);
  1115. #ifdef SHOW_WORKING
  1116. if (i != j) {
  1117. fprintf(stderr, "%s [%d] [%d] %s(%s)\n",
  1118. __FUNCTION__, i, j,
  1119. inverse ? "inverse " : "", reason);
  1120. }
  1121. #endif
  1122. return (i != j);
  1123. }
  1124. #ifdef SHOW_WORKING
  1125. #define merge_lines(a, b, c, d) \
  1126. merge_lines(a, b, c, d, __FUNCTION__)
  1127. #endif
  1128. /* Count the number of lines of a particular type currently going into the
  1129. * given dot. */
  1130. static int dot_order(const game_state* state, int dot, char line_type)
  1131. {
  1132. int n = 0;
  1133. grid *g = state->game_grid;
  1134. grid_dot *d = g->dots[dot];
  1135. int i;
  1136. for (i = 0; i < d->order; i++) {
  1137. grid_edge *e = d->edges[i];
  1138. if (state->lines[e->index] == line_type)
  1139. ++n;
  1140. }
  1141. return n;
  1142. }
  1143. /* Count the number of lines of a particular type currently surrounding the
  1144. * given face */
  1145. static int face_order(const game_state* state, int face, char line_type)
  1146. {
  1147. int n = 0;
  1148. grid *g = state->game_grid;
  1149. grid_face *f = g->faces[face];
  1150. int i;
  1151. for (i = 0; i < f->order; i++) {
  1152. grid_edge *e = f->edges[i];
  1153. if (state->lines[e->index] == line_type)
  1154. ++n;
  1155. }
  1156. return n;
  1157. }
  1158. /* Set all lines bordering a dot of type old_type to type new_type
  1159. * Return value tells caller whether this function actually did anything */
  1160. static bool dot_setall(solver_state *sstate, int dot,
  1161. char old_type, char new_type)
  1162. {
  1163. bool retval = false, r;
  1164. game_state *state = sstate->state;
  1165. grid *g;
  1166. grid_dot *d;
  1167. int i;
  1168. if (old_type == new_type)
  1169. return false;
  1170. g = state->game_grid;
  1171. d = g->dots[dot];
  1172. for (i = 0; i < d->order; i++) {
  1173. int line_index = d->edges[i]->index;
  1174. if (state->lines[line_index] == old_type) {
  1175. r = solver_set_line(sstate, line_index, new_type);
  1176. assert(r);
  1177. retval = true;
  1178. }
  1179. }
  1180. return retval;
  1181. }
  1182. /* Set all lines bordering a face of type old_type to type new_type */
  1183. static bool face_setall(solver_state *sstate, int face,
  1184. char old_type, char new_type)
  1185. {
  1186. bool retval = false, r;
  1187. game_state *state = sstate->state;
  1188. grid *g;
  1189. grid_face *f;
  1190. int i;
  1191. if (old_type == new_type)
  1192. return false;
  1193. g = state->game_grid;
  1194. f = g->faces[face];
  1195. for (i = 0; i < f->order; i++) {
  1196. int line_index = f->edges[i]->index;
  1197. if (state->lines[line_index] == old_type) {
  1198. r = solver_set_line(sstate, line_index, new_type);
  1199. assert(r);
  1200. retval = true;
  1201. }
  1202. }
  1203. return retval;
  1204. }
  1205. /* ----------------------------------------------------------------------
  1206. * Loop generation and clue removal
  1207. */
  1208. static void add_full_clues(game_state *state, random_state *rs)
  1209. {
  1210. signed char *clues = state->clues;
  1211. grid *g = state->game_grid;
  1212. char *board = snewn(g->num_faces, char);
  1213. int i;
  1214. generate_loop(g, board, rs, NULL, NULL);
  1215. /* Fill out all the clues by initialising to 0, then iterating over
  1216. * all edges and incrementing each clue as we find edges that border
  1217. * between BLACK/WHITE faces. While we're at it, we verify that the
  1218. * algorithm does work, and there aren't any GREY faces still there. */
  1219. memset(clues, 0, g->num_faces);
  1220. for (i = 0; i < g->num_edges; i++) {
  1221. grid_edge *e = g->edges[i];
  1222. grid_face *f1 = e->face1;
  1223. grid_face *f2 = e->face2;
  1224. enum face_colour c1 = FACE_COLOUR(f1);
  1225. enum face_colour c2 = FACE_COLOUR(f2);
  1226. assert(c1 != FACE_GREY);
  1227. assert(c2 != FACE_GREY);
  1228. if (c1 != c2) {
  1229. if (f1) clues[f1->index]++;
  1230. if (f2) clues[f2->index]++;
  1231. }
  1232. }
  1233. sfree(board);
  1234. }
  1235. static bool game_has_unique_soln(const game_state *state, int diff)
  1236. {
  1237. bool ret;
  1238. solver_state *sstate_new;
  1239. solver_state *sstate = new_solver_state(state, diff);
  1240. sstate_new = solve_game_rec(sstate);
  1241. assert(sstate_new->solver_status != SOLVER_MISTAKE);
  1242. ret = (sstate_new->solver_status == SOLVER_SOLVED);
  1243. free_solver_state(sstate_new);
  1244. free_solver_state(sstate);
  1245. return ret;
  1246. }
  1247. /* Remove clues one at a time at random. */
  1248. static game_state *remove_clues(game_state *state, random_state *rs,
  1249. int diff)
  1250. {
  1251. int *face_list;
  1252. int num_faces = state->game_grid->num_faces;
  1253. game_state *ret = dup_game(state), *saved_ret;
  1254. int n;
  1255. /* We need to remove some clues. We'll do this by forming a list of all
  1256. * available clues, shuffling it, then going along one at a
  1257. * time clearing each clue in turn for which doing so doesn't render the
  1258. * board unsolvable. */
  1259. face_list = snewn(num_faces, int);
  1260. for (n = 0; n < num_faces; ++n) {
  1261. face_list[n] = n;
  1262. }
  1263. shuffle(face_list, num_faces, sizeof(int), rs);
  1264. for (n = 0; n < num_faces; ++n) {
  1265. saved_ret = dup_game(ret);
  1266. ret->clues[face_list[n]] = -1;
  1267. if (game_has_unique_soln(ret, diff)) {
  1268. free_game(saved_ret);
  1269. } else {
  1270. free_game(ret);
  1271. ret = saved_ret;
  1272. }
  1273. }
  1274. sfree(face_list);
  1275. return ret;
  1276. }
  1277. static char *new_game_desc(const game_params *params, random_state *rs,
  1278. char **aux, bool interactive)
  1279. {
  1280. /* solution and description both use run-length encoding in obvious ways */
  1281. char *retval, *game_desc, *grid_desc;
  1282. grid *g;
  1283. game_state *state = snew(game_state);
  1284. game_state *state_new;
  1285. grid_desc = grid_new_desc(grid_types[params->type], params->w, params->h, rs);
  1286. state->game_grid = g = loopy_generate_grid(params, grid_desc);
  1287. state->clues = snewn(g->num_faces, signed char);
  1288. state->lines = snewn(g->num_edges, char);
  1289. state->line_errors = snewn(g->num_edges, bool);
  1290. state->exactly_one_loop = false;
  1291. state->grid_type = params->type;
  1292. newboard_please:
  1293. memset(state->lines, LINE_UNKNOWN, g->num_edges);
  1294. memset(state->line_errors, 0, g->num_edges * sizeof(bool));
  1295. state->solved = false;
  1296. state->cheated = false;
  1297. /* Get a new random solvable board with all its clues filled in. Yes, this
  1298. * can loop for ever if the params are suitably unfavourable, but
  1299. * preventing games smaller than 4x4 seems to stop this happening */
  1300. do {
  1301. add_full_clues(state, rs);
  1302. } while (!game_has_unique_soln(state, params->diff));
  1303. state_new = remove_clues(state, rs, params->diff);
  1304. free_game(state);
  1305. state = state_new;
  1306. if (params->diff > 0 && game_has_unique_soln(state, params->diff-1)) {
  1307. #ifdef SHOW_WORKING
  1308. fprintf(stderr, "Rejecting board, it is too easy\n");
  1309. #endif
  1310. goto newboard_please;
  1311. }
  1312. game_desc = state_to_text(state);
  1313. free_game(state);
  1314. if (grid_desc) {
  1315. retval = snewn(strlen(grid_desc) + 1 + strlen(game_desc) + 1, char);
  1316. sprintf(retval, "%s%c%s", grid_desc, (int)GRID_DESC_SEP, game_desc);
  1317. sfree(grid_desc);
  1318. sfree(game_desc);
  1319. } else {
  1320. retval = game_desc;
  1321. }
  1322. assert(!validate_desc(params, retval));
  1323. return retval;
  1324. }
  1325. static game_state *new_game(midend *me, const game_params *params,
  1326. const char *desc)
  1327. {
  1328. int i;
  1329. game_state *state = snew(game_state);
  1330. int empties_to_make = 0;
  1331. int n,n2;
  1332. const char *dp;
  1333. char *grid_desc;
  1334. grid *g;
  1335. int num_faces, num_edges;
  1336. grid_desc = extract_grid_desc(&desc);
  1337. state->game_grid = g = loopy_generate_grid(params, grid_desc);
  1338. if (grid_desc) sfree(grid_desc);
  1339. dp = desc;
  1340. num_faces = g->num_faces;
  1341. num_edges = g->num_edges;
  1342. state->clues = snewn(num_faces, signed char);
  1343. state->lines = snewn(num_edges, char);
  1344. state->line_errors = snewn(num_edges, bool);
  1345. state->exactly_one_loop = false;
  1346. state->solved = state->cheated = false;
  1347. state->grid_type = params->type;
  1348. for (i = 0; i < num_faces; i++) {
  1349. if (empties_to_make) {
  1350. empties_to_make--;
  1351. state->clues[i] = -1;
  1352. continue;
  1353. }
  1354. assert(*dp);
  1355. n = *dp - '0';
  1356. n2 = *dp - 'A' + 10;
  1357. if (n >= 0 && n < 10) {
  1358. state->clues[i] = n;
  1359. } else if (n2 >= 10 && n2 < 36) {
  1360. state->clues[i] = n2;
  1361. } else {
  1362. n = *dp - 'a' + 1;
  1363. assert(n > 0);
  1364. state->clues[i] = -1;
  1365. empties_to_make = n - 1;
  1366. }
  1367. ++dp;
  1368. }
  1369. memset(state->lines, LINE_UNKNOWN, num_edges);
  1370. memset(state->line_errors, 0, num_edges * sizeof(bool));
  1371. return state;
  1372. }
  1373. /* Calculates the line_errors data, and checks if the current state is a
  1374. * solution */
  1375. static bool check_completion(game_state *state)
  1376. {
  1377. grid *g = state->game_grid;
  1378. int i;
  1379. bool ret;
  1380. DSF *dsf;
  1381. int *component_state;
  1382. int nsilly, nloop, npath, largest_comp, largest_size, total_pathsize;
  1383. enum { COMP_NONE, COMP_LOOP, COMP_PATH, COMP_SILLY, COMP_EMPTY };
  1384. memset(state->line_errors, 0, g->num_edges * sizeof(bool));
  1385. /*
  1386. * Find loops in the grid, and determine whether the puzzle is
  1387. * solved.
  1388. *
  1389. * Loopy is a bit more complicated than most puzzles that care
  1390. * about loop detection. In most of them, loops are simply
  1391. * _forbidden_; so the obviously right way to do
  1392. * error-highlighting during play is to light up a graph edge red
  1393. * iff it is part of a loop, which is exactly what the centralised
  1394. * findloop.c makes easy.
  1395. *
  1396. * But Loopy is unusual in that you're _supposed_ to be making a
  1397. * loop - and yet _some_ loops are not the right loop. So we need
  1398. * to be more discriminating, by identifying loops one by one and
  1399. * then thinking about which ones to highlight, and so findloop.c
  1400. * isn't quite the right tool for the job in this case.
  1401. *
  1402. * Worse still, consider situations in which the grid contains a
  1403. * loop and also some non-loop edges: there are some cases like
  1404. * this in which the user's intuitive expectation would be to
  1405. * highlight the loop (if you're only about half way through the
  1406. * puzzle and have accidentally made a little loop in some corner
  1407. * of the grid), and others in which they'd be more likely to
  1408. * expect you to highlight the non-loop edges (if you've just
  1409. * closed off a whole loop that you thought was the entire
  1410. * solution, but forgot some disconnected edges in a corner
  1411. * somewhere). So while it's easy enough to check whether the
  1412. * solution is _right_, highlighting the wrong parts is a tricky
  1413. * problem for this puzzle!
  1414. *
  1415. * I'd quite like, in some situations, to identify the largest
  1416. * loop among the player's YES edges, and then light up everything
  1417. * other than that. But finding the longest cycle in a graph is an
  1418. * NP-complete problem (because, in particular, it must return a
  1419. * Hamilton cycle if one exists).
  1420. *
  1421. * However, I think we can make the problem tractable by
  1422. * exercising the Puzzles principle that it isn't absolutely
  1423. * necessary to highlight _all_ errors: the key point is that by
  1424. * the time the user has filled in the whole grid, they should
  1425. * either have seen a completion flash, or have _some_ error
  1426. * highlight showing them why the solution isn't right. So in
  1427. * principle it would be *just about* good enough to highlight
  1428. * just one error in the whole grid, if there was really no better
  1429. * way. But we'd like to highlight as many errors as possible.
  1430. *
  1431. * In this case, I think the simple approach is to make use of the
  1432. * fact that no vertex may have degree > 2, and that's really
  1433. * simple to detect. So the plan goes like this:
  1434. *
  1435. * - Form the dsf of connected components of the graph vertices.
  1436. *
  1437. * - Highlight an error at any vertex with degree > 2. (It so
  1438. * happens that we do this by lighting up all the edges
  1439. * incident to that vertex, but that's an output detail.)
  1440. *
  1441. * - Any component that contains such a vertex is now excluded
  1442. * from further consideration, because it already has a
  1443. * highlight.
  1444. *
  1445. * - The remaining components have no vertex with degree > 2, and
  1446. * hence they all consist of either a simple loop, or a simple
  1447. * path with two endpoints.
  1448. *
  1449. * - For these purposes, group together all the paths and imagine
  1450. * them to be a single component (because in most normal
  1451. * situations the player will gradually build up the solution
  1452. * _not_ all in one connected segment, but as lots of separate
  1453. * little path pieces that gradually connect to each other).
  1454. *
  1455. * - After doing that, if there is exactly one (sensible)
  1456. * component - be it a collection of paths or a loop - then
  1457. * highlight no further edge errors. (The former case is normal
  1458. * during play, and the latter is a potentially solved puzzle.)
  1459. *
  1460. * - Otherwise, find the largest of the sensible components,
  1461. * leave that one unhighlighted, and light the rest up in red.
  1462. */
  1463. dsf = dsf_new(g->num_dots);
  1464. /* Build the dsf. */
  1465. for (i = 0; i < g->num_edges; i++) {
  1466. if (state->lines[i] == LINE_YES) {
  1467. grid_edge *e = g->edges[i];
  1468. int d1 = e->dot1->index, d2 = e->dot2->index;
  1469. dsf_merge(dsf, d1, d2);
  1470. }
  1471. }
  1472. /* Initialise a state variable for each connected component. */
  1473. component_state = snewn(g->num_dots, int);
  1474. for (i = 0; i < g->num_dots; i++) {
  1475. if (dsf_canonify(dsf, i) == i)
  1476. component_state[i] = COMP_LOOP;
  1477. else
  1478. component_state[i] = COMP_NONE;
  1479. }
  1480. /* Check for dots with degree > 3. Here we also spot dots of
  1481. * degree 1 in which the user has marked all the non-edges as
  1482. * LINE_NO, because those are also clear vertex-level errors, so
  1483. * we give them the same treatment of excluding their connected
  1484. * component from the subsequent loop analysis. */
  1485. for (i = 0; i < g->num_dots; i++) {
  1486. int comp = dsf_canonify(dsf, i);
  1487. int yes = dot_order(state, i, LINE_YES);
  1488. int unknown = dot_order(state, i, LINE_UNKNOWN);
  1489. if ((yes == 1 && unknown == 0) || (yes >= 3)) {
  1490. /* violation, so mark all YES edges as errors */
  1491. grid_dot *d = g->dots[i];
  1492. int j;
  1493. for (j = 0; j < d->order; j++) {
  1494. int e = d->edges[j]->index;
  1495. if (state->lines[e] == LINE_YES)
  1496. state->line_errors[e] = true;
  1497. }
  1498. /* And mark this component as not worthy of further
  1499. * consideration. */
  1500. component_state[comp] = COMP_SILLY;
  1501. } else if (yes == 0) {
  1502. /* A completely isolated dot must also be excluded it from
  1503. * the subsequent loop highlighting pass, but we tag it
  1504. * with a different enum value to avoid it counting
  1505. * towards the components that inhibit returning a win
  1506. * status. */
  1507. component_state[comp] = COMP_EMPTY;
  1508. } else if (yes == 1) {
  1509. /* A dot with degree 1 that didn't fall into the 'clearly
  1510. * erroneous' case above indicates that this connected
  1511. * component will be a path rather than a loop - unless
  1512. * something worse elsewhere in the component has
  1513. * classified it as silly. */
  1514. if (component_state[comp] != COMP_SILLY)
  1515. component_state[comp] = COMP_PATH;
  1516. }
  1517. }
  1518. /* Count up the components. Also, find the largest sensible
  1519. * component. (Tie-breaking condition is derived from the order of
  1520. * vertices in the grid data structure, which is fairly arbitrary
  1521. * but at least stays stable throughout the game.) */
  1522. nsilly = nloop = npath = 0;
  1523. total_pathsize = 0;
  1524. largest_comp = largest_size = -1;
  1525. for (i = 0; i < g->num_dots; i++) {
  1526. if (component_state[i] == COMP_SILLY) {
  1527. nsilly++;
  1528. } else if (component_state[i] == COMP_PATH) {
  1529. total_pathsize += dsf_size(dsf, i);
  1530. npath = 1;
  1531. } else if (component_state[i] == COMP_LOOP) {
  1532. int this_size;
  1533. nloop++;
  1534. if ((this_size = dsf_size(dsf, i)) > largest_size) {
  1535. largest_comp = i;
  1536. largest_size = this_size;
  1537. }
  1538. }
  1539. }
  1540. if (largest_size < total_pathsize) {
  1541. largest_comp = -1; /* means the paths */
  1542. largest_size = total_pathsize;
  1543. }
  1544. if (nloop > 0 && nloop + npath > 1) {
  1545. /*
  1546. * If there are at least two sensible components including at
  1547. * least one loop, highlight all edges in every sensible
  1548. * component that is not the largest one.
  1549. */
  1550. for (i = 0; i < g->num_edges; i++) {
  1551. if (state->lines[i] == LINE_YES) {
  1552. grid_edge *e = g->edges[i];
  1553. int d1 = e->dot1->index; /* either endpoint is good enough */
  1554. int comp = dsf_canonify(dsf, d1);
  1555. if ((component_state[comp] == COMP_PATH &&
  1556. -1 != largest_comp) ||
  1557. (component_state[comp] == COMP_LOOP &&
  1558. comp != largest_comp))
  1559. state->line_errors[i] = true;
  1560. }
  1561. }
  1562. }
  1563. if (nloop == 1 && npath == 0 && nsilly == 0) {
  1564. /*
  1565. * If there is exactly one component and it is a loop, then
  1566. * the puzzle is potentially complete, so check the clues.
  1567. */
  1568. ret = true;
  1569. for (i = 0; i < g->num_faces; i++) {
  1570. int c = state->clues[i];
  1571. if (c >= 0 && face_order(state, i, LINE_YES) != c) {
  1572. ret = false;
  1573. break;
  1574. }
  1575. }
  1576. /*
  1577. * Also, whether or not the puzzle is actually complete, set
  1578. * the flag that says this game_state has exactly one loop and
  1579. * nothing else, which will be used to vary the semantics of
  1580. * clue highlighting at display time.
  1581. */
  1582. state->exactly_one_loop = true;
  1583. } else {
  1584. ret = false;
  1585. state->exactly_one_loop = false;
  1586. }
  1587. sfree(component_state);
  1588. dsf_free(dsf);
  1589. return ret;
  1590. }
  1591. /* ----------------------------------------------------------------------
  1592. * Solver logic
  1593. *
  1594. * Our solver modes operate as follows. Each mode also uses the modes above it.
  1595. *
  1596. * Easy Mode
  1597. * Just implement the rules of the game.
  1598. *
  1599. * Normal and Tricky Modes
  1600. * For each (adjacent) pair of lines through each dot we store a bit for
  1601. * whether at least one of them is on and whether at most one is on. (If we
  1602. * know both or neither is on that's already stored more directly.)
  1603. *
  1604. * Advanced Mode
  1605. * Use flip dsf data structure to make equivalence classes of lines that are
  1606. * known identical to or opposite to one another.
  1607. */
  1608. /* DLines:
  1609. * For general grids, we consider "dlines" to be pairs of lines joined
  1610. * at a dot. The lines must be adjacent around the dot, so we can think of
  1611. * a dline as being a dot+face combination. Or, a dot+edge combination where
  1612. * the second edge is taken to be the next clockwise edge from the dot.
  1613. * Original loopy code didn't have this extra restriction of the lines being
  1614. * adjacent. From my tests with square grids, this extra restriction seems to
  1615. * take little, if anything, away from the quality of the puzzles.
  1616. * A dline can be uniquely identified by an edge/dot combination, given that
  1617. * a dline-pair always goes clockwise around its common dot. The edge/dot
  1618. * combination can be represented by an edge/bool combination - if bool is
  1619. * true, use edge->dot1 else use edge->dot2. So the total number of dlines is
  1620. * exactly twice the number of edges in the grid - although the dlines
  1621. * spanning the infinite face are not all that useful to the solver.
  1622. * Note that, by convention, a dline goes clockwise around its common dot,
  1623. * which means the dline goes anti-clockwise around its common face.
  1624. */
  1625. /* Helper functions for obtaining an index into an array of dlines, given
  1626. * various information. We assume the grid layout conventions about how
  1627. * the various lists are interleaved - see grid_make_consistent() for
  1628. * details. */
  1629. /* i points to the first edge of the dline pair, reading clockwise around
  1630. * the dot. */
  1631. static int dline_index_from_dot(grid *g, grid_dot *d, int i)
  1632. {
  1633. grid_edge *e = d->edges[i];
  1634. int ret;
  1635. #ifdef DEBUG_DLINES
  1636. grid_edge *e2;
  1637. int i2 = i+1;
  1638. if (i2 == d->order) i2 = 0;
  1639. e2 = d->edges[i2];
  1640. #endif
  1641. ret = 2 * (e->index) + ((e->dot1 == d) ? 1 : 0);
  1642. #ifdef DEBUG_DLINES
  1643. printf("dline_index_from_dot: d=%d,i=%d, edges [%d,%d] - %d\n",
  1644. (int)(d->index), i, (int)(e->index), (int)(e2 ->index), ret);
  1645. #endif
  1646. return ret;
  1647. }
  1648. /* i points to the second edge of the dline pair, reading clockwise around
  1649. * the face. That is, the edges of the dline, starting at edge{i}, read
  1650. * anti-clockwise around the face. By layout conventions, the common dot
  1651. * of the dline will be f->dots[i] */
  1652. static int dline_index_from_face(grid *g, grid_face *f, int i)
  1653. {
  1654. grid_edge *e = f->edges[i];
  1655. grid_dot *d = f->dots[i];
  1656. int ret;
  1657. #ifdef DEBUG_DLINES
  1658. grid_edge *e2;
  1659. int i2 = i - 1;
  1660. if (i2 < 0) i2 += f->order;
  1661. e2 = f->edges[i2];
  1662. #endif
  1663. ret = 2 * (e->index) + ((e->dot1 == d) ? 1 : 0);
  1664. #ifdef DEBUG_DLINES
  1665. printf("dline_index_from_face: f=%d,i=%d, edges [%d,%d] - %d\n",
  1666. (int)(f->index), i, (int)(e->index), (int)(e2->index), ret);
  1667. #endif
  1668. return ret;
  1669. }
  1670. static bool is_atleastone(const char *dline_array, int index)
  1671. {
  1672. return BIT_SET(dline_array[index], 0);
  1673. }
  1674. static bool set_atleastone(char *dline_array, int index)
  1675. {
  1676. return SET_BIT(dline_array[index], 0);
  1677. }
  1678. static bool is_atmostone(const char *dline_array, int index)
  1679. {
  1680. return BIT_SET(dline_array[index], 1);
  1681. }
  1682. static bool set_atmostone(char *dline_array, int index)
  1683. {
  1684. return SET_BIT(dline_array[index], 1);
  1685. }
  1686. static void array_setall(char *array, char from, char to, int len)
  1687. {
  1688. char *p = array, *p_old = p;
  1689. int len_remaining = len;
  1690. while ((p = memchr(p, from, len_remaining))) {
  1691. *p = to;
  1692. len_remaining -= p - p_old;
  1693. p_old = p;
  1694. }
  1695. }
  1696. /* Helper, called when doing dline dot deductions, in the case where we
  1697. * have 4 UNKNOWNs, and two of them (adjacent) have *exactly* one YES between
  1698. * them (because of dline atmostone/atleastone).
  1699. * On entry, edge points to the first of these two UNKNOWNs. This function
  1700. * will find the opposite UNKNOWNS (if they are adjacent to one another)
  1701. * and set their corresponding dline to atleastone. (Setting atmostone
  1702. * already happens in earlier dline deductions) */
  1703. static bool dline_set_opp_atleastone(solver_state *sstate,
  1704. grid_dot *d, int edge)
  1705. {
  1706. game_state *state = sstate->state;
  1707. grid *g = state->game_grid;
  1708. int N = d->order;
  1709. int opp, opp2;
  1710. for (opp = 0; opp < N; opp++) {
  1711. int opp_dline_index;
  1712. if (opp == edge || opp == edge+1 || opp == edge-1)
  1713. continue;
  1714. if (opp == 0 && edge == N-1)
  1715. continue;
  1716. if (opp == N-1 && edge == 0)
  1717. continue;
  1718. opp2 = opp + 1;
  1719. if (opp2 == N) opp2 = 0;
  1720. /* Check if opp, opp2 point to LINE_UNKNOWNs */
  1721. if (state->lines[d->edges[opp]->index] != LINE_UNKNOWN)
  1722. continue;
  1723. if (state->lines[d->edges[opp2]->index] != LINE_UNKNOWN)
  1724. continue;
  1725. /* Found opposite UNKNOWNS and they're next to each other */
  1726. opp_dline_index = dline_index_from_dot(g, d, opp);
  1727. return set_atleastone(sstate->dlines, opp_dline_index);
  1728. }
  1729. return false;
  1730. }
  1731. /* Set pairs of lines around this face which are known to be identical, to
  1732. * the given line_state */
  1733. static bool face_setall_identical(solver_state *sstate, int face_index,
  1734. enum line_state line_new)
  1735. {
  1736. /* can[dir] contains the canonical line associated with the line in
  1737. * direction dir from the square in question. Similarly inv[dir] is
  1738. * whether or not the line in question is inverse to its canonical
  1739. * element. */
  1740. bool retval = false;
  1741. game_state *state = sstate->state;
  1742. grid *g = state->game_grid;
  1743. grid_face *f = g->faces[face_index];
  1744. int N = f->order;
  1745. int i, j;
  1746. int can1, can2;
  1747. bool inv1, inv2;
  1748. for (i = 0; i < N; i++) {
  1749. int line1_index = f->edges[i]->index;
  1750. if (state->lines[line1_index] != LINE_UNKNOWN)
  1751. continue;
  1752. for (j = i + 1; j < N; j++) {
  1753. int line2_index = f->edges[j]->index;
  1754. if (state->lines[line2_index] != LINE_UNKNOWN)
  1755. continue;
  1756. /* Found two UNKNOWNS */
  1757. can1 = dsf_canonify_flip(sstate->linedsf, line1_index, &inv1);
  1758. can2 = dsf_canonify_flip(sstate->linedsf, line2_index, &inv2);
  1759. if (can1 == can2 && inv1 == inv2) {
  1760. solver_set_line(sstate, line1_index, line_new);
  1761. solver_set_line(sstate, line2_index, line_new);
  1762. }
  1763. }
  1764. }
  1765. return retval;
  1766. }
  1767. /* Given a dot or face, and a count of LINE_UNKNOWNs, find them and
  1768. * return the edge indices into e. */
  1769. static void find_unknowns(game_state *state,
  1770. grid_edge **edge_list, /* Edge list to search (from a face or a dot) */
  1771. int expected_count, /* Number of UNKNOWNs (comes from solver's cache) */
  1772. int *e /* Returned edge indices */)
  1773. {
  1774. int c = 0;
  1775. while (c < expected_count) {
  1776. int line_index = (*edge_list)->index;
  1777. if (state->lines[line_index] == LINE_UNKNOWN) {
  1778. e[c] = line_index;
  1779. c++;
  1780. }
  1781. ++edge_list;
  1782. }
  1783. }
  1784. /* If we have a list of edges, and we know whether the number of YESs should
  1785. * be odd or even, and there are only a few UNKNOWNs, we can do some simple
  1786. * linedsf deductions. This can be used for both face and dot deductions.
  1787. * Returns the difficulty level of the next solver that should be used,
  1788. * or DIFF_MAX if no progress was made. */
  1789. static int parity_deductions(solver_state *sstate,
  1790. grid_edge **edge_list, /* Edge list (from a face or a dot) */
  1791. int total_parity, /* Expected number of YESs modulo 2 (either 0 or 1) */
  1792. int unknown_count)
  1793. {
  1794. game_state *state = sstate->state;
  1795. int diff = DIFF_MAX;
  1796. DSF *linedsf = sstate->linedsf;
  1797. if (unknown_count == 2) {
  1798. /* Lines are known alike/opposite, depending on inv. */
  1799. int e[2];
  1800. find_unknowns(state, edge_list, 2, e);
  1801. if (merge_lines(sstate, e[0], e[1], total_parity))
  1802. diff = min(diff, DIFF_HARD);
  1803. } else if (unknown_count == 3) {
  1804. int e[3];
  1805. int can[3]; /* canonical edges */
  1806. bool inv[3]; /* whether can[x] is inverse to e[x] */
  1807. find_unknowns(state, edge_list, 3, e);
  1808. can[0] = dsf_canonify_flip(linedsf, e[0], inv);
  1809. can[1] = dsf_canonify_flip(linedsf, e[1], inv+1);
  1810. can[2] = dsf_canonify_flip(linedsf, e[2], inv+2);
  1811. if (can[0] == can[1]) {
  1812. if (solver_set_line(sstate, e[2], (total_parity^inv[0]^inv[1]) ?
  1813. LINE_YES : LINE_NO))
  1814. diff = min(diff, DIFF_EASY);
  1815. }
  1816. if (can[0] == can[2]) {
  1817. if (solver_set_line(sstate, e[1], (total_parity^inv[0]^inv[2]) ?
  1818. LINE_YES : LINE_NO))
  1819. diff = min(diff, DIFF_EASY);
  1820. }
  1821. if (can[1] == can[2]) {
  1822. if (solver_set_line(sstate, e[0], (total_parity^inv[1]^inv[2]) ?
  1823. LINE_YES : LINE_NO))
  1824. diff = min(diff, DIFF_EASY);
  1825. }
  1826. } else if (unknown_count == 4) {
  1827. int e[4];
  1828. int can[4]; /* canonical edges */
  1829. bool inv[4]; /* whether can[x] is inverse to e[x] */
  1830. find_unknowns(state, edge_list, 4, e);
  1831. can[0] = dsf_canonify_flip(linedsf, e[0], inv);
  1832. can[1] = dsf_canonify_flip(linedsf, e[1], inv+1);
  1833. can[2] = dsf_canonify_flip(linedsf, e[2], inv+2);
  1834. can[3] = dsf_canonify_flip(linedsf, e[3], inv+3);
  1835. if (can[0] == can[1]) {
  1836. if (merge_lines(sstate, e[2], e[3], total_parity^inv[0]^inv[1]))
  1837. diff = min(diff, DIFF_HARD);
  1838. } else if (can[0] == can[2]) {
  1839. if (merge_lines(sstate, e[1], e[3], total_parity^inv[0]^inv[2]))
  1840. diff = min(diff, DIFF_HARD);
  1841. } else if (can[0] == can[3]) {
  1842. if (merge_lines(sstate, e[1], e[2], total_parity^inv[0]^inv[3]))
  1843. diff = min(diff, DIFF_HARD);
  1844. } else if (can[1] == can[2]) {
  1845. if (merge_lines(sstate, e[0], e[3], total_parity^inv[1]^inv[2]))
  1846. diff = min(diff, DIFF_HARD);
  1847. } else if (can[1] == can[3]) {
  1848. if (merge_lines(sstate, e[0], e[2], total_parity^inv[1]^inv[3]))
  1849. diff = min(diff, DIFF_HARD);
  1850. } else if (can[2] == can[3]) {
  1851. if (merge_lines(sstate, e[0], e[1], total_parity^inv[2]^inv[3]))
  1852. diff = min(diff, DIFF_HARD);
  1853. }
  1854. }
  1855. return diff;
  1856. }
  1857. /*
  1858. * These are the main solver functions.
  1859. *
  1860. * Their return values are diff values corresponding to the lowest mode solver
  1861. * that would notice the work that they have done. For example if the normal
  1862. * mode solver adds actual lines or crosses, it will return DIFF_EASY as the
  1863. * easy mode solver might be able to make progress using that. It doesn't make
  1864. * sense for one of them to return a diff value higher than that of the
  1865. * function itself.
  1866. *
  1867. * Each function returns the lowest value it can, as early as possible, in
  1868. * order to try and pass as much work as possible back to the lower level
  1869. * solvers which progress more quickly.
  1870. */
  1871. /* PROPOSED NEW DESIGN:
  1872. * We have a work queue consisting of 'events' notifying us that something has
  1873. * happened that a particular solver mode might be interested in. For example
  1874. * the hard mode solver might do something that helps the normal mode solver at
  1875. * dot [x,y] in which case it will enqueue an event recording this fact. Then
  1876. * we pull events off the work queue, and hand each in turn to the solver that
  1877. * is interested in them. If a solver reports that it failed we pass the same
  1878. * event on to progressively more advanced solvers and the loop detector. Once
  1879. * we've exhausted an event, or it has helped us progress, we drop it and
  1880. * continue to the next one. The events are sorted first in order of solver
  1881. * complexity (easy first) then order of insertion (oldest first).
  1882. * Once we run out of events we loop over each permitted solver in turn
  1883. * (easiest first) until either a deduction is made (and an event therefore
  1884. * emerges) or no further deductions can be made (in which case we've failed).
  1885. *
  1886. * QUESTIONS:
  1887. * * How do we 'loop over' a solver when both dots and squares are concerned.
  1888. * Answer: first all squares then all dots.
  1889. */
  1890. static int trivial_deductions(solver_state *sstate)
  1891. {
  1892. int i, current_yes, current_no;
  1893. game_state *state = sstate->state;
  1894. grid *g = state->game_grid;
  1895. int diff = DIFF_MAX;
  1896. /* Per-face deductions */
  1897. for (i = 0; i < g->num_faces; i++) {
  1898. grid_face *f = g->faces[i];
  1899. if (sstate->face_solved[i])
  1900. continue;
  1901. current_yes = sstate->face_yes_count[i];
  1902. current_no = sstate->face_no_count[i];
  1903. if (current_yes + current_no == f->order) {
  1904. sstate->face_solved[i] = true;
  1905. continue;
  1906. }
  1907. if (state->clues[i] < 0)
  1908. continue;
  1909. /*
  1910. * This code checks whether the numeric clue on a face is so
  1911. * large as to permit all its remaining LINE_UNKNOWNs to be
  1912. * filled in as LINE_YES, or alternatively so small as to
  1913. * permit them all to be filled in as LINE_NO.
  1914. */
  1915. if (state->clues[i] < current_yes) {
  1916. sstate->solver_status = SOLVER_MISTAKE;
  1917. return DIFF_EASY;
  1918. }
  1919. if (state->clues[i] == current_yes) {
  1920. if (face_setall(sstate, i, LINE_UNKNOWN, LINE_NO))
  1921. diff = min(diff, DIFF_EASY);
  1922. sstate->face_solved[i] = true;
  1923. continue;
  1924. }
  1925. if (f->order - state->clues[i] < current_no) {
  1926. sstate->solver_status = SOLVER_MISTAKE;
  1927. return DIFF_EASY;
  1928. }
  1929. if (f->order - state->clues[i] == current_no) {
  1930. if (face_setall(sstate, i, LINE_UNKNOWN, LINE_YES))
  1931. diff = min(diff, DIFF_EASY);
  1932. sstate->face_solved[i] = true;
  1933. continue;
  1934. }
  1935. if (f->order - state->clues[i] == current_no + 1 &&
  1936. f->order - current_yes - current_no > 2) {
  1937. /*
  1938. * One small refinement to the above: we also look for any
  1939. * adjacent pair of LINE_UNKNOWNs around the face with
  1940. * some LINE_YES incident on it from elsewhere. If we find
  1941. * one, then we know that pair of LINE_UNKNOWNs can't
  1942. * _both_ be LINE_YES, and hence that pushes us one line
  1943. * closer to being able to determine all the rest.
  1944. */
  1945. int j, k, e1, e2, e, d;
  1946. for (j = 0; j < f->order; j++) {
  1947. e1 = f->edges[j]->index;
  1948. e2 = f->edges[j+1 < f->order ? j+1 : 0]->index;
  1949. if (g->edges[e1]->dot1 == g->edges[e2]->dot1 ||
  1950. g->edges[e1]->dot1 == g->edges[e2]->dot2) {
  1951. d = g->edges[e1]->dot1->index;
  1952. } else {
  1953. assert(g->edges[e1]->dot2 == g->edges[e2]->dot1 ||
  1954. g->edges[e1]->dot2 == g->edges[e2]->dot2);
  1955. d = g->edges[e1]->dot2->index;
  1956. }
  1957. if (state->lines[e1] == LINE_UNKNOWN &&
  1958. state->lines[e2] == LINE_UNKNOWN) {
  1959. for (k = 0; k < g->dots[d]->order; k++) {
  1960. int e = g->dots[d]->edges[k]->index;
  1961. if (state->lines[e] == LINE_YES)
  1962. goto found; /* multi-level break */
  1963. }
  1964. }
  1965. }
  1966. continue;
  1967. found:
  1968. /*
  1969. * If we get here, we've found such a pair of edges, and
  1970. * they're e1 and e2.
  1971. */
  1972. for (j = 0; j < f->order; j++) {
  1973. e = f->edges[j]->index;
  1974. if (state->lines[e] == LINE_UNKNOWN && e != e1 && e != e2) {
  1975. bool r = solver_set_line(sstate, e, LINE_YES);
  1976. assert(r);
  1977. diff = min(diff, DIFF_EASY);
  1978. }
  1979. }
  1980. }
  1981. }
  1982. check_caches(sstate);
  1983. /* Per-dot deductions */
  1984. for (i = 0; i < g->num_dots; i++) {
  1985. grid_dot *d = g->dots[i];
  1986. int yes, no, unknown;
  1987. if (sstate->dot_solved[i])
  1988. continue;
  1989. yes = sstate->dot_yes_count[i];
  1990. no = sstate->dot_no_count[i];
  1991. unknown = d->order - yes - no;
  1992. if (yes == 0) {
  1993. if (unknown == 0) {
  1994. sstate->dot_solved[i] = true;
  1995. } else if (unknown == 1) {
  1996. dot_setall(sstate, i, LINE_UNKNOWN, LINE_NO);
  1997. diff = min(diff, DIFF_EASY);
  1998. sstate->dot_solved[i] = true;
  1999. }
  2000. } else if (yes == 1) {
  2001. if (unknown == 0) {
  2002. sstate->solver_status = SOLVER_MISTAKE;
  2003. return DIFF_EASY;
  2004. } else if (unknown == 1) {
  2005. dot_setall(sstate, i, LINE_UNKNOWN, LINE_YES);
  2006. diff = min(diff, DIFF_EASY);
  2007. }
  2008. } else if (yes == 2) {
  2009. if (unknown > 0) {
  2010. dot_setall(sstate, i, LINE_UNKNOWN, LINE_NO);
  2011. diff = min(diff, DIFF_EASY);
  2012. }
  2013. sstate->dot_solved[i] = true;
  2014. } else {
  2015. sstate->solver_status = SOLVER_MISTAKE;
  2016. return DIFF_EASY;
  2017. }
  2018. }
  2019. check_caches(sstate);
  2020. return diff;
  2021. }
  2022. static int dline_deductions(solver_state *sstate)
  2023. {
  2024. game_state *state = sstate->state;
  2025. grid *g = state->game_grid;
  2026. char *dlines = sstate->dlines;
  2027. int i;
  2028. int diff = DIFF_MAX;
  2029. /* ------ Face deductions ------ */
  2030. /* Given a set of dline atmostone/atleastone constraints, need to figure
  2031. * out if we can deduce any further info. For more general faces than
  2032. * squares, this turns out to be a tricky problem.
  2033. * The approach taken here is to define (per face) NxN matrices:
  2034. * "maxs" and "mins".
  2035. * The entries maxs(j,k) and mins(j,k) define the upper and lower limits
  2036. * for the possible number of edges that are YES between positions j and k
  2037. * going clockwise around the face. Can think of j and k as marking dots
  2038. * around the face (recall the labelling scheme: edge0 joins dot0 to dot1,
  2039. * edge1 joins dot1 to dot2 etc).
  2040. * Trivially, mins(j,j) = maxs(j,j) = 0, and we don't even bother storing
  2041. * these. mins(j,j+1) and maxs(j,j+1) are determined by whether edge{j}
  2042. * is YES, NO or UNKNOWN. mins(j,j+2) and maxs(j,j+2) are related to
  2043. * the dline atmostone/atleastone status for edges j and j+1.
  2044. *
  2045. * Then we calculate the remaining entries recursively. We definitely
  2046. * know that
  2047. * mins(j,k) >= { mins(j,u) + mins(u,k) } for any u between j and k.
  2048. * This is because any valid placement of YESs between j and k must give
  2049. * a valid placement between j and u, and also between u and k.
  2050. * I believe it's sufficient to use just the two values of u:
  2051. * j+1 and j+2. Seems to work well in practice - the bounds we compute
  2052. * are rigorous, even if they might not be best-possible.
  2053. *
  2054. * Once we have maxs and mins calculated, we can make inferences about
  2055. * each dline{j,j+1} by looking at the possible complementary edge-counts
  2056. * mins(j+2,j) and maxs(j+2,j) and comparing these with the face clue.
  2057. * As well as dlines, we can make similar inferences about single edges.
  2058. * For example, consider a pentagon with clue 3, and we know at most one
  2059. * of (edge0, edge1) is YES, and at most one of (edge2, edge3) is YES.
  2060. * We could then deduce edge4 is YES, because maxs(0,4) would be 2, so
  2061. * that final edge would have to be YES to make the count up to 3.
  2062. */
  2063. /* Much quicker to allocate arrays on the stack than the heap, so
  2064. * define the largest possible face size, and base our array allocations
  2065. * on that. We check this with an assertion, in case someone decides to
  2066. * make a grid which has larger faces than this. Note, this algorithm
  2067. * could get quite expensive if there are many large faces. */
  2068. #define MAX_FACE_SIZE 14
  2069. for (i = 0; i < g->num_faces; i++) {
  2070. int maxs[MAX_FACE_SIZE][MAX_FACE_SIZE];
  2071. int mins[MAX_FACE_SIZE][MAX_FACE_SIZE];
  2072. grid_face *f = g->faces[i];
  2073. int N = f->order;
  2074. int j,m;
  2075. int clue = state->clues[i];
  2076. assert(N <= MAX_FACE_SIZE);
  2077. if (sstate->face_solved[i])
  2078. continue;
  2079. if (clue < 0) continue;
  2080. /* Calculate the (j,j+1) entries */
  2081. for (j = 0; j < N; j++) {
  2082. int edge_index = f->edges[j]->index;
  2083. int dline_index;
  2084. enum line_state line1 = state->lines[edge_index];
  2085. enum line_state line2;
  2086. int tmp;
  2087. int k = j + 1;
  2088. if (k >= N) k = 0;
  2089. maxs[j][k] = (line1 == LINE_NO) ? 0 : 1;
  2090. mins[j][k] = (line1 == LINE_YES) ? 1 : 0;
  2091. /* Calculate the (j,j+2) entries */
  2092. dline_index = dline_index_from_face(g, f, k);
  2093. edge_index = f->edges[k]->index;
  2094. line2 = state->lines[edge_index];
  2095. k++;
  2096. if (k >= N) k = 0;
  2097. /* max */
  2098. tmp = 2;
  2099. if (line1 == LINE_NO) tmp--;
  2100. if (line2 == LINE_NO) tmp--;
  2101. if (tmp == 2 && is_atmostone(dlines, dline_index))
  2102. tmp = 1;
  2103. maxs[j][k] = tmp;
  2104. /* min */
  2105. tmp = 0;
  2106. if (line1 == LINE_YES) tmp++;
  2107. if (line2 == LINE_YES) tmp++;
  2108. if (tmp == 0 && is_atleastone(dlines, dline_index))
  2109. tmp = 1;
  2110. mins[j][k] = tmp;
  2111. }
  2112. /* Calculate the (j,j+m) entries for m between 3 and N-1 */
  2113. for (m = 3; m < N; m++) {
  2114. for (j = 0; j < N; j++) {
  2115. int k = j + m;
  2116. int u = j + 1;
  2117. int v = j + 2;
  2118. int tmp;
  2119. if (k >= N) k -= N;
  2120. if (u >= N) u -= N;
  2121. if (v >= N) v -= N;
  2122. maxs[j][k] = maxs[j][u] + maxs[u][k];
  2123. mins[j][k] = mins[j][u] + mins[u][k];
  2124. tmp = maxs[j][v] + maxs[v][k];
  2125. maxs[j][k] = min(maxs[j][k], tmp);
  2126. tmp = mins[j][v] + mins[v][k];
  2127. mins[j][k] = max(mins[j][k], tmp);
  2128. }
  2129. }
  2130. /* See if we can make any deductions */
  2131. for (j = 0; j < N; j++) {
  2132. int k;
  2133. grid_edge *e = f->edges[j];
  2134. int line_index = e->index;
  2135. int dline_index;
  2136. if (state->lines[line_index] != LINE_UNKNOWN)
  2137. continue;
  2138. k = j + 1;
  2139. if (k >= N) k = 0;
  2140. /* minimum YESs in the complement of this edge */
  2141. if (mins[k][j] > clue) {
  2142. sstate->solver_status = SOLVER_MISTAKE;
  2143. return DIFF_EASY;
  2144. }
  2145. if (mins[k][j] == clue) {
  2146. /* setting this edge to YES would make at least
  2147. * (clue+1) edges - contradiction */
  2148. solver_set_line(sstate, line_index, LINE_NO);
  2149. diff = min(diff, DIFF_EASY);
  2150. }
  2151. if (maxs[k][j] < clue - 1) {
  2152. sstate->solver_status = SOLVER_MISTAKE;
  2153. return DIFF_EASY;
  2154. }
  2155. if (maxs[k][j] == clue - 1) {
  2156. /* Only way to satisfy the clue is to set edge{j} as YES */
  2157. solver_set_line(sstate, line_index, LINE_YES);
  2158. diff = min(diff, DIFF_EASY);
  2159. }
  2160. /* More advanced deduction that allows propagation along diagonal
  2161. * chains of faces connected by dots, for example, 3-2-...-2-3
  2162. * in square grids. */
  2163. if (sstate->diff >= DIFF_TRICKY) {
  2164. /* Now see if we can make dline deduction for edges{j,j+1} */
  2165. e = f->edges[k];
  2166. if (state->lines[e->index] != LINE_UNKNOWN)
  2167. /* Only worth doing this for an UNKNOWN,UNKNOWN pair.
  2168. * Dlines where one of the edges is known, are handled in the
  2169. * dot-deductions */
  2170. continue;
  2171. dline_index = dline_index_from_face(g, f, k);
  2172. k++;
  2173. if (k >= N) k = 0;
  2174. /* minimum YESs in the complement of this dline */
  2175. if (mins[k][j] > clue - 2) {
  2176. /* Adding 2 YESs would break the clue */
  2177. if (set_atmostone(dlines, dline_index))
  2178. diff = min(diff, DIFF_NORMAL);
  2179. }
  2180. /* maximum YESs in the complement of this dline */
  2181. if (maxs[k][j] < clue) {
  2182. /* Adding 2 NOs would mean not enough YESs */
  2183. if (set_atleastone(dlines, dline_index))
  2184. diff = min(diff, DIFF_NORMAL);
  2185. }
  2186. }
  2187. }
  2188. }
  2189. if (diff < DIFF_NORMAL)
  2190. return diff;
  2191. /* ------ Dot deductions ------ */
  2192. for (i = 0; i < g->num_dots; i++) {
  2193. grid_dot *d = g->dots[i];
  2194. int N = d->order;
  2195. int yes, no, unknown;
  2196. int j;
  2197. if (sstate->dot_solved[i])
  2198. continue;
  2199. yes = sstate->dot_yes_count[i];
  2200. no = sstate->dot_no_count[i];
  2201. unknown = N - yes - no;
  2202. for (j = 0; j < N; j++) {
  2203. int k;
  2204. int dline_index;
  2205. int line1_index, line2_index;
  2206. enum line_state line1, line2;
  2207. k = j + 1;
  2208. if (k >= N) k = 0;
  2209. dline_index = dline_index_from_dot(g, d, j);
  2210. line1_index = d->edges[j]->index;
  2211. line2_index = d->edges[k] ->index;
  2212. line1 = state->lines[line1_index];
  2213. line2 = state->lines[line2_index];
  2214. /* Infer dline state from line state */
  2215. if (line1 == LINE_NO || line2 == LINE_NO) {
  2216. if (set_atmostone(dlines, dline_index))
  2217. diff = min(diff, DIFF_NORMAL);
  2218. }
  2219. if (line1 == LINE_YES || line2 == LINE_YES) {
  2220. if (set_atleastone(dlines, dline_index))
  2221. diff = min(diff, DIFF_NORMAL);
  2222. }
  2223. /* Infer line state from dline state */
  2224. if (is_atmostone(dlines, dline_index)) {
  2225. if (line1 == LINE_YES && line2 == LINE_UNKNOWN) {
  2226. solver_set_line(sstate, line2_index, LINE_NO);
  2227. diff = min(diff, DIFF_EASY);
  2228. }
  2229. if (line2 == LINE_YES && line1 == LINE_UNKNOWN) {
  2230. solver_set_line(sstate, line1_index, LINE_NO);
  2231. diff = min(diff, DIFF_EASY);
  2232. }
  2233. }
  2234. if (is_atleastone(dlines, dline_index)) {
  2235. if (line1 == LINE_NO && line2 == LINE_UNKNOWN) {
  2236. solver_set_line(sstate, line2_index, LINE_YES);
  2237. diff = min(diff, DIFF_EASY);
  2238. }
  2239. if (line2 == LINE_NO && line1 == LINE_UNKNOWN) {
  2240. solver_set_line(sstate, line1_index, LINE_YES);
  2241. diff = min(diff, DIFF_EASY);
  2242. }
  2243. }
  2244. /* Deductions that depend on the numbers of lines.
  2245. * Only bother if both lines are UNKNOWN, otherwise the
  2246. * easy-mode solver (or deductions above) would have taken
  2247. * care of it. */
  2248. if (line1 != LINE_UNKNOWN || line2 != LINE_UNKNOWN)
  2249. continue;
  2250. if (yes == 0 && unknown == 2) {
  2251. /* Both these unknowns must be identical. If we know
  2252. * atmostone or atleastone, we can make progress. */
  2253. if (is_atmostone(dlines, dline_index)) {
  2254. solver_set_line(sstate, line1_index, LINE_NO);
  2255. solver_set_line(sstate, line2_index, LINE_NO);
  2256. diff = min(diff, DIFF_EASY);
  2257. }
  2258. if (is_atleastone(dlines, dline_index)) {
  2259. solver_set_line(sstate, line1_index, LINE_YES);
  2260. solver_set_line(sstate, line2_index, LINE_YES);
  2261. diff = min(diff, DIFF_EASY);
  2262. }
  2263. }
  2264. if (yes == 1) {
  2265. if (set_atmostone(dlines, dline_index))
  2266. diff = min(diff, DIFF_NORMAL);
  2267. if (unknown == 2) {
  2268. if (set_atleastone(dlines, dline_index))
  2269. diff = min(diff, DIFF_NORMAL);
  2270. }
  2271. }
  2272. /* More advanced deduction that allows propagation along diagonal
  2273. * chains of faces connected by dots, for example: 3-2-...-2-3
  2274. * in square grids. */
  2275. if (sstate->diff >= DIFF_TRICKY) {
  2276. /* If we have atleastone set for this dline, infer
  2277. * atmostone for each "opposite" dline (that is, each
  2278. * dline without edges in common with this one).
  2279. * Again, this test is only worth doing if both these
  2280. * lines are UNKNOWN. For if one of these lines were YES,
  2281. * the (yes == 1) test above would kick in instead. */
  2282. if (is_atleastone(dlines, dline_index)) {
  2283. int opp;
  2284. for (opp = 0; opp < N; opp++) {
  2285. int opp_dline_index;
  2286. if (opp == j || opp == j+1 || opp == j-1)
  2287. continue;
  2288. if (j == 0 && opp == N-1)
  2289. continue;
  2290. if (j == N-1 && opp == 0)
  2291. continue;
  2292. opp_dline_index = dline_index_from_dot(g, d, opp);
  2293. if (set_atmostone(dlines, opp_dline_index))
  2294. diff = min(diff, DIFF_NORMAL);
  2295. }
  2296. if (yes == 0 && is_atmostone(dlines, dline_index)) {
  2297. /* This dline has *exactly* one YES and there are no
  2298. * other YESs. This allows more deductions. */
  2299. if (unknown == 3) {
  2300. /* Third unknown must be YES */
  2301. for (opp = 0; opp < N; opp++) {
  2302. int opp_index;
  2303. if (opp == j || opp == k)
  2304. continue;
  2305. opp_index = d->edges[opp]->index;
  2306. if (state->lines[opp_index] == LINE_UNKNOWN) {
  2307. solver_set_line(sstate, opp_index,
  2308. LINE_YES);
  2309. diff = min(diff, DIFF_EASY);
  2310. }
  2311. }
  2312. } else if (unknown == 4) {
  2313. /* Exactly one of opposite UNKNOWNS is YES. We've
  2314. * already set atmostone, so set atleastone as
  2315. * well.
  2316. */
  2317. if (dline_set_opp_atleastone(sstate, d, j))
  2318. diff = min(diff, DIFF_NORMAL);
  2319. }
  2320. }
  2321. }
  2322. }
  2323. }
  2324. }
  2325. return diff;
  2326. }
  2327. static int linedsf_deductions(solver_state *sstate)
  2328. {
  2329. game_state *state = sstate->state;
  2330. grid *g = state->game_grid;
  2331. char *dlines = sstate->dlines;
  2332. int i;
  2333. int diff = DIFF_MAX;
  2334. int diff_tmp;
  2335. /* ------ Face deductions ------ */
  2336. /* A fully-general linedsf deduction seems overly complicated
  2337. * (I suspect the problem is NP-complete, though in practice it might just
  2338. * be doable because faces are limited in size).
  2339. * For simplicity, we only consider *pairs* of LINE_UNKNOWNS that are
  2340. * known to be identical. If setting them both to YES (or NO) would break
  2341. * the clue, set them to NO (or YES). */
  2342. for (i = 0; i < g->num_faces; i++) {
  2343. int N, yes, no, unknown;
  2344. int clue;
  2345. if (sstate->face_solved[i])
  2346. continue;
  2347. clue = state->clues[i];
  2348. if (clue < 0)
  2349. continue;
  2350. N = g->faces[i]->order;
  2351. yes = sstate->face_yes_count[i];
  2352. if (yes + 1 == clue) {
  2353. if (face_setall_identical(sstate, i, LINE_NO))
  2354. diff = min(diff, DIFF_EASY);
  2355. }
  2356. no = sstate->face_no_count[i];
  2357. if (no + 1 == N - clue) {
  2358. if (face_setall_identical(sstate, i, LINE_YES))
  2359. diff = min(diff, DIFF_EASY);
  2360. }
  2361. /* Reload YES count, it might have changed */
  2362. yes = sstate->face_yes_count[i];
  2363. unknown = N - no - yes;
  2364. /* Deductions with small number of LINE_UNKNOWNs, based on overall
  2365. * parity of lines. */
  2366. diff_tmp = parity_deductions(sstate, g->faces[i]->edges,
  2367. (clue - yes) % 2, unknown);
  2368. diff = min(diff, diff_tmp);
  2369. }
  2370. /* ------ Dot deductions ------ */
  2371. for (i = 0; i < g->num_dots; i++) {
  2372. grid_dot *d = g->dots[i];
  2373. int N = d->order;
  2374. int j;
  2375. int yes, no, unknown;
  2376. /* Go through dlines, and do any dline<->linedsf deductions wherever
  2377. * we find two UNKNOWNS. */
  2378. for (j = 0; j < N; j++) {
  2379. int dline_index = dline_index_from_dot(g, d, j);
  2380. int line1_index;
  2381. int line2_index;
  2382. int can1, can2;
  2383. bool inv1, inv2;
  2384. int j2;
  2385. line1_index = d->edges[j]->index;
  2386. if (state->lines[line1_index] != LINE_UNKNOWN)
  2387. continue;
  2388. j2 = j + 1;
  2389. if (j2 == N) j2 = 0;
  2390. line2_index = d->edges[j2]->index;
  2391. if (state->lines[line2_index] != LINE_UNKNOWN)
  2392. continue;
  2393. /* Infer dline flags from linedsf */
  2394. can1 = dsf_canonify_flip(sstate->linedsf, line1_index, &inv1);
  2395. can2 = dsf_canonify_flip(sstate->linedsf, line2_index, &inv2);
  2396. if (can1 == can2 && inv1 != inv2) {
  2397. /* These are opposites, so set dline atmostone/atleastone */
  2398. if (set_atmostone(dlines, dline_index))
  2399. diff = min(diff, DIFF_NORMAL);
  2400. if (set_atleastone(dlines, dline_index))
  2401. diff = min(diff, DIFF_NORMAL);
  2402. continue;
  2403. }
  2404. /* Infer linedsf from dline flags */
  2405. if (is_atmostone(dlines, dline_index)
  2406. && is_atleastone(dlines, dline_index)) {
  2407. if (merge_lines(sstate, line1_index, line2_index, true))
  2408. diff = min(diff, DIFF_HARD);
  2409. }
  2410. }
  2411. /* Deductions with small number of LINE_UNKNOWNs, based on overall
  2412. * parity of lines. */
  2413. yes = sstate->dot_yes_count[i];
  2414. no = sstate->dot_no_count[i];
  2415. unknown = N - yes - no;
  2416. diff_tmp = parity_deductions(sstate, d->edges,
  2417. yes % 2, unknown);
  2418. diff = min(diff, diff_tmp);
  2419. }
  2420. /* ------ Edge dsf deductions ------ */
  2421. /* If the state of a line is known, deduce the state of its canonical line
  2422. * too, and vice versa. */
  2423. for (i = 0; i < g->num_edges; i++) {
  2424. int can;
  2425. bool inv;
  2426. enum line_state s;
  2427. can = dsf_canonify_flip(sstate->linedsf, i, &inv);
  2428. if (can == i)
  2429. continue;
  2430. s = sstate->state->lines[can];
  2431. if (s != LINE_UNKNOWN) {
  2432. if (solver_set_line(sstate, i, inv ? OPP(s) : s))
  2433. diff = min(diff, DIFF_EASY);
  2434. } else {
  2435. s = sstate->state->lines[i];
  2436. if (s != LINE_UNKNOWN) {
  2437. if (solver_set_line(sstate, can, inv ? OPP(s) : s))
  2438. diff = min(diff, DIFF_EASY);
  2439. }
  2440. }
  2441. }
  2442. return diff;
  2443. }
  2444. static int loop_deductions(solver_state *sstate)
  2445. {
  2446. int edgecount = 0, clues = 0, satclues = 0, sm1clues = 0;
  2447. game_state *state = sstate->state;
  2448. grid *g = state->game_grid;
  2449. int shortest_chainlen = g->num_dots;
  2450. int dots_connected;
  2451. bool progress = false;
  2452. int i;
  2453. /*
  2454. * Go through the grid and update for all the new edges.
  2455. * Since merge_dots() is idempotent, the simplest way to
  2456. * do this is just to update for _all_ the edges.
  2457. * Also, while we're here, we count the edges.
  2458. */
  2459. for (i = 0; i < g->num_edges; i++) {
  2460. if (state->lines[i] == LINE_YES) {
  2461. merge_dots(sstate, i);
  2462. edgecount++;
  2463. }
  2464. }
  2465. /*
  2466. * Count the clues, count the satisfied clues, and count the
  2467. * satisfied-minus-one clues.
  2468. */
  2469. for (i = 0; i < g->num_faces; i++) {
  2470. int c = state->clues[i];
  2471. if (c >= 0) {
  2472. int o = sstate->face_yes_count[i];
  2473. if (o == c)
  2474. satclues++;
  2475. else if (o == c-1)
  2476. sm1clues++;
  2477. clues++;
  2478. }
  2479. }
  2480. for (i = 0; i < g->num_dots; ++i) {
  2481. dots_connected =
  2482. sstate->looplen[dsf_canonify(sstate->dotdsf, i)];
  2483. if (dots_connected > 1)
  2484. shortest_chainlen = min(shortest_chainlen, dots_connected);
  2485. }
  2486. assert(sstate->solver_status == SOLVER_INCOMPLETE);
  2487. if (satclues == clues && shortest_chainlen == edgecount) {
  2488. sstate->solver_status = SOLVER_SOLVED;
  2489. /* This discovery clearly counts as progress, even if we haven't
  2490. * just added any lines or anything */
  2491. progress = true;
  2492. goto finished_loop_deductionsing;
  2493. }
  2494. /*
  2495. * Now go through looking for LINE_UNKNOWN edges which
  2496. * connect two dots that are already in the same
  2497. * equivalence class. If we find one, test to see if the
  2498. * loop it would create is a solution.
  2499. */
  2500. for (i = 0; i < g->num_edges; i++) {
  2501. grid_edge *e = g->edges[i];
  2502. int d1 = e->dot1->index;
  2503. int d2 = e->dot2->index;
  2504. int eqclass, val;
  2505. if (state->lines[i] != LINE_UNKNOWN)
  2506. continue;
  2507. eqclass = dsf_canonify(sstate->dotdsf, d1);
  2508. if (eqclass != dsf_canonify(sstate->dotdsf, d2))
  2509. continue;
  2510. val = LINE_NO; /* loop is bad until proven otherwise */
  2511. /*
  2512. * This edge would form a loop. Next
  2513. * question: how long would the loop be?
  2514. * Would it equal the total number of edges
  2515. * (plus the one we'd be adding if we added
  2516. * it)?
  2517. */
  2518. if (sstate->looplen[eqclass] == edgecount + 1) {
  2519. int sm1_nearby;
  2520. /*
  2521. * This edge would form a loop which
  2522. * took in all the edges in the entire
  2523. * grid. So now we need to work out
  2524. * whether it would be a valid solution
  2525. * to the puzzle, which means we have to
  2526. * check if it satisfies all the clues.
  2527. * This means that every clue must be
  2528. * either satisfied or satisfied-minus-
  2529. * 1, and also that the number of
  2530. * satisfied-minus-1 clues must be at
  2531. * most two and they must lie on either
  2532. * side of this edge.
  2533. */
  2534. sm1_nearby = 0;
  2535. if (e->face1) {
  2536. int f = e->face1->index;
  2537. int c = state->clues[f];
  2538. if (c >= 0 && sstate->face_yes_count[f] == c - 1)
  2539. sm1_nearby++;
  2540. }
  2541. if (e->face2) {
  2542. int f = e->face2->index;
  2543. int c = state->clues[f];
  2544. if (c >= 0 && sstate->face_yes_count[f] == c - 1)
  2545. sm1_nearby++;
  2546. }
  2547. if (sm1clues == sm1_nearby &&
  2548. sm1clues + satclues == clues) {
  2549. val = LINE_YES; /* loop is good! */
  2550. }
  2551. }
  2552. /*
  2553. * Right. Now we know that adding this edge
  2554. * would form a loop, and we know whether
  2555. * that loop would be a viable solution or
  2556. * not.
  2557. *
  2558. * If adding this edge produces a solution,
  2559. * then we know we've found _a_ solution but
  2560. * we don't know that it's _the_ solution -
  2561. * if it were provably the solution then
  2562. * we'd have deduced this edge some time ago
  2563. * without the need to do loop detection. So
  2564. * in this state we return SOLVER_AMBIGUOUS,
  2565. * which has the effect that hitting Solve
  2566. * on a user-provided puzzle will fill in a
  2567. * solution but using the solver to
  2568. * construct new puzzles won't consider this
  2569. * a reasonable deduction for the user to
  2570. * make.
  2571. */
  2572. progress = solver_set_line(sstate, i, val);
  2573. assert(progress);
  2574. if (val == LINE_YES) {
  2575. sstate->solver_status = SOLVER_AMBIGUOUS;
  2576. goto finished_loop_deductionsing;
  2577. }
  2578. }
  2579. finished_loop_deductionsing:
  2580. return progress ? DIFF_EASY : DIFF_MAX;
  2581. }
  2582. /* This will return a dynamically allocated solver_state containing the (more)
  2583. * solved grid */
  2584. static solver_state *solve_game_rec(const solver_state *sstate_start)
  2585. {
  2586. solver_state *sstate;
  2587. /* Index of the solver we should call next. */
  2588. int i = 0;
  2589. /* As a speed-optimisation, we avoid re-running solvers that we know
  2590. * won't make any progress. This happens when a high-difficulty
  2591. * solver makes a deduction that can only help other high-difficulty
  2592. * solvers.
  2593. * For example: if a new 'dline' flag is set by dline_deductions, the
  2594. * trivial_deductions solver cannot do anything with this information.
  2595. * If we've already run the trivial_deductions solver (because it's
  2596. * earlier in the list), there's no point running it again.
  2597. *
  2598. * Therefore: if a solver is earlier in the list than "threshold_index",
  2599. * we don't bother running it if it's difficulty level is less than
  2600. * "threshold_diff".
  2601. */
  2602. int threshold_diff = 0;
  2603. int threshold_index = 0;
  2604. sstate = dup_solver_state(sstate_start);
  2605. check_caches(sstate);
  2606. while (i < NUM_SOLVERS) {
  2607. if (sstate->solver_status == SOLVER_MISTAKE)
  2608. return sstate;
  2609. if (sstate->solver_status == SOLVER_SOLVED ||
  2610. sstate->solver_status == SOLVER_AMBIGUOUS) {
  2611. /* solver finished */
  2612. break;
  2613. }
  2614. if ((solver_diffs[i] >= threshold_diff || i >= threshold_index)
  2615. && solver_diffs[i] <= sstate->diff) {
  2616. /* current_solver is eligible, so use it */
  2617. int next_diff = solver_fns[i](sstate);
  2618. if (next_diff != DIFF_MAX) {
  2619. /* solver made progress, so use new thresholds and
  2620. * start again at top of list. */
  2621. threshold_diff = next_diff;
  2622. threshold_index = i;
  2623. i = 0;
  2624. continue;
  2625. }
  2626. }
  2627. /* current_solver is ineligible, or failed to make progress, so
  2628. * go to the next solver in the list */
  2629. i++;
  2630. }
  2631. if (sstate->solver_status == SOLVER_SOLVED ||
  2632. sstate->solver_status == SOLVER_AMBIGUOUS) {
  2633. /* s/LINE_UNKNOWN/LINE_NO/g */
  2634. array_setall(sstate->state->lines, LINE_UNKNOWN, LINE_NO,
  2635. sstate->state->game_grid->num_edges);
  2636. return sstate;
  2637. }
  2638. return sstate;
  2639. }
  2640. static char *solve_game(const game_state *state, const game_state *currstate,
  2641. const char *aux, const char **error)
  2642. {
  2643. char *soln = NULL;
  2644. solver_state *sstate, *new_sstate;
  2645. sstate = new_solver_state(state, DIFF_MAX);
  2646. new_sstate = solve_game_rec(sstate);
  2647. if (new_sstate->solver_status == SOLVER_SOLVED) {
  2648. soln = encode_solve_move(new_sstate->state);
  2649. } else if (new_sstate->solver_status == SOLVER_AMBIGUOUS) {
  2650. soln = encode_solve_move(new_sstate->state);
  2651. /**error = "Solver found ambiguous solutions"; */
  2652. } else {
  2653. soln = encode_solve_move(new_sstate->state);
  2654. /**error = "Solver failed"; */
  2655. }
  2656. free_solver_state(new_sstate);
  2657. free_solver_state(sstate);
  2658. return soln;
  2659. }
  2660. /* ----------------------------------------------------------------------
  2661. * Drawing and mouse-handling
  2662. */
  2663. static char *interpret_move(const game_state *state, game_ui *ui,
  2664. const game_drawstate *ds,
  2665. int x, int y, int button)
  2666. {
  2667. grid *g = state->game_grid;
  2668. grid_edge *e;
  2669. int i;
  2670. char *movebuf;
  2671. int movelen, movesize;
  2672. char button_char = ' ';
  2673. enum line_state old_state;
  2674. button &= ~MOD_MASK;
  2675. /* Convert mouse-click (x,y) to grid coordinates */
  2676. x -= BORDER(ds->tilesize);
  2677. y -= BORDER(ds->tilesize);
  2678. x = x * g->tilesize / ds->tilesize;
  2679. y = y * g->tilesize / ds->tilesize;
  2680. x += g->lowest_x;
  2681. y += g->lowest_y;
  2682. e = grid_nearest_edge(g, x, y);
  2683. if (e == NULL)
  2684. return NULL;
  2685. i = e->index;
  2686. /* I think it's only possible to play this game with mouse clicks, sorry */
  2687. /* Maybe will add mouse drag support some time */
  2688. old_state = state->lines[i];
  2689. switch (button) {
  2690. case LEFT_BUTTON:
  2691. switch (old_state) {
  2692. case LINE_UNKNOWN:
  2693. button_char = 'y';
  2694. break;
  2695. case LINE_YES:
  2696. #ifdef STYLUS_BASED
  2697. button_char = 'n';
  2698. break;
  2699. #endif
  2700. case LINE_NO:
  2701. button_char = 'u';
  2702. break;
  2703. }
  2704. break;
  2705. case MIDDLE_BUTTON:
  2706. button_char = 'u';
  2707. break;
  2708. case RIGHT_BUTTON:
  2709. switch (old_state) {
  2710. case LINE_UNKNOWN:
  2711. button_char = 'n';
  2712. break;
  2713. case LINE_NO:
  2714. #ifdef STYLUS_BASED
  2715. button_char = 'y';
  2716. break;
  2717. #endif
  2718. case LINE_YES:
  2719. button_char = 'u';
  2720. break;
  2721. }
  2722. break;
  2723. default:
  2724. return NULL;
  2725. }
  2726. movelen = 0;
  2727. movesize = 80;
  2728. movebuf = snewn(movesize, char);
  2729. movelen = sprintf(movebuf, "%d%c", i, (int)button_char);
  2730. if (ui->autofollow != AF_OFF) {
  2731. int dotid;
  2732. for (dotid = 0; dotid < 2; dotid++) {
  2733. grid_dot *dot = (dotid == 0 ? e->dot1 : e->dot2);
  2734. grid_edge *e_this = e;
  2735. while (1) {
  2736. int j, n_found;
  2737. grid_edge *e_next = NULL;
  2738. for (j = n_found = 0; j < dot->order; j++) {
  2739. grid_edge *e_candidate = dot->edges[j];
  2740. int i_candidate = e_candidate->index;
  2741. if (e_candidate != e_this &&
  2742. (ui->autofollow == AF_FIXED ||
  2743. state->lines[i] == LINE_NO ||
  2744. state->lines[i_candidate] != LINE_NO)) {
  2745. e_next = e_candidate;
  2746. n_found++;
  2747. }
  2748. }
  2749. if (n_found != 1 ||
  2750. state->lines[e_next->index] != state->lines[i])
  2751. break;
  2752. if (e_next == e) {
  2753. /*
  2754. * Special case: we might have come all the way
  2755. * round a loop and found our way back to the same
  2756. * edge we started from. In that situation, we
  2757. * must terminate not only this while loop, but
  2758. * the 'for' outside it that was tracing in both
  2759. * directions from the starting edge, because if
  2760. * we let it trace in the second direction then
  2761. * we'll only find ourself traversing the same
  2762. * loop in the other order and generate an encoded
  2763. * move string that mentions the same set of edges
  2764. * twice.
  2765. */
  2766. goto autofollow_done;
  2767. }
  2768. dot = (e_next->dot1 != dot ? e_next->dot1 : e_next->dot2);
  2769. if (movelen > movesize - 40) {
  2770. movesize = movesize * 5 / 4 + 128;
  2771. movebuf = sresize(movebuf, movesize, char);
  2772. }
  2773. e_this = e_next;
  2774. movelen += sprintf(movebuf+movelen, "%d%c",
  2775. (int)(e_this->index), button_char);
  2776. }
  2777. autofollow_done:;
  2778. }
  2779. }
  2780. return sresize(movebuf, movelen+1, char);
  2781. }
  2782. static game_state *execute_move(const game_state *state, const char *move)
  2783. {
  2784. int i;
  2785. game_state *newstate = dup_game(state);
  2786. if (move[0] == 'S') {
  2787. move++;
  2788. newstate->cheated = true;
  2789. }
  2790. while (*move) {
  2791. i = atoi(move);
  2792. if (i < 0 || i >= newstate->game_grid->num_edges)
  2793. goto fail;
  2794. move += strspn(move, "1234567890");
  2795. switch (*(move++)) {
  2796. case 'y':
  2797. newstate->lines[i] = LINE_YES;
  2798. break;
  2799. case 'n':
  2800. newstate->lines[i] = LINE_NO;
  2801. break;
  2802. case 'u':
  2803. newstate->lines[i] = LINE_UNKNOWN;
  2804. break;
  2805. default:
  2806. goto fail;
  2807. }
  2808. }
  2809. /*
  2810. * Check for completion.
  2811. */
  2812. if (check_completion(newstate))
  2813. newstate->solved = true;
  2814. return newstate;
  2815. fail:
  2816. free_game(newstate);
  2817. return NULL;
  2818. }
  2819. /* ----------------------------------------------------------------------
  2820. * Drawing routines.
  2821. */
  2822. /* Convert from grid coordinates to screen coordinates */
  2823. static void grid_to_screen(const game_drawstate *ds, const grid *g,
  2824. int grid_x, int grid_y, int *x, int *y)
  2825. {
  2826. *x = grid_x - g->lowest_x;
  2827. *y = grid_y - g->lowest_y;
  2828. *x = *x * ds->tilesize / g->tilesize;
  2829. *y = *y * ds->tilesize / g->tilesize;
  2830. *x += BORDER(ds->tilesize);
  2831. *y += BORDER(ds->tilesize);
  2832. }
  2833. /* Returns (into x,y) position of centre of face for rendering the text clue.
  2834. */
  2835. static void face_text_pos(const game_drawstate *ds, const grid *g,
  2836. grid_face *f, int *xret, int *yret)
  2837. {
  2838. int faceindex = f->index;
  2839. /*
  2840. * Return the cached position for this face, if we've already
  2841. * worked it out.
  2842. */
  2843. if (ds->textx[faceindex] >= 0) {
  2844. *xret = ds->textx[faceindex];
  2845. *yret = ds->texty[faceindex];
  2846. return;
  2847. }
  2848. /*
  2849. * Otherwise, use the incentre computed by grid.c and convert it
  2850. * to screen coordinates.
  2851. */
  2852. grid_find_incentre(f);
  2853. grid_to_screen(ds, g, f->ix, f->iy,
  2854. &ds->textx[faceindex], &ds->texty[faceindex]);
  2855. *xret = ds->textx[faceindex];
  2856. *yret = ds->texty[faceindex];
  2857. }
  2858. static void face_text_bbox(game_drawstate *ds, grid *g, grid_face *f,
  2859. int *x, int *y, int *w, int *h)
  2860. {
  2861. int xx, yy;
  2862. face_text_pos(ds, g, f, &xx, &yy);
  2863. /* There seems to be a certain amount of trial-and-error involved
  2864. * in working out the correct bounding-box for the text. */
  2865. *x = xx - ds->tilesize * 5 / 4 - 1;
  2866. *y = yy - ds->tilesize/4 - 3;
  2867. *w = ds->tilesize * 5 / 2 + 2;
  2868. *h = ds->tilesize/2 + 5;
  2869. }
  2870. static void game_redraw_clue(drawing *dr, game_drawstate *ds,
  2871. const game_state *state, int i)
  2872. {
  2873. grid *g = state->game_grid;
  2874. grid_face *f = g->faces[i];
  2875. int x, y;
  2876. char c[20];
  2877. sprintf(c, "%d", state->clues[i]);
  2878. face_text_pos(ds, g, f, &x, &y);
  2879. draw_text(dr, x, y,
  2880. FONT_VARIABLE, ds->tilesize/2,
  2881. ALIGN_VCENTRE | ALIGN_HCENTRE,
  2882. ds->clue_error[i] ? COL_MISTAKE :
  2883. ds->clue_satisfied[i] ? COL_SATISFIED : COL_FOREGROUND, c);
  2884. }
  2885. static void edge_bbox(game_drawstate *ds, grid *g, grid_edge *e,
  2886. int *x, int *y, int *w, int *h)
  2887. {
  2888. int x1 = e->dot1->x;
  2889. int y1 = e->dot1->y;
  2890. int x2 = e->dot2->x;
  2891. int y2 = e->dot2->y;
  2892. int xmin, xmax, ymin, ymax;
  2893. grid_to_screen(ds, g, x1, y1, &x1, &y1);
  2894. grid_to_screen(ds, g, x2, y2, &x2, &y2);
  2895. /* Allow extra margin for dots, and thickness of lines */
  2896. xmin = min(x1, x2) - (ds->tilesize + 15) / 16;
  2897. xmax = max(x1, x2) + (ds->tilesize + 15) / 16;
  2898. ymin = min(y1, y2) - (ds->tilesize + 15) / 16;
  2899. ymax = max(y1, y2) + (ds->tilesize + 15) / 16;
  2900. *x = xmin;
  2901. *y = ymin;
  2902. *w = xmax - xmin + 1;
  2903. *h = ymax - ymin + 1;
  2904. }
  2905. static void dot_bbox(game_drawstate *ds, grid *g, grid_dot *d,
  2906. int *x, int *y, int *w, int *h)
  2907. {
  2908. int x1, y1;
  2909. int xmin, xmax, ymin, ymax;
  2910. grid_to_screen(ds, g, d->x, d->y, &x1, &y1);
  2911. xmin = x1 - (ds->tilesize * 5 + 63) / 64;
  2912. xmax = x1 + (ds->tilesize * 5 + 63) / 64;
  2913. ymin = y1 - (ds->tilesize * 5 + 63) / 64;
  2914. ymax = y1 + (ds->tilesize * 5 + 63) / 64;
  2915. *x = xmin;
  2916. *y = ymin;
  2917. *w = xmax - xmin + 1;
  2918. *h = ymax - ymin + 1;
  2919. }
  2920. static const int loopy_line_redraw_phases[] = {
  2921. COL_FAINT, COL_LINEUNKNOWN, COL_FOREGROUND, COL_HIGHLIGHT, COL_MISTAKE
  2922. };
  2923. #define NPHASES lenof(loopy_line_redraw_phases)
  2924. static void game_redraw_line(drawing *dr, game_drawstate *ds,const game_ui *ui,
  2925. const game_state *state, int i, int phase)
  2926. {
  2927. grid *g = state->game_grid;
  2928. grid_edge *e = g->edges[i];
  2929. int x1, x2, y1, y2;
  2930. int line_colour;
  2931. if (state->line_errors[i])
  2932. line_colour = COL_MISTAKE;
  2933. else if (state->lines[i] == LINE_UNKNOWN)
  2934. line_colour = COL_LINEUNKNOWN;
  2935. else if (state->lines[i] == LINE_NO)
  2936. line_colour = COL_FAINT;
  2937. else if (ds->flashing)
  2938. line_colour = COL_HIGHLIGHT;
  2939. else
  2940. line_colour = COL_FOREGROUND;
  2941. if (line_colour != loopy_line_redraw_phases[phase])
  2942. return;
  2943. /* Convert from grid to screen coordinates */
  2944. grid_to_screen(ds, g, e->dot1->x, e->dot1->y, &x1, &y1);
  2945. grid_to_screen(ds, g, e->dot2->x, e->dot2->y, &x2, &y2);
  2946. if (line_colour == COL_FAINT) {
  2947. if (ui->draw_faint_lines)
  2948. draw_thick_line(dr, ds->tilesize/24.0,
  2949. x1 + 0.5, y1 + 0.5,
  2950. x2 + 0.5, y2 + 0.5,
  2951. line_colour);
  2952. } else {
  2953. draw_thick_line(dr, ds->tilesize*3/32.0,
  2954. x1 + 0.5, y1 + 0.5,
  2955. x2 + 0.5, y2 + 0.5,
  2956. line_colour);
  2957. }
  2958. }
  2959. static void game_redraw_dot(drawing *dr, game_drawstate *ds,
  2960. const game_state *state, int i)
  2961. {
  2962. grid *g = state->game_grid;
  2963. grid_dot *d = g->dots[i];
  2964. int x, y;
  2965. grid_to_screen(ds, g, d->x, d->y, &x, &y);
  2966. draw_circle(dr, x, y, ds->tilesize*2.5/32.0, COL_FOREGROUND, COL_FOREGROUND);
  2967. }
  2968. static bool boxes_intersect(int x0, int y0, int w0, int h0,
  2969. int x1, int y1, int w1, int h1)
  2970. {
  2971. /*
  2972. * Two intervals intersect iff neither is wholly on one side of
  2973. * the other. Two boxes intersect iff their horizontal and
  2974. * vertical intervals both intersect.
  2975. */
  2976. return (x0 < x1+w1 && x1 < x0+w0 && y0 < y1+h1 && y1 < y0+h0);
  2977. }
  2978. static void game_redraw_in_rect(drawing *dr, game_drawstate *ds,
  2979. const game_ui *ui, const game_state *state,
  2980. int x, int y, int w, int h)
  2981. {
  2982. grid *g = state->game_grid;
  2983. int i, phase;
  2984. int bx, by, bw, bh;
  2985. clip(dr, x, y, w, h);
  2986. draw_rect(dr, x, y, w, h, COL_BACKGROUND);
  2987. for (i = 0; i < g->num_faces; i++) {
  2988. if (state->clues[i] >= 0) {
  2989. face_text_bbox(ds, g, g->faces[i], &bx, &by, &bw, &bh);
  2990. if (boxes_intersect(x, y, w, h, bx, by, bw, bh))
  2991. game_redraw_clue(dr, ds, state, i);
  2992. }
  2993. }
  2994. for (phase = 0; phase < NPHASES; phase++) {
  2995. for (i = 0; i < g->num_edges; i++) {
  2996. edge_bbox(ds, g, g->edges[i], &bx, &by, &bw, &bh);
  2997. if (boxes_intersect(x, y, w, h, bx, by, bw, bh))
  2998. game_redraw_line(dr, ds, ui, state, i, phase);
  2999. }
  3000. }
  3001. for (i = 0; i < g->num_dots; i++) {
  3002. dot_bbox(ds, g, g->dots[i], &bx, &by, &bw, &bh);
  3003. if (boxes_intersect(x, y, w, h, bx, by, bw, bh))
  3004. game_redraw_dot(dr, ds, state, i);
  3005. }
  3006. unclip(dr);
  3007. draw_update(dr, x, y, w, h);
  3008. }
  3009. static void game_redraw(drawing *dr, game_drawstate *ds,
  3010. const game_state *oldstate, const game_state *state,
  3011. int dir, const game_ui *ui,
  3012. float animtime, float flashtime)
  3013. {
  3014. #define REDRAW_OBJECTS_LIMIT 16 /* Somewhat arbitrary tradeoff */
  3015. grid *g = state->game_grid;
  3016. int border = BORDER(ds->tilesize);
  3017. int i;
  3018. bool flash_changed;
  3019. bool redraw_everything = false;
  3020. int edges[REDRAW_OBJECTS_LIMIT], nedges = 0;
  3021. int faces[REDRAW_OBJECTS_LIMIT], nfaces = 0;
  3022. /* Redrawing is somewhat involved.
  3023. *
  3024. * An update can theoretically affect an arbitrary number of edges
  3025. * (consider, for example, completing or breaking a cycle which doesn't
  3026. * satisfy all the clues -- we'll switch many edges between error and
  3027. * normal states). On the other hand, redrawing the whole grid takes a
  3028. * while, making the game feel sluggish, and many updates are actually
  3029. * quite well localized.
  3030. *
  3031. * This redraw algorithm attempts to cope with both situations gracefully
  3032. * and correctly. For localized changes, we set a clip rectangle, fill
  3033. * it with background, and then redraw (a plausible but conservative
  3034. * guess at) the objects which intersect the rectangle; if several
  3035. * objects need redrawing, we'll do them individually. However, if lots
  3036. * of objects are affected, we'll just redraw everything.
  3037. *
  3038. * The reason for all of this is that it's just not safe to do the redraw
  3039. * piecemeal. If you try to draw an antialiased diagonal line over
  3040. * itself, you get a slightly thicker antialiased diagonal line, which
  3041. * looks rather ugly after a while.
  3042. *
  3043. * So, we take two passes over the grid. The first attempts to work out
  3044. * what needs doing, and the second actually does it.
  3045. */
  3046. if (!ds->started) {
  3047. redraw_everything = true;
  3048. /*
  3049. * But we must still go through the upcoming loops, so that we
  3050. * set up stuff in ds correctly for the initial redraw.
  3051. */
  3052. }
  3053. /* First, trundle through the faces. */
  3054. for (i = 0; i < g->num_faces; i++) {
  3055. grid_face *f = g->faces[i];
  3056. int sides = f->order;
  3057. int yes_order, no_order;
  3058. bool clue_mistake;
  3059. bool clue_satisfied;
  3060. int n = state->clues[i];
  3061. if (n < 0)
  3062. continue;
  3063. yes_order = face_order(state, i, LINE_YES);
  3064. if (state->exactly_one_loop) {
  3065. /*
  3066. * Special case: if the set of LINE_YES edges in the grid
  3067. * consists of exactly one loop and nothing else, then we
  3068. * switch to treating LINE_UNKNOWN the same as LINE_NO for
  3069. * purposes of clue checking.
  3070. *
  3071. * This is because some people like to play Loopy without
  3072. * using the right-click, i.e. never setting anything to
  3073. * LINE_NO. Without this special case, if a person playing
  3074. * in that style fills in what they think is a correct
  3075. * solution loop but in fact it has an underfilled clue,
  3076. * then we will display no victory flash and also no error
  3077. * highlight explaining why not. With this special case,
  3078. * we light up underfilled clues at the instant the loop
  3079. * is closed. (Of course, *overfilled* clues are fine
  3080. * either way.)
  3081. *
  3082. * (It might still be considered unfortunate that we can't
  3083. * warn this style of player any earlier, if they make a
  3084. * mistake very near the beginning which doesn't show up
  3085. * until they close the last edge of the loop. One other
  3086. * thing we _could_ do here is to treat any LINE_UNKNOWN
  3087. * as LINE_NO if either of its endpoints has yes-degree 2,
  3088. * reflecting the fact that setting that line to YES would
  3089. * be an obvious error. But I don't think even that could
  3090. * catch _all_ clue errors in a timely manner; I think
  3091. * there are some that won't be displayed until the loop
  3092. * is filled in, even so, and there's no way to avoid that
  3093. * with complete reliability except to switch to being a
  3094. * player who sets things to LINE_NO.)
  3095. */
  3096. no_order = sides - yes_order;
  3097. } else {
  3098. no_order = face_order(state, i, LINE_NO);
  3099. }
  3100. clue_mistake = (yes_order > n || no_order > (sides-n));
  3101. clue_satisfied = (yes_order == n && no_order == (sides-n));
  3102. if (clue_mistake != ds->clue_error[i] ||
  3103. clue_satisfied != ds->clue_satisfied[i]) {
  3104. ds->clue_error[i] = clue_mistake;
  3105. ds->clue_satisfied[i] = clue_satisfied;
  3106. if (nfaces == REDRAW_OBJECTS_LIMIT)
  3107. redraw_everything = true;
  3108. else
  3109. faces[nfaces++] = i;
  3110. }
  3111. }
  3112. /* Work out what the flash state needs to be. */
  3113. if (flashtime > 0 &&
  3114. (flashtime <= FLASH_TIME/3 ||
  3115. flashtime >= FLASH_TIME*2/3)) {
  3116. flash_changed = !ds->flashing;
  3117. ds->flashing = true;
  3118. } else {
  3119. flash_changed = ds->flashing;
  3120. ds->flashing = false;
  3121. }
  3122. /* Now, trundle through the edges. */
  3123. for (i = 0; i < g->num_edges; i++) {
  3124. char new_ds =
  3125. state->line_errors[i] ? DS_LINE_ERROR : state->lines[i];
  3126. if (new_ds != ds->lines[i] ||
  3127. (flash_changed && state->lines[i] == LINE_YES)) {
  3128. ds->lines[i] = new_ds;
  3129. if (nedges == REDRAW_OBJECTS_LIMIT)
  3130. redraw_everything = true;
  3131. else
  3132. edges[nedges++] = i;
  3133. }
  3134. }
  3135. /* Pass one is now done. Now we do the actual drawing. */
  3136. if (redraw_everything) {
  3137. int grid_width = g->highest_x - g->lowest_x;
  3138. int grid_height = g->highest_y - g->lowest_y;
  3139. int w = grid_width * ds->tilesize / g->tilesize;
  3140. int h = grid_height * ds->tilesize / g->tilesize;
  3141. game_redraw_in_rect(dr, ds, ui, state,
  3142. 0, 0, w + 2*border + 1, h + 2*border + 1);
  3143. } else {
  3144. /* Right. Now we roll up our sleeves. */
  3145. for (i = 0; i < nfaces; i++) {
  3146. grid_face *f = g->faces[faces[i]];
  3147. int x, y, w, h;
  3148. face_text_bbox(ds, g, f, &x, &y, &w, &h);
  3149. game_redraw_in_rect(dr, ds, ui, state, x, y, w, h);
  3150. }
  3151. for (i = 0; i < nedges; i++) {
  3152. grid_edge *e = g->edges[edges[i]];
  3153. int x, y, w, h;
  3154. edge_bbox(ds, g, e, &x, &y, &w, &h);
  3155. game_redraw_in_rect(dr, ds, ui, state, x, y, w, h);
  3156. }
  3157. }
  3158. ds->started = true;
  3159. }
  3160. static float game_flash_length(const game_state *oldstate,
  3161. const game_state *newstate, int dir, game_ui *ui)
  3162. {
  3163. if (!oldstate->solved && newstate->solved &&
  3164. !oldstate->cheated && !newstate->cheated) {
  3165. return FLASH_TIME;
  3166. }
  3167. return 0.0F;
  3168. }
  3169. static void game_get_cursor_location(const game_ui *ui,
  3170. const game_drawstate *ds,
  3171. const game_state *state,
  3172. const game_params *params,
  3173. int *x, int *y, int *w, int *h)
  3174. {
  3175. }
  3176. static int game_status(const game_state *state)
  3177. {
  3178. return state->solved ? +1 : 0;
  3179. }
  3180. static void game_print_size(const game_params *params, const game_ui *ui,
  3181. float *x, float *y)
  3182. {
  3183. int pw, ph;
  3184. /*
  3185. * I'll use 7mm "squares" by default.
  3186. */
  3187. game_compute_size(params, 700, ui, &pw, &ph);
  3188. *x = pw / 100.0F;
  3189. *y = ph / 100.0F;
  3190. }
  3191. static void game_print(drawing *dr, const game_state *state, const game_ui *ui,
  3192. int tilesize)
  3193. {
  3194. int ink = print_mono_colour(dr, 0);
  3195. int i;
  3196. game_drawstate ads, *ds = &ads;
  3197. grid *g = state->game_grid;
  3198. ds->tilesize = tilesize;
  3199. ds->textx = snewn(g->num_faces, int);
  3200. ds->texty = snewn(g->num_faces, int);
  3201. for (i = 0; i < g->num_faces; i++)
  3202. ds->textx[i] = ds->texty[i] = -1;
  3203. for (i = 0; i < g->num_dots; i++) {
  3204. int x, y;
  3205. grid_to_screen(ds, g, g->dots[i]->x, g->dots[i]->y, &x, &y);
  3206. draw_circle(dr, x, y, ds->tilesize / 15, ink, ink);
  3207. }
  3208. /*
  3209. * Clues.
  3210. */
  3211. for (i = 0; i < g->num_faces; i++) {
  3212. grid_face *f = g->faces[i];
  3213. int clue = state->clues[i];
  3214. if (clue >= 0) {
  3215. char c[20];
  3216. int x, y;
  3217. sprintf(c, "%d", state->clues[i]);
  3218. face_text_pos(ds, g, f, &x, &y);
  3219. draw_text(dr, x, y,
  3220. FONT_VARIABLE, ds->tilesize / 2,
  3221. ALIGN_VCENTRE | ALIGN_HCENTRE, ink, c);
  3222. }
  3223. }
  3224. /*
  3225. * Lines.
  3226. */
  3227. for (i = 0; i < g->num_edges; i++) {
  3228. int thickness = (state->lines[i] == LINE_YES) ? 30 : 150;
  3229. grid_edge *e = g->edges[i];
  3230. int x1, y1, x2, y2;
  3231. grid_to_screen(ds, g, e->dot1->x, e->dot1->y, &x1, &y1);
  3232. grid_to_screen(ds, g, e->dot2->x, e->dot2->y, &x2, &y2);
  3233. if (state->lines[i] == LINE_YES)
  3234. {
  3235. /* (dx, dy) points from (x1, y1) to (x2, y2).
  3236. * The line is then "fattened" in a perpendicular
  3237. * direction to create a thin rectangle. */
  3238. double d = sqrt(SQ((double)x1 - x2) + SQ((double)y1 - y2));
  3239. double dx = (x2 - x1) / d;
  3240. double dy = (y2 - y1) / d;
  3241. int points[8];
  3242. dx = (dx * ds->tilesize) / thickness;
  3243. dy = (dy * ds->tilesize) / thickness;
  3244. points[0] = x1 + (int)dy;
  3245. points[1] = y1 - (int)dx;
  3246. points[2] = x1 - (int)dy;
  3247. points[3] = y1 + (int)dx;
  3248. points[4] = x2 - (int)dy;
  3249. points[5] = y2 + (int)dx;
  3250. points[6] = x2 + (int)dy;
  3251. points[7] = y2 - (int)dx;
  3252. draw_polygon(dr, points, 4, ink, ink);
  3253. }
  3254. else
  3255. {
  3256. /* Draw a dotted line */
  3257. int divisions = 6;
  3258. int j;
  3259. for (j = 1; j < divisions; j++) {
  3260. /* Weighted average */
  3261. int x = (x1 * (divisions -j) + x2 * j) / divisions;
  3262. int y = (y1 * (divisions -j) + y2 * j) / divisions;
  3263. draw_circle(dr, x, y, ds->tilesize / thickness, ink, ink);
  3264. }
  3265. }
  3266. }
  3267. sfree(ds->textx);
  3268. sfree(ds->texty);
  3269. }
  3270. #ifdef COMBINED
  3271. #define thegame loopy
  3272. #endif
  3273. const struct game thegame = {
  3274. "Loopy", "games.loopy", "loopy",
  3275. default_params,
  3276. NULL, game_preset_menu,
  3277. decode_params,
  3278. encode_params,
  3279. free_params,
  3280. dup_params,
  3281. true, game_configure, custom_params,
  3282. validate_params,
  3283. new_game_desc,
  3284. validate_desc,
  3285. new_game,
  3286. dup_game,
  3287. free_game,
  3288. true, solve_game,
  3289. true, game_can_format_as_text_now, game_text_format,
  3290. get_prefs, set_prefs,
  3291. new_ui,
  3292. free_ui,
  3293. NULL, /* encode_ui */
  3294. NULL, /* decode_ui */
  3295. NULL, /* game_request_keys */
  3296. game_changed_state,
  3297. NULL, /* current_key_label */
  3298. interpret_move,
  3299. execute_move,
  3300. PREFERRED_TILE_SIZE, game_compute_size, game_set_size,
  3301. game_colours,
  3302. game_new_drawstate,
  3303. game_free_drawstate,
  3304. game_redraw,
  3305. game_anim_length,
  3306. game_flash_length,
  3307. game_get_cursor_location,
  3308. game_status,
  3309. true, false, game_print_size, game_print,
  3310. false /* wants_statusbar */,
  3311. false, NULL, /* timing_state */
  3312. 0, /* mouse_priorities */
  3313. };
  3314. #ifdef STANDALONE_SOLVER
  3315. /*
  3316. * Half-hearted standalone solver. It can't output the solution to
  3317. * anything but a square puzzle, and it can't log the deductions
  3318. * it makes either. But it can solve square puzzles, and more
  3319. * importantly it can use its solver to grade the difficulty of
  3320. * any puzzle you give it.
  3321. */
  3322. #include <stdarg.h>
  3323. int main(int argc, char **argv)
  3324. {
  3325. game_params *p;
  3326. game_state *s;
  3327. char *id = NULL, *desc;
  3328. const char *err;
  3329. bool grade = false;
  3330. int ret, diff;
  3331. #if 0 /* verbose solver not supported here (yet) */
  3332. bool really_verbose = false;
  3333. #endif
  3334. while (--argc > 0) {
  3335. char *p = *++argv;
  3336. #if 0 /* verbose solver not supported here (yet) */
  3337. if (!strcmp(p, "-v")) {
  3338. really_verbose = true;
  3339. } else
  3340. #endif
  3341. if (!strcmp(p, "-g")) {
  3342. grade = true;
  3343. } else if (*p == '-') {
  3344. fprintf(stderr, "%s: unrecognised option `%s'\n", argv[0], p);
  3345. return 1;
  3346. } else {
  3347. id = p;
  3348. }
  3349. }
  3350. if (!id) {
  3351. fprintf(stderr, "usage: %s [-g | -v] <game_id>\n", argv[0]);
  3352. return 1;
  3353. }
  3354. desc = strchr(id, ':');
  3355. if (!desc) {
  3356. fprintf(stderr, "%s: game id expects a colon in it\n", argv[0]);
  3357. return 1;
  3358. }
  3359. *desc++ = '\0';
  3360. p = default_params();
  3361. decode_params(p, id);
  3362. err = validate_desc(p, desc);
  3363. if (err) {
  3364. fprintf(stderr, "%s: %s\n", argv[0], err);
  3365. return 1;
  3366. }
  3367. s = new_game(NULL, p, desc);
  3368. /*
  3369. * When solving an Easy puzzle, we don't want to bother the
  3370. * user with Hard-level deductions. For this reason, we grade
  3371. * the puzzle internally before doing anything else.
  3372. */
  3373. ret = -1; /* placate optimiser */
  3374. for (diff = 0; diff < DIFF_MAX; diff++) {
  3375. solver_state *sstate_new;
  3376. solver_state *sstate = new_solver_state((game_state *)s, diff);
  3377. sstate_new = solve_game_rec(sstate);
  3378. if (sstate_new->solver_status == SOLVER_MISTAKE)
  3379. ret = 0;
  3380. else if (sstate_new->solver_status == SOLVER_SOLVED)
  3381. ret = 1;
  3382. else
  3383. ret = 2;
  3384. free_solver_state(sstate_new);
  3385. free_solver_state(sstate);
  3386. if (ret < 2)
  3387. break;
  3388. }
  3389. if (diff == DIFF_MAX) {
  3390. if (grade)
  3391. printf("Difficulty rating: harder than Hard, or ambiguous\n");
  3392. else
  3393. printf("Unable to find a unique solution\n");
  3394. } else {
  3395. if (grade) {
  3396. if (ret == 0)
  3397. printf("Difficulty rating: impossible (no solution exists)\n");
  3398. else if (ret == 1)
  3399. printf("Difficulty rating: %s\n", diffnames[diff]);
  3400. } else {
  3401. solver_state *sstate_new;
  3402. solver_state *sstate = new_solver_state((game_state *)s, diff);
  3403. /* If we supported a verbose solver, we'd set verbosity here */
  3404. sstate_new = solve_game_rec(sstate);
  3405. if (sstate_new->solver_status == SOLVER_MISTAKE)
  3406. printf("Puzzle is inconsistent\n");
  3407. else {
  3408. assert(sstate_new->solver_status == SOLVER_SOLVED);
  3409. if (s->grid_type == 0) {
  3410. fputs(game_text_format(sstate_new->state), stdout);
  3411. } else {
  3412. printf("Unable to output non-square grids\n");
  3413. }
  3414. }
  3415. free_solver_state(sstate_new);
  3416. free_solver_state(sstate);
  3417. }
  3418. }
  3419. return 0;
  3420. }
  3421. #endif
  3422. /* vim: set shiftwidth=4 tabstop=8: */