signpost.c 76 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561
  1. /*
  2. * signpost.c: implementation of the janko game 'arrow path'
  3. */
  4. #include <stdio.h>
  5. #include <stdlib.h>
  6. #include <string.h>
  7. #include <assert.h>
  8. #include <ctype.h>
  9. #include <limits.h>
  10. #ifdef NO_TGMATH_H
  11. # include <math.h>
  12. #else
  13. # include <tgmath.h>
  14. #endif
  15. #include "puzzles.h"
  16. #define PREFERRED_TILE_SIZE 48
  17. #define TILE_SIZE (ds->tilesize)
  18. #define BLITTER_SIZE TILE_SIZE
  19. #define BORDER (TILE_SIZE / 2)
  20. #define COORD(x) ( (x) * TILE_SIZE + BORDER )
  21. #define FROMCOORD(x) ( ((x) - BORDER + TILE_SIZE) / TILE_SIZE - 1 )
  22. #define INGRID(s,x,y) ((x) >= 0 && (x) < (s)->w && (y) >= 0 && (y) < (s)->h)
  23. #define FLASH_SPIN 0.7F
  24. #define NBACKGROUNDS 16
  25. enum {
  26. COL_BACKGROUND, COL_HIGHLIGHT, COL_LOWLIGHT,
  27. COL_GRID, COL_CURSOR, COL_ERROR, COL_DRAG_ORIGIN,
  28. COL_ARROW, COL_ARROW_BG_DIM,
  29. COL_NUMBER, COL_NUMBER_SET, COL_NUMBER_SET_MID,
  30. COL_B0, /* background colours */
  31. COL_M0 = COL_B0 + 1*NBACKGROUNDS, /* mid arrow colours */
  32. COL_D0 = COL_B0 + 2*NBACKGROUNDS, /* dim arrow colours */
  33. COL_X0 = COL_B0 + 3*NBACKGROUNDS, /* dim arrow colours */
  34. NCOLOURS = COL_B0 + 4*NBACKGROUNDS
  35. };
  36. struct game_params {
  37. int w, h;
  38. bool force_corner_start;
  39. };
  40. enum { DIR_N = 0, DIR_NE, DIR_E, DIR_SE, DIR_S, DIR_SW, DIR_W, DIR_NW, DIR_MAX };
  41. static const char *dirstrings[8] = { "N ", "NE", "E ", "SE", "S ", "SW", "W ", "NW" };
  42. static const int dxs[DIR_MAX] = { 0, 1, 1, 1, 0, -1, -1, -1 };
  43. static const int dys[DIR_MAX] = { -1, -1, 0, 1, 1, 1, 0, -1 };
  44. #define DIR_OPPOSITE(d) ((d+4)%8)
  45. struct game_state {
  46. int w, h, n;
  47. bool completed, used_solve, impossible;
  48. int *dirs; /* direction enums, size n */
  49. int *nums; /* numbers, size n */
  50. unsigned int *flags; /* flags, size n */
  51. int *next, *prev; /* links to other cell indexes, size n (-1 absent) */
  52. DSF *dsf; /* connects regions with a dsf. */
  53. int *numsi; /* for each number, which index is it in? (-1 absent) */
  54. };
  55. #define FLAG_IMMUTABLE 1
  56. #define FLAG_ERROR 2
  57. /* --- Generally useful functions --- */
  58. #define ISREALNUM(state, num) ((num) > 0 && (num) <= (state)->n)
  59. static int whichdir(int fromx, int fromy, int tox, int toy)
  60. {
  61. int i, dx, dy;
  62. dx = tox - fromx;
  63. dy = toy - fromy;
  64. if (dx && dy && abs(dx) != abs(dy)) return -1;
  65. if (dx) dx = dx / abs(dx); /* limit to (-1, 0, 1) */
  66. if (dy) dy = dy / abs(dy); /* ditto */
  67. for (i = 0; i < DIR_MAX; i++) {
  68. if (dx == dxs[i] && dy == dys[i]) return i;
  69. }
  70. return -1;
  71. }
  72. static int whichdiri(game_state *state, int fromi, int toi)
  73. {
  74. int w = state->w;
  75. return whichdir(fromi%w, fromi/w, toi%w, toi/w);
  76. }
  77. static bool ispointing(const game_state *state, int fromx, int fromy,
  78. int tox, int toy)
  79. {
  80. int w = state->w, dir = state->dirs[fromy*w+fromx];
  81. /* (by convention) squares do not point to themselves. */
  82. if (fromx == tox && fromy == toy) return false;
  83. /* the final number points to nothing. */
  84. if (state->nums[fromy*w + fromx] == state->n) return false;
  85. while (1) {
  86. if (!INGRID(state, fromx, fromy)) return false;
  87. if (fromx == tox && fromy == toy) return true;
  88. fromx += dxs[dir]; fromy += dys[dir];
  89. }
  90. return false; /* not reached */
  91. }
  92. static bool ispointingi(game_state *state, int fromi, int toi)
  93. {
  94. int w = state->w;
  95. return ispointing(state, fromi%w, fromi/w, toi%w, toi/w);
  96. }
  97. /* Taking the number 'num', work out the gap between it and the next
  98. * available number up or down (depending on d). Return true if the
  99. * region at (x,y) will fit in that gap. */
  100. static bool move_couldfit(
  101. const game_state *state, int num, int d, int x, int y)
  102. {
  103. int n, gap, i = y*state->w+x, sz;
  104. assert(d != 0);
  105. /* The 'gap' is the number of missing numbers in the grid between
  106. * our number and the next one in the sequence (up or down), or
  107. * the end of the sequence (if we happen not to have 1/n present) */
  108. for (n = num + d, gap = 0;
  109. ISREALNUM(state, n) && state->numsi[n] == -1;
  110. n += d, gap++) ; /* empty loop */
  111. if (gap == 0) {
  112. /* no gap, so the only allowable move is that that directly
  113. * links the two numbers. */
  114. n = state->nums[i];
  115. return n != num+d;
  116. }
  117. if (state->prev[i] == -1 && state->next[i] == -1)
  118. return true; /* single unconnected square, always OK */
  119. sz = dsf_size(state->dsf, i);
  120. return sz <= gap;
  121. }
  122. static bool isvalidmove(const game_state *state, bool clever,
  123. int fromx, int fromy, int tox, int toy)
  124. {
  125. int w = state->w, from = fromy*w+fromx, to = toy*w+tox;
  126. int nfrom, nto;
  127. if (!INGRID(state, fromx, fromy) || !INGRID(state, tox, toy))
  128. return false;
  129. /* can only move where we point */
  130. if (!ispointing(state, fromx, fromy, tox, toy))
  131. return false;
  132. nfrom = state->nums[from]; nto = state->nums[to];
  133. /* can't move _from_ the preset final number, or _to_ the preset 1. */
  134. if (((nfrom == state->n) && (state->flags[from] & FLAG_IMMUTABLE)) ||
  135. ((nto == 1) && (state->flags[to] & FLAG_IMMUTABLE)))
  136. return false;
  137. /* can't create a new connection between cells in the same region
  138. * as that would create a loop. */
  139. if (dsf_equivalent(state->dsf, from, to))
  140. return false;
  141. /* if both cells are actual numbers, can't drag if we're not
  142. * one digit apart. */
  143. if (ISREALNUM(state, nfrom) && ISREALNUM(state, nto)) {
  144. if (nfrom != nto-1)
  145. return false;
  146. } else if (clever && ISREALNUM(state, nfrom)) {
  147. if (!move_couldfit(state, nfrom, +1, tox, toy))
  148. return false;
  149. } else if (clever && ISREALNUM(state, nto)) {
  150. if (!move_couldfit(state, nto, -1, fromx, fromy))
  151. return false;
  152. }
  153. return true;
  154. }
  155. static void makelink(game_state *state, int from, int to)
  156. {
  157. if (state->next[from] != -1)
  158. state->prev[state->next[from]] = -1;
  159. state->next[from] = to;
  160. if (state->prev[to] != -1)
  161. state->next[state->prev[to]] = -1;
  162. state->prev[to] = from;
  163. }
  164. static bool game_can_format_as_text_now(const game_params *params)
  165. {
  166. if (params->w * params->h >= 100) return false;
  167. return true;
  168. }
  169. static char *game_text_format(const game_state *state)
  170. {
  171. int len = state->h * 2 * (4*state->w + 1) + state->h + 2;
  172. int x, y, i, num, n, set;
  173. char *ret, *p;
  174. p = ret = snewn(len, char);
  175. for (y = 0; y < state->h; y++) {
  176. for (x = 0; x < state->h; x++) {
  177. i = y*state->w+x;
  178. *p++ = dirstrings[state->dirs[i]][0];
  179. *p++ = dirstrings[state->dirs[i]][1];
  180. *p++ = (state->flags[i] & FLAG_IMMUTABLE) ? 'I' : ' ';
  181. *p++ = ' ';
  182. }
  183. *p++ = '\n';
  184. for (x = 0; x < state->h; x++) {
  185. i = y*state->w+x;
  186. num = state->nums[i];
  187. if (num == 0) {
  188. *p++ = ' ';
  189. *p++ = ' ';
  190. *p++ = ' ';
  191. } else {
  192. n = num % (state->n+1);
  193. set = num / (state->n+1);
  194. assert(n <= 99); /* two digits only! */
  195. if (set != 0)
  196. *p++ = set+'a'-1;
  197. *p++ = (n >= 10) ? ('0' + (n/10)) : ' ';
  198. *p++ = '0' + (n%10);
  199. if (set == 0)
  200. *p++ = ' ';
  201. }
  202. *p++ = ' ';
  203. }
  204. *p++ = '\n';
  205. *p++ = '\n';
  206. }
  207. *p++ = '\0';
  208. return ret;
  209. }
  210. static void debug_state(const char *desc, game_state *state)
  211. {
  212. #ifdef DEBUGGING
  213. char *dbg;
  214. if (state->n >= 100) {
  215. debug(("[ no game_text_format for this size ]"));
  216. return;
  217. }
  218. dbg = game_text_format(state);
  219. debug(("%s\n%s", desc, dbg));
  220. sfree(dbg);
  221. #endif
  222. }
  223. static void strip_nums(game_state *state) {
  224. int i;
  225. for (i = 0; i < state->n; i++) {
  226. if (!(state->flags[i] & FLAG_IMMUTABLE))
  227. state->nums[i] = 0;
  228. }
  229. memset(state->next, -1, state->n*sizeof(int));
  230. memset(state->prev, -1, state->n*sizeof(int));
  231. memset(state->numsi, -1, (state->n+1)*sizeof(int));
  232. dsf_reinit(state->dsf);
  233. }
  234. static bool check_nums(game_state *orig, game_state *copy, bool only_immutable)
  235. {
  236. int i;
  237. bool ret = true;
  238. assert(copy->n == orig->n);
  239. for (i = 0; i < copy->n; i++) {
  240. if (only_immutable && !(copy->flags[i] & FLAG_IMMUTABLE)) continue;
  241. assert(copy->nums[i] >= 0);
  242. assert(copy->nums[i] <= copy->n);
  243. if (copy->nums[i] != orig->nums[i]) {
  244. debug(("check_nums: (%d,%d) copy=%d, orig=%d.",
  245. i%orig->w, i/orig->w, copy->nums[i], orig->nums[i]));
  246. ret = false;
  247. }
  248. }
  249. return ret;
  250. }
  251. /* --- Game parameter/presets functions --- */
  252. static game_params *default_params(void)
  253. {
  254. game_params *ret = snew(game_params);
  255. ret->w = ret->h = 4;
  256. ret->force_corner_start = true;
  257. return ret;
  258. }
  259. static const struct game_params signpost_presets[] = {
  260. { 4, 4, 1 },
  261. { 4, 4, 0 },
  262. { 5, 5, 1 },
  263. { 5, 5, 0 },
  264. { 6, 6, 1 },
  265. { 7, 7, 1 }
  266. };
  267. static bool game_fetch_preset(int i, char **name, game_params **params)
  268. {
  269. game_params *ret;
  270. char buf[80];
  271. if (i < 0 || i >= lenof(signpost_presets))
  272. return false;
  273. ret = default_params();
  274. *ret = signpost_presets[i];
  275. *params = ret;
  276. sprintf(buf, "%dx%d%s", ret->w, ret->h,
  277. ret->force_corner_start ? "" : ", free ends");
  278. *name = dupstr(buf);
  279. return true;
  280. }
  281. static void free_params(game_params *params)
  282. {
  283. sfree(params);
  284. }
  285. static game_params *dup_params(const game_params *params)
  286. {
  287. game_params *ret = snew(game_params);
  288. *ret = *params; /* structure copy */
  289. return ret;
  290. }
  291. static void decode_params(game_params *ret, char const *string)
  292. {
  293. ret->w = ret->h = atoi(string);
  294. while (*string && isdigit((unsigned char)*string)) string++;
  295. if (*string == 'x') {
  296. string++;
  297. ret->h = atoi(string);
  298. while (*string && isdigit((unsigned char)*string)) string++;
  299. }
  300. ret->force_corner_start = false;
  301. if (*string == 'c') {
  302. string++;
  303. ret->force_corner_start = true;
  304. }
  305. }
  306. static char *encode_params(const game_params *params, bool full)
  307. {
  308. char data[256];
  309. if (full)
  310. sprintf(data, "%dx%d%s", params->w, params->h,
  311. params->force_corner_start ? "c" : "");
  312. else
  313. sprintf(data, "%dx%d", params->w, params->h);
  314. return dupstr(data);
  315. }
  316. static config_item *game_configure(const game_params *params)
  317. {
  318. config_item *ret;
  319. char buf[80];
  320. ret = snewn(4, config_item);
  321. ret[0].name = "Width";
  322. ret[0].type = C_STRING;
  323. sprintf(buf, "%d", params->w);
  324. ret[0].u.string.sval = dupstr(buf);
  325. ret[1].name = "Height";
  326. ret[1].type = C_STRING;
  327. sprintf(buf, "%d", params->h);
  328. ret[1].u.string.sval = dupstr(buf);
  329. ret[2].name = "Start and end in corners";
  330. ret[2].type = C_BOOLEAN;
  331. ret[2].u.boolean.bval = params->force_corner_start;
  332. ret[3].name = NULL;
  333. ret[3].type = C_END;
  334. return ret;
  335. }
  336. static game_params *custom_params(const config_item *cfg)
  337. {
  338. game_params *ret = snew(game_params);
  339. ret->w = atoi(cfg[0].u.string.sval);
  340. ret->h = atoi(cfg[1].u.string.sval);
  341. ret->force_corner_start = cfg[2].u.boolean.bval;
  342. return ret;
  343. }
  344. static const char *validate_params(const game_params *params, bool full)
  345. {
  346. if (params->w < 1) return "Width must be at least one";
  347. if (params->h < 1) return "Height must be at least one";
  348. if (params->w > INT_MAX / params->h)
  349. return "Width times height must not be unreasonably large";
  350. if (full && params->w == 1 && params->h == 1)
  351. /* The UI doesn't let us move these from unsolved to solved,
  352. * so we disallow generating (but not playing) them. */
  353. return "Width and height cannot both be one";
  354. return NULL;
  355. }
  356. /* --- Game description string generation and unpicking --- */
  357. static void blank_game_into(game_state *state)
  358. {
  359. memset(state->dirs, 0, state->n*sizeof(int));
  360. memset(state->nums, 0, state->n*sizeof(int));
  361. memset(state->flags, 0, state->n*sizeof(unsigned int));
  362. memset(state->next, -1, state->n*sizeof(int));
  363. memset(state->prev, -1, state->n*sizeof(int));
  364. memset(state->numsi, -1, (state->n+1)*sizeof(int));
  365. }
  366. static game_state *blank_game(int w, int h)
  367. {
  368. game_state *state = snew(game_state);
  369. memset(state, 0, sizeof(game_state));
  370. state->w = w;
  371. state->h = h;
  372. state->n = w*h;
  373. state->dirs = snewn(state->n, int);
  374. state->nums = snewn(state->n, int);
  375. state->flags = snewn(state->n, unsigned int);
  376. state->next = snewn(state->n, int);
  377. state->prev = snewn(state->n, int);
  378. state->dsf = dsf_new(state->n);
  379. state->numsi = snewn(state->n+1, int);
  380. blank_game_into(state);
  381. return state;
  382. }
  383. static void dup_game_to(game_state *to, const game_state *from)
  384. {
  385. to->completed = from->completed;
  386. to->used_solve = from->used_solve;
  387. to->impossible = from->impossible;
  388. memcpy(to->dirs, from->dirs, to->n*sizeof(int));
  389. memcpy(to->flags, from->flags, to->n*sizeof(unsigned int));
  390. memcpy(to->nums, from->nums, to->n*sizeof(int));
  391. memcpy(to->next, from->next, to->n*sizeof(int));
  392. memcpy(to->prev, from->prev, to->n*sizeof(int));
  393. dsf_copy(to->dsf, from->dsf);
  394. memcpy(to->numsi, from->numsi, (to->n+1)*sizeof(int));
  395. }
  396. static game_state *dup_game(const game_state *state)
  397. {
  398. game_state *ret = blank_game(state->w, state->h);
  399. dup_game_to(ret, state);
  400. return ret;
  401. }
  402. static void free_game(game_state *state)
  403. {
  404. sfree(state->dirs);
  405. sfree(state->nums);
  406. sfree(state->flags);
  407. sfree(state->next);
  408. sfree(state->prev);
  409. dsf_free(state->dsf);
  410. sfree(state->numsi);
  411. sfree(state);
  412. }
  413. static void unpick_desc(const game_params *params, const char *desc,
  414. game_state **sout, const char **mout)
  415. {
  416. game_state *state = blank_game(params->w, params->h);
  417. const char *msg = NULL;
  418. char c;
  419. int num = 0, i = 0;
  420. while (*desc) {
  421. if (i >= state->n) {
  422. msg = "Game description longer than expected";
  423. goto done;
  424. }
  425. c = *desc;
  426. if (isdigit((unsigned char)c)) {
  427. num = (num*10) + (int)(c-'0');
  428. if (num > state->n) {
  429. msg = "Number too large";
  430. goto done;
  431. }
  432. } else if ((c-'a') >= 0 && (c-'a') < DIR_MAX) {
  433. state->nums[i] = num;
  434. state->flags[i] = num ? FLAG_IMMUTABLE : 0;
  435. num = 0;
  436. state->dirs[i] = c - 'a';
  437. i++;
  438. } else if (!*desc) {
  439. msg = "Game description shorter than expected";
  440. goto done;
  441. } else {
  442. msg = "Game description contains unexpected characters";
  443. goto done;
  444. }
  445. desc++;
  446. }
  447. if (i < state->n) {
  448. msg = "Game description shorter than expected";
  449. goto done;
  450. }
  451. done:
  452. if (msg) { /* sth went wrong. */
  453. if (mout) *mout = msg;
  454. free_game(state);
  455. } else {
  456. if (mout) *mout = NULL;
  457. if (sout) *sout = state;
  458. else free_game(state);
  459. }
  460. }
  461. static char *generate_desc(game_state *state, bool issolve)
  462. {
  463. char *ret, buf[80];
  464. int retlen, i, k;
  465. ret = NULL; retlen = 0;
  466. if (issolve) {
  467. ret = sresize(ret, 2, char);
  468. ret[0] = 'S'; ret[1] = '\0';
  469. retlen += 1;
  470. }
  471. for (i = 0; i < state->n; i++) {
  472. if (state->nums[i])
  473. k = sprintf(buf, "%d%c", state->nums[i], (int)(state->dirs[i]+'a'));
  474. else
  475. k = sprintf(buf, "%c", (int)(state->dirs[i]+'a'));
  476. ret = sresize(ret, retlen + k + 1, char);
  477. strcpy(ret + retlen, buf);
  478. retlen += k;
  479. }
  480. return ret;
  481. }
  482. /* --- Game generation --- */
  483. /* Fills in preallocated arrays ai (indices) and ad (directions)
  484. * showing all non-numbered cells adjacent to index i, returns length */
  485. /* This function has been somewhat optimised... */
  486. static int cell_adj(game_state *state, int i, int *ai, int *ad)
  487. {
  488. int n = 0, a, x, y, sx, sy, dx, dy, newi;
  489. int w = state->w, h = state->h;
  490. sx = i % w; sy = i / w;
  491. for (a = 0; a < DIR_MAX; a++) {
  492. x = sx; y = sy;
  493. dx = dxs[a]; dy = dys[a];
  494. while (1) {
  495. x += dx; y += dy;
  496. if (x < 0 || y < 0 || x >= w || y >= h) break;
  497. newi = y*w + x;
  498. if (state->nums[newi] == 0) {
  499. ai[n] = newi;
  500. ad[n] = a;
  501. n++;
  502. }
  503. }
  504. }
  505. return n;
  506. }
  507. static bool new_game_fill(game_state *state, random_state *rs,
  508. int headi, int taili)
  509. {
  510. int nfilled, an, j;
  511. bool ret = false;
  512. int *aidx, *adir;
  513. aidx = snewn(state->n, int);
  514. adir = snewn(state->n, int);
  515. debug(("new_game_fill: headi=%d, taili=%d.", headi, taili));
  516. memset(state->nums, 0, state->n*sizeof(int));
  517. state->nums[headi] = 1;
  518. state->nums[taili] = state->n;
  519. state->dirs[taili] = 0;
  520. nfilled = 2;
  521. assert(state->n > 1);
  522. while (nfilled < state->n) {
  523. /* Try and expand _from_ headi; keep going if there's only one
  524. * place to go to. */
  525. an = cell_adj(state, headi, aidx, adir);
  526. do {
  527. if (an == 0) goto done;
  528. j = random_upto(rs, an);
  529. state->dirs[headi] = adir[j];
  530. state->nums[aidx[j]] = state->nums[headi] + 1;
  531. nfilled++;
  532. headi = aidx[j];
  533. an = cell_adj(state, headi, aidx, adir);
  534. } while (an == 1);
  535. if (nfilled == state->n) break;
  536. /* Try and expand _to_ taili; keep going if there's only one
  537. * place to go to. */
  538. an = cell_adj(state, taili, aidx, adir);
  539. do {
  540. if (an == 0) goto done;
  541. j = random_upto(rs, an);
  542. state->dirs[aidx[j]] = DIR_OPPOSITE(adir[j]);
  543. state->nums[aidx[j]] = state->nums[taili] - 1;
  544. nfilled++;
  545. taili = aidx[j];
  546. an = cell_adj(state, taili, aidx, adir);
  547. } while (an == 1);
  548. }
  549. /* If we get here we have headi and taili set but unconnected
  550. * by direction: we need to set headi's direction so as to point
  551. * at taili. */
  552. state->dirs[headi] = whichdiri(state, headi, taili);
  553. /* it could happen that our last two weren't in line; if that's the
  554. * case, we have to start again. */
  555. if (state->dirs[headi] != -1) ret = true;
  556. done:
  557. sfree(aidx);
  558. sfree(adir);
  559. return ret;
  560. }
  561. /* Better generator: with the 'generate, sprinkle numbers, solve,
  562. * repeat' algorithm we're _never_ generating anything greater than
  563. * 6x6, and spending all of our time in new_game_fill (and very little
  564. * in solve_state).
  565. *
  566. * So, new generator steps:
  567. * generate the grid, at random (same as now). Numbers 1 and N get
  568. immutable flag immediately.
  569. * squirrel that away for the solved state.
  570. *
  571. * (solve:) Try and solve it.
  572. * If we solved it, we're done:
  573. * generate the description from current immutable numbers,
  574. * free stuff that needs freeing,
  575. * return description + solved state.
  576. * If we didn't solve it:
  577. * count #tiles in state we've made deductions about.
  578. * while (1):
  579. * randomise a scratch array.
  580. * for each index in scratch (in turn):
  581. * if the cell isn't empty, continue (through scratch array)
  582. * set number + immutable in state.
  583. * try and solve state.
  584. * if we've solved it, we're done.
  585. * otherwise, count #tiles. If it's more than we had before:
  586. * good, break from this loop and re-randomise.
  587. * otherwise (number didn't help):
  588. * remove number and try next in scratch array.
  589. * if we've got to the end of the scratch array, no luck:
  590. free everything we need to, and go back to regenerate the grid.
  591. */
  592. static int solve_state(game_state *state);
  593. static void debug_desc(const char *what, game_state *state)
  594. {
  595. #if DEBUGGING
  596. {
  597. char *desc = generate_desc(state, 0);
  598. debug(("%s game state: %dx%d:%s", what, state->w, state->h, desc));
  599. sfree(desc);
  600. }
  601. #endif
  602. }
  603. /* Expects a fully-numbered game_state on input, and makes sure
  604. * FLAG_IMMUTABLE is only set on those numbers we need to solve
  605. * (as for a real new-game); returns true if it managed
  606. * this (such that it could solve it), or false if not. */
  607. static bool new_game_strip(game_state *state, random_state *rs)
  608. {
  609. int *scratch, i, j;
  610. bool ret = true;
  611. game_state *copy = dup_game(state);
  612. debug(("new_game_strip."));
  613. strip_nums(copy);
  614. debug_desc("Stripped", copy);
  615. if (solve_state(copy) > 0) {
  616. debug(("new_game_strip: soluble immediately after strip."));
  617. free_game(copy);
  618. return true;
  619. }
  620. scratch = snewn(state->n, int);
  621. for (i = 0; i < state->n; i++) scratch[i] = i;
  622. shuffle(scratch, state->n, sizeof(int), rs);
  623. /* This is scungy. It might just be quick enough.
  624. * It goes through, adding set numbers in empty squares
  625. * until either we run out of empty squares (in the one
  626. * we're half-solving) or else we solve it properly.
  627. * NB that we run the entire solver each time, which
  628. * strips the grid beforehand; we will save time if we
  629. * avoid that. */
  630. for (i = 0; i < state->n; i++) {
  631. j = scratch[i];
  632. if (copy->nums[j] > 0 && copy->nums[j] <= state->n)
  633. continue; /* already solved to a real number here. */
  634. assert(state->nums[j] <= state->n);
  635. debug(("new_game_strip: testing add IMMUTABLE number %d at square (%d,%d).",
  636. state->nums[j], j%state->w, j/state->w));
  637. copy->nums[j] = state->nums[j];
  638. copy->flags[j] |= FLAG_IMMUTABLE;
  639. state->flags[j] |= FLAG_IMMUTABLE;
  640. debug_state("Copy of state: ", copy);
  641. strip_nums(copy);
  642. if (solve_state(copy) > 0) goto solved;
  643. assert(check_nums(state, copy, true));
  644. }
  645. ret = false;
  646. goto done;
  647. solved:
  648. debug(("new_game_strip: now solved."));
  649. /* Since we added basically at random, try now to remove numbers
  650. * and see if we can still solve it; if we can (still), really
  651. * remove the number. Make sure we don't remove the anchor numbers
  652. * 1 and N. */
  653. for (i = 0; i < state->n; i++) {
  654. j = scratch[i];
  655. if ((state->flags[j] & FLAG_IMMUTABLE) &&
  656. (state->nums[j] != 1 && state->nums[j] != state->n)) {
  657. debug(("new_game_strip: testing remove IMMUTABLE number %d at square (%d,%d).",
  658. state->nums[j], j%state->w, j/state->w));
  659. state->flags[j] &= ~FLAG_IMMUTABLE;
  660. dup_game_to(copy, state);
  661. strip_nums(copy);
  662. if (solve_state(copy) > 0) {
  663. assert(check_nums(state, copy, false));
  664. debug(("new_game_strip: OK, removing number"));
  665. } else {
  666. assert(state->nums[j] <= state->n);
  667. debug(("new_game_strip: cannot solve, putting IMMUTABLE back."));
  668. copy->nums[j] = state->nums[j];
  669. state->flags[j] |= FLAG_IMMUTABLE;
  670. }
  671. }
  672. }
  673. done:
  674. debug(("new_game_strip: %ssuccessful.", ret ? "" : "not "));
  675. sfree(scratch);
  676. free_game(copy);
  677. return ret;
  678. }
  679. static char *new_game_desc(const game_params *params, random_state *rs,
  680. char **aux, bool interactive)
  681. {
  682. game_state *state = blank_game(params->w, params->h);
  683. char *ret;
  684. int headi, taili;
  685. /* this shouldn't happen (validate_params), but let's play it safe */
  686. if (params->w == 1 && params->h == 1) return dupstr("1a");
  687. generate:
  688. blank_game_into(state);
  689. /* keep trying until we fill successfully. */
  690. do {
  691. if (params->force_corner_start) {
  692. headi = 0;
  693. taili = state->n-1;
  694. } else {
  695. do {
  696. headi = random_upto(rs, state->n);
  697. taili = random_upto(rs, state->n);
  698. } while (headi == taili);
  699. }
  700. } while (!new_game_fill(state, rs, headi, taili));
  701. debug_state("Filled game:", state);
  702. assert(state->nums[headi] <= state->n);
  703. assert(state->nums[taili] <= state->n);
  704. state->flags[headi] |= FLAG_IMMUTABLE;
  705. state->flags[taili] |= FLAG_IMMUTABLE;
  706. /* This will have filled in directions and _all_ numbers.
  707. * Store the game definition for this, as the solved-state. */
  708. if (!new_game_strip(state, rs)) {
  709. goto generate;
  710. }
  711. strip_nums(state);
  712. {
  713. game_state *tosolve = dup_game(state);
  714. assert(solve_state(tosolve) > 0);
  715. free_game(tosolve);
  716. }
  717. ret = generate_desc(state, false);
  718. free_game(state);
  719. return ret;
  720. }
  721. static const char *validate_desc(const game_params *params, const char *desc)
  722. {
  723. const char *ret = NULL;
  724. unpick_desc(params, desc, NULL, &ret);
  725. return ret;
  726. }
  727. /* --- Linked-list and numbers array --- */
  728. /* Assuming numbers are always up-to-date, there are only four possibilities
  729. * for regions changing after a single valid move:
  730. *
  731. * 1) two differently-coloured regions being combined (the resulting colouring
  732. * should be based on the larger of the two regions)
  733. * 2) a numbered region having a single number added to the start (the
  734. * region's colour will remain, and the numbers will shift by 1)
  735. * 3) a numbered region having a single number added to the end (the
  736. * region's colour and numbering remains as-is)
  737. * 4) two unnumbered squares being joined (will pick the smallest unused set
  738. * of colours to use for the new region).
  739. *
  740. * There should never be any complications with regions containing 3 colours
  741. * being combined, since two of those colours should have been merged on a
  742. * previous move.
  743. *
  744. * Most of the complications are in ensuring we don't accidentally set two
  745. * regions with the same colour (e.g. if a region was split). If this happens
  746. * we always try and give the largest original portion the original colour.
  747. */
  748. #define COLOUR(a) ((a) / (state->n+1))
  749. #define START(c) ((c) * (state->n+1))
  750. struct head_meta {
  751. int i; /* position */
  752. int sz; /* size of region */
  753. int start; /* region start number preferred, or 0 if !preference */
  754. int preference; /* 0 if we have no preference (and should just pick one) */
  755. const char *why;
  756. };
  757. static void head_number(game_state *state, int i, struct head_meta *head)
  758. {
  759. int off = 0, ss, j = i, c, n, sz;
  760. /* Insist we really were passed the head of a chain. */
  761. assert(state->prev[i] == -1 && state->next[i] != -1);
  762. head->i = i;
  763. head->sz = dsf_size(state->dsf, i);
  764. head->why = NULL;
  765. /* Search through this chain looking for real numbers, checking that
  766. * they match up (if there are more than one). */
  767. head->preference = 0;
  768. while (j != -1) {
  769. if (state->flags[j] & FLAG_IMMUTABLE) {
  770. ss = state->nums[j] - off;
  771. if (!head->preference) {
  772. head->start = ss;
  773. head->preference = 1;
  774. head->why = "contains cell with immutable number";
  775. } else if (head->start != ss) {
  776. debug(("head_number: chain with non-sequential numbers!"));
  777. state->impossible = true;
  778. }
  779. }
  780. off++;
  781. j = state->next[j];
  782. assert(j != i); /* we have created a loop, obviously wrong */
  783. }
  784. if (head->preference) goto done;
  785. if (state->nums[i] == 0 && state->nums[state->next[i]] > state->n) {
  786. /* (probably) empty cell onto the head of a coloured region:
  787. * make sure we start at a 0 offset. */
  788. head->start = START(COLOUR(state->nums[state->next[i]]));
  789. head->preference = 1;
  790. head->why = "adding blank cell to head of numbered region";
  791. } else if (state->nums[i] <= state->n) {
  792. /* if we're 0 we're probably just blank -- but even if we're a
  793. * (real) numbered region, we don't have an immutable number
  794. * in it (any more) otherwise it'd have been caught above, so
  795. * reassign the colour. */
  796. head->start = 0;
  797. head->preference = 0;
  798. head->why = "lowest available colour group";
  799. } else {
  800. c = COLOUR(state->nums[i]);
  801. n = 1;
  802. sz = dsf_size(state->dsf, i);
  803. j = i;
  804. while (state->next[j] != -1) {
  805. j = state->next[j];
  806. if (state->nums[j] == 0 && state->next[j] == -1) {
  807. head->start = START(c);
  808. head->preference = 1;
  809. head->why = "adding blank cell to end of numbered region";
  810. goto done;
  811. }
  812. if (COLOUR(state->nums[j]) == c)
  813. n++;
  814. else {
  815. int start_alternate = START(COLOUR(state->nums[j]));
  816. if (n < (sz - n)) {
  817. head->start = start_alternate;
  818. head->preference = 1;
  819. head->why = "joining two coloured regions, swapping to larger colour";
  820. } else {
  821. head->start = START(c);
  822. head->preference = 1;
  823. head->why = "joining two coloured regions, taking largest";
  824. }
  825. goto done;
  826. }
  827. }
  828. /* If we got here then we may have split a region into
  829. * two; make sure we don't assign a colour we've already used. */
  830. if (c == 0) {
  831. /* not convinced this shouldn't be an assertion failure here. */
  832. head->start = 0;
  833. head->preference = 0;
  834. } else {
  835. head->start = START(c);
  836. head->preference = 1;
  837. }
  838. head->why = "got to end of coloured region";
  839. }
  840. done:
  841. assert(head->why != NULL);
  842. if (head->preference)
  843. debug(("Chain at (%d,%d) numbered for preference at %d (colour %d): %s.",
  844. head->i%state->w, head->i/state->w,
  845. head->start, COLOUR(head->start), head->why));
  846. else
  847. debug(("Chain at (%d,%d) using next available colour: %s.",
  848. head->i%state->w, head->i/state->w,
  849. head->why));
  850. }
  851. #if 0
  852. static void debug_numbers(game_state *state)
  853. {
  854. int i, w=state->w;
  855. for (i = 0; i < state->n; i++) {
  856. debug(("(%d,%d) --> (%d,%d) --> (%d,%d)",
  857. state->prev[i]==-1 ? -1 : state->prev[i]%w,
  858. state->prev[i]==-1 ? -1 : state->prev[i]/w,
  859. i%w, i/w,
  860. state->next[i]==-1 ? -1 : state->next[i]%w,
  861. state->next[i]==-1 ? -1 : state->next[i]/w));
  862. }
  863. w = w+1;
  864. }
  865. #endif
  866. static void connect_numbers(game_state *state)
  867. {
  868. int i, di, dni;
  869. dsf_reinit(state->dsf);
  870. for (i = 0; i < state->n; i++) {
  871. if (state->next[i] != -1) {
  872. assert(state->prev[state->next[i]] == i);
  873. di = dsf_canonify(state->dsf, i);
  874. dni = dsf_canonify(state->dsf, state->next[i]);
  875. if (di == dni) {
  876. debug(("connect_numbers: chain forms a loop."));
  877. state->impossible = true;
  878. }
  879. dsf_merge(state->dsf, di, dni);
  880. }
  881. }
  882. }
  883. static int compare_heads(const void *a, const void *b)
  884. {
  885. const struct head_meta *ha = (const struct head_meta *)a;
  886. const struct head_meta *hb = (const struct head_meta *)b;
  887. /* Heads with preferred colours first... */
  888. if (ha->preference && !hb->preference) return -1;
  889. if (hb->preference && !ha->preference) return 1;
  890. /* ...then heads with low colours first... */
  891. if (ha->start < hb->start) return -1;
  892. if (ha->start > hb->start) return 1;
  893. /* ... then large regions first... */
  894. if (ha->sz > hb->sz) return -1;
  895. if (ha->sz < hb->sz) return 1;
  896. /* ... then position. */
  897. if (ha->i > hb->i) return -1;
  898. if (ha->i < hb->i) return 1;
  899. return 0;
  900. }
  901. static int lowest_start(game_state *state, struct head_meta *heads, int nheads)
  902. {
  903. int n, c;
  904. /* NB start at 1: colour 0 is real numbers */
  905. for (c = 1; c < state->n; c++) {
  906. for (n = 0; n < nheads; n++) {
  907. if (COLOUR(heads[n].start) == c)
  908. goto used;
  909. }
  910. return c;
  911. used:
  912. ;
  913. }
  914. assert(!"No available colours!");
  915. return 0;
  916. }
  917. static void update_numbers(game_state *state)
  918. {
  919. int i, j, n, nnum, nheads;
  920. struct head_meta *heads = snewn(state->n, struct head_meta);
  921. for (n = 0; n < state->n; n++)
  922. state->numsi[n] = -1;
  923. for (i = 0; i < state->n; i++) {
  924. if (state->flags[i] & FLAG_IMMUTABLE) {
  925. assert(state->nums[i] > 0);
  926. assert(state->nums[i] <= state->n);
  927. state->numsi[state->nums[i]] = i;
  928. }
  929. else if (state->prev[i] == -1 && state->next[i] == -1)
  930. state->nums[i] = 0;
  931. }
  932. connect_numbers(state);
  933. /* Construct an array of the heads of all current regions, together
  934. * with their preferred colours. */
  935. nheads = 0;
  936. for (i = 0; i < state->n; i++) {
  937. /* Look for a cell that is the start of a chain
  938. * (has a next but no prev). */
  939. if (state->prev[i] != -1 || state->next[i] == -1) continue;
  940. head_number(state, i, &heads[nheads++]);
  941. }
  942. /* Sort that array:
  943. * - heads with preferred colours first, then
  944. * - heads with low colours first, then
  945. * - large regions first
  946. */
  947. qsort(heads, nheads, sizeof(struct head_meta), compare_heads);
  948. /* Remove duplicate-coloured regions. */
  949. for (n = nheads-1; n >= 0; n--) { /* order is important! */
  950. if ((n != 0) && (heads[n].start == heads[n-1].start)) {
  951. /* We have a duplicate-coloured region: since we're
  952. * sorted in size order and this is not the first
  953. * of its colour it's not the largest: recolour it. */
  954. heads[n].start = START(lowest_start(state, heads, nheads));
  955. heads[n].preference = -1; /* '-1' means 'was duplicate' */
  956. }
  957. else if (!heads[n].preference) {
  958. assert(heads[n].start == 0);
  959. heads[n].start = START(lowest_start(state, heads, nheads));
  960. }
  961. }
  962. debug(("Region colouring after duplicate removal:"));
  963. for (n = 0; n < nheads; n++) {
  964. debug((" Chain at (%d,%d) sz %d numbered at %d (colour %d): %s%s",
  965. heads[n].i % state->w, heads[n].i / state->w, heads[n].sz,
  966. heads[n].start, COLOUR(heads[n].start), heads[n].why,
  967. heads[n].preference == 0 ? " (next available)" :
  968. heads[n].preference < 0 ? " (duplicate, next available)" : ""));
  969. nnum = heads[n].start;
  970. j = heads[n].i;
  971. while (j != -1) {
  972. if (!(state->flags[j] & FLAG_IMMUTABLE)) {
  973. if (nnum > 0 && nnum <= state->n)
  974. state->numsi[nnum] = j;
  975. state->nums[j] = nnum;
  976. }
  977. nnum++;
  978. j = state->next[j];
  979. assert(j != heads[n].i); /* loop?! */
  980. }
  981. }
  982. /*debug_numbers(state);*/
  983. sfree(heads);
  984. }
  985. static bool check_completion(game_state *state, bool mark_errors)
  986. {
  987. int n, j, k;
  988. bool error = false, complete;
  989. /* NB This only marks errors that are possible to perpetrate with
  990. * the current UI in interpret_move. Things like forming loops in
  991. * linked sections and having numbers not add up should be forbidden
  992. * by the code elsewhere, so we don't bother marking those (because
  993. * it would add lots of tricky drawing code for very little gain). */
  994. if (mark_errors) {
  995. for (j = 0; j < state->n; j++)
  996. state->flags[j] &= ~FLAG_ERROR;
  997. }
  998. /* Search for repeated numbers. */
  999. for (j = 0; j < state->n; j++) {
  1000. if (state->nums[j] > 0 && state->nums[j] <= state->n) {
  1001. for (k = j+1; k < state->n; k++) {
  1002. if (state->nums[k] == state->nums[j]) {
  1003. if (mark_errors) {
  1004. state->flags[j] |= FLAG_ERROR;
  1005. state->flags[k] |= FLAG_ERROR;
  1006. }
  1007. error = true;
  1008. }
  1009. }
  1010. }
  1011. }
  1012. /* Search and mark numbers n not pointing to n+1; if any numbers
  1013. * are missing we know we've not completed. */
  1014. complete = true;
  1015. for (n = 1; n < state->n; n++) {
  1016. if (state->numsi[n] == -1 || state->numsi[n+1] == -1)
  1017. complete = false;
  1018. else if (!ispointingi(state, state->numsi[n], state->numsi[n+1])) {
  1019. if (mark_errors) {
  1020. state->flags[state->numsi[n]] |= FLAG_ERROR;
  1021. state->flags[state->numsi[n+1]] |= FLAG_ERROR;
  1022. }
  1023. error = true;
  1024. } else {
  1025. /* make sure the link is explicitly made here; for instance, this
  1026. * is nice if the user drags from 2 out (making 3) and a 4 is also
  1027. * visible; this ensures that the link from 3 to 4 is also made. */
  1028. if (mark_errors)
  1029. makelink(state, state->numsi[n], state->numsi[n+1]);
  1030. }
  1031. }
  1032. /* Search and mark numbers less than 0, or 0 with links. */
  1033. for (n = 1; n < state->n; n++) {
  1034. if ((state->nums[n] < 0) ||
  1035. (state->nums[n] == 0 &&
  1036. (state->next[n] != -1 || state->prev[n] != -1))) {
  1037. error = true;
  1038. if (mark_errors)
  1039. state->flags[n] |= FLAG_ERROR;
  1040. }
  1041. }
  1042. if (error) return false;
  1043. return complete;
  1044. }
  1045. static game_state *new_game(midend *me, const game_params *params,
  1046. const char *desc)
  1047. {
  1048. game_state *state = NULL;
  1049. unpick_desc(params, desc, &state, NULL);
  1050. if (!state) assert(!"new_game failed to unpick");
  1051. update_numbers(state);
  1052. check_completion(state, true); /* update any auto-links */
  1053. return state;
  1054. }
  1055. /* --- Solver --- */
  1056. /* If a tile has a single tile it can link _to_, or there's only a single
  1057. * location that can link to a given tile, fill that link in. */
  1058. static int solve_single(game_state *state, game_state *copy, int *from)
  1059. {
  1060. int i, j, sx, sy, x, y, d, poss, w=state->w, nlinks = 0;
  1061. /* The from array is a list of 'which square can link _to_ us';
  1062. * we start off with from as '-1' (meaning 'not found'); if we find
  1063. * something that can link to us it is set to that index, and then if
  1064. * we find another we set it to -2. */
  1065. memset(from, -1, state->n*sizeof(int));
  1066. /* poss is 'can I link to anything' with the same meanings. */
  1067. for (i = 0; i < state->n; i++) {
  1068. if (state->next[i] != -1) continue;
  1069. if (state->nums[i] == state->n) continue; /* no next from last no. */
  1070. d = state->dirs[i];
  1071. poss = -1;
  1072. sx = x = i%w; sy = y = i/w;
  1073. while (1) {
  1074. x += dxs[d]; y += dys[d];
  1075. if (!INGRID(state, x, y)) break;
  1076. if (!isvalidmove(state, true, sx, sy, x, y)) continue;
  1077. /* can't link to somewhere with a back-link we would have to
  1078. * break (the solver just doesn't work like this). */
  1079. j = y*w+x;
  1080. if (state->prev[j] != -1) continue;
  1081. if (state->nums[i] > 0 && state->nums[j] > 0 &&
  1082. state->nums[i] <= state->n && state->nums[j] <= state->n &&
  1083. state->nums[j] == state->nums[i]+1) {
  1084. debug(("Solver: forcing link through existing consecutive numbers."));
  1085. poss = j;
  1086. from[j] = i;
  1087. break;
  1088. }
  1089. /* if there's been a valid move already, we have to move on;
  1090. * we can't make any deductions here. */
  1091. poss = (poss == -1) ? j : -2;
  1092. /* Modify the from array as described above (which is enumerating
  1093. * what points to 'j' in a similar way). */
  1094. from[j] = (from[j] == -1) ? i : -2;
  1095. }
  1096. if (poss == -2) {
  1097. /*debug(("Solver: (%d,%d) has multiple possible next squares.", sx, sy));*/
  1098. ;
  1099. } else if (poss == -1) {
  1100. debug(("Solver: nowhere possible for (%d,%d) to link to.", sx, sy));
  1101. copy->impossible = true;
  1102. return -1;
  1103. } else {
  1104. debug(("Solver: linking (%d,%d) to only possible next (%d,%d).",
  1105. sx, sy, poss%w, poss/w));
  1106. makelink(copy, i, poss);
  1107. nlinks++;
  1108. }
  1109. }
  1110. for (i = 0; i < state->n; i++) {
  1111. if (state->prev[i] != -1) continue;
  1112. if (state->nums[i] == 1) continue; /* no prev from 1st no. */
  1113. x = i%w; y = i/w;
  1114. if (from[i] == -1) {
  1115. debug(("Solver: nowhere possible to link to (%d,%d)", x, y));
  1116. copy->impossible = true;
  1117. return -1;
  1118. } else if (from[i] == -2) {
  1119. /*debug(("Solver: (%d,%d) has multiple possible prev squares.", x, y));*/
  1120. ;
  1121. } else {
  1122. debug(("Solver: linking only possible prev (%d,%d) to (%d,%d).",
  1123. from[i]%w, from[i]/w, x, y));
  1124. makelink(copy, from[i], i);
  1125. nlinks++;
  1126. }
  1127. }
  1128. return nlinks;
  1129. }
  1130. /* Returns 1 if we managed to solve it, 0 otherwise. */
  1131. static int solve_state(game_state *state)
  1132. {
  1133. game_state *copy = dup_game(state);
  1134. int *scratch = snewn(state->n, int), ret;
  1135. debug_state("Before solver: ", state);
  1136. while (1) {
  1137. update_numbers(state);
  1138. if (solve_single(state, copy, scratch)) {
  1139. dup_game_to(state, copy);
  1140. if (state->impossible) break; else continue;
  1141. }
  1142. break;
  1143. }
  1144. free_game(copy);
  1145. sfree(scratch);
  1146. update_numbers(state);
  1147. ret = state->impossible ? -1 : check_completion(state, false);
  1148. debug(("Solver finished: %s",
  1149. ret < 0 ? "impossible" : ret > 0 ? "solved" : "not solved"));
  1150. debug_state("After solver: ", state);
  1151. return ret;
  1152. }
  1153. static char *solve_game(const game_state *state, const game_state *currstate,
  1154. const char *aux, const char **error)
  1155. {
  1156. game_state *tosolve;
  1157. char *ret = NULL;
  1158. int result;
  1159. tosolve = dup_game(currstate);
  1160. result = solve_state(tosolve);
  1161. if (result > 0)
  1162. ret = generate_desc(tosolve, true);
  1163. free_game(tosolve);
  1164. if (ret) return ret;
  1165. tosolve = dup_game(state);
  1166. result = solve_state(tosolve);
  1167. if (result < 0)
  1168. *error = "Puzzle is impossible.";
  1169. else if (result == 0)
  1170. *error = "Unable to solve puzzle.";
  1171. else
  1172. ret = generate_desc(tosolve, true);
  1173. free_game(tosolve);
  1174. return ret;
  1175. }
  1176. /* --- UI and move routines. --- */
  1177. struct game_ui {
  1178. int cx, cy;
  1179. bool cshow;
  1180. bool dragging, drag_is_from;
  1181. int sx, sy; /* grid coords of start cell */
  1182. int dx, dy; /* pixel coords of drag posn */
  1183. /*
  1184. * Trivial and foolish configurable option done on purest whim.
  1185. * With this option enabled, the victory flash is done by rotating
  1186. * each square in the opposite direction from its immediate
  1187. * neighbours, so that they behave like a field of interlocking
  1188. * gears. With it disabled, they all rotate in the same direction.
  1189. * Choose for yourself which is more brain-twisting :-)
  1190. */
  1191. bool gear_mode;
  1192. };
  1193. static void legacy_prefs_override(struct game_ui *ui_out)
  1194. {
  1195. static bool initialised = false;
  1196. static int gear_mode = -1;
  1197. if (!initialised) {
  1198. initialised = true;
  1199. gear_mode = getenv_bool("SIGNPOST_GEARS", -1);
  1200. }
  1201. if (gear_mode != -1)
  1202. ui_out->gear_mode = gear_mode;
  1203. }
  1204. static game_ui *new_ui(const game_state *state)
  1205. {
  1206. game_ui *ui = snew(game_ui);
  1207. /* NB: if this is ever changed to as to require more than a structure
  1208. * copy to clone, there's code that needs fixing in game_redraw too. */
  1209. ui->cx = ui->cy = 0;
  1210. ui->cshow = getenv_bool("PUZZLES_SHOW_CURSOR", false);
  1211. ui->dragging = false;
  1212. ui->sx = ui->sy = ui->dx = ui->dy = 0;
  1213. ui->gear_mode = false;
  1214. legacy_prefs_override(ui);
  1215. return ui;
  1216. }
  1217. static void free_ui(game_ui *ui)
  1218. {
  1219. sfree(ui);
  1220. }
  1221. static config_item *get_prefs(game_ui *ui)
  1222. {
  1223. config_item *ret;
  1224. ret = snewn(2, config_item);
  1225. ret[0].name = "Victory rotation effect";
  1226. ret[0].kw = "flash-type";
  1227. ret[0].type = C_CHOICES;
  1228. ret[0].u.choices.choicenames = ":Unidirectional:Meshing gears";
  1229. ret[0].u.choices.choicekws = ":unidirectional:gears";
  1230. ret[0].u.choices.selected = ui->gear_mode;
  1231. ret[1].name = NULL;
  1232. ret[1].type = C_END;
  1233. return ret;
  1234. }
  1235. static void set_prefs(game_ui *ui, const config_item *cfg)
  1236. {
  1237. ui->gear_mode = cfg[0].u.choices.selected;
  1238. }
  1239. static void game_changed_state(game_ui *ui, const game_state *oldstate,
  1240. const game_state *newstate)
  1241. {
  1242. if (!oldstate->completed && newstate->completed) {
  1243. ui->cshow = false;
  1244. ui->dragging = false;
  1245. }
  1246. }
  1247. static const char *current_key_label(const game_ui *ui,
  1248. const game_state *state, int button)
  1249. {
  1250. if (IS_CURSOR_SELECT(button) && ui->cshow) {
  1251. if (ui->dragging) {
  1252. if (ui->drag_is_from) {
  1253. if (isvalidmove(state, false, ui->sx, ui->sy, ui->cx, ui->cy))
  1254. return "To here";
  1255. } else {
  1256. if (isvalidmove(state, false, ui->cx, ui->cy, ui->sx, ui->sy))
  1257. return "From here";
  1258. }
  1259. return "Cancel";
  1260. } else {
  1261. return button == CURSOR_SELECT ? "From here" : "To here";
  1262. }
  1263. }
  1264. return "";
  1265. }
  1266. struct game_drawstate {
  1267. int tilesize;
  1268. bool started, solved;
  1269. int w, h, n;
  1270. int *nums, *dirp;
  1271. unsigned int *f;
  1272. double angle_offset;
  1273. bool dragging;
  1274. int dx, dy;
  1275. blitter *dragb;
  1276. };
  1277. static char *interpret_move(const game_state *state, game_ui *ui,
  1278. const game_drawstate *ds,
  1279. int mx, int my, int button)
  1280. {
  1281. int x = FROMCOORD(mx), y = FROMCOORD(my), w = state->w;
  1282. char buf[80];
  1283. if (IS_CURSOR_MOVE(button)) {
  1284. move_cursor(button, &ui->cx, &ui->cy, state->w, state->h, false);
  1285. ui->cshow = true;
  1286. if (ui->dragging) {
  1287. ui->dx = COORD(ui->cx) + TILE_SIZE/2;
  1288. ui->dy = COORD(ui->cy) + TILE_SIZE/2;
  1289. }
  1290. return MOVE_UI_UPDATE;
  1291. } else if (IS_CURSOR_SELECT(button)) {
  1292. if (!ui->cshow)
  1293. ui->cshow = true;
  1294. else if (ui->dragging) {
  1295. ui->dragging = false;
  1296. if (ui->sx == ui->cx && ui->sy == ui->cy) return MOVE_UI_UPDATE;
  1297. if (ui->drag_is_from) {
  1298. if (!isvalidmove(state, false, ui->sx, ui->sy, ui->cx, ui->cy))
  1299. return MOVE_UI_UPDATE;
  1300. sprintf(buf, "L%d,%d-%d,%d", ui->sx, ui->sy, ui->cx, ui->cy);
  1301. } else {
  1302. if (!isvalidmove(state, false, ui->cx, ui->cy, ui->sx, ui->sy))
  1303. return MOVE_UI_UPDATE;
  1304. sprintf(buf, "L%d,%d-%d,%d", ui->cx, ui->cy, ui->sx, ui->sy);
  1305. }
  1306. return dupstr(buf);
  1307. } else {
  1308. ui->dragging = true;
  1309. ui->sx = ui->cx;
  1310. ui->sy = ui->cy;
  1311. ui->dx = COORD(ui->cx) + TILE_SIZE/2;
  1312. ui->dy = COORD(ui->cy) + TILE_SIZE/2;
  1313. ui->drag_is_from = (button == CURSOR_SELECT);
  1314. }
  1315. return MOVE_UI_UPDATE;
  1316. }
  1317. if (IS_MOUSE_DOWN(button)) {
  1318. if (ui->cshow) {
  1319. ui->cshow = false;
  1320. ui->dragging = false;
  1321. }
  1322. assert(!ui->dragging);
  1323. if (!INGRID(state, x, y)) return NULL;
  1324. if (button == LEFT_BUTTON) {
  1325. /* disallow dragging from the final number. */
  1326. if ((state->nums[y*w+x] == state->n) &&
  1327. (state->flags[y*w+x] & FLAG_IMMUTABLE))
  1328. return NULL;
  1329. } else if (button == RIGHT_BUTTON) {
  1330. /* disallow dragging to the first number. */
  1331. if ((state->nums[y*w+x] == 1) &&
  1332. (state->flags[y*w+x] & FLAG_IMMUTABLE))
  1333. return NULL;
  1334. }
  1335. ui->dragging = true;
  1336. ui->drag_is_from = (button == LEFT_BUTTON);
  1337. ui->sx = x;
  1338. ui->sy = y;
  1339. ui->dx = mx;
  1340. ui->dy = my;
  1341. ui->cshow = false;
  1342. return MOVE_UI_UPDATE;
  1343. } else if (IS_MOUSE_DRAG(button) && ui->dragging) {
  1344. ui->dx = mx;
  1345. ui->dy = my;
  1346. return MOVE_UI_UPDATE;
  1347. } else if (IS_MOUSE_RELEASE(button) && ui->dragging) {
  1348. ui->dragging = false;
  1349. if (ui->sx == x && ui->sy == y) return MOVE_UI_UPDATE; /* single click */
  1350. if (!INGRID(state, x, y)) {
  1351. int si = ui->sy*w+ui->sx;
  1352. if (state->prev[si] == -1 && state->next[si] == -1)
  1353. return MOVE_UI_UPDATE;
  1354. sprintf(buf, "%c%d,%d",
  1355. (int)(ui->drag_is_from ? 'C' : 'X'), ui->sx, ui->sy);
  1356. return dupstr(buf);
  1357. }
  1358. if (ui->drag_is_from) {
  1359. if (!isvalidmove(state, false, ui->sx, ui->sy, x, y))
  1360. return MOVE_UI_UPDATE;
  1361. sprintf(buf, "L%d,%d-%d,%d", ui->sx, ui->sy, x, y);
  1362. } else {
  1363. if (!isvalidmove(state, false, x, y, ui->sx, ui->sy))
  1364. return MOVE_UI_UPDATE;
  1365. sprintf(buf, "L%d,%d-%d,%d", x, y, ui->sx, ui->sy);
  1366. }
  1367. return dupstr(buf);
  1368. } /* else if (button == 'H' || button == 'h')
  1369. return dupstr("H"); */
  1370. else if ((button == 'x' || button == 'X') && ui->cshow) {
  1371. int si = ui->cy*w + ui->cx;
  1372. if (state->prev[si] == -1 && state->next[si] == -1)
  1373. return MOVE_UI_UPDATE;
  1374. sprintf(buf, "%c%d,%d",
  1375. (int)((button == 'x') ? 'C' : 'X'), ui->cx, ui->cy);
  1376. return dupstr(buf);
  1377. }
  1378. return NULL;
  1379. }
  1380. static void unlink_cell(game_state *state, int si)
  1381. {
  1382. debug(("Unlinking (%d,%d).", si%state->w, si/state->w));
  1383. if (state->prev[si] != -1) {
  1384. debug((" ... removing prev link from (%d,%d).",
  1385. state->prev[si]%state->w, state->prev[si]/state->w));
  1386. state->next[state->prev[si]] = -1;
  1387. state->prev[si] = -1;
  1388. }
  1389. if (state->next[si] != -1) {
  1390. debug((" ... removing next link to (%d,%d).",
  1391. state->next[si]%state->w, state->next[si]/state->w));
  1392. state->prev[state->next[si]] = -1;
  1393. state->next[si] = -1;
  1394. }
  1395. }
  1396. static game_state *execute_move(const game_state *state, const char *move)
  1397. {
  1398. game_state *ret = NULL;
  1399. int sx, sy, ex, ey, si, ei, w = state->w;
  1400. char c;
  1401. debug(("move: %s", move));
  1402. if (move[0] == 'S') {
  1403. game_params p;
  1404. game_state *tmp;
  1405. const char *valid;
  1406. int i;
  1407. p.w = state->w; p.h = state->h;
  1408. valid = validate_desc(&p, move+1);
  1409. if (valid) {
  1410. debug(("execute_move: move not valid: %s", valid));
  1411. return NULL;
  1412. }
  1413. ret = dup_game(state);
  1414. tmp = new_game(NULL, &p, move+1);
  1415. for (i = 0; i < state->n; i++) {
  1416. ret->prev[i] = tmp->prev[i];
  1417. ret->next[i] = tmp->next[i];
  1418. }
  1419. free_game(tmp);
  1420. ret->used_solve = true;
  1421. } else if (sscanf(move, "L%d,%d-%d,%d", &sx, &sy, &ex, &ey) == 4) {
  1422. if (!isvalidmove(state, false, sx, sy, ex, ey)) return NULL;
  1423. ret = dup_game(state);
  1424. si = sy*w+sx; ei = ey*w+ex;
  1425. makelink(ret, si, ei);
  1426. } else if (sscanf(move, "%c%d,%d", &c, &sx, &sy) == 3) {
  1427. int sset;
  1428. if (c != 'C' && c != 'X') return NULL;
  1429. if (!INGRID(state, sx, sy)) return NULL;
  1430. si = sy*w+sx;
  1431. if (state->prev[si] == -1 && state->next[si] == -1)
  1432. return NULL;
  1433. ret = dup_game(state);
  1434. sset = state->nums[si] / (state->n+1);
  1435. if (c == 'C' || (c == 'X' && sset == 0)) {
  1436. /* Unlink the single cell we dragged from the board. */
  1437. unlink_cell(ret, si);
  1438. } else {
  1439. int i, set;
  1440. for (i = 0; i < state->n; i++) {
  1441. /* Unlink all cells in the same set as the one we dragged
  1442. * from the board. */
  1443. if (state->nums[i] == 0) continue;
  1444. set = state->nums[i] / (state->n+1);
  1445. if (set != sset) continue;
  1446. unlink_cell(ret, i);
  1447. }
  1448. }
  1449. } else if (strcmp(move, "H") == 0) {
  1450. ret = dup_game(state);
  1451. solve_state(ret);
  1452. }
  1453. if (ret) {
  1454. update_numbers(ret);
  1455. if (check_completion(ret, true)) ret->completed = true;
  1456. }
  1457. return ret;
  1458. }
  1459. /* ----------------------------------------------------------------------
  1460. * Drawing routines.
  1461. */
  1462. static void game_compute_size(const game_params *params, int tilesize,
  1463. const game_ui *ui, int *x, int *y)
  1464. {
  1465. /* Ick: fake up `ds->tilesize' for macro expansion purposes */
  1466. struct { int tilesize, order; } ads, *ds = &ads;
  1467. ads.tilesize = tilesize;
  1468. *x = TILE_SIZE * params->w + 2 * BORDER;
  1469. *y = TILE_SIZE * params->h + 2 * BORDER;
  1470. }
  1471. static void game_set_size(drawing *dr, game_drawstate *ds,
  1472. const game_params *params, int tilesize)
  1473. {
  1474. ds->tilesize = tilesize;
  1475. assert(TILE_SIZE > 0);
  1476. assert(!ds->dragb);
  1477. ds->dragb = blitter_new(dr, BLITTER_SIZE, BLITTER_SIZE);
  1478. }
  1479. /* Colours chosen from the webby palette to work as a background to black text,
  1480. * W then some plausible approximation to pastelly ROYGBIV; we then interpolate
  1481. * between consecutive pairs to give another 8 (and then the drawing routine
  1482. * will reuse backgrounds). */
  1483. static const unsigned long bgcols[8] = {
  1484. 0xffffff, /* white */
  1485. 0xffa07a, /* lightsalmon */
  1486. 0x98fb98, /* green */
  1487. 0x7fffd4, /* aquamarine */
  1488. 0x9370db, /* medium purple */
  1489. 0xffa500, /* orange */
  1490. 0x87cefa, /* lightskyblue */
  1491. 0xffff00, /* yellow */
  1492. };
  1493. static float *game_colours(frontend *fe, int *ncolours)
  1494. {
  1495. float *ret = snewn(3 * NCOLOURS, float);
  1496. int c, i;
  1497. game_mkhighlight(fe, ret, COL_BACKGROUND, COL_HIGHLIGHT, COL_LOWLIGHT);
  1498. for (i = 0; i < 3; i++) {
  1499. ret[COL_NUMBER * 3 + i] = 0.0F;
  1500. ret[COL_ARROW * 3 + i] = 0.0F;
  1501. ret[COL_CURSOR * 3 + i] = ret[COL_BACKGROUND * 3 + i] / 2.0F;
  1502. ret[COL_GRID * 3 + i] = ret[COL_BACKGROUND * 3 + i] / 1.3F;
  1503. }
  1504. ret[COL_NUMBER_SET * 3 + 0] = 0.0F;
  1505. ret[COL_NUMBER_SET * 3 + 1] = 0.0F;
  1506. ret[COL_NUMBER_SET * 3 + 2] = 0.9F;
  1507. ret[COL_ERROR * 3 + 0] = 1.0F;
  1508. ret[COL_ERROR * 3 + 1] = 0.0F;
  1509. ret[COL_ERROR * 3 + 2] = 0.0F;
  1510. ret[COL_DRAG_ORIGIN * 3 + 0] = 0.2F;
  1511. ret[COL_DRAG_ORIGIN * 3 + 1] = 1.0F;
  1512. ret[COL_DRAG_ORIGIN * 3 + 2] = 0.2F;
  1513. for (c = 0; c < 8; c++) {
  1514. ret[(COL_B0 + c) * 3 + 0] = (float)((bgcols[c] & 0xff0000) >> 16) / 256.0F;
  1515. ret[(COL_B0 + c) * 3 + 1] = (float)((bgcols[c] & 0xff00) >> 8) / 256.0F;
  1516. ret[(COL_B0 + c) * 3 + 2] = (float)((bgcols[c] & 0xff)) / 256.0F;
  1517. }
  1518. for (c = 0; c < 8; c++) {
  1519. for (i = 0; i < 3; i++) {
  1520. ret[(COL_B0 + 8 + c) * 3 + i] =
  1521. (ret[(COL_B0 + c) * 3 + i] + ret[(COL_B0 + c + 1) * 3 + i]) / 2.0F;
  1522. }
  1523. }
  1524. #define average(r,a,b,w) do { \
  1525. for (i = 0; i < 3; i++) \
  1526. ret[(r)*3+i] = ret[(a)*3+i] + w * (ret[(b)*3+i] - ret[(a)*3+i]); \
  1527. } while (0)
  1528. average(COL_ARROW_BG_DIM, COL_BACKGROUND, COL_ARROW, 0.1F);
  1529. average(COL_NUMBER_SET_MID, COL_B0, COL_NUMBER_SET, 0.3F);
  1530. for (c = 0; c < NBACKGROUNDS; c++) {
  1531. /* I assume here that COL_ARROW and COL_NUMBER are the same.
  1532. * Otherwise I'd need two sets of COL_M*. */
  1533. average(COL_M0 + c, COL_B0 + c, COL_NUMBER, 0.3F);
  1534. average(COL_D0 + c, COL_B0 + c, COL_NUMBER, 0.1F);
  1535. average(COL_X0 + c, COL_BACKGROUND, COL_B0 + c, 0.5F);
  1536. }
  1537. *ncolours = NCOLOURS;
  1538. return ret;
  1539. }
  1540. static game_drawstate *game_new_drawstate(drawing *dr, const game_state *state)
  1541. {
  1542. struct game_drawstate *ds = snew(struct game_drawstate);
  1543. int i;
  1544. ds->tilesize = 0;
  1545. ds->started = false;
  1546. ds->solved = false;
  1547. ds->w = state->w;
  1548. ds->h = state->h;
  1549. ds->n = state->n;
  1550. ds->nums = snewn(state->n, int);
  1551. ds->dirp = snewn(state->n, int);
  1552. ds->f = snewn(state->n, unsigned int);
  1553. for (i = 0; i < state->n; i++) {
  1554. ds->nums[i] = 0;
  1555. ds->dirp[i] = -1;
  1556. ds->f[i] = 0;
  1557. }
  1558. ds->angle_offset = 0.0F;
  1559. ds->dragging = false;
  1560. ds->dx = ds->dy = 0;
  1561. ds->dragb = NULL;
  1562. return ds;
  1563. }
  1564. static void game_free_drawstate(drawing *dr, game_drawstate *ds)
  1565. {
  1566. sfree(ds->nums);
  1567. sfree(ds->dirp);
  1568. sfree(ds->f);
  1569. if (ds->dragb) blitter_free(dr, ds->dragb);
  1570. sfree(ds);
  1571. }
  1572. /* cx, cy are top-left corner. sz is the 'radius' of the arrow.
  1573. * ang is in radians, clockwise from 0 == straight up. */
  1574. static void draw_arrow(drawing *dr, int cx, int cy, int sz, double ang,
  1575. int cfill, int cout)
  1576. {
  1577. int coords[14];
  1578. int xdx, ydx, xdy, ydy, xdx3, xdy3;
  1579. double s = sin(ang), c = cos(ang);
  1580. xdx3 = (int)(sz * (c/3 + 1) + 0.5) - sz;
  1581. xdy3 = (int)(sz * (s/3 + 1) + 0.5) - sz;
  1582. xdx = (int)(sz * (c + 1) + 0.5) - sz;
  1583. xdy = (int)(sz * (s + 1) + 0.5) - sz;
  1584. ydx = -xdy;
  1585. ydy = xdx;
  1586. coords[2*0 + 0] = cx - ydx;
  1587. coords[2*0 + 1] = cy - ydy;
  1588. coords[2*1 + 0] = cx + xdx;
  1589. coords[2*1 + 1] = cy + xdy;
  1590. coords[2*2 + 0] = cx + xdx3;
  1591. coords[2*2 + 1] = cy + xdy3;
  1592. coords[2*3 + 0] = cx + xdx3 + ydx;
  1593. coords[2*3 + 1] = cy + xdy3 + ydy;
  1594. coords[2*4 + 0] = cx - xdx3 + ydx;
  1595. coords[2*4 + 1] = cy - xdy3 + ydy;
  1596. coords[2*5 + 0] = cx - xdx3;
  1597. coords[2*5 + 1] = cy - xdy3;
  1598. coords[2*6 + 0] = cx - xdx;
  1599. coords[2*6 + 1] = cy - xdy;
  1600. draw_polygon(dr, coords, 7, cfill, cout);
  1601. }
  1602. static void draw_arrow_dir(drawing *dr, int cx, int cy, int sz, int dir,
  1603. int cfill, int cout, double angle_offset)
  1604. {
  1605. double ang = 2.0 * PI * (double)dir / 8.0 + angle_offset;
  1606. draw_arrow(dr, cx, cy, sz, ang, cfill, cout);
  1607. }
  1608. /* cx, cy are centre coordinates.. */
  1609. static void draw_star(drawing *dr, int cx, int cy, int rad, int npoints,
  1610. int cfill, int cout, double angle_offset)
  1611. {
  1612. int *coords, n;
  1613. double a, r;
  1614. assert(npoints > 0);
  1615. coords = snewn(npoints * 2 * 2, int);
  1616. for (n = 0; n < npoints * 2; n++) {
  1617. a = 2.0 * PI * ((double)n / ((double)npoints * 2.0)) + angle_offset;
  1618. r = (n % 2) ? (double)rad/2.0 : (double)rad;
  1619. /* We're rotating the point at (0, -r) by a degrees */
  1620. coords[2*n+0] = cx + (int)( r * sin(a));
  1621. coords[2*n+1] = cy + (int)(-r * cos(a));
  1622. }
  1623. draw_polygon(dr, coords, npoints*2, cfill, cout);
  1624. sfree(coords);
  1625. }
  1626. static int num2col(game_drawstate *ds, int num)
  1627. {
  1628. int set = num / (ds->n+1);
  1629. if (num <= 0 || set == 0) return COL_B0;
  1630. return COL_B0 + 1 + ((set-1) % 15);
  1631. }
  1632. #define ARROW_HALFSZ (7 * TILE_SIZE / 32)
  1633. #define F_CUR 0x001 /* Cursor on this tile. */
  1634. #define F_DRAG_SRC 0x002 /* Tile is source of a drag. */
  1635. #define F_ERROR 0x004 /* Tile marked in error. */
  1636. #define F_IMMUTABLE 0x008 /* Tile (number) is immutable. */
  1637. #define F_ARROW_POINT 0x010 /* Tile points to other tile */
  1638. #define F_ARROW_INPOINT 0x020 /* Other tile points in here. */
  1639. #define F_DIM 0x040 /* Tile is dim */
  1640. static void tile_redraw(drawing *dr, game_drawstate *ds, int tx, int ty,
  1641. int dir, int dirp, int num, unsigned int f,
  1642. double angle_offset, int print_ink)
  1643. {
  1644. int cb = TILE_SIZE / 16, textsz;
  1645. char buf[20];
  1646. int arrowcol, sarrowcol, setcol, textcol;
  1647. int acx, acy, asz;
  1648. bool empty = false;
  1649. if (num == 0 && !(f & F_ARROW_POINT) && !(f & F_ARROW_INPOINT)) {
  1650. empty = true;
  1651. /*
  1652. * We don't display text in empty cells: typically these are
  1653. * signified by num=0. However, in some cases a cell could
  1654. * have had the number 0 assigned to it if the user made an
  1655. * error (e.g. tried to connect a chain of length 5 to the
  1656. * immutable number 4) so we _do_ display the 0 if the cell
  1657. * has a link in or a link out.
  1658. */
  1659. }
  1660. /* Calculate colours. */
  1661. if (print_ink >= 0) {
  1662. /*
  1663. * We're printing, so just do everything in black.
  1664. */
  1665. arrowcol = textcol = print_ink;
  1666. setcol = sarrowcol = -1; /* placate optimiser */
  1667. } else {
  1668. setcol = empty ? COL_BACKGROUND : num2col(ds, num);
  1669. #define dim(fg,bg) ( \
  1670. (bg)==COL_BACKGROUND ? COL_ARROW_BG_DIM : \
  1671. (bg) + COL_D0 - COL_B0 \
  1672. )
  1673. #define mid(fg,bg) ( \
  1674. (fg)==COL_NUMBER_SET ? COL_NUMBER_SET_MID : \
  1675. (bg) + COL_M0 - COL_B0 \
  1676. )
  1677. #define dimbg(bg) ( \
  1678. (bg)==COL_BACKGROUND ? COL_BACKGROUND : \
  1679. (bg) + COL_X0 - COL_B0 \
  1680. )
  1681. if (f & F_DRAG_SRC) arrowcol = COL_DRAG_ORIGIN;
  1682. else if (f & F_DIM) arrowcol = dim(COL_ARROW, setcol);
  1683. else if (f & F_ARROW_POINT) arrowcol = mid(COL_ARROW, setcol);
  1684. else arrowcol = COL_ARROW;
  1685. if ((f & F_ERROR) && !(f & F_IMMUTABLE)) textcol = COL_ERROR;
  1686. else {
  1687. if (f & F_IMMUTABLE) textcol = COL_NUMBER_SET;
  1688. else textcol = COL_NUMBER;
  1689. if (f & F_DIM) textcol = dim(textcol, setcol);
  1690. else if (((f & F_ARROW_POINT) || num==ds->n) &&
  1691. ((f & F_ARROW_INPOINT) || num==1))
  1692. textcol = mid(textcol, setcol);
  1693. }
  1694. if (f & F_DIM) sarrowcol = dim(COL_ARROW, setcol);
  1695. else sarrowcol = COL_ARROW;
  1696. }
  1697. /* Clear tile background */
  1698. if (print_ink < 0) {
  1699. draw_rect(dr, tx, ty, TILE_SIZE, TILE_SIZE,
  1700. (f & F_DIM) ? dimbg(setcol) : setcol);
  1701. }
  1702. /* Draw large (outwards-pointing) arrow. */
  1703. asz = ARROW_HALFSZ; /* 'radius' of arrow/star. */
  1704. acx = tx+TILE_SIZE/2+asz; /* centre x */
  1705. acy = ty+TILE_SIZE/2+asz; /* centre y */
  1706. if (num == ds->n && (f & F_IMMUTABLE))
  1707. draw_star(dr, acx, acy, asz, 5, arrowcol, arrowcol, angle_offset);
  1708. else
  1709. draw_arrow_dir(dr, acx, acy, asz, dir, arrowcol, arrowcol, angle_offset);
  1710. if (print_ink < 0 && (f & F_CUR))
  1711. draw_rect_corners(dr, acx, acy, asz+1, COL_CURSOR);
  1712. /* Draw dot iff this tile requires a predecessor and doesn't have one. */
  1713. if (print_ink < 0) {
  1714. acx = tx+TILE_SIZE/2-asz;
  1715. acy = ty+TILE_SIZE/2+asz;
  1716. if (!(f & F_ARROW_INPOINT) && num != 1) {
  1717. draw_circle(dr, acx, acy, asz / 4, sarrowcol, sarrowcol);
  1718. }
  1719. }
  1720. /* Draw text (number or set). */
  1721. if (!empty) {
  1722. int set = (num <= 0) ? 0 : num / (ds->n+1);
  1723. char *p = buf;
  1724. if (set == 0 || num <= 0) {
  1725. sprintf(buf, "%d", num);
  1726. } else {
  1727. int n = num % (ds->n+1);
  1728. p += sizeof(buf) - 1;
  1729. if (n != 0) {
  1730. sprintf(buf, "+%d", n); /* Just to get the length... */
  1731. p -= strlen(buf);
  1732. sprintf(p, "+%d", n);
  1733. } else {
  1734. *p = '\0';
  1735. }
  1736. do {
  1737. set--;
  1738. p--;
  1739. *p = (char)((set % 26)+'a');
  1740. set /= 26;
  1741. } while (set);
  1742. }
  1743. textsz = min(2*asz, (TILE_SIZE - 2 * cb) / (int)strlen(p));
  1744. draw_text(dr, tx + cb, ty + TILE_SIZE/4, FONT_VARIABLE, textsz,
  1745. ALIGN_VCENTRE | ALIGN_HLEFT, textcol, p);
  1746. }
  1747. if (print_ink < 0) {
  1748. draw_rect_outline(dr, tx, ty, TILE_SIZE, TILE_SIZE, COL_GRID);
  1749. draw_update(dr, tx, ty, TILE_SIZE, TILE_SIZE);
  1750. }
  1751. }
  1752. static void draw_drag_indicator(drawing *dr, game_drawstate *ds,
  1753. const game_state *state, const game_ui *ui,
  1754. bool validdrag)
  1755. {
  1756. int dir, w = ds->w, acol = COL_ARROW;
  1757. int fx = FROMCOORD(ui->dx), fy = FROMCOORD(ui->dy);
  1758. double ang;
  1759. if (validdrag) {
  1760. /* If we could move here, lock the arrow to the appropriate direction. */
  1761. dir = ui->drag_is_from ? state->dirs[ui->sy*w+ui->sx] : state->dirs[fy*w+fx];
  1762. ang = (2.0 * PI * dir) / 8.0; /* similar to calculation in draw_arrow_dir. */
  1763. } else {
  1764. /* Draw an arrow pointing away from/towards the origin cell. */
  1765. int ox = COORD(ui->sx) + TILE_SIZE/2, oy = COORD(ui->sy) + TILE_SIZE/2;
  1766. double tana, offset;
  1767. double xdiff = abs(ox - ui->dx), ydiff = abs(oy - ui->dy);
  1768. if (xdiff == 0) {
  1769. ang = (oy > ui->dy) ? 0.0F : PI;
  1770. } else if (ydiff == 0) {
  1771. ang = (ox > ui->dx) ? 3.0F*PI/2.0F : PI/2.0F;
  1772. } else {
  1773. if (ui->dx > ox && ui->dy < oy) {
  1774. tana = xdiff / ydiff;
  1775. offset = 0.0F;
  1776. } else if (ui->dx > ox && ui->dy > oy) {
  1777. tana = ydiff / xdiff;
  1778. offset = PI/2.0F;
  1779. } else if (ui->dx < ox && ui->dy > oy) {
  1780. tana = xdiff / ydiff;
  1781. offset = PI;
  1782. } else {
  1783. tana = ydiff / xdiff;
  1784. offset = 3.0F * PI / 2.0F;
  1785. }
  1786. ang = atan(tana) + offset;
  1787. }
  1788. if (!ui->drag_is_from) ang += PI; /* point to origin, not away from. */
  1789. }
  1790. draw_arrow(dr, ui->dx, ui->dy, ARROW_HALFSZ, ang, acol, acol);
  1791. }
  1792. static void game_redraw(drawing *dr, game_drawstate *ds,
  1793. const game_state *oldstate, const game_state *state,
  1794. int dir, const game_ui *ui,
  1795. float animtime, float flashtime)
  1796. {
  1797. int x, y, i, w = ds->w, dirp;
  1798. bool force = false;
  1799. unsigned int f;
  1800. double angle_offset = 0.0;
  1801. game_state *postdrop = NULL;
  1802. if (flashtime > 0.0F)
  1803. angle_offset = 2.0 * PI * (flashtime / FLASH_SPIN);
  1804. if (angle_offset != ds->angle_offset) {
  1805. ds->angle_offset = angle_offset;
  1806. force = true;
  1807. }
  1808. if (ds->dragging) {
  1809. assert(ds->dragb);
  1810. blitter_load(dr, ds->dragb, ds->dx, ds->dy);
  1811. draw_update(dr, ds->dx, ds->dy, BLITTER_SIZE, BLITTER_SIZE);
  1812. ds->dragging = false;
  1813. }
  1814. /* If an in-progress drag would make a valid move if finished, we
  1815. * reflect that move in the board display. We let interpret_move do
  1816. * most of the heavy lifting for us: we have to copy the game_ui so
  1817. * as not to stomp on the real UI's drag state. */
  1818. if (ui->dragging) {
  1819. game_ui uicopy = *ui;
  1820. char *movestr = interpret_move(state, &uicopy, ds, ui->dx, ui->dy, LEFT_RELEASE);
  1821. if (movestr != NULL && strcmp(movestr, "") != 0) {
  1822. postdrop = execute_move(state, movestr);
  1823. sfree(movestr);
  1824. state = postdrop;
  1825. }
  1826. }
  1827. if (!ds->started) {
  1828. int aw = TILE_SIZE * state->w;
  1829. int ah = TILE_SIZE * state->h;
  1830. draw_rect_outline(dr, BORDER - 1, BORDER - 1, aw + 2, ah + 2, COL_GRID);
  1831. draw_update(dr, 0, 0, aw + 2 * BORDER, ah + 2 * BORDER);
  1832. }
  1833. for (x = 0; x < state->w; x++) {
  1834. for (y = 0; y < state->h; y++) {
  1835. i = y*w + x;
  1836. f = 0;
  1837. dirp = -1;
  1838. if (ui->cshow && x == ui->cx && y == ui->cy)
  1839. f |= F_CUR;
  1840. if (ui->dragging) {
  1841. if (x == ui->sx && y == ui->sy)
  1842. f |= F_DRAG_SRC;
  1843. else if (ui->drag_is_from) {
  1844. if (!ispointing(state, ui->sx, ui->sy, x, y))
  1845. f |= F_DIM;
  1846. } else {
  1847. if (!ispointing(state, x, y, ui->sx, ui->sy))
  1848. f |= F_DIM;
  1849. }
  1850. }
  1851. if (state->impossible ||
  1852. state->nums[i] < 0 || state->flags[i] & FLAG_ERROR)
  1853. f |= F_ERROR;
  1854. if (state->flags[i] & FLAG_IMMUTABLE)
  1855. f |= F_IMMUTABLE;
  1856. if (state->next[i] != -1)
  1857. f |= F_ARROW_POINT;
  1858. if (state->prev[i] != -1) {
  1859. /* Currently the direction here is from our square _back_
  1860. * to its previous. We could change this to give the opposite
  1861. * sense to the direction. */
  1862. f |= F_ARROW_INPOINT;
  1863. dirp = whichdir(x, y, state->prev[i]%w, state->prev[i]/w);
  1864. }
  1865. if (state->nums[i] != ds->nums[i] ||
  1866. f != ds->f[i] || dirp != ds->dirp[i] ||
  1867. force || !ds->started) {
  1868. int sign = (ui->gear_mode ? 1 - 2 * ((x ^ y) & 1) : 1);
  1869. tile_redraw(dr, ds,
  1870. BORDER + x * TILE_SIZE,
  1871. BORDER + y * TILE_SIZE,
  1872. state->dirs[i], dirp, state->nums[i], f,
  1873. sign * angle_offset, -1);
  1874. ds->nums[i] = state->nums[i];
  1875. ds->f[i] = f;
  1876. ds->dirp[i] = dirp;
  1877. }
  1878. }
  1879. }
  1880. if (ui->dragging) {
  1881. ds->dragging = true;
  1882. ds->dx = ui->dx - BLITTER_SIZE/2;
  1883. ds->dy = ui->dy - BLITTER_SIZE/2;
  1884. blitter_save(dr, ds->dragb, ds->dx, ds->dy);
  1885. draw_drag_indicator(dr, ds, state, ui, postdrop != NULL);
  1886. }
  1887. if (postdrop) free_game(postdrop);
  1888. if (!ds->started) ds->started = true;
  1889. }
  1890. static float game_anim_length(const game_state *oldstate,
  1891. const game_state *newstate, int dir, game_ui *ui)
  1892. {
  1893. return 0.0F;
  1894. }
  1895. static float game_flash_length(const game_state *oldstate,
  1896. const game_state *newstate, int dir, game_ui *ui)
  1897. {
  1898. if (!oldstate->completed &&
  1899. newstate->completed && !newstate->used_solve)
  1900. return FLASH_SPIN;
  1901. else
  1902. return 0.0F;
  1903. }
  1904. static void game_get_cursor_location(const game_ui *ui,
  1905. const game_drawstate *ds,
  1906. const game_state *state,
  1907. const game_params *params,
  1908. int *x, int *y, int *w, int *h)
  1909. {
  1910. if(ui->cshow) {
  1911. *x = COORD(ui->cx);
  1912. *y = COORD(ui->cy);
  1913. *w = *h = TILE_SIZE;
  1914. }
  1915. }
  1916. static int game_status(const game_state *state)
  1917. {
  1918. return state->completed ? +1 : 0;
  1919. }
  1920. static void game_print_size(const game_params *params, const game_ui *ui,
  1921. float *x, float *y)
  1922. {
  1923. int pw, ph;
  1924. game_compute_size(params, 1300, ui, &pw, &ph);
  1925. *x = pw / 100.0F;
  1926. *y = ph / 100.0F;
  1927. }
  1928. static void game_print(drawing *dr, const game_state *state, const game_ui *ui,
  1929. int tilesize)
  1930. {
  1931. int ink = print_mono_colour(dr, 0);
  1932. int x, y;
  1933. /* Fake up just enough of a drawstate */
  1934. game_drawstate ads, *ds = &ads;
  1935. ds->tilesize = tilesize;
  1936. ds->n = state->n;
  1937. /*
  1938. * Border and grid.
  1939. */
  1940. print_line_width(dr, TILE_SIZE / 40);
  1941. for (x = 1; x < state->w; x++)
  1942. draw_line(dr, COORD(x), COORD(0), COORD(x), COORD(state->h), ink);
  1943. for (y = 1; y < state->h; y++)
  1944. draw_line(dr, COORD(0), COORD(y), COORD(state->w), COORD(y), ink);
  1945. print_line_width(dr, 2*TILE_SIZE / 40);
  1946. draw_rect_outline(dr, COORD(0), COORD(0), TILE_SIZE*state->w,
  1947. TILE_SIZE*state->h, ink);
  1948. /*
  1949. * Arrows and numbers.
  1950. */
  1951. print_line_width(dr, 0);
  1952. for (y = 0; y < state->h; y++)
  1953. for (x = 0; x < state->w; x++)
  1954. tile_redraw(dr, ds, COORD(x), COORD(y), state->dirs[y*state->w+x],
  1955. 0, state->nums[y*state->w+x], 0, 0.0, ink);
  1956. }
  1957. #ifdef COMBINED
  1958. #define thegame signpost
  1959. #endif
  1960. const struct game thegame = {
  1961. "Signpost", "games.signpost", "signpost",
  1962. default_params,
  1963. game_fetch_preset, NULL,
  1964. decode_params,
  1965. encode_params,
  1966. free_params,
  1967. dup_params,
  1968. true, game_configure, custom_params,
  1969. validate_params,
  1970. new_game_desc,
  1971. validate_desc,
  1972. new_game,
  1973. dup_game,
  1974. free_game,
  1975. true, solve_game,
  1976. true, game_can_format_as_text_now, game_text_format,
  1977. get_prefs, set_prefs,
  1978. new_ui,
  1979. free_ui,
  1980. NULL, /* encode_ui */
  1981. NULL, /* decode_ui */
  1982. NULL, /* game_request_keys */
  1983. game_changed_state,
  1984. current_key_label,
  1985. interpret_move,
  1986. execute_move,
  1987. PREFERRED_TILE_SIZE, game_compute_size, game_set_size,
  1988. game_colours,
  1989. game_new_drawstate,
  1990. game_free_drawstate,
  1991. game_redraw,
  1992. game_anim_length,
  1993. game_flash_length,
  1994. game_get_cursor_location,
  1995. game_status,
  1996. true, false, game_print_size, game_print,
  1997. false, /* wants_statusbar */
  1998. false, NULL, /* timing_state */
  1999. REQUIRE_RBUTTON, /* flags */
  2000. };
  2001. #ifdef STANDALONE_SOLVER
  2002. #include <time.h>
  2003. #include <stdarg.h>
  2004. static const char *quis = NULL;
  2005. static void usage(FILE *out) {
  2006. fprintf(out, "usage: %s [--stdin] [--soak] [--seed SEED] <params>|<game id>\n", quis);
  2007. }
  2008. static void cycle_seed(char **seedstr, random_state *rs)
  2009. {
  2010. char newseed[16];
  2011. int j;
  2012. newseed[15] = '\0';
  2013. newseed[0] = '1' + (char)random_upto(rs, 9);
  2014. for (j = 1; j < 15; j++)
  2015. newseed[j] = '0' + (char)random_upto(rs, 10);
  2016. sfree(*seedstr);
  2017. *seedstr = dupstr(newseed);
  2018. }
  2019. static void start_soak(game_params *p, char *seedstr)
  2020. {
  2021. time_t tt_start, tt_now, tt_last;
  2022. char *desc, *aux;
  2023. random_state *rs;
  2024. long n = 0, nnums = 0, i;
  2025. game_state *state;
  2026. tt_start = tt_now = time(NULL);
  2027. printf("Soak-generating a %dx%d grid.\n", p->w, p->h);
  2028. while (1) {
  2029. rs = random_new(seedstr, strlen(seedstr));
  2030. desc = thegame.new_desc(p, rs, &aux, 0);
  2031. state = thegame.new_game(NULL, p, desc);
  2032. for (i = 0; i < state->n; i++) {
  2033. if (state->flags[i] & FLAG_IMMUTABLE)
  2034. nnums++;
  2035. }
  2036. thegame.free_game(state);
  2037. sfree(desc);
  2038. cycle_seed(&seedstr, rs);
  2039. random_free(rs);
  2040. n++;
  2041. tt_last = time(NULL);
  2042. if (tt_last > tt_now) {
  2043. tt_now = tt_last;
  2044. printf("%ld total, %3.1f/s, %3.1f nums/grid (%3.1f%%).\n",
  2045. n,
  2046. (double)n / ((double)tt_now - tt_start),
  2047. (double)nnums / (double)n,
  2048. ((double)nnums * 100.0) / ((double)n * (double)p->w * (double)p->h) );
  2049. }
  2050. }
  2051. }
  2052. static void process_desc(char *id)
  2053. {
  2054. char *desc, *solvestr;
  2055. const char *err;
  2056. game_params *p;
  2057. game_state *s;
  2058. printf("%s\n ", id);
  2059. desc = strchr(id, ':');
  2060. if (!desc) {
  2061. fprintf(stderr, "%s: expecting game description.", quis);
  2062. exit(1);
  2063. }
  2064. *desc++ = '\0';
  2065. p = thegame.default_params();
  2066. thegame.decode_params(p, id);
  2067. err = thegame.validate_params(p, 1);
  2068. if (err) {
  2069. fprintf(stderr, "%s: %s", quis, err);
  2070. thegame.free_params(p);
  2071. return;
  2072. }
  2073. err = thegame.validate_desc(p, desc);
  2074. if (err) {
  2075. fprintf(stderr, "%s: %s\nDescription: %s\n", quis, err, desc);
  2076. thegame.free_params(p);
  2077. return;
  2078. }
  2079. s = thegame.new_game(NULL, p, desc);
  2080. solvestr = thegame.solve(s, s, NULL, &err);
  2081. if (!solvestr)
  2082. fprintf(stderr, "%s\n", err);
  2083. else
  2084. printf("Puzzle is soluble.\n");
  2085. thegame.free_game(s);
  2086. thegame.free_params(p);
  2087. }
  2088. int main(int argc, char *argv[])
  2089. {
  2090. char *id = NULL, *desc, *aux = NULL;
  2091. const char *err;
  2092. bool soak = false, verbose = false, stdin_desc = false;
  2093. int n = 1, i;
  2094. char *seedstr = NULL, newseed[16];
  2095. setvbuf(stdout, NULL, _IONBF, 0);
  2096. quis = argv[0];
  2097. while (--argc > 0) {
  2098. char *p = (char*)(*++argv);
  2099. if (!strcmp(p, "-v") || !strcmp(p, "--verbose"))
  2100. verbose = true;
  2101. else if (!strcmp(p, "--stdin"))
  2102. stdin_desc = true;
  2103. else if (!strcmp(p, "-e") || !strcmp(p, "--seed")) {
  2104. seedstr = dupstr(*++argv);
  2105. argc--;
  2106. } else if (!strcmp(p, "-n") || !strcmp(p, "--number")) {
  2107. n = atoi(*++argv);
  2108. argc--;
  2109. } else if (!strcmp(p, "-s") || !strcmp(p, "--soak")) {
  2110. soak = true;
  2111. } else if (*p == '-') {
  2112. fprintf(stderr, "%s: unrecognised option `%s'\n", argv[0], p);
  2113. usage(stderr);
  2114. exit(1);
  2115. } else {
  2116. id = p;
  2117. }
  2118. }
  2119. sprintf(newseed, "%lu", (unsigned long) time(NULL));
  2120. seedstr = dupstr(newseed);
  2121. if (id || !stdin_desc) {
  2122. if (id && strchr(id, ':')) {
  2123. /* Parameters and description passed on cmd-line:
  2124. * try and solve it. */
  2125. process_desc(id);
  2126. } else {
  2127. /* No description passed on cmd-line: decode parameters
  2128. * (with optional seed too) */
  2129. game_params *p = thegame.default_params();
  2130. if (id) {
  2131. char *cmdseed = strchr(id, '#');
  2132. if (cmdseed) {
  2133. *cmdseed++ = '\0';
  2134. sfree(seedstr);
  2135. seedstr = dupstr(cmdseed);
  2136. }
  2137. thegame.decode_params(p, id);
  2138. }
  2139. err = thegame.validate_params(p, 1);
  2140. if (err) {
  2141. fprintf(stderr, "%s: %s", quis, err);
  2142. thegame.free_params(p);
  2143. exit(1);
  2144. }
  2145. /* We have a set of valid parameters; either soak with it
  2146. * or generate a single game description and print to stdout. */
  2147. if (soak)
  2148. start_soak(p, seedstr);
  2149. else {
  2150. char *pstring = thegame.encode_params(p, 0);
  2151. for (i = 0; i < n; i++) {
  2152. random_state *rs = random_new(seedstr, strlen(seedstr));
  2153. if (verbose) printf("%s#%s\n", pstring, seedstr);
  2154. desc = thegame.new_desc(p, rs, &aux, 0);
  2155. printf("%s:%s\n", pstring, desc);
  2156. sfree(desc);
  2157. cycle_seed(&seedstr, rs);
  2158. random_free(rs);
  2159. }
  2160. sfree(pstring);
  2161. }
  2162. thegame.free_params(p);
  2163. }
  2164. }
  2165. if (stdin_desc) {
  2166. char buf[4096];
  2167. while (fgets(buf, sizeof(buf), stdin)) {
  2168. buf[strcspn(buf, "\r\n")] = '\0';
  2169. process_desc(buf);
  2170. }
  2171. }
  2172. sfree(seedstr);
  2173. return 0;
  2174. }
  2175. #endif
  2176. /* vim: set shiftwidth=4 tabstop=8: */