magnets.c 78 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698
  1. /*
  2. * magnets.c: implementation of janko.at 'magnets puzzle' game.
  3. *
  4. * http://64.233.179.104/translate_c?hl=en&u=http://www.janko.at/Raetsel/Magnete/Beispiel.htm
  5. *
  6. * Puzzle definition is just the size, and then the list of + (across then
  7. * down) and - (across then down) present, then domino edges.
  8. *
  9. * An example:
  10. *
  11. * + 2 0 1
  12. * +-----+
  13. * 1|+ -| |1
  14. * |-+-+ |
  15. * 0|-|#| |1
  16. * | +-+-|
  17. * 2|+|- +|1
  18. * +-----+
  19. * 1 2 0 -
  20. *
  21. * 3x3:201,102,120,111,LRTT*BBLR
  22. *
  23. * 'Zotmeister' examples:
  24. * 5x5:.2..1,3..1.,.2..2,2..2.,LRLRTTLRTBBT*BTTBLRBBLRLR
  25. * 9x9:3.51...33,.2..23.13,..33.33.2,12...5.3.,**TLRTLR*,*TBLRBTLR,TBLRLRBTT,BLRTLRTBB,LRTB*TBLR,LRBLRBLRT,TTTLRLRTB,BBBTLRTB*,*LRBLRB**
  26. *
  27. * Janko 6x6 with solution:
  28. * 6x6:322223,323132,232223,232223,LRTLRTTTBLRBBBTTLRLRBBLRTTLRTTBBLRBB
  29. *
  30. * janko 8x8:
  31. * 8x8:34131323,23131334,43122323,21332243,LRTLRLRT,LRBTTTTB,LRTBBBBT,TTBTLRTB,BBTBTTBT,TTBTBBTB,BBTBLRBT,LRBLRLRB
  32. */
  33. #include <stdio.h>
  34. #include <stdlib.h>
  35. #include <string.h>
  36. #include <assert.h>
  37. #include <ctype.h>
  38. #include <limits.h>
  39. #ifdef NO_TGMATH_H
  40. # include <math.h>
  41. #else
  42. # include <tgmath.h>
  43. #endif
  44. #include "puzzles.h"
  45. #ifdef STANDALONE_SOLVER
  46. static bool verbose = false;
  47. #endif
  48. enum {
  49. COL_BACKGROUND, COL_HIGHLIGHT, COL_LOWLIGHT,
  50. COL_TEXT, COL_ERROR, COL_CURSOR, COL_DONE,
  51. COL_NEUTRAL, COL_NEGATIVE, COL_POSITIVE, COL_NOT,
  52. NCOLOURS
  53. };
  54. /* Cell states. */
  55. enum { EMPTY = 0, NEUTRAL = EMPTY, POSITIVE = 1, NEGATIVE = 2 };
  56. #if defined DEBUGGING || defined STANDALONE_SOLVER
  57. static const char *cellnames[3] = { "neutral", "positive", "negative" };
  58. #define NAME(w) ( ((w) < 0 || (w) > 2) ? "(out of range)" : cellnames[(w)] )
  59. #endif
  60. #define GRID2CHAR(g) ( ((g) >= 0 && (g) <= 2) ? ".+-"[(g)] : '?' )
  61. #define CHAR2GRID(c) ( (c) == '+' ? POSITIVE : (c) == '-' ? NEGATIVE : NEUTRAL )
  62. #define INGRID(s,x,y) ((x) >= 0 && (x) < (s)->w && (y) >= 0 && (y) < (s)->h)
  63. #define OPPOSITE(x) ( ((x)*2) % 3 ) /* 0 --> 0,
  64. 1 --> 2,
  65. 2 --> 4 --> 1 */
  66. #define FLASH_TIME 0.7F
  67. /* Macro ickery copied from slant.c */
  68. #define DIFFLIST(A) \
  69. A(EASY,Easy,e) \
  70. A(TRICKY,Tricky,t)
  71. #define ENUM(upper,title,lower) DIFF_ ## upper,
  72. #define TITLE(upper,title,lower) #title,
  73. #define ENCODE(upper,title,lower) #lower
  74. #define CONFIG(upper,title,lower) ":" #title
  75. enum { DIFFLIST(ENUM) DIFFCOUNT };
  76. static char const *const magnets_diffnames[] = { DIFFLIST(TITLE) "(count)" };
  77. static char const magnets_diffchars[] = DIFFLIST(ENCODE);
  78. #define DIFFCONFIG DIFFLIST(CONFIG)
  79. /* --------------------------------------------------------------- */
  80. /* Game parameter functions. */
  81. struct game_params {
  82. int w, h, diff;
  83. bool stripclues;
  84. };
  85. #define DEFAULT_PRESET 2
  86. static const struct game_params magnets_presets[] = {
  87. {6, 5, DIFF_EASY, 0},
  88. {6, 5, DIFF_TRICKY, 0},
  89. {6, 5, DIFF_TRICKY, 1},
  90. {8, 7, DIFF_EASY, 0},
  91. {8, 7, DIFF_TRICKY, 0},
  92. {8, 7, DIFF_TRICKY, 1},
  93. {10, 9, DIFF_TRICKY, 0},
  94. {10, 9, DIFF_TRICKY, 1}
  95. };
  96. static game_params *default_params(void)
  97. {
  98. game_params *ret = snew(game_params);
  99. *ret = magnets_presets[DEFAULT_PRESET];
  100. return ret;
  101. }
  102. static bool game_fetch_preset(int i, char **name, game_params **params)
  103. {
  104. game_params *ret;
  105. char buf[64];
  106. if (i < 0 || i >= lenof(magnets_presets)) return false;
  107. ret = default_params();
  108. *ret = magnets_presets[i]; /* struct copy */
  109. *params = ret;
  110. sprintf(buf, "%dx%d %s%s",
  111. magnets_presets[i].w, magnets_presets[i].h,
  112. magnets_diffnames[magnets_presets[i].diff],
  113. magnets_presets[i].stripclues ? ", strip clues" : "");
  114. *name = dupstr(buf);
  115. return true;
  116. }
  117. static void free_params(game_params *params)
  118. {
  119. sfree(params);
  120. }
  121. static game_params *dup_params(const game_params *params)
  122. {
  123. game_params *ret = snew(game_params);
  124. *ret = *params; /* structure copy */
  125. return ret;
  126. }
  127. static void decode_params(game_params *ret, char const *string)
  128. {
  129. ret->w = ret->h = atoi(string);
  130. while (*string && isdigit((unsigned char) *string)) ++string;
  131. if (*string == 'x') {
  132. string++;
  133. ret->h = atoi(string);
  134. while (*string && isdigit((unsigned char)*string)) string++;
  135. }
  136. ret->diff = DIFF_EASY;
  137. if (*string == 'd') {
  138. int i;
  139. string++;
  140. for (i = 0; i < DIFFCOUNT; i++)
  141. if (*string == magnets_diffchars[i])
  142. ret->diff = i;
  143. if (*string) string++;
  144. }
  145. ret->stripclues = false;
  146. if (*string == 'S') {
  147. string++;
  148. ret->stripclues = true;
  149. }
  150. }
  151. static char *encode_params(const game_params *params, bool full)
  152. {
  153. char buf[256];
  154. sprintf(buf, "%dx%d", params->w, params->h);
  155. if (full)
  156. sprintf(buf + strlen(buf), "d%c%s",
  157. magnets_diffchars[params->diff],
  158. params->stripclues ? "S" : "");
  159. return dupstr(buf);
  160. }
  161. static config_item *game_configure(const game_params *params)
  162. {
  163. config_item *ret;
  164. char buf[64];
  165. ret = snewn(5, config_item);
  166. ret[0].name = "Width";
  167. ret[0].type = C_STRING;
  168. sprintf(buf, "%d", params->w);
  169. ret[0].u.string.sval = dupstr(buf);
  170. ret[1].name = "Height";
  171. ret[1].type = C_STRING;
  172. sprintf(buf, "%d", params->h);
  173. ret[1].u.string.sval = dupstr(buf);
  174. ret[2].name = "Difficulty";
  175. ret[2].type = C_CHOICES;
  176. ret[2].u.choices.choicenames = DIFFCONFIG;
  177. ret[2].u.choices.selected = params->diff;
  178. ret[3].name = "Strip clues";
  179. ret[3].type = C_BOOLEAN;
  180. ret[3].u.boolean.bval = params->stripclues;
  181. ret[4].name = NULL;
  182. ret[4].type = C_END;
  183. return ret;
  184. }
  185. static game_params *custom_params(const config_item *cfg)
  186. {
  187. game_params *ret = snew(game_params);
  188. ret->w = atoi(cfg[0].u.string.sval);
  189. ret->h = atoi(cfg[1].u.string.sval);
  190. ret->diff = cfg[2].u.choices.selected;
  191. ret->stripclues = cfg[3].u.boolean.bval;
  192. return ret;
  193. }
  194. static const char *validate_params(const game_params *params, bool full)
  195. {
  196. if (params->w < 2) return "Width must be at least two";
  197. if (params->h < 2) return "Height must be at least two";
  198. if (params->w > INT_MAX / params->h)
  199. return "Width times height must not be unreasonably large";
  200. if (params->diff >= DIFF_TRICKY) {
  201. if (params->w < 5 && params->h < 5)
  202. return "Either width or height must be at least five for Tricky";
  203. } else {
  204. if (params->w < 3 && params->h < 3)
  205. return "Either width or height must be at least three";
  206. }
  207. if (params->diff < 0 || params->diff >= DIFFCOUNT)
  208. return "Unknown difficulty level";
  209. return NULL;
  210. }
  211. /* --------------------------------------------------------------- */
  212. /* Game state allocation, deallocation. */
  213. struct game_common {
  214. int *dominoes; /* size w*h, dominoes[i] points to other end of domino. */
  215. int *rowcount; /* size 3*h, array of [plus, minus, neutral] counts */
  216. int *colcount; /* size 3*w, ditto */
  217. int refcount;
  218. };
  219. #define GS_ERROR 1
  220. #define GS_SET 2
  221. #define GS_NOTPOSITIVE 4
  222. #define GS_NOTNEGATIVE 8
  223. #define GS_NOTNEUTRAL 16
  224. #define GS_MARK 32
  225. #define GS_NOTMASK (GS_NOTPOSITIVE|GS_NOTNEGATIVE|GS_NOTNEUTRAL)
  226. #define NOTFLAG(w) ( (w) == NEUTRAL ? GS_NOTNEUTRAL : \
  227. (w) == POSITIVE ? GS_NOTPOSITIVE : \
  228. (w) == NEGATIVE ? GS_NOTNEGATIVE : \
  229. 0 )
  230. #define POSSIBLE(f,w) (!(state->flags[(f)] & NOTFLAG(w)))
  231. struct game_state {
  232. int w, h, wh;
  233. int *grid; /* size w*h, for cell state (pos/neg) */
  234. unsigned int *flags; /* size w*h */
  235. bool solved, completed, numbered;
  236. bool *counts_done;
  237. struct game_common *common; /* domino layout never changes. */
  238. };
  239. static void clear_state(game_state *ret)
  240. {
  241. int i;
  242. ret->solved = false;
  243. ret->completed = false;
  244. ret->numbered = false;
  245. memset(ret->common->rowcount, 0, ret->h*3*sizeof(int));
  246. memset(ret->common->colcount, 0, ret->w*3*sizeof(int));
  247. memset(ret->counts_done, 0, (ret->h + ret->w) * 2 * sizeof(bool));
  248. for (i = 0; i < ret->wh; i++) {
  249. ret->grid[i] = EMPTY;
  250. ret->flags[i] = 0;
  251. ret->common->dominoes[i] = i;
  252. }
  253. }
  254. static game_state *new_state(int w, int h)
  255. {
  256. game_state *ret = snew(game_state);
  257. memset(ret, 0, sizeof(game_state));
  258. ret->w = w;
  259. ret->h = h;
  260. ret->wh = w*h;
  261. ret->grid = snewn(ret->wh, int);
  262. ret->flags = snewn(ret->wh, unsigned int);
  263. ret->counts_done = snewn((ret->h + ret->w) * 2, bool);
  264. ret->common = snew(struct game_common);
  265. ret->common->refcount = 1;
  266. ret->common->dominoes = snewn(ret->wh, int);
  267. ret->common->rowcount = snewn(ret->h*3, int);
  268. ret->common->colcount = snewn(ret->w*3, int);
  269. clear_state(ret);
  270. return ret;
  271. }
  272. static game_state *dup_game(const game_state *src)
  273. {
  274. game_state *dest = snew(game_state);
  275. dest->w = src->w;
  276. dest->h = src->h;
  277. dest->wh = src->wh;
  278. dest->solved = src->solved;
  279. dest->completed = src->completed;
  280. dest->numbered = src->numbered;
  281. dest->common = src->common;
  282. dest->common->refcount++;
  283. dest->grid = snewn(dest->wh, int);
  284. memcpy(dest->grid, src->grid, dest->wh*sizeof(int));
  285. dest->counts_done = snewn((dest->h + dest->w) * 2, bool);
  286. memcpy(dest->counts_done, src->counts_done,
  287. (dest->h + dest->w) * 2 * sizeof(bool));
  288. dest->flags = snewn(dest->wh, unsigned int);
  289. memcpy(dest->flags, src->flags, dest->wh*sizeof(unsigned int));
  290. return dest;
  291. }
  292. static void free_game(game_state *state)
  293. {
  294. state->common->refcount--;
  295. if (state->common->refcount == 0) {
  296. sfree(state->common->dominoes);
  297. sfree(state->common->rowcount);
  298. sfree(state->common->colcount);
  299. sfree(state->common);
  300. }
  301. sfree(state->counts_done);
  302. sfree(state->flags);
  303. sfree(state->grid);
  304. sfree(state);
  305. }
  306. /* --------------------------------------------------------------- */
  307. /* Game generation and reading. */
  308. /* For a game of size w*h the game description is:
  309. * w-sized string of column + numbers (L-R), or '.' for none
  310. * semicolon
  311. * h-sized string of row + numbers (T-B), or '.'
  312. * semicolon
  313. * w-sized string of column - numbers (L-R), or '.'
  314. * semicolon
  315. * h-sized string of row - numbers (T-B), or '.'
  316. * semicolon
  317. * w*h-sized string of 'L', 'R', 'U', 'D' for domino associations,
  318. * or '*' for a black singleton square.
  319. *
  320. * for a total length of 2w + 2h + wh + 4.
  321. */
  322. static char n2c(int num) { /* XXX cloned from singles.c */
  323. if (num == -1)
  324. return '.';
  325. if (num < 10)
  326. return '0' + num;
  327. else if (num < 10+26)
  328. return 'a' + num - 10;
  329. else
  330. return 'A' + num - 10 - 26;
  331. return '?';
  332. }
  333. static int c2n(char c) { /* XXX cloned from singles.c */
  334. if (isdigit((unsigned char)c))
  335. return (int)(c - '0');
  336. else if (c >= 'a' && c <= 'z')
  337. return (int)(c - 'a' + 10);
  338. else if (c >= 'A' && c <= 'Z')
  339. return (int)(c - 'A' + 10 + 26);
  340. return -1;
  341. }
  342. static const char *readrow(const char *desc, int n, int *array, int off,
  343. const char **prob)
  344. {
  345. int i, num;
  346. char c;
  347. for (i = 0; i < n; i++) {
  348. c = *desc++;
  349. if (c == 0) goto badchar;
  350. if (c == '.')
  351. num = -1;
  352. else {
  353. num = c2n(c);
  354. if (num < 0) goto badchar;
  355. }
  356. array[i*3+off] = num;
  357. }
  358. c = *desc++;
  359. if (c != ',') goto badchar;
  360. return desc;
  361. badchar:
  362. *prob = (c == 0) ?
  363. "Game description too short" :
  364. "Game description contained unexpected characters";
  365. return NULL;
  366. }
  367. static game_state *new_game_int(const game_params *params, const char *desc,
  368. const char **prob)
  369. {
  370. game_state *state = new_state(params->w, params->h);
  371. int x, y, idx, *count;
  372. char c;
  373. *prob = NULL;
  374. /* top row, left-to-right */
  375. desc = readrow(desc, state->w, state->common->colcount, POSITIVE, prob);
  376. if (*prob) goto done;
  377. /* left column, top-to-bottom */
  378. desc = readrow(desc, state->h, state->common->rowcount, POSITIVE, prob);
  379. if (*prob) goto done;
  380. /* bottom row, left-to-right */
  381. desc = readrow(desc, state->w, state->common->colcount, NEGATIVE, prob);
  382. if (*prob) goto done;
  383. /* right column, top-to-bottom */
  384. desc = readrow(desc, state->h, state->common->rowcount, NEGATIVE, prob);
  385. if (*prob) goto done;
  386. /* Add neutral counts (== size - pos - neg) to columns and rows.
  387. * Any singleton cells will just be treated as permanently neutral. */
  388. count = state->common->colcount;
  389. for (x = 0; x < state->w; x++) {
  390. if (count[x*3+POSITIVE] < 0 || count[x*3+NEGATIVE] < 0)
  391. count[x*3+NEUTRAL] = -1;
  392. else {
  393. count[x*3+NEUTRAL] =
  394. state->h - count[x*3+POSITIVE] - count[x*3+NEGATIVE];
  395. if (count[x*3+NEUTRAL] < 0) {
  396. *prob = "Column counts inconsistent";
  397. goto done;
  398. }
  399. }
  400. }
  401. count = state->common->rowcount;
  402. for (y = 0; y < state->h; y++) {
  403. if (count[y*3+POSITIVE] < 0 || count[y*3+NEGATIVE] < 0)
  404. count[y*3+NEUTRAL] = -1;
  405. else {
  406. count[y*3+NEUTRAL] =
  407. state->w - count[y*3+POSITIVE] - count[y*3+NEGATIVE];
  408. if (count[y*3+NEUTRAL] < 0) {
  409. *prob = "Row counts inconsistent";
  410. goto done;
  411. }
  412. }
  413. }
  414. for (y = 0; y < state->h; y++) {
  415. for (x = 0; x < state->w; x++) {
  416. idx = y*state->w + x;
  417. nextchar:
  418. c = *desc++;
  419. if (c == 'L') /* this square is LHS of a domino */
  420. state->common->dominoes[idx] = idx+1;
  421. else if (c == 'R') /* ... RHS of a domino */
  422. state->common->dominoes[idx] = idx-1;
  423. else if (c == 'T') /* ... top of a domino */
  424. state->common->dominoes[idx] = idx+state->w;
  425. else if (c == 'B') /* ... bottom of a domino */
  426. state->common->dominoes[idx] = idx-state->w;
  427. else if (c == '*') /* singleton */
  428. state->common->dominoes[idx] = idx;
  429. else if (c == ',') /* spacer, ignore */
  430. goto nextchar;
  431. else goto badchar;
  432. }
  433. }
  434. /* Check dominoes as input are sensibly consistent
  435. * (i.e. each end points to the other) */
  436. for (idx = 0; idx < state->wh; idx++) {
  437. if (state->common->dominoes[idx] < 0 ||
  438. state->common->dominoes[idx] >= state->wh ||
  439. (state->common->dominoes[idx] % state->w != idx % state->w &&
  440. state->common->dominoes[idx] / state->w != idx / state->w) ||
  441. state->common->dominoes[state->common->dominoes[idx]] != idx) {
  442. *prob = "Domino descriptions inconsistent";
  443. goto done;
  444. }
  445. if (state->common->dominoes[idx] == idx) {
  446. state->grid[idx] = NEUTRAL;
  447. state->flags[idx] |= GS_SET;
  448. }
  449. }
  450. /* Success. */
  451. state->numbered = true;
  452. goto done;
  453. badchar:
  454. *prob = (c == 0) ?
  455. "Game description too short" :
  456. "Game description contained unexpected characters";
  457. done:
  458. if (*prob) {
  459. free_game(state);
  460. return NULL;
  461. }
  462. return state;
  463. }
  464. static const char *validate_desc(const game_params *params, const char *desc)
  465. {
  466. const char *prob;
  467. game_state *st = new_game_int(params, desc, &prob);
  468. if (!st) return prob;
  469. free_game(st);
  470. return NULL;
  471. }
  472. static game_state *new_game(midend *me, const game_params *params,
  473. const char *desc)
  474. {
  475. const char *prob;
  476. game_state *st = new_game_int(params, desc, &prob);
  477. assert(st);
  478. return st;
  479. }
  480. static char *generate_desc(game_state *new)
  481. {
  482. int x, y, idx, other, w = new->w, h = new->h;
  483. char *desc = snewn(new->wh + 2*(w + h) + 5, char), *p = desc;
  484. for (x = 0; x < w; x++) *p++ = n2c(new->common->colcount[x*3+POSITIVE]);
  485. *p++ = ',';
  486. for (y = 0; y < h; y++) *p++ = n2c(new->common->rowcount[y*3+POSITIVE]);
  487. *p++ = ',';
  488. for (x = 0; x < w; x++) *p++ = n2c(new->common->colcount[x*3+NEGATIVE]);
  489. *p++ = ',';
  490. for (y = 0; y < h; y++) *p++ = n2c(new->common->rowcount[y*3+NEGATIVE]);
  491. *p++ = ',';
  492. for (y = 0; y < h; y++) {
  493. for (x = 0; x < w; x++) {
  494. idx = y*w + x;
  495. other = new->common->dominoes[idx];
  496. if (other == idx) *p++ = '*';
  497. else if (other == idx+1) *p++ = 'L';
  498. else if (other == idx-1) *p++ = 'R';
  499. else if (other == idx+w) *p++ = 'T';
  500. else if (other == idx-w) *p++ = 'B';
  501. else assert(!"mad domino orientation");
  502. }
  503. }
  504. *p = '\0';
  505. return desc;
  506. }
  507. static void game_text_hborder(const game_state *state, char **p_r)
  508. {
  509. char *p = *p_r;
  510. int x;
  511. *p++ = ' ';
  512. *p++ = '+';
  513. for (x = 0; x < state->w*2-1; x++) *p++ = '-';
  514. *p++ = '+';
  515. *p++ = '\n';
  516. *p_r = p;
  517. }
  518. static bool game_can_format_as_text_now(const game_params *params)
  519. {
  520. return true;
  521. }
  522. static char *game_text_format(const game_state *state)
  523. {
  524. int len, x, y, i;
  525. char *ret, *p;
  526. len = ((state->w*2)+4) * ((state->h*2)+4) + 2;
  527. p = ret = snewn(len, char);
  528. /* top row: '+' then column totals for plus. */
  529. *p++ = '+';
  530. for (x = 0; x < state->w; x++) {
  531. *p++ = ' ';
  532. *p++ = n2c(state->common->colcount[x*3+POSITIVE]);
  533. }
  534. *p++ = '\n';
  535. /* top border. */
  536. game_text_hborder(state, &p);
  537. for (y = 0; y < state->h; y++) {
  538. *p++ = n2c(state->common->rowcount[y*3+POSITIVE]);
  539. *p++ = '|';
  540. for (x = 0; x < state->w; x++) {
  541. i = y*state->w+x;
  542. *p++ = state->common->dominoes[i] == i ? '#' :
  543. state->grid[i] == POSITIVE ? '+' :
  544. state->grid[i] == NEGATIVE ? '-' :
  545. state->flags[i] & GS_SET ? '*' : ' ';
  546. if (x < (state->w-1))
  547. *p++ = state->common->dominoes[i] == i+1 ? ' ' : '|';
  548. }
  549. *p++ = '|';
  550. *p++ = n2c(state->common->rowcount[y*3+NEGATIVE]);
  551. *p++ = '\n';
  552. if (y < (state->h-1)) {
  553. *p++ = ' ';
  554. *p++ = '|';
  555. for (x = 0; x < state->w; x++) {
  556. i = y*state->w+x;
  557. *p++ = state->common->dominoes[i] == i+state->w ? ' ' : '-';
  558. if (x < (state->w-1))
  559. *p++ = '+';
  560. }
  561. *p++ = '|';
  562. *p++ = '\n';
  563. }
  564. }
  565. /* bottom border. */
  566. game_text_hborder(state, &p);
  567. /* bottom row: column totals for minus then '-'. */
  568. *p++ = ' ';
  569. for (x = 0; x < state->w; x++) {
  570. *p++ = ' ';
  571. *p++ = n2c(state->common->colcount[x*3+NEGATIVE]);
  572. }
  573. *p++ = ' ';
  574. *p++ = '-';
  575. *p++ = '\n';
  576. *p++ = '\0';
  577. return ret;
  578. }
  579. static void game_debug(game_state *state, const char *desc)
  580. {
  581. char *fmt = game_text_format(state);
  582. debug(("%s:\n%s\n", desc, fmt));
  583. sfree(fmt);
  584. }
  585. enum { ROW, COLUMN };
  586. typedef struct rowcol {
  587. int i, di, n, roworcol, num;
  588. int *targets;
  589. const char *name;
  590. } rowcol;
  591. static rowcol mkrowcol(const game_state *state, int num, int roworcol)
  592. {
  593. rowcol rc;
  594. rc.roworcol = roworcol;
  595. rc.num = num;
  596. if (roworcol == ROW) {
  597. rc.i = num * state->w;
  598. rc.di = 1;
  599. rc.n = state->w;
  600. rc.targets = &(state->common->rowcount[num*3]);
  601. rc.name = "row";
  602. } else if (roworcol == COLUMN) {
  603. rc.i = num;
  604. rc.di = state->w;
  605. rc.n = state->h;
  606. rc.targets = &(state->common->colcount[num*3]);
  607. rc.name = "column";
  608. } else {
  609. assert(!"unknown roworcol");
  610. }
  611. return rc;
  612. }
  613. static int count_rowcol(const game_state *state, int num, int roworcol,
  614. int which)
  615. {
  616. int i, count = 0;
  617. rowcol rc = mkrowcol(state, num, roworcol);
  618. for (i = 0; i < rc.n; i++, rc.i += rc.di) {
  619. if (which < 0) {
  620. if (state->grid[rc.i] == EMPTY &&
  621. !(state->flags[rc.i] & GS_SET))
  622. count++;
  623. } else if (state->grid[rc.i] == which)
  624. count++;
  625. }
  626. return count;
  627. }
  628. static void check_rowcol(game_state *state, int num, int roworcol, int which,
  629. bool *wrong, bool *incomplete)
  630. {
  631. int count, target = mkrowcol(state, num, roworcol).targets[which];
  632. if (target == -1) return; /* no number to check against. */
  633. count = count_rowcol(state, num, roworcol, which);
  634. if (count < target) *incomplete = true;
  635. if (count > target) *wrong = true;
  636. }
  637. static int check_completion(game_state *state)
  638. {
  639. int i, j, x, y, idx, w = state->w, h = state->h;
  640. int which = POSITIVE;
  641. bool wrong = false, incomplete = false;
  642. /* Check row and column counts for magnets. */
  643. for (which = POSITIVE, j = 0; j < 2; which = OPPOSITE(which), j++) {
  644. for (i = 0; i < w; i++)
  645. check_rowcol(state, i, COLUMN, which, &wrong, &incomplete);
  646. for (i = 0; i < h; i++)
  647. check_rowcol(state, i, ROW, which, &wrong, &incomplete);
  648. }
  649. /* Check each domino has been filled, and that we don't have
  650. * touching identical terminals. */
  651. for (i = 0; i < state->wh; i++) state->flags[i] &= ~GS_ERROR;
  652. for (x = 0; x < w; x++) {
  653. for (y = 0; y < h; y++) {
  654. idx = y*w + x;
  655. if (state->common->dominoes[idx] == idx)
  656. continue; /* no domino here */
  657. if (!(state->flags[idx] & GS_SET))
  658. incomplete = true;
  659. which = state->grid[idx];
  660. if (which != NEUTRAL) {
  661. #define CHECK(xx,yy) do { \
  662. if (INGRID(state,xx,yy) && \
  663. (state->grid[(yy)*w+(xx)] == which)) { \
  664. wrong = true; \
  665. state->flags[(yy)*w+(xx)] |= GS_ERROR; \
  666. state->flags[y*w+x] |= GS_ERROR; \
  667. } \
  668. } while(0)
  669. CHECK(x,y-1);
  670. CHECK(x,y+1);
  671. CHECK(x-1,y);
  672. CHECK(x+1,y);
  673. #undef CHECK
  674. }
  675. }
  676. }
  677. return wrong ? -1 : incomplete ? 0 : 1;
  678. }
  679. static const int dx[4] = {-1, 1, 0, 0};
  680. static const int dy[4] = {0, 0, -1, 1};
  681. static void solve_clearflags(game_state *state)
  682. {
  683. int i;
  684. for (i = 0; i < state->wh; i++) {
  685. state->flags[i] &= ~GS_NOTMASK;
  686. if (state->common->dominoes[i] != i)
  687. state->flags[i] &= ~GS_SET;
  688. }
  689. }
  690. /* Knowing a given cell cannot be a certain colour also tells us
  691. * something about the other cell in that domino. */
  692. static int solve_unflag(game_state *state, int i, int which,
  693. const char *why, rowcol *rc)
  694. {
  695. int ii, ret = 0;
  696. #if defined DEBUGGING || defined STANDALONE_SOLVER
  697. int w = state->w;
  698. #endif
  699. assert(i >= 0 && i < state->wh);
  700. ii = state->common->dominoes[i];
  701. if (ii == i) return 0;
  702. if (rc)
  703. debug(("solve_unflag: (%d,%d) for %s %d", i%w, i/w, rc->name, rc->num));
  704. if ((state->flags[i] & GS_SET) && (state->grid[i] == which)) {
  705. debug(("solve_unflag: (%d,%d) already %s, cannot unflag (for %s).",
  706. i%w, i/w, NAME(which), why));
  707. return -1;
  708. }
  709. if ((state->flags[ii] & GS_SET) && (state->grid[ii] == OPPOSITE(which))) {
  710. debug(("solve_unflag: (%d,%d) opposite already %s, cannot unflag (for %s).",
  711. ii%w, ii/w, NAME(OPPOSITE(which)), why));
  712. return -1;
  713. }
  714. if (POSSIBLE(i, which)) {
  715. state->flags[i] |= NOTFLAG(which);
  716. ret++;
  717. debug(("solve_unflag: (%d,%d) CANNOT be %s (%s)",
  718. i%w, i/w, NAME(which), why));
  719. }
  720. if (POSSIBLE(ii, OPPOSITE(which))) {
  721. state->flags[ii] |= NOTFLAG(OPPOSITE(which));
  722. ret++;
  723. debug(("solve_unflag: (%d,%d) CANNOT be %s (%s, other half)",
  724. ii%w, ii/w, NAME(OPPOSITE(which)), why));
  725. }
  726. #ifdef STANDALONE_SOLVER
  727. if (verbose && ret) {
  728. printf("(%d,%d)", i%w, i/w);
  729. if (rc) printf(" in %s %d", rc->name, rc->num);
  730. printf(" cannot be %s (%s); opposite (%d,%d) not %s.\n",
  731. NAME(which), why, ii%w, ii/w, NAME(OPPOSITE(which)));
  732. }
  733. #endif
  734. return ret;
  735. }
  736. static int solve_unflag_surrounds(game_state *state, int i, int which)
  737. {
  738. int x = i%state->w, y = i/state->w, xx, yy, j, ii;
  739. assert(INGRID(state, x, y));
  740. for (j = 0; j < 4; j++) {
  741. xx = x+dx[j]; yy = y+dy[j];
  742. if (!INGRID(state, xx, yy)) continue;
  743. ii = yy*state->w+xx;
  744. if (solve_unflag(state, ii, which, "adjacent to set cell", NULL) < 0)
  745. return -1;
  746. }
  747. return 0;
  748. }
  749. /* Sets a cell to a particular colour, and also perform other
  750. * housekeeping around that. */
  751. static int solve_set(game_state *state, int i, int which,
  752. const char *why, rowcol *rc)
  753. {
  754. int ii;
  755. #if defined DEBUGGING || defined STANDALONE_SOLVER
  756. int w = state->w;
  757. #endif
  758. ii = state->common->dominoes[i];
  759. if (state->flags[i] & GS_SET) {
  760. if (state->grid[i] == which) {
  761. return 0; /* was already set and held, do nothing. */
  762. } else {
  763. debug(("solve_set: (%d,%d) is held and %s, cannot set to %s",
  764. i%w, i/w, NAME(state->grid[i]), NAME(which)));
  765. return -1;
  766. }
  767. }
  768. if ((state->flags[ii] & GS_SET) && state->grid[ii] != OPPOSITE(which)) {
  769. debug(("solve_set: (%d,%d) opposite is held and %s, cannot set to %s",
  770. ii%w, ii/w, NAME(state->grid[ii]), NAME(OPPOSITE(which))));
  771. return -1;
  772. }
  773. if (!POSSIBLE(i, which)) {
  774. debug(("solve_set: (%d,%d) NOT %s, cannot set.", i%w, i/w, NAME(which)));
  775. return -1;
  776. }
  777. if (!POSSIBLE(ii, OPPOSITE(which))) {
  778. debug(("solve_set: (%d,%d) NOT %s, cannot set (%d,%d).",
  779. ii%w, ii/w, NAME(OPPOSITE(which)), i%w, i/w));
  780. return -1;
  781. }
  782. #ifdef STANDALONE_SOLVER
  783. if (verbose) {
  784. printf("(%d,%d)", i%w, i/w);
  785. if (rc) printf(" in %s %d", rc->name, rc->num);
  786. printf(" set to %s (%s), opposite (%d,%d) set to %s.\n",
  787. NAME(which), why, ii%w, ii/w, NAME(OPPOSITE(which)));
  788. }
  789. #endif
  790. if (rc)
  791. debug(("solve_set: (%d,%d) for %s %d", i%w, i/w, rc->name, rc->num));
  792. debug(("solve_set: (%d,%d) setting to %s (%s), surrounds first:",
  793. i%w, i/w, NAME(which), why));
  794. if (which != NEUTRAL) {
  795. if (solve_unflag_surrounds(state, i, which) < 0)
  796. return -1;
  797. if (solve_unflag_surrounds(state, ii, OPPOSITE(which)) < 0)
  798. return -1;
  799. }
  800. state->grid[i] = which;
  801. state->grid[ii] = OPPOSITE(which);
  802. state->flags[i] |= GS_SET;
  803. state->flags[ii] |= GS_SET;
  804. debug(("solve_set: (%d,%d) set to %s (%s)", i%w, i/w, NAME(which), why));
  805. return 1;
  806. }
  807. /* counts should be int[4]. */
  808. static void solve_counts(game_state *state, rowcol rc, int *counts, int *unset)
  809. {
  810. int i, j, which;
  811. assert(counts);
  812. for (i = 0; i < 4; i++) {
  813. counts[i] = 0;
  814. if (unset) unset[i] = 0;
  815. }
  816. for (i = rc.i, j = 0; j < rc.n; i += rc.di, j++) {
  817. if (state->flags[i] & GS_SET) {
  818. assert(state->grid[i] < 3);
  819. counts[state->grid[i]]++;
  820. } else if (unset) {
  821. for (which = 0; which <= 2; which++) {
  822. if (POSSIBLE(i, which))
  823. unset[which]++;
  824. }
  825. }
  826. }
  827. }
  828. static int solve_checkfull(game_state *state, rowcol rc, int *counts)
  829. {
  830. int starti = rc.i, j, which, didsth = 0, target;
  831. int unset[4];
  832. assert(state->numbered); /* only useful (should only be called) if numbered. */
  833. solve_counts(state, rc, counts, unset);
  834. for (which = 0; which <= 2; which++) {
  835. target = rc.targets[which];
  836. if (target == -1) continue;
  837. /*debug(("%s %d for %s: target %d, count %d, unset %d",
  838. rc.name, rc.num, NAME(which),
  839. target, counts[which], unset[which]));*/
  840. if (target < counts[which]) {
  841. debug(("%s %d has too many (%d) %s squares (target %d), impossible!",
  842. rc.name, rc.num, counts[which], NAME(which), target));
  843. return -1;
  844. }
  845. if (target == counts[which]) {
  846. /* We have the correct no. of the colour in this row/column
  847. * already; unflag all the rest. */
  848. for (rc.i = starti, j = 0; j < rc.n; rc.i += rc.di, j++) {
  849. if (state->flags[rc.i] & GS_SET) continue;
  850. if (!POSSIBLE(rc.i, which)) continue;
  851. if (solve_unflag(state, rc.i, which, "row/col full", &rc) < 0)
  852. return -1;
  853. didsth = 1;
  854. }
  855. } else if ((target - counts[which]) == unset[which]) {
  856. /* We need all the remaining unset squares for this colour;
  857. * set them all. */
  858. for (rc.i = starti, j = 0; j < rc.n; rc.i += rc.di, j++) {
  859. if (state->flags[rc.i] & GS_SET) continue;
  860. if (!POSSIBLE(rc.i, which)) continue;
  861. if (solve_set(state, rc.i, which, "row/col needs all unset", &rc) < 0)
  862. return -1;
  863. didsth = 1;
  864. }
  865. }
  866. }
  867. return didsth;
  868. }
  869. static int solve_startflags(game_state *state)
  870. {
  871. int x, y, i;
  872. for (x = 0; x < state->w; x++) {
  873. for (y = 0; y < state->h; y++) {
  874. i = y*state->w+x;
  875. if (state->common->dominoes[i] == i) continue;
  876. if (state->grid[i] != NEUTRAL ||
  877. state->flags[i] & GS_SET) {
  878. if (solve_set(state, i, state->grid[i], "initial set-and-hold", NULL) < 0)
  879. return -1;
  880. }
  881. }
  882. }
  883. return 0;
  884. }
  885. typedef int (*rowcolfn)(game_state *state, rowcol rc, int *counts);
  886. static int solve_rowcols(game_state *state, rowcolfn fn)
  887. {
  888. int x, y, didsth = 0, ret;
  889. rowcol rc;
  890. int counts[4];
  891. for (x = 0; x < state->w; x++) {
  892. rc = mkrowcol(state, x, COLUMN);
  893. solve_counts(state, rc, counts, NULL);
  894. ret = fn(state, rc, counts);
  895. if (ret < 0) return ret;
  896. didsth += ret;
  897. }
  898. for (y = 0; y < state->h; y++) {
  899. rc = mkrowcol(state, y, ROW);
  900. solve_counts(state, rc, counts, NULL);
  901. ret = fn(state, rc, counts);
  902. if (ret < 0) return ret;
  903. didsth += ret;
  904. }
  905. return didsth;
  906. }
  907. static int solve_force(game_state *state)
  908. {
  909. int i, which, didsth = 0;
  910. unsigned long f;
  911. for (i = 0; i < state->wh; i++) {
  912. if (state->flags[i] & GS_SET) continue;
  913. if (state->common->dominoes[i] == i) continue;
  914. f = state->flags[i] & GS_NOTMASK;
  915. which = -1;
  916. if (f == (GS_NOTPOSITIVE|GS_NOTNEGATIVE))
  917. which = NEUTRAL;
  918. if (f == (GS_NOTPOSITIVE|GS_NOTNEUTRAL))
  919. which = NEGATIVE;
  920. if (f == (GS_NOTNEGATIVE|GS_NOTNEUTRAL))
  921. which = POSITIVE;
  922. if (which != -1) {
  923. if (solve_set(state, i, which, "forced by flags", NULL) < 0)
  924. return -1;
  925. didsth = 1;
  926. }
  927. }
  928. return didsth;
  929. }
  930. static int solve_neither(game_state *state)
  931. {
  932. int i, j, didsth = 0;
  933. for (i = 0; i < state->wh; i++) {
  934. if (state->flags[i] & GS_SET) continue;
  935. j = state->common->dominoes[i];
  936. if (i == j) continue;
  937. if (((state->flags[i] & GS_NOTPOSITIVE) &&
  938. (state->flags[j] & GS_NOTPOSITIVE)) ||
  939. ((state->flags[i] & GS_NOTNEGATIVE) &&
  940. (state->flags[j] & GS_NOTNEGATIVE))) {
  941. if (solve_set(state, i, NEUTRAL, "neither tile magnet", NULL) < 0)
  942. return -1;
  943. didsth = 1;
  944. }
  945. }
  946. return didsth;
  947. }
  948. static int solve_advancedfull(game_state *state, rowcol rc, int *counts)
  949. {
  950. int i, j, nfound = 0, ret = 0;
  951. bool clearpos = false, clearneg = false;
  952. /* For this row/col, look for a domino entirely within the row where
  953. * both ends can only be + or - (but isn't held).
  954. * The +/- counts can thus be decremented by 1 each, and the 'unset'
  955. * count by 2.
  956. *
  957. * Once that's done for all such dominoes (and they're marked), try
  958. * and made usual deductions about rest of the row based on new totals. */
  959. if (rc.targets[POSITIVE] == -1 && rc.targets[NEGATIVE] == -1)
  960. return 0; /* don't have a target for either colour, nothing to do. */
  961. if ((rc.targets[POSITIVE] >= 0 && counts[POSITIVE] == rc.targets[POSITIVE]) &&
  962. (rc.targets[NEGATIVE] >= 0 && counts[NEGATIVE] == rc.targets[NEGATIVE]))
  963. return 0; /* both colours are full up already, nothing to do. */
  964. for (i = rc.i, j = 0; j < rc.n; i += rc.di, j++)
  965. state->flags[i] &= ~GS_MARK;
  966. for (i = rc.i, j = 0; j < rc.n; i += rc.di, j++) {
  967. if (state->flags[i] & GS_SET) continue;
  968. /* We're looking for a domino in our row/col, thus if
  969. * dominoes[i] -> i+di we've found one. */
  970. if (state->common->dominoes[i] != i+rc.di) continue;
  971. /* We need both squares of this domino to be either + or -
  972. * (i.e. both NOTNEUTRAL only). */
  973. if (((state->flags[i] & GS_NOTMASK) != GS_NOTNEUTRAL) ||
  974. ((state->flags[i+rc.di] & GS_NOTMASK) != GS_NOTNEUTRAL))
  975. continue;
  976. debug(("Domino in %s %d at (%d,%d) must be polarised.",
  977. rc.name, rc.num, i%state->w, i/state->w));
  978. state->flags[i] |= GS_MARK;
  979. state->flags[i+rc.di] |= GS_MARK;
  980. nfound++;
  981. }
  982. if (nfound == 0) return 0;
  983. /* nfound is #dominoes we matched, which will all be marked. */
  984. counts[POSITIVE] += nfound;
  985. counts[NEGATIVE] += nfound;
  986. if (rc.targets[POSITIVE] >= 0 && counts[POSITIVE] == rc.targets[POSITIVE]) {
  987. debug(("%s %d has now filled POSITIVE:", rc.name, rc.num));
  988. clearpos = true;
  989. }
  990. if (rc.targets[NEGATIVE] >= 0 && counts[NEGATIVE] == rc.targets[NEGATIVE]) {
  991. debug(("%s %d has now filled NEGATIVE:", rc.name, rc.num));
  992. clearneg = true;
  993. }
  994. if (!clearpos && !clearneg) return 0;
  995. for (i = rc.i, j = 0; j < rc.n; i += rc.di, j++) {
  996. if (state->flags[i] & GS_SET) continue;
  997. if (state->flags[i] & GS_MARK) continue;
  998. if (clearpos && !(state->flags[i] & GS_NOTPOSITIVE)) {
  999. if (solve_unflag(state, i, POSITIVE, "row/col full (+ve) [tricky]", &rc) < 0)
  1000. return -1;
  1001. ret++;
  1002. }
  1003. if (clearneg && !(state->flags[i] & GS_NOTNEGATIVE)) {
  1004. if (solve_unflag(state, i, NEGATIVE, "row/col full (-ve) [tricky]", &rc) < 0)
  1005. return -1;
  1006. ret++;
  1007. }
  1008. }
  1009. return ret;
  1010. }
  1011. /* If we only have one neutral still to place on a row/column then no
  1012. dominoes entirely in that row/column can be neutral. */
  1013. static int solve_nonneutral(game_state *state, rowcol rc, int *counts)
  1014. {
  1015. int i, j, ret = 0;
  1016. if (rc.targets[NEUTRAL] != counts[NEUTRAL]+1)
  1017. return 0;
  1018. for (i = rc.i, j = 0; j < rc.n; i += rc.di, j++) {
  1019. if (state->flags[i] & GS_SET) continue;
  1020. if (state->common->dominoes[i] != i+rc.di) continue;
  1021. if (!(state->flags[i] & GS_NOTNEUTRAL)) {
  1022. if (solve_unflag(state, i, NEUTRAL, "single neutral in row/col [tricky]", &rc) < 0)
  1023. return -1;
  1024. ret++;
  1025. }
  1026. }
  1027. return ret;
  1028. }
  1029. /* If we need to fill all unfilled cells with +-, and we need 1 more of
  1030. * one than the other, and we have a single odd-numbered region of unfilled
  1031. * cells, that odd-numbered region must start and end with the extra number. */
  1032. static int solve_oddlength(game_state *state, rowcol rc, int *counts)
  1033. {
  1034. int i, j, ret = 0, extra, tpos, tneg;
  1035. int start = -1, length = 0, startodd = -1;
  1036. bool inempty = false;
  1037. /* need zero neutral cells still to find... */
  1038. if (rc.targets[NEUTRAL] != counts[NEUTRAL])
  1039. return 0;
  1040. /* ...and #positive and #negative to differ by one. */
  1041. tpos = rc.targets[POSITIVE] - counts[POSITIVE];
  1042. tneg = rc.targets[NEGATIVE] - counts[NEGATIVE];
  1043. if (tpos == tneg+1)
  1044. extra = POSITIVE;
  1045. else if (tneg == tpos+1)
  1046. extra = NEGATIVE;
  1047. else return 0;
  1048. for (i = rc.i, j = 0; j < rc.n; i += rc.di, j++) {
  1049. if (state->flags[i] & GS_SET) {
  1050. if (inempty) {
  1051. if (length % 2) {
  1052. /* we've just finished an odd-length section. */
  1053. if (startodd != -1) goto twoodd;
  1054. startodd = start;
  1055. }
  1056. inempty = false;
  1057. }
  1058. } else {
  1059. if (inempty)
  1060. length++;
  1061. else {
  1062. start = i;
  1063. length = 1;
  1064. inempty = true;
  1065. }
  1066. }
  1067. }
  1068. if (inempty && (length % 2)) {
  1069. if (startodd != -1) goto twoodd;
  1070. startodd = start;
  1071. }
  1072. if (startodd != -1)
  1073. ret = solve_set(state, startodd, extra, "odd-length section start", &rc);
  1074. return ret;
  1075. twoodd:
  1076. debug(("%s %d has >1 odd-length sections, starting at %d,%d and %d,%d.",
  1077. rc.name, rc.num,
  1078. startodd%state->w, startodd/state->w,
  1079. start%state->w, start/state->w));
  1080. return 0;
  1081. }
  1082. /* Count the number of remaining empty dominoes in any row/col.
  1083. * If that number is equal to the #remaining positive,
  1084. * or to the #remaining negative, no empty cells can be neutral. */
  1085. static int solve_countdominoes_neutral(game_state *state, rowcol rc, int *counts)
  1086. {
  1087. int i, j, ndom = 0, ret = 0;
  1088. bool nonn = false;
  1089. if ((rc.targets[POSITIVE] == -1) && (rc.targets[NEGATIVE] == -1))
  1090. return 0; /* need at least one target to compare. */
  1091. for (i = rc.i, j = 0; j < rc.n; i += rc.di, j++) {
  1092. if (state->flags[i] & GS_SET) continue;
  1093. assert(state->grid[i] == EMPTY);
  1094. /* Skip solo cells, or second cell in domino. */
  1095. if ((state->common->dominoes[i] == i) ||
  1096. (state->common->dominoes[i] == i-rc.di))
  1097. continue;
  1098. ndom++;
  1099. }
  1100. if ((rc.targets[POSITIVE] != -1) &&
  1101. (rc.targets[POSITIVE]-counts[POSITIVE] == ndom))
  1102. nonn = true;
  1103. if ((rc.targets[NEGATIVE] != -1) &&
  1104. (rc.targets[NEGATIVE]-counts[NEGATIVE] == ndom))
  1105. nonn = true;
  1106. if (!nonn) return 0;
  1107. for (i = rc.i, j = 0; j < rc.n; i += rc.di, j++) {
  1108. if (state->flags[i] & GS_SET) continue;
  1109. if (!(state->flags[i] & GS_NOTNEUTRAL)) {
  1110. if (solve_unflag(state, i, NEUTRAL, "all dominoes +/- [tricky]", &rc) < 0)
  1111. return -1;
  1112. ret++;
  1113. }
  1114. }
  1115. return ret;
  1116. }
  1117. static int solve_domino_count(game_state *state, rowcol rc, int i, int which)
  1118. {
  1119. int nposs = 0;
  1120. /* Skip solo cells or 2nd in domino. */
  1121. if ((state->common->dominoes[i] == i) ||
  1122. (state->common->dominoes[i] == i-rc.di))
  1123. return 0;
  1124. if (state->flags[i] & GS_SET)
  1125. return 0;
  1126. if (POSSIBLE(i, which))
  1127. nposs++;
  1128. if (state->common->dominoes[i] == i+rc.di) {
  1129. /* second cell of domino is on our row: test that too. */
  1130. if (POSSIBLE(i+rc.di, which))
  1131. nposs++;
  1132. }
  1133. return nposs;
  1134. }
  1135. /* Count number of dominoes we could put each of + and - into. If it is equal
  1136. * to the #left, any domino we can only put + or - in one cell of must have it. */
  1137. static int solve_countdominoes_nonneutral(game_state *state, rowcol rc, int *counts)
  1138. {
  1139. int which, w, i, j, ndom = 0, didsth = 0, toset;
  1140. for (which = POSITIVE, w = 0; w < 2; which = OPPOSITE(which), w++) {
  1141. if (rc.targets[which] == -1) continue;
  1142. for (i = rc.i, j = 0; j < rc.n; i += rc.di, j++) {
  1143. if (solve_domino_count(state, rc, i, which) > 0)
  1144. ndom++;
  1145. }
  1146. if ((rc.targets[which] - counts[which]) != ndom)
  1147. continue;
  1148. for (i = rc.i, j = 0; j < rc.n; i += rc.di, j++) {
  1149. if (solve_domino_count(state, rc, i, which) == 1) {
  1150. if (POSSIBLE(i, which))
  1151. toset = i;
  1152. else {
  1153. /* paranoia, should have been checked by solve_domino_count. */
  1154. assert(state->common->dominoes[i] == i+rc.di);
  1155. assert(POSSIBLE(i+rc.di, which));
  1156. toset = i+rc.di;
  1157. }
  1158. if (solve_set(state, toset, which, "all empty dominoes need +/- [tricky]", &rc) < 0)
  1159. return -1;
  1160. didsth++;
  1161. }
  1162. }
  1163. }
  1164. return didsth;
  1165. }
  1166. /* danger, evil macro. can't use the do { ... } while(0) trick because
  1167. * the continue breaks. */
  1168. #define SOLVE_FOR_ROWCOLS(fn) \
  1169. ret = solve_rowcols(state, fn); \
  1170. if (ret < 0) { debug(("%s said impossible, cannot solve", #fn)); return -1; } \
  1171. if (ret > 0) continue
  1172. static int solve_state(game_state *state, int diff)
  1173. {
  1174. int ret;
  1175. debug(("solve_state, difficulty %s", magnets_diffnames[diff]));
  1176. solve_clearflags(state);
  1177. if (solve_startflags(state) < 0) return -1;
  1178. while (1) {
  1179. ret = solve_force(state);
  1180. if (ret > 0) continue;
  1181. if (ret < 0) return -1;
  1182. ret = solve_neither(state);
  1183. if (ret > 0) continue;
  1184. if (ret < 0) return -1;
  1185. SOLVE_FOR_ROWCOLS(solve_checkfull);
  1186. SOLVE_FOR_ROWCOLS(solve_oddlength);
  1187. if (diff < DIFF_TRICKY) break;
  1188. SOLVE_FOR_ROWCOLS(solve_advancedfull);
  1189. SOLVE_FOR_ROWCOLS(solve_nonneutral);
  1190. SOLVE_FOR_ROWCOLS(solve_countdominoes_neutral);
  1191. SOLVE_FOR_ROWCOLS(solve_countdominoes_nonneutral);
  1192. /* more ... */
  1193. break;
  1194. }
  1195. return check_completion(state);
  1196. }
  1197. static char *game_state_diff(const game_state *src, const game_state *dst,
  1198. bool issolve)
  1199. {
  1200. char *ret = NULL, buf[80], c;
  1201. int retlen = 0, x, y, i, k;
  1202. assert(src->w == dst->w && src->h == dst->h);
  1203. if (issolve) {
  1204. ret = sresize(ret, 3, char);
  1205. ret[0] = 'S'; ret[1] = ';'; ret[2] = '\0';
  1206. retlen += 2;
  1207. }
  1208. for (x = 0; x < dst->w; x++) {
  1209. for (y = 0; y < dst->h; y++) {
  1210. i = y*dst->w+x;
  1211. if (src->common->dominoes[i] == i) continue;
  1212. #define APPEND do { \
  1213. ret = sresize(ret, retlen + k + 1, char); \
  1214. strcpy(ret + retlen, buf); \
  1215. retlen += k; \
  1216. } while(0)
  1217. if ((src->grid[i] != dst->grid[i]) ||
  1218. ((src->flags[i] & GS_SET) != (dst->flags[i] & GS_SET))) {
  1219. if (dst->grid[i] == EMPTY && !(dst->flags[i] & GS_SET))
  1220. c = ' ';
  1221. else
  1222. c = GRID2CHAR(dst->grid[i]);
  1223. k = sprintf(buf, "%c%d,%d;", (int)c, x, y);
  1224. APPEND;
  1225. }
  1226. }
  1227. }
  1228. debug(("game_state_diff returns %s", ret));
  1229. return ret;
  1230. }
  1231. static void solve_from_aux(const game_state *state, const char *aux)
  1232. {
  1233. int i;
  1234. assert(strlen(aux) == state->wh);
  1235. for (i = 0; i < state->wh; i++) {
  1236. state->grid[i] = CHAR2GRID(aux[i]);
  1237. state->flags[i] |= GS_SET;
  1238. }
  1239. }
  1240. static char *solve_game(const game_state *state, const game_state *currstate,
  1241. const char *aux, const char **error)
  1242. {
  1243. game_state *solved = dup_game(currstate);
  1244. char *move = NULL;
  1245. int ret;
  1246. if (aux && strlen(aux) == state->wh) {
  1247. solve_from_aux(solved, aux);
  1248. goto solved;
  1249. }
  1250. if (solve_state(solved, DIFFCOUNT) > 0) goto solved;
  1251. free_game(solved);
  1252. solved = dup_game(state);
  1253. ret = solve_state(solved, DIFFCOUNT);
  1254. if (ret > 0) goto solved;
  1255. free_game(solved);
  1256. *error = (ret < 0) ? "Puzzle is impossible." : "Unable to solve puzzle.";
  1257. return NULL;
  1258. solved:
  1259. move = game_state_diff(currstate, solved, true);
  1260. free_game(solved);
  1261. return move;
  1262. }
  1263. static int solve_unnumbered(game_state *state)
  1264. {
  1265. int i, ret;
  1266. while (1) {
  1267. ret = solve_force(state);
  1268. if (ret > 0) continue;
  1269. if (ret < 0) return -1;
  1270. ret = solve_neither(state);
  1271. if (ret > 0) continue;
  1272. if (ret < 0) return -1;
  1273. break;
  1274. }
  1275. for (i = 0; i < state->wh; i++) {
  1276. if (!(state->flags[i] & GS_SET)) return 0;
  1277. }
  1278. return 1;
  1279. }
  1280. static int lay_dominoes(game_state *state, random_state *rs, int *scratch)
  1281. {
  1282. int n, i, ret = 0, nlaid = 0, n_initial_neutral;
  1283. for (i = 0; i < state->wh; i++) {
  1284. scratch[i] = i;
  1285. state->grid[i] = EMPTY;
  1286. state->flags[i] = (state->common->dominoes[i] == i) ? GS_SET : 0;
  1287. }
  1288. shuffle(scratch, state->wh, sizeof(int), rs);
  1289. n_initial_neutral = (state->wh > 100) ? 5 : (state->wh / 10);
  1290. for (n = 0; n < state->wh; n++) {
  1291. /* Find a space ... */
  1292. i = scratch[n];
  1293. if (state->flags[i] & GS_SET) continue; /* already laid here. */
  1294. /* ...and lay a domino if we can. */
  1295. debug(("Laying domino at i:%d, (%d,%d)\n", i, i%state->w, i/state->w));
  1296. /* The choice of which type of domino to lay here leads to subtle differences
  1297. * in the sorts of boards that get produced. Too much bias towards magnets
  1298. * leads to games that are too easy.
  1299. *
  1300. * Currently, it lays a small set of dominoes at random as neutral, and
  1301. * then lays the rest preferring to be magnets -- however, if the
  1302. * current layout is such that a magnet won't go there, then it lays
  1303. * another neutral.
  1304. *
  1305. * The number of initially neutral dominoes is limited as grids get bigger:
  1306. * too many neutral dominoes invariably ends up with insoluble puzzle at
  1307. * this size, and the positioning process means it'll always end up laying
  1308. * more than the initial 5 anyway.
  1309. */
  1310. /* We should always be able to lay a neutral anywhere. */
  1311. assert(!(state->flags[i] & GS_NOTNEUTRAL));
  1312. if (n < n_initial_neutral) {
  1313. debug((" ...laying neutral\n"));
  1314. ret = solve_set(state, i, NEUTRAL, "layout initial neutral", NULL);
  1315. } else {
  1316. debug((" ... preferring magnet\n"));
  1317. if (!(state->flags[i] & GS_NOTPOSITIVE))
  1318. ret = solve_set(state, i, POSITIVE, "layout", NULL);
  1319. else if (!(state->flags[i] & GS_NOTNEGATIVE))
  1320. ret = solve_set(state, i, NEGATIVE, "layout", NULL);
  1321. else
  1322. ret = solve_set(state, i, NEUTRAL, "layout", NULL);
  1323. }
  1324. if (!ret) {
  1325. debug(("Unable to lay anything at (%d,%d), giving up.",
  1326. i%state->w, i/state->w));
  1327. ret = -1;
  1328. break;
  1329. }
  1330. nlaid++;
  1331. ret = solve_unnumbered(state);
  1332. if (ret == -1)
  1333. debug(("solve_unnumbered decided impossible.\n"));
  1334. if (ret != 0)
  1335. break;
  1336. }
  1337. debug(("Laid %d dominoes, total %d dominoes.\n", nlaid, state->wh/2));
  1338. (void)nlaid;
  1339. game_debug(state, "Final layout");
  1340. return ret;
  1341. }
  1342. static void gen_game(game_state *new, random_state *rs)
  1343. {
  1344. int ret, x, y, val;
  1345. int *scratch = snewn(new->wh, int);
  1346. #ifdef STANDALONE_SOLVER
  1347. if (verbose) printf("Generating new game...\n");
  1348. #endif
  1349. clear_state(new);
  1350. sfree(new->common->dominoes); /* bit grotty. */
  1351. new->common->dominoes = domino_layout(new->w, new->h, rs);
  1352. do {
  1353. ret = lay_dominoes(new, rs, scratch);
  1354. } while(ret == -1);
  1355. /* for each cell, update colcount/rowcount as appropriate. */
  1356. memset(new->common->colcount, 0, new->w*3*sizeof(int));
  1357. memset(new->common->rowcount, 0, new->h*3*sizeof(int));
  1358. for (x = 0; x < new->w; x++) {
  1359. for (y = 0; y < new->h; y++) {
  1360. val = new->grid[y*new->w+x];
  1361. new->common->colcount[x*3+val]++;
  1362. new->common->rowcount[y*3+val]++;
  1363. }
  1364. }
  1365. new->numbered = true;
  1366. sfree(scratch);
  1367. }
  1368. static void generate_aux(game_state *new, char *aux)
  1369. {
  1370. int i;
  1371. for (i = 0; i < new->wh; i++)
  1372. aux[i] = GRID2CHAR(new->grid[i]);
  1373. aux[new->wh] = '\0';
  1374. }
  1375. static int check_difficulty(const game_params *params, game_state *new,
  1376. random_state *rs)
  1377. {
  1378. int *scratch, *grid_correct, slen, i;
  1379. memset(new->grid, EMPTY, new->wh*sizeof(int));
  1380. if (params->diff > DIFF_EASY) {
  1381. /* If this is too easy, return. */
  1382. if (solve_state(new, params->diff-1) > 0) {
  1383. debug(("Puzzle is too easy."));
  1384. return -1;
  1385. }
  1386. }
  1387. if (solve_state(new, params->diff) <= 0) {
  1388. debug(("Puzzle is not soluble at requested difficulty."));
  1389. return -1;
  1390. }
  1391. if (!params->stripclues) return 0;
  1392. /* Copy the correct grid away. */
  1393. grid_correct = snewn(new->wh, int);
  1394. memcpy(grid_correct, new->grid, new->wh*sizeof(int));
  1395. /* Create shuffled array of side-clue locations. */
  1396. slen = new->w*2 + new->h*2;
  1397. scratch = snewn(slen, int);
  1398. for (i = 0; i < slen; i++) scratch[i] = i;
  1399. shuffle(scratch, slen, sizeof(int), rs);
  1400. /* For each clue, check whether removing it makes the puzzle unsoluble;
  1401. * put it back if so. */
  1402. for (i = 0; i < slen; i++) {
  1403. int num = scratch[i], which, roworcol, target, targetn, ret;
  1404. rowcol rc;
  1405. /* work out which clue we meant. */
  1406. if (num < new->w+new->h) { which = POSITIVE; }
  1407. else { which = NEGATIVE; num -= new->w+new->h; }
  1408. if (num < new->w) { roworcol = COLUMN; }
  1409. else { roworcol = ROW; num -= new->w; }
  1410. /* num is now the row/column index in question. */
  1411. rc = mkrowcol(new, num, roworcol);
  1412. /* Remove clue, storing original... */
  1413. target = rc.targets[which];
  1414. targetn = rc.targets[NEUTRAL];
  1415. rc.targets[which] = -1;
  1416. rc.targets[NEUTRAL] = -1;
  1417. /* ...and see if we can still solve it. */
  1418. game_debug(new, "removed clue, new board:");
  1419. memset(new->grid, EMPTY, new->wh * sizeof(int));
  1420. ret = solve_state(new, params->diff);
  1421. assert(ret != -1);
  1422. if (ret == 0 ||
  1423. memcmp(new->grid, grid_correct, new->wh*sizeof(int)) != 0) {
  1424. /* We made it ambiguous: put clue back. */
  1425. debug(("...now impossible/different, put clue back."));
  1426. rc.targets[which] = target;
  1427. rc.targets[NEUTRAL] = targetn;
  1428. }
  1429. }
  1430. sfree(scratch);
  1431. sfree(grid_correct);
  1432. return 0;
  1433. }
  1434. static char *new_game_desc(const game_params *params, random_state *rs,
  1435. char **aux_r, bool interactive)
  1436. {
  1437. game_state *new = new_state(params->w, params->h);
  1438. char *desc, *aux = snewn(new->wh+1, char);
  1439. do {
  1440. gen_game(new, rs);
  1441. generate_aux(new, aux);
  1442. } while (check_difficulty(params, new, rs) < 0);
  1443. /* now we're complete, generate the description string
  1444. * and an aux_info for the completed game. */
  1445. desc = generate_desc(new);
  1446. free_game(new);
  1447. *aux_r = aux;
  1448. return desc;
  1449. }
  1450. struct game_ui {
  1451. int cur_x, cur_y;
  1452. bool cur_visible;
  1453. };
  1454. static game_ui *new_ui(const game_state *state)
  1455. {
  1456. game_ui *ui = snew(game_ui);
  1457. ui->cur_x = ui->cur_y = 0;
  1458. ui->cur_visible = getenv_bool("PUZZLES_SHOW_CURSOR", false);
  1459. return ui;
  1460. }
  1461. static void free_ui(game_ui *ui)
  1462. {
  1463. sfree(ui);
  1464. }
  1465. static void game_changed_state(game_ui *ui, const game_state *oldstate,
  1466. const game_state *newstate)
  1467. {
  1468. if (!oldstate->completed && newstate->completed)
  1469. ui->cur_visible = false;
  1470. }
  1471. static const char *current_key_label(const game_ui *ui,
  1472. const game_state *state, int button)
  1473. {
  1474. int idx;
  1475. if (IS_CURSOR_SELECT(button)) {
  1476. if (!ui->cur_visible) return "";
  1477. idx = ui->cur_y * state->w + ui->cur_x;
  1478. if (button == CURSOR_SELECT) {
  1479. if (state->grid[idx] == NEUTRAL && state->flags[idx] & GS_SET)
  1480. return "";
  1481. switch (state->grid[idx]) {
  1482. case EMPTY: return "+";
  1483. case POSITIVE: return "-";
  1484. case NEGATIVE: return "Clear";
  1485. }
  1486. }
  1487. if (button == CURSOR_SELECT2) {
  1488. if (state->grid[idx] != NEUTRAL) return "";
  1489. if (state->flags[idx] & GS_SET) /* neutral */
  1490. return "?";
  1491. if (state->flags[idx] & GS_NOTNEUTRAL) /* !neutral */
  1492. return "Clear";
  1493. else
  1494. return "X";
  1495. }
  1496. }
  1497. return "";
  1498. }
  1499. struct game_drawstate {
  1500. int tilesize;
  1501. bool started, solved;
  1502. int w, h;
  1503. unsigned long *what; /* size w*h */
  1504. unsigned long *colwhat, *rowwhat; /* size 3*w, 3*h */
  1505. };
  1506. #define DS_WHICH_MASK 0xf
  1507. #define DS_ERROR 0x10
  1508. #define DS_CURSOR 0x20
  1509. #define DS_SET 0x40
  1510. #define DS_NOTPOS 0x80
  1511. #define DS_NOTNEG 0x100
  1512. #define DS_NOTNEU 0x200
  1513. #define DS_FLASH 0x400
  1514. #define PREFERRED_TILE_SIZE 32
  1515. #define TILE_SIZE (ds->tilesize)
  1516. #define BORDER (TILE_SIZE / 8)
  1517. #define COORD(x) ( (x+1) * TILE_SIZE + BORDER )
  1518. #define FROMCOORD(x) ( (x - BORDER) / TILE_SIZE - 1 )
  1519. static bool is_clue(const game_state *state, int x, int y)
  1520. {
  1521. int h = state->h, w = state->w;
  1522. if (((x == -1 || x == w) && y >= 0 && y < h) ||
  1523. ((y == -1 || y == h) && x >= 0 && x < w))
  1524. return true;
  1525. return false;
  1526. }
  1527. static int clue_index(const game_state *state, int x, int y)
  1528. {
  1529. int h = state->h, w = state->w;
  1530. if (y == -1)
  1531. return x;
  1532. else if (x == w)
  1533. return w + y;
  1534. else if (y == h)
  1535. return 2 * w + h - x - 1;
  1536. else if (x == -1)
  1537. return 2 * (w + h) - y - 1;
  1538. return -1;
  1539. }
  1540. static char *interpret_move(const game_state *state, game_ui *ui,
  1541. const game_drawstate *ds,
  1542. int x, int y, int button)
  1543. {
  1544. int gx = FROMCOORD(x), gy = FROMCOORD(y), idx, curr;
  1545. char *nullret = NULL, buf[80], movech;
  1546. enum { CYCLE_MAGNET, CYCLE_NEUTRAL } action;
  1547. if (IS_CURSOR_MOVE(button)) {
  1548. move_cursor(button, &ui->cur_x, &ui->cur_y, state->w, state->h, false);
  1549. ui->cur_visible = true;
  1550. return MOVE_UI_UPDATE;
  1551. } else if (IS_CURSOR_SELECT(button)) {
  1552. if (!ui->cur_visible) {
  1553. ui->cur_visible = true;
  1554. return MOVE_UI_UPDATE;
  1555. }
  1556. action = (button == CURSOR_SELECT) ? CYCLE_MAGNET : CYCLE_NEUTRAL;
  1557. gx = ui->cur_x;
  1558. gy = ui->cur_y;
  1559. } else if (INGRID(state, gx, gy) &&
  1560. (button == LEFT_BUTTON || button == RIGHT_BUTTON)) {
  1561. if (ui->cur_visible) {
  1562. ui->cur_visible = false;
  1563. nullret = MOVE_UI_UPDATE;
  1564. }
  1565. action = (button == LEFT_BUTTON) ? CYCLE_MAGNET : CYCLE_NEUTRAL;
  1566. } else if (button == LEFT_BUTTON && is_clue(state, gx, gy)) {
  1567. sprintf(buf, "D%d,%d", gx, gy);
  1568. return dupstr(buf);
  1569. } else
  1570. return NULL;
  1571. idx = gy * state->w + gx;
  1572. if (state->common->dominoes[idx] == idx) return nullret;
  1573. curr = state->grid[idx];
  1574. if (action == CYCLE_MAGNET) {
  1575. /* ... empty --> positive --> negative --> empty ... */
  1576. if (state->grid[idx] == NEUTRAL && state->flags[idx] & GS_SET)
  1577. return nullret; /* can't cycle a magnet from a neutral. */
  1578. movech = (curr == EMPTY) ? '+' : (curr == POSITIVE) ? '-' : ' ';
  1579. } else if (action == CYCLE_NEUTRAL) {
  1580. /* ... empty -> neutral -> !neutral --> empty ... */
  1581. if (state->grid[idx] != NEUTRAL)
  1582. return nullret; /* can't cycle through neutral from a magnet. */
  1583. /* All of these are grid == EMPTY == NEUTRAL; it twiddles
  1584. * combinations of flags. */
  1585. if (state->flags[idx] & GS_SET) /* neutral */
  1586. movech = '?';
  1587. else if (state->flags[idx] & GS_NOTNEUTRAL) /* !neutral */
  1588. movech = ' ';
  1589. else
  1590. movech = '.';
  1591. } else {
  1592. assert(!"unknown action");
  1593. movech = 0; /* placate optimiser */
  1594. }
  1595. sprintf(buf, "%c%d,%d", movech, gx, gy);
  1596. return dupstr(buf);
  1597. }
  1598. static game_state *execute_move(const game_state *state, const char *move)
  1599. {
  1600. game_state *ret = dup_game(state);
  1601. int x, y, n, idx, idx2;
  1602. char c;
  1603. if (!*move) goto badmove;
  1604. while (*move) {
  1605. c = *move++;
  1606. if (c == 'S') {
  1607. ret->solved = true;
  1608. n = 0;
  1609. } else if (c == '+' || c == '-' ||
  1610. c == '.' || c == ' ' || c == '?') {
  1611. if ((sscanf(move, "%d,%d%n", &x, &y, &n) != 2) ||
  1612. !INGRID(state, x, y)) goto badmove;
  1613. idx = y*state->w + x;
  1614. idx2 = state->common->dominoes[idx];
  1615. if (idx == idx2) goto badmove;
  1616. ret->flags[idx] &= ~GS_NOTMASK;
  1617. ret->flags[idx2] &= ~GS_NOTMASK;
  1618. if (c == ' ' || c == '?') {
  1619. ret->grid[idx] = EMPTY;
  1620. ret->grid[idx2] = EMPTY;
  1621. ret->flags[idx] &= ~GS_SET;
  1622. ret->flags[idx2] &= ~GS_SET;
  1623. if (c == '?') {
  1624. ret->flags[idx] |= GS_NOTNEUTRAL;
  1625. ret->flags[idx2] |= GS_NOTNEUTRAL;
  1626. }
  1627. } else {
  1628. ret->grid[idx] = CHAR2GRID(c);
  1629. ret->grid[idx2] = OPPOSITE(CHAR2GRID(c));
  1630. ret->flags[idx] |= GS_SET;
  1631. ret->flags[idx2] |= GS_SET;
  1632. }
  1633. } else if (c == 'D' && sscanf(move, "%d,%d%n", &x, &y, &n) == 2 &&
  1634. is_clue(ret, x, y)) {
  1635. ret->counts_done[clue_index(ret, x, y)] ^= 1;
  1636. } else
  1637. goto badmove;
  1638. move += n;
  1639. if (*move == ';') move++;
  1640. else if (*move) goto badmove;
  1641. }
  1642. if (check_completion(ret) == 1)
  1643. ret->completed = true;
  1644. return ret;
  1645. badmove:
  1646. free_game(ret);
  1647. return NULL;
  1648. }
  1649. /* ----------------------------------------------------------------------
  1650. * Drawing routines.
  1651. */
  1652. static void game_compute_size(const game_params *params, int tilesize,
  1653. const game_ui *ui, int *x, int *y)
  1654. {
  1655. /* Ick: fake up `ds->tilesize' for macro expansion purposes */
  1656. struct { int tilesize; } ads, *ds = &ads;
  1657. ads.tilesize = tilesize;
  1658. *x = TILE_SIZE * (params->w+2) + 2 * BORDER;
  1659. *y = TILE_SIZE * (params->h+2) + 2 * BORDER;
  1660. }
  1661. static void game_set_size(drawing *dr, game_drawstate *ds,
  1662. const game_params *params, int tilesize)
  1663. {
  1664. ds->tilesize = tilesize;
  1665. }
  1666. static float *game_colours(frontend *fe, int *ncolours)
  1667. {
  1668. float *ret = snewn(3 * NCOLOURS, float);
  1669. int i;
  1670. game_mkhighlight(fe, ret, COL_BACKGROUND, COL_HIGHLIGHT, COL_LOWLIGHT);
  1671. for (i = 0; i < 3; i++) {
  1672. ret[COL_TEXT * 3 + i] = 0.0F;
  1673. ret[COL_NEGATIVE * 3 + i] = 0.0F;
  1674. ret[COL_CURSOR * 3 + i] = 0.9F;
  1675. ret[COL_DONE * 3 + i] = ret[COL_BACKGROUND * 3 + i] / 1.5F;
  1676. }
  1677. ret[COL_POSITIVE * 3 + 0] = 0.8F;
  1678. ret[COL_POSITIVE * 3 + 1] = 0.0F;
  1679. ret[COL_POSITIVE * 3 + 2] = 0.0F;
  1680. ret[COL_NEUTRAL * 3 + 0] = 0.10F;
  1681. ret[COL_NEUTRAL * 3 + 1] = 0.60F;
  1682. ret[COL_NEUTRAL * 3 + 2] = 0.10F;
  1683. ret[COL_ERROR * 3 + 0] = 1.0F;
  1684. ret[COL_ERROR * 3 + 1] = 0.0F;
  1685. ret[COL_ERROR * 3 + 2] = 0.0F;
  1686. ret[COL_NOT * 3 + 0] = 0.2F;
  1687. ret[COL_NOT * 3 + 1] = 0.2F;
  1688. ret[COL_NOT * 3 + 2] = 1.0F;
  1689. *ncolours = NCOLOURS;
  1690. return ret;
  1691. }
  1692. static game_drawstate *game_new_drawstate(drawing *dr, const game_state *state)
  1693. {
  1694. struct game_drawstate *ds = snew(struct game_drawstate);
  1695. ds->tilesize = 0;
  1696. ds->started = false;
  1697. ds->solved = false;
  1698. ds->w = state->w;
  1699. ds->h = state->h;
  1700. ds->what = snewn(state->wh, unsigned long);
  1701. memset(ds->what, 0, state->wh*sizeof(unsigned long));
  1702. ds->colwhat = snewn(state->w*3, unsigned long);
  1703. memset(ds->colwhat, 0, state->w*3*sizeof(unsigned long));
  1704. ds->rowwhat = snewn(state->h*3, unsigned long);
  1705. memset(ds->rowwhat, 0, state->h*3*sizeof(unsigned long));
  1706. return ds;
  1707. }
  1708. static void game_free_drawstate(drawing *dr, game_drawstate *ds)
  1709. {
  1710. sfree(ds->colwhat);
  1711. sfree(ds->rowwhat);
  1712. sfree(ds->what);
  1713. sfree(ds);
  1714. }
  1715. static void draw_num(drawing *dr, game_drawstate *ds, int rowcol, int which,
  1716. int idx, int colbg, int col, int num)
  1717. {
  1718. char buf[32];
  1719. int cx, cy, tsz;
  1720. if (num < 0) return;
  1721. sprintf(buf, "%d", num);
  1722. tsz = (strlen(buf) == 1) ? (7*TILE_SIZE/10) : (9*TILE_SIZE/10)/strlen(buf);
  1723. if (rowcol == ROW) {
  1724. cx = BORDER;
  1725. if (which == NEGATIVE) cx += TILE_SIZE * (ds->w+1);
  1726. cy = BORDER + TILE_SIZE * (idx+1);
  1727. } else {
  1728. cx = BORDER + TILE_SIZE * (idx+1);
  1729. cy = BORDER;
  1730. if (which == NEGATIVE) cy += TILE_SIZE * (ds->h+1);
  1731. }
  1732. draw_rect(dr, cx, cy, TILE_SIZE, TILE_SIZE, colbg);
  1733. draw_text(dr, cx + TILE_SIZE/2, cy + TILE_SIZE/2, FONT_VARIABLE, tsz,
  1734. ALIGN_VCENTRE | ALIGN_HCENTRE, col, buf);
  1735. draw_update(dr, cx, cy, TILE_SIZE, TILE_SIZE);
  1736. }
  1737. static void draw_sym(drawing *dr, game_drawstate *ds, int x, int y, int which, int col)
  1738. {
  1739. int cx = COORD(x), cy = COORD(y);
  1740. int ccx = cx + TILE_SIZE/2, ccy = cy + TILE_SIZE/2;
  1741. int roff = TILE_SIZE/4, rsz = 2*roff+1;
  1742. int soff = TILE_SIZE/16, ssz = 2*soff+1;
  1743. if (which == POSITIVE || which == NEGATIVE) {
  1744. draw_rect(dr, ccx - roff, ccy - soff, rsz, ssz, col);
  1745. if (which == POSITIVE)
  1746. draw_rect(dr, ccx - soff, ccy - roff, ssz, rsz, col);
  1747. } else if (col == COL_NOT) {
  1748. /* not-a-neutral is a blue question mark. */
  1749. char qu[2] = { '?', 0 };
  1750. draw_text(dr, ccx, ccy, FONT_VARIABLE, 7*TILE_SIZE/10,
  1751. ALIGN_VCENTRE | ALIGN_HCENTRE, col, qu);
  1752. } else {
  1753. draw_line(dr, ccx - roff, ccy - roff, ccx + roff, ccy + roff, col);
  1754. draw_line(dr, ccx + roff, ccy - roff, ccx - roff, ccy + roff, col);
  1755. }
  1756. }
  1757. enum {
  1758. TYPE_L,
  1759. TYPE_R,
  1760. TYPE_T,
  1761. TYPE_B,
  1762. TYPE_BLANK
  1763. };
  1764. /* NOT responsible for redrawing background or updating. */
  1765. static void draw_tile_col(drawing *dr, game_drawstate *ds, int *dominoes,
  1766. int x, int y, int which, int bg, int fg, int perc)
  1767. {
  1768. int cx = COORD(x), cy = COORD(y), i, other, type = TYPE_BLANK;
  1769. int gutter, radius, coffset;
  1770. /* gutter is TSZ/16 for 100%, 8*TSZ/16 (TSZ/2) for 0% */
  1771. gutter = (TILE_SIZE / 16) + ((100 - perc) * (7*TILE_SIZE / 16))/100;
  1772. radius = (perc * (TILE_SIZE / 8)) / 100;
  1773. coffset = gutter + radius;
  1774. i = y*ds->w + x;
  1775. other = dominoes[i];
  1776. if (other == i) return;
  1777. else if (other == i+1) type = TYPE_L;
  1778. else if (other == i-1) type = TYPE_R;
  1779. else if (other == i+ds->w) type = TYPE_T;
  1780. else if (other == i-ds->w) type = TYPE_B;
  1781. else assert(!"mad domino orientation");
  1782. /* domino drawing shamelessly stolen from dominosa.c. */
  1783. if (type == TYPE_L || type == TYPE_T)
  1784. draw_circle(dr, cx+coffset, cy+coffset,
  1785. radius, bg, bg);
  1786. if (type == TYPE_R || type == TYPE_T)
  1787. draw_circle(dr, cx+TILE_SIZE-1-coffset, cy+coffset,
  1788. radius, bg, bg);
  1789. if (type == TYPE_L || type == TYPE_B)
  1790. draw_circle(dr, cx+coffset, cy+TILE_SIZE-1-coffset,
  1791. radius, bg, bg);
  1792. if (type == TYPE_R || type == TYPE_B)
  1793. draw_circle(dr, cx+TILE_SIZE-1-coffset,
  1794. cy+TILE_SIZE-1-coffset,
  1795. radius, bg, bg);
  1796. for (i = 0; i < 2; i++) {
  1797. int x1, y1, x2, y2;
  1798. x1 = cx + (i ? gutter : coffset);
  1799. y1 = cy + (i ? coffset : gutter);
  1800. x2 = cx + TILE_SIZE-1 - (i ? gutter : coffset);
  1801. y2 = cy + TILE_SIZE-1 - (i ? coffset : gutter);
  1802. if (type == TYPE_L)
  1803. x2 = cx + TILE_SIZE;
  1804. else if (type == TYPE_R)
  1805. x1 = cx;
  1806. else if (type == TYPE_T)
  1807. y2 = cy + TILE_SIZE ;
  1808. else if (type == TYPE_B)
  1809. y1 = cy;
  1810. draw_rect(dr, x1, y1, x2-x1+1, y2-y1+1, bg);
  1811. }
  1812. if (fg != -1) draw_sym(dr, ds, x, y, which, fg);
  1813. }
  1814. static void draw_tile(drawing *dr, game_drawstate *ds, int *dominoes,
  1815. int x, int y, unsigned long flags)
  1816. {
  1817. int cx = COORD(x), cy = COORD(y), bg, fg, perc = 100;
  1818. int which = flags & DS_WHICH_MASK;
  1819. flags &= ~DS_WHICH_MASK;
  1820. draw_rect(dr, cx, cy, TILE_SIZE, TILE_SIZE, COL_BACKGROUND);
  1821. if (flags & DS_CURSOR)
  1822. bg = COL_CURSOR; /* off-white white for cursor */
  1823. else if (which == POSITIVE)
  1824. bg = COL_POSITIVE;
  1825. else if (which == NEGATIVE)
  1826. bg = COL_NEGATIVE;
  1827. else if (flags & DS_SET)
  1828. bg = COL_NEUTRAL; /* green inner for neutral cells */
  1829. else
  1830. bg = COL_LOWLIGHT; /* light grey for empty cells. */
  1831. if (which == EMPTY && !(flags & DS_SET)) {
  1832. int notwhich = -1;
  1833. fg = -1; /* don't draw cross unless actually set as neutral. */
  1834. if (flags & DS_NOTPOS) notwhich = POSITIVE;
  1835. if (flags & DS_NOTNEG) notwhich = NEGATIVE;
  1836. if (flags & DS_NOTNEU) notwhich = NEUTRAL;
  1837. if (notwhich != -1) {
  1838. which = notwhich;
  1839. fg = COL_NOT;
  1840. }
  1841. } else
  1842. fg = (flags & DS_ERROR) ? COL_ERROR :
  1843. (flags & DS_CURSOR) ? COL_TEXT : COL_BACKGROUND;
  1844. draw_rect(dr, cx, cy, TILE_SIZE, TILE_SIZE, COL_BACKGROUND);
  1845. if (flags & DS_FLASH) {
  1846. int bordercol = COL_HIGHLIGHT;
  1847. draw_tile_col(dr, ds, dominoes, x, y, which, bordercol, -1, perc);
  1848. perc = 3*perc/4;
  1849. }
  1850. draw_tile_col(dr, ds, dominoes, x, y, which, bg, fg, perc);
  1851. draw_update(dr, cx, cy, TILE_SIZE, TILE_SIZE);
  1852. }
  1853. static int get_count_color(const game_state *state, int rowcol, int which,
  1854. int index, int target)
  1855. {
  1856. int idx;
  1857. int count = count_rowcol(state, index, rowcol, which);
  1858. if ((count > target) ||
  1859. (count < target && !count_rowcol(state, index, rowcol, -1))) {
  1860. return COL_ERROR;
  1861. } else if (rowcol == COLUMN) {
  1862. idx = clue_index(state, index, which == POSITIVE ? -1 : state->h);
  1863. } else {
  1864. idx = clue_index(state, which == POSITIVE ? -1 : state->w, index);
  1865. }
  1866. if (state->counts_done[idx]) {
  1867. return COL_DONE;
  1868. }
  1869. return COL_TEXT;
  1870. }
  1871. static void game_redraw(drawing *dr, game_drawstate *ds,
  1872. const game_state *oldstate, const game_state *state,
  1873. int dir, const game_ui *ui,
  1874. float animtime, float flashtime)
  1875. {
  1876. int x, y, w = state->w, h = state->h, which, i, j;
  1877. bool flash;
  1878. flash = (int)(flashtime * 5 / FLASH_TIME) % 2;
  1879. if (!ds->started) {
  1880. /* draw corner +-. */
  1881. draw_sym(dr, ds, -1, -1, POSITIVE, COL_TEXT);
  1882. draw_sym(dr, ds, state->w, state->h, NEGATIVE, COL_TEXT);
  1883. draw_update(dr, 0, 0,
  1884. TILE_SIZE * (ds->w+2) + 2 * BORDER,
  1885. TILE_SIZE * (ds->h+2) + 2 * BORDER);
  1886. }
  1887. /* Draw grid */
  1888. for (y = 0; y < h; y++) {
  1889. for (x = 0; x < w; x++) {
  1890. int idx = y*w+x;
  1891. unsigned long c = state->grid[idx];
  1892. if (state->flags[idx] & GS_ERROR)
  1893. c |= DS_ERROR;
  1894. if (state->flags[idx] & GS_SET)
  1895. c |= DS_SET;
  1896. if (x == ui->cur_x && y == ui->cur_y && ui->cur_visible)
  1897. c |= DS_CURSOR;
  1898. if (flash)
  1899. c |= DS_FLASH;
  1900. if (state->flags[idx] & GS_NOTPOSITIVE)
  1901. c |= DS_NOTPOS;
  1902. if (state->flags[idx] & GS_NOTNEGATIVE)
  1903. c |= DS_NOTNEG;
  1904. if (state->flags[idx] & GS_NOTNEUTRAL)
  1905. c |= DS_NOTNEU;
  1906. if (ds->what[idx] != c || !ds->started) {
  1907. draw_tile(dr, ds, state->common->dominoes, x, y, c);
  1908. ds->what[idx] = c;
  1909. }
  1910. }
  1911. }
  1912. /* Draw counts around side */
  1913. for (which = POSITIVE, j = 0; j < 2; which = OPPOSITE(which), j++) {
  1914. for (i = 0; i < w; i++) {
  1915. int index = i * 3 + which;
  1916. int target = state->common->colcount[index];
  1917. int color = get_count_color(state, COLUMN, which, i, target);
  1918. if (color != ds->colwhat[index] || !ds->started) {
  1919. draw_num(dr, ds, COLUMN, which, i, COL_BACKGROUND, color, target);
  1920. ds->colwhat[index] = color;
  1921. }
  1922. }
  1923. for (i = 0; i < h; i++) {
  1924. int index = i * 3 + which;
  1925. int target = state->common->rowcount[index];
  1926. int color = get_count_color(state, ROW, which, i, target);
  1927. if (color != ds->rowwhat[index] || !ds->started) {
  1928. draw_num(dr, ds, ROW, which, i, COL_BACKGROUND, color, target);
  1929. ds->rowwhat[index] = color;
  1930. }
  1931. }
  1932. }
  1933. ds->started = true;
  1934. }
  1935. static float game_anim_length(const game_state *oldstate,
  1936. const game_state *newstate, int dir, game_ui *ui)
  1937. {
  1938. return 0.0F;
  1939. }
  1940. static float game_flash_length(const game_state *oldstate,
  1941. const game_state *newstate, int dir, game_ui *ui)
  1942. {
  1943. if (!oldstate->completed && newstate->completed &&
  1944. !oldstate->solved && !newstate->solved)
  1945. return FLASH_TIME;
  1946. return 0.0F;
  1947. }
  1948. static void game_get_cursor_location(const game_ui *ui,
  1949. const game_drawstate *ds,
  1950. const game_state *state,
  1951. const game_params *params,
  1952. int *x, int *y, int *w, int *h)
  1953. {
  1954. if(ui->cur_visible) {
  1955. *x = COORD(ui->cur_x);
  1956. *y = COORD(ui->cur_y);
  1957. *w = *h = TILE_SIZE;
  1958. }
  1959. }
  1960. static int game_status(const game_state *state)
  1961. {
  1962. return state->completed ? +1 : 0;
  1963. }
  1964. static void game_print_size(const game_params *params, const game_ui *ui,
  1965. float *x, float *y)
  1966. {
  1967. int pw, ph;
  1968. /*
  1969. * I'll use 6mm squares by default.
  1970. */
  1971. game_compute_size(params, 600, ui, &pw, &ph);
  1972. *x = pw / 100.0F;
  1973. *y = ph / 100.0F;
  1974. }
  1975. static void game_print(drawing *dr, const game_state *state, const game_ui *ui,
  1976. int tilesize)
  1977. {
  1978. int w = state->w, h = state->h;
  1979. int ink = print_mono_colour(dr, 0);
  1980. int paper = print_mono_colour(dr, 1);
  1981. int x, y, which, i, j;
  1982. /* Ick: fake up `ds->tilesize' for macro expansion purposes */
  1983. game_drawstate ads, *ds = &ads;
  1984. game_set_size(dr, ds, NULL, tilesize);
  1985. ds->w = w; ds->h = h;
  1986. /* Border. */
  1987. print_line_width(dr, TILE_SIZE/12);
  1988. /* Numbers and +/- for corners. */
  1989. draw_sym(dr, ds, -1, -1, POSITIVE, ink);
  1990. draw_sym(dr, ds, state->w, state->h, NEGATIVE, ink);
  1991. for (which = POSITIVE, j = 0; j < 2; which = OPPOSITE(which), j++) {
  1992. for (i = 0; i < w; i++) {
  1993. draw_num(dr, ds, COLUMN, which, i, paper, ink,
  1994. state->common->colcount[i*3+which]);
  1995. }
  1996. for (i = 0; i < h; i++) {
  1997. draw_num(dr, ds, ROW, which, i, paper, ink,
  1998. state->common->rowcount[i*3+which]);
  1999. }
  2000. }
  2001. /* Dominoes. */
  2002. for (x = 0; x < w; x++) {
  2003. for (y = 0; y < h; y++) {
  2004. i = y*state->w + x;
  2005. if (state->common->dominoes[i] == i+1 ||
  2006. state->common->dominoes[i] == i+w) {
  2007. int dx = state->common->dominoes[i] == i+1 ? 2 : 1;
  2008. int dy = 3 - dx;
  2009. int xx, yy;
  2010. int cx = COORD(x), cy = COORD(y);
  2011. print_line_width(dr, 0);
  2012. /* Ink the domino */
  2013. for (yy = 0; yy < 2; yy++)
  2014. for (xx = 0; xx < 2; xx++)
  2015. draw_circle(dr,
  2016. cx+xx*dx*TILE_SIZE+(1-2*xx)*3*TILE_SIZE/16,
  2017. cy+yy*dy*TILE_SIZE+(1-2*yy)*3*TILE_SIZE/16,
  2018. TILE_SIZE/8, ink, ink);
  2019. draw_rect(dr, cx + TILE_SIZE/16, cy + 3*TILE_SIZE/16,
  2020. dx*TILE_SIZE - 2*(TILE_SIZE/16),
  2021. dy*TILE_SIZE - 6*(TILE_SIZE/16), ink);
  2022. draw_rect(dr, cx + 3*TILE_SIZE/16, cy + TILE_SIZE/16,
  2023. dx*TILE_SIZE - 6*(TILE_SIZE/16),
  2024. dy*TILE_SIZE - 2*(TILE_SIZE/16), ink);
  2025. /* Un-ink the domino interior */
  2026. for (yy = 0; yy < 2; yy++)
  2027. for (xx = 0; xx < 2; xx++)
  2028. draw_circle(dr,
  2029. cx+xx*dx*TILE_SIZE+(1-2*xx)*3*TILE_SIZE/16,
  2030. cy+yy*dy*TILE_SIZE+(1-2*yy)*3*TILE_SIZE/16,
  2031. 3*TILE_SIZE/32, paper, paper);
  2032. draw_rect(dr, cx + 3*TILE_SIZE/32, cy + 3*TILE_SIZE/16,
  2033. dx*TILE_SIZE - 2*(3*TILE_SIZE/32),
  2034. dy*TILE_SIZE - 6*(TILE_SIZE/16), paper);
  2035. draw_rect(dr, cx + 3*TILE_SIZE/16, cy + 3*TILE_SIZE/32,
  2036. dx*TILE_SIZE - 6*(TILE_SIZE/16),
  2037. dy*TILE_SIZE - 2*(3*TILE_SIZE/32), paper);
  2038. }
  2039. }
  2040. }
  2041. /* Grid symbols (solution). */
  2042. for (x = 0; x < w; x++) {
  2043. for (y = 0; y < h; y++) {
  2044. i = y*state->w + x;
  2045. if ((state->grid[i] != NEUTRAL) || (state->flags[i] & GS_SET))
  2046. draw_sym(dr, ds, x, y, state->grid[i], ink);
  2047. }
  2048. }
  2049. }
  2050. #ifdef COMBINED
  2051. #define thegame magnets
  2052. #endif
  2053. const struct game thegame = {
  2054. "Magnets", "games.magnets", "magnets",
  2055. default_params,
  2056. game_fetch_preset, NULL,
  2057. decode_params,
  2058. encode_params,
  2059. free_params,
  2060. dup_params,
  2061. true, game_configure, custom_params,
  2062. validate_params,
  2063. new_game_desc,
  2064. validate_desc,
  2065. new_game,
  2066. dup_game,
  2067. free_game,
  2068. true, solve_game,
  2069. true, game_can_format_as_text_now, game_text_format,
  2070. NULL, NULL, /* get_prefs, set_prefs */
  2071. new_ui,
  2072. free_ui,
  2073. NULL, /* encode_ui */
  2074. NULL, /* decode_ui */
  2075. NULL, /* game_request_keys */
  2076. game_changed_state,
  2077. current_key_label,
  2078. interpret_move,
  2079. execute_move,
  2080. PREFERRED_TILE_SIZE, game_compute_size, game_set_size,
  2081. game_colours,
  2082. game_new_drawstate,
  2083. game_free_drawstate,
  2084. game_redraw,
  2085. game_anim_length,
  2086. game_flash_length,
  2087. game_get_cursor_location,
  2088. game_status,
  2089. true, false, game_print_size, game_print,
  2090. false, /* wants_statusbar */
  2091. false, NULL, /* timing_state */
  2092. REQUIRE_RBUTTON, /* flags */
  2093. };
  2094. #ifdef STANDALONE_SOLVER
  2095. #include <time.h>
  2096. #include <stdarg.h>
  2097. static const char *quis = NULL;
  2098. static bool csv = false;
  2099. static void usage(FILE *out) {
  2100. fprintf(out, "usage: %s [-v] [--print] <params>|<game id>\n", quis);
  2101. }
  2102. static void doprint(game_state *state)
  2103. {
  2104. char *fmt = game_text_format(state);
  2105. printf("%s", fmt);
  2106. sfree(fmt);
  2107. }
  2108. static void pnum(int n, int ntot, const char *desc)
  2109. {
  2110. printf("%2.1f%% (%d) %s", (double)n*100.0 / (double)ntot, n, desc);
  2111. }
  2112. static void start_soak(game_params *p, random_state *rs)
  2113. {
  2114. time_t tt_start, tt_now, tt_last;
  2115. char *aux;
  2116. game_state *s, *s2;
  2117. int n = 0, nsolved = 0, nimpossible = 0, ntricky = 0, ret, i;
  2118. long nn, nn_total = 0, nn_solved = 0, nn_tricky = 0;
  2119. tt_start = tt_now = time(NULL);
  2120. if (csv)
  2121. printf("time, w, h, #generated, #solved, #tricky, #impossible, "
  2122. "#neutral, #neutral/solved, #neutral/tricky\n");
  2123. else
  2124. printf("Soak-testing a %dx%d grid.\n", p->w, p->h);
  2125. s = new_state(p->w, p->h);
  2126. aux = snewn(s->wh+1, char);
  2127. while (1) {
  2128. gen_game(s, rs);
  2129. nn = 0;
  2130. for (i = 0; i < s->wh; i++) {
  2131. if (s->grid[i] == NEUTRAL) nn++;
  2132. }
  2133. generate_aux(s, aux);
  2134. memset(s->grid, EMPTY, s->wh * sizeof(int));
  2135. s2 = dup_game(s);
  2136. ret = solve_state(s, DIFFCOUNT);
  2137. n++;
  2138. nn_total += nn;
  2139. if (ret > 0) {
  2140. nsolved++;
  2141. nn_solved += nn;
  2142. if (solve_state(s2, DIFF_EASY) <= 0) {
  2143. ntricky++;
  2144. nn_tricky += nn;
  2145. }
  2146. } else if (ret < 0) {
  2147. char *desc = generate_desc(s);
  2148. solve_from_aux(s, aux);
  2149. printf("Game considered impossible:\n %dx%d:%s\n",
  2150. p->w, p->h, desc);
  2151. sfree(desc);
  2152. doprint(s);
  2153. nimpossible++;
  2154. }
  2155. free_game(s2);
  2156. tt_last = time(NULL);
  2157. if (tt_last > tt_now) {
  2158. tt_now = tt_last;
  2159. if (csv) {
  2160. printf("%d,%d,%d, %d,%d,%d,%d, %ld,%ld,%ld\n",
  2161. (int)(tt_now - tt_start), p->w, p->h,
  2162. n, nsolved, ntricky, nimpossible,
  2163. nn_total, nn_solved, nn_tricky);
  2164. } else {
  2165. printf("%d total, %3.1f/s, ",
  2166. n, (double)n / ((double)tt_now - tt_start));
  2167. pnum(nsolved, n, "solved"); printf(", ");
  2168. pnum(ntricky, n, "tricky");
  2169. if (nimpossible > 0)
  2170. pnum(nimpossible, n, "impossible");
  2171. printf("\n");
  2172. printf(" overall %3.1f%% neutral (%3.1f%% for solved, %3.1f%% for tricky)\n",
  2173. (double)(nn_total * 100) / (double)(p->w * p->h * n),
  2174. (double)(nn_solved * 100) / (double)(p->w * p->h * nsolved),
  2175. (double)(nn_tricky * 100) / (double)(p->w * p->h * ntricky));
  2176. }
  2177. }
  2178. }
  2179. free_game(s);
  2180. sfree(aux);
  2181. }
  2182. int main(int argc, char *argv[])
  2183. {
  2184. bool print = false, soak = false, solved = false;
  2185. int ret;
  2186. char *id = NULL, *desc, *desc_gen = NULL, *aux = NULL;
  2187. const char *err;
  2188. game_state *s = NULL;
  2189. game_params *p = NULL;
  2190. random_state *rs = NULL;
  2191. time_t seed = time(NULL);
  2192. setvbuf(stdout, NULL, _IONBF, 0);
  2193. quis = argv[0];
  2194. while (--argc > 0) {
  2195. char *p = (char*)(*++argv);
  2196. if (!strcmp(p, "-v") || !strcmp(p, "--verbose")) {
  2197. verbose = true;
  2198. } else if (!strcmp(p, "--csv")) {
  2199. csv = true;
  2200. } else if (!strcmp(p, "-e") || !strcmp(p, "--seed")) {
  2201. seed = atoi(*++argv);
  2202. argc--;
  2203. } else if (!strcmp(p, "-p") || !strcmp(p, "--print")) {
  2204. print = true;
  2205. } else if (!strcmp(p, "-s") || !strcmp(p, "--soak")) {
  2206. soak = true;
  2207. } else if (*p == '-') {
  2208. fprintf(stderr, "%s: unrecognised option `%s'\n", argv[0], p);
  2209. usage(stderr);
  2210. exit(1);
  2211. } else {
  2212. id = p;
  2213. }
  2214. }
  2215. rs = random_new((void*)&seed, sizeof(time_t));
  2216. if (!id) {
  2217. fprintf(stderr, "usage: %s [-v] [--soak] <params> | <game_id>\n", argv[0]);
  2218. goto done;
  2219. }
  2220. desc = strchr(id, ':');
  2221. if (desc) *desc++ = '\0';
  2222. p = default_params();
  2223. decode_params(p, id);
  2224. err = validate_params(p, true);
  2225. if (err) {
  2226. fprintf(stderr, "%s: %s\n", argv[0], err);
  2227. goto done;
  2228. }
  2229. if (soak) {
  2230. if (desc) {
  2231. fprintf(stderr, "%s: --soak needs parameters, not description.\n", quis);
  2232. goto done;
  2233. }
  2234. start_soak(p, rs);
  2235. goto done;
  2236. }
  2237. if (!desc)
  2238. desc = desc_gen = new_game_desc(p, rs, &aux, false);
  2239. err = validate_desc(p, desc);
  2240. if (err) {
  2241. fprintf(stderr, "%s: %s\nDescription: %s\n", quis, err, desc);
  2242. goto done;
  2243. }
  2244. s = new_game(NULL, p, desc);
  2245. printf("%s:%s (seed %ld)\n", id, desc, (long)seed);
  2246. if (aux) {
  2247. /* We just generated this ourself. */
  2248. if (verbose || print) {
  2249. doprint(s);
  2250. solve_from_aux(s, aux);
  2251. solved = true;
  2252. }
  2253. } else {
  2254. doprint(s);
  2255. verbose = true;
  2256. ret = solve_state(s, DIFFCOUNT);
  2257. if (ret < 0) printf("Puzzle is impossible.\n");
  2258. else if (ret == 0) printf("Puzzle is ambiguous.\n");
  2259. else printf("Puzzle was solved.\n");
  2260. verbose = false;
  2261. solved = true;
  2262. }
  2263. if (solved) doprint(s);
  2264. done:
  2265. if (desc_gen) sfree(desc_gen);
  2266. if (p) free_params(p);
  2267. if (s) free_game(s);
  2268. if (rs) random_free(rs);
  2269. if (aux) sfree(aux);
  2270. return 0;
  2271. }
  2272. #endif
  2273. /* vim: set shiftwidth=4 tabstop=8: */