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