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.
12 * - Improve singleton removal.
13 * + It would be nice to limit the size of the generated
14 * rectangles in accordance with existing constraints such as
15 * the maximum rectangle size and the one about not
16 * generating a rectangle the full width or height of the
18 * + This could be achieved by making a less random choice
19 * about which of the available options to use.
20 * + Alternatively, we could create our rectangle and then
49 #define INDEX(state, x, y) (((y) * (state)->w) + (x))
50 #define index(state, a, x, y) ((a) [ INDEX(state,x,y) ])
51 #define grid(state,x,y) index(state, (state)->grid, x, y)
52 #define vedge(state,x,y) index(state, (state)->vedge, x, y)
53 #define hedge(state,x,y) index(state, (state)->hedge, x, y)
55 #define CRANGE(state,x,y,dx,dy) ( (x) >= dx && (x) < (state)->w && \
56 (y) >= dy && (y) < (state)->h )
57 #define RANGE(state,x,y) CRANGE(state,x,y,0,0)
58 #define HRANGE(state,x,y) CRANGE(state,x,y,0,1)
59 #define VRANGE(state,x,y) CRANGE(state,x,y,1,0)
61 #define PREFERRED_TILE_SIZE 24
62 #define TILE_SIZE (ds->tilesize)
66 #define BORDER (TILE_SIZE * 3 / 4)
69 #define CORNER_TOLERANCE 0.15F
70 #define CENTRE_TOLERANCE 0.15F
72 #define FLASH_TIME 0.13F
74 #define COORD(x) ( (x) * TILE_SIZE + BORDER )
75 #define FROMCOORD(x) ( ((x) - BORDER) / TILE_SIZE )
79 int *grid; /* contains the numbers */
80 unsigned char *vedge; /* (w+1) x h */
81 unsigned char *hedge; /* w x (h+1) */
82 int completed, cheated;
83 unsigned char *correct;
86 static game_params *default_params(void)
88 game_params *ret = snew(game_params);
91 ret->expandfactor = 0.0F;
97 static int game_fetch_preset(int i, char **name, game_params **params)
104 case 0: w = 7, h = 7; break;
105 case 1: w = 9, h = 9; break;
106 case 2: w = 11, h = 11; break;
107 case 3: w = 13, h = 13; break;
108 case 4: w = 15, h = 15; break;
110 case 5: w = 17, h = 17; break;
111 case 6: w = 19, h = 19; break;
113 default: return FALSE;
116 sprintf(buf, "%dx%d", w, h);
118 *params = ret = snew(game_params);
121 ret->expandfactor = 0.0F;
126 static void free_params(game_params *params)
131 static game_params *dup_params(game_params *params)
133 game_params *ret = snew(game_params);
134 *ret = *params; /* structure copy */
138 static void decode_params(game_params *ret, char const *string)
140 ret->w = ret->h = atoi(string);
141 while (*string && isdigit((unsigned char)*string)) string++;
142 if (*string == 'x') {
144 ret->h = atoi(string);
145 while (*string && isdigit((unsigned char)*string)) string++;
147 if (*string == 'e') {
149 ret->expandfactor = atof(string);
151 (*string == '.' || isdigit((unsigned char)*string))) string++;
153 if (*string == 'a') {
159 static char *encode_params(game_params *params, int full)
163 sprintf(data, "%dx%d", params->w, params->h);
164 if (full && params->expandfactor)
165 sprintf(data + strlen(data), "e%g", params->expandfactor);
166 if (full && !params->unique)
172 static config_item *game_configure(game_params *params)
177 ret = snewn(5, config_item);
179 ret[0].name = "Width";
180 ret[0].type = C_STRING;
181 sprintf(buf, "%d", params->w);
182 ret[0].sval = dupstr(buf);
185 ret[1].name = "Height";
186 ret[1].type = C_STRING;
187 sprintf(buf, "%d", params->h);
188 ret[1].sval = dupstr(buf);
191 ret[2].name = "Expansion factor";
192 ret[2].type = C_STRING;
193 sprintf(buf, "%g", params->expandfactor);
194 ret[2].sval = dupstr(buf);
197 ret[3].name = "Ensure unique solution";
198 ret[3].type = C_BOOLEAN;
200 ret[3].ival = params->unique;
210 static game_params *custom_params(config_item *cfg)
212 game_params *ret = snew(game_params);
214 ret->w = atoi(cfg[0].sval);
215 ret->h = atoi(cfg[1].sval);
216 ret->expandfactor = atof(cfg[2].sval);
217 ret->unique = cfg[3].ival;
222 static char *validate_params(game_params *params, int full)
224 if (params->w <= 0 || params->h <= 0)
225 return "Width and height must both be greater than zero";
226 if (params->w*params->h < 2)
227 return "Grid area must be greater than one";
228 if (params->expandfactor < 0.0F)
229 return "Expansion factor may not be negative";
250 struct point *points;
253 /* ----------------------------------------------------------------------
254 * Solver for Rectangles games.
256 * This solver is souped up beyond the needs of actually _solving_
257 * a puzzle. It is also designed to cope with uncertainty about
258 * where the numbers have been placed. This is because I run it on
259 * my generated grids _before_ placing the numbers, and have it
260 * tell me where I need to place the numbers to ensure a unique
264 static void remove_rect_placement(int w, int h,
265 struct rectlist *rectpositions,
267 int rectnum, int placement)
271 #ifdef SOLVER_DIAGNOSTICS
272 printf("ruling out rect %d placement at %d,%d w=%d h=%d\n", rectnum,
273 rectpositions[rectnum].rects[placement].x,
274 rectpositions[rectnum].rects[placement].y,
275 rectpositions[rectnum].rects[placement].w,
276 rectpositions[rectnum].rects[placement].h);
280 * Decrement each entry in the overlaps array to reflect the
281 * removal of this rectangle placement.
283 for (yy = 0; yy < rectpositions[rectnum].rects[placement].h; yy++) {
284 y = yy + rectpositions[rectnum].rects[placement].y;
285 for (xx = 0; xx < rectpositions[rectnum].rects[placement].w; xx++) {
286 x = xx + rectpositions[rectnum].rects[placement].x;
288 assert(overlaps[(rectnum * h + y) * w + x] != 0);
290 if (overlaps[(rectnum * h + y) * w + x] > 0)
291 overlaps[(rectnum * h + y) * w + x]--;
296 * Remove the placement from the list of positions for that
297 * rectangle, by interchanging it with the one on the end.
299 if (placement < rectpositions[rectnum].n - 1) {
302 t = rectpositions[rectnum].rects[rectpositions[rectnum].n - 1];
303 rectpositions[rectnum].rects[rectpositions[rectnum].n - 1] =
304 rectpositions[rectnum].rects[placement];
305 rectpositions[rectnum].rects[placement] = t;
307 rectpositions[rectnum].n--;
310 static void remove_number_placement(int w, int h, struct numberdata *number,
311 int index, int *rectbyplace)
314 * Remove the entry from the rectbyplace array.
316 rectbyplace[number->points[index].y * w + number->points[index].x] = -1;
319 * Remove the placement from the list of candidates for that
320 * number, by interchanging it with the one on the end.
322 if (index < number->npoints - 1) {
325 t = number->points[number->npoints - 1];
326 number->points[number->npoints - 1] = number->points[index];
327 number->points[index] = t;
333 * Returns 0 for failure to solve due to inconsistency; 1 for
334 * success; 2 for failure to complete a solution due to either
335 * ambiguity or it being too difficult.
337 static int rect_solver(int w, int h, int nrects, struct numberdata *numbers,
338 unsigned char *hedge, unsigned char *vedge,
341 struct rectlist *rectpositions;
342 int *overlaps, *rectbyplace, *workspace;
346 * Start by setting up a list of candidate positions for each
349 rectpositions = snewn(nrects, struct rectlist);
350 for (i = 0; i < nrects; i++) {
351 int rw, rh, area = numbers[i].area;
352 int j, minx, miny, maxx, maxy;
354 int rlistn, rlistsize;
357 * For each rectangle, begin by finding the bounding
358 * rectangle of its candidate number placements.
363 for (j = 0; j < numbers[i].npoints; j++) {
364 if (minx > numbers[i].points[j].x) minx = numbers[i].points[j].x;
365 if (miny > numbers[i].points[j].y) miny = numbers[i].points[j].y;
366 if (maxx < numbers[i].points[j].x) maxx = numbers[i].points[j].x;
367 if (maxy < numbers[i].points[j].y) maxy = numbers[i].points[j].y;
371 * Now loop over all possible rectangle placements
372 * overlapping a point within that bounding rectangle;
373 * ensure each one actually contains a candidate number
374 * placement, and add it to the list.
377 rlistn = rlistsize = 0;
379 for (rw = 1; rw <= area && rw <= w; rw++) {
388 for (y = miny - rh + 1; y <= maxy; y++) {
389 if (y < 0 || y+rh > h)
392 for (x = minx - rw + 1; x <= maxx; x++) {
393 if (x < 0 || x+rw > w)
397 * See if we can find a candidate number
398 * placement within this rectangle.
400 for (j = 0; j < numbers[i].npoints; j++)
401 if (numbers[i].points[j].x >= x &&
402 numbers[i].points[j].x < x+rw &&
403 numbers[i].points[j].y >= y &&
404 numbers[i].points[j].y < y+rh)
407 if (j < numbers[i].npoints) {
409 * Add this to the list of candidate
410 * placements for this rectangle.
412 if (rlistn >= rlistsize) {
413 rlistsize = rlistn + 32;
414 rlist = sresize(rlist, rlistsize, struct rect);
418 rlist[rlistn].w = rw;
419 rlist[rlistn].h = rh;
420 #ifdef SOLVER_DIAGNOSTICS
421 printf("rect %d [area %d]: candidate position at"
422 " %d,%d w=%d h=%d\n",
423 i, area, x, y, rw, rh);
431 rectpositions[i].rects = rlist;
432 rectpositions[i].n = rlistn;
436 * Next, construct a multidimensional array tracking how many
437 * candidate positions for each rectangle overlap each square.
439 * Indexing of this array is by the formula
441 * overlaps[(rectindex * h + y) * w + x]
443 * A positive or zero value indicates what it sounds as if it
444 * should; -1 indicates that this square _cannot_ be part of
445 * this rectangle; and -2 indicates that it _definitely_ is
446 * (which is distinct from 1, because one might very well know
447 * that _if_ square S is part of rectangle R then it must be
448 * because R is placed in a certain position without knowing
449 * that it definitely _is_).
451 overlaps = snewn(nrects * w * h, int);
452 memset(overlaps, 0, nrects * w * h * sizeof(int));
453 for (i = 0; i < nrects; i++) {
456 for (j = 0; j < rectpositions[i].n; j++) {
459 for (yy = 0; yy < rectpositions[i].rects[j].h; yy++)
460 for (xx = 0; xx < rectpositions[i].rects[j].w; xx++)
461 overlaps[(i * h + yy+rectpositions[i].rects[j].y) * w +
462 xx+rectpositions[i].rects[j].x]++;
467 * Also we want an array covering the grid once, to make it
468 * easy to figure out which squares are candidate number
469 * placements for which rectangles. (The existence of this
470 * single array assumes that no square starts off as a
471 * candidate number placement for more than one rectangle. This
472 * assumption is justified, because this solver is _either_
473 * used to solve real problems - in which case there is a
474 * single placement for every number - _or_ used to decide on
475 * number placements for a new puzzle, in which case each
476 * number's placements are confined to the intended position of
477 * the rectangle containing that number.)
479 rectbyplace = snewn(w * h, int);
480 for (i = 0; i < w*h; i++)
483 for (i = 0; i < nrects; i++) {
486 for (j = 0; j < numbers[i].npoints; j++) {
487 int x = numbers[i].points[j].x;
488 int y = numbers[i].points[j].y;
490 assert(rectbyplace[y * w + x] == -1);
491 rectbyplace[y * w + x] = i;
495 workspace = snewn(nrects, int);
498 * Now run the actual deduction loop.
501 int done_something = FALSE;
503 #ifdef SOLVER_DIAGNOSTICS
504 printf("starting deduction loop\n");
506 for (i = 0; i < nrects; i++) {
507 printf("rect %d overlaps:\n", i);
510 for (y = 0; y < h; y++) {
511 for (x = 0; x < w; x++) {
512 printf("%3d", overlaps[(i * h + y) * w + x]);
518 printf("rectbyplace:\n");
521 for (y = 0; y < h; y++) {
522 for (x = 0; x < w; x++) {
523 printf("%3d", rectbyplace[y * w + x]);
531 * Housekeeping. Look for rectangles whose number has only
532 * one candidate position left, and mark that square as
533 * known if it isn't already.
535 for (i = 0; i < nrects; i++) {
536 if (numbers[i].npoints == 1) {
537 int x = numbers[i].points[0].x;
538 int y = numbers[i].points[0].y;
539 if (overlaps[(i * h + y) * w + x] >= -1) {
542 if (overlaps[(i * h + y) * w + x] <= 0) {
543 ret = 0; /* inconsistency */
546 #ifdef SOLVER_DIAGNOSTICS
547 printf("marking %d,%d as known for rect %d"
548 " (sole remaining number position)\n", x, y, i);
551 for (j = 0; j < nrects; j++)
552 overlaps[(j * h + y) * w + x] = -1;
554 overlaps[(i * h + y) * w + x] = -2;
560 * Now look at the intersection of all possible placements
561 * for each rectangle, and mark all squares in that
562 * intersection as known for that rectangle if they aren't
565 for (i = 0; i < nrects; i++) {
566 int minx, miny, maxx, maxy, xx, yy, j;
572 for (j = 0; j < rectpositions[i].n; j++) {
573 int x = rectpositions[i].rects[j].x;
574 int y = rectpositions[i].rects[j].y;
575 int w = rectpositions[i].rects[j].w;
576 int h = rectpositions[i].rects[j].h;
578 if (minx < x) minx = x;
579 if (miny < y) miny = y;
580 if (maxx > x+w) maxx = x+w;
581 if (maxy > y+h) maxy = y+h;
584 for (yy = miny; yy < maxy; yy++)
585 for (xx = minx; xx < maxx; xx++)
586 if (overlaps[(i * h + yy) * w + xx] >= -1) {
587 if (overlaps[(i * h + yy) * w + xx] <= 0) {
588 ret = 0; /* inconsistency */
591 #ifdef SOLVER_DIAGNOSTICS
592 printf("marking %d,%d as known for rect %d"
593 " (intersection of all placements)\n",
597 for (j = 0; j < nrects; j++)
598 overlaps[(j * h + yy) * w + xx] = -1;
600 overlaps[(i * h + yy) * w + xx] = -2;
605 * Rectangle-focused deduction. Look at each rectangle in
606 * turn and try to rule out some of its candidate
609 for (i = 0; i < nrects; i++) {
612 for (j = 0; j < rectpositions[i].n; j++) {
616 for (k = 0; k < nrects; k++)
619 for (yy = 0; yy < rectpositions[i].rects[j].h; yy++) {
620 int y = yy + rectpositions[i].rects[j].y;
621 for (xx = 0; xx < rectpositions[i].rects[j].w; xx++) {
622 int x = xx + rectpositions[i].rects[j].x;
624 if (overlaps[(i * h + y) * w + x] == -1) {
626 * This placement overlaps a square
627 * which is _known_ to be part of
628 * another rectangle. Therefore we must
631 #ifdef SOLVER_DIAGNOSTICS
632 printf("rect %d placement at %d,%d w=%d h=%d "
633 "contains %d,%d which is known-other\n", i,
634 rectpositions[i].rects[j].x,
635 rectpositions[i].rects[j].y,
636 rectpositions[i].rects[j].w,
637 rectpositions[i].rects[j].h,
643 if (rectbyplace[y * w + x] != -1) {
645 * This placement overlaps one of the
646 * candidate number placements for some
647 * rectangle. Count it.
649 workspace[rectbyplace[y * w + x]]++;
656 * If we haven't ruled this placement out
657 * already, see if it overlaps _all_ of the
658 * candidate number placements for any
659 * rectangle. If so, we can rule it out.
661 for (k = 0; k < nrects; k++)
662 if (k != i && workspace[k] == numbers[k].npoints) {
663 #ifdef SOLVER_DIAGNOSTICS
664 printf("rect %d placement at %d,%d w=%d h=%d "
665 "contains all number points for rect %d\n",
667 rectpositions[i].rects[j].x,
668 rectpositions[i].rects[j].y,
669 rectpositions[i].rects[j].w,
670 rectpositions[i].rects[j].h,
678 * Failing that, see if it overlaps at least
679 * one of the candidate number placements for
680 * itself! (This might not be the case if one
681 * of those number placements has been removed
684 if (!del && workspace[i] == 0) {
685 #ifdef SOLVER_DIAGNOSTICS
686 printf("rect %d placement at %d,%d w=%d h=%d "
687 "contains none of its own number points\n",
689 rectpositions[i].rects[j].x,
690 rectpositions[i].rects[j].y,
691 rectpositions[i].rects[j].w,
692 rectpositions[i].rects[j].h);
699 remove_rect_placement(w, h, rectpositions, overlaps, i, j);
701 j--; /* don't skip over next placement */
703 done_something = TRUE;
709 * Square-focused deduction. Look at each square not marked
710 * as known, and see if there are any which can only be
711 * part of a single rectangle.
715 for (y = 0; y < h; y++) for (x = 0; x < w; x++) {
716 /* Known squares are marked as <0 everywhere, so we only need
717 * to check the overlaps entry for rect 0. */
718 if (overlaps[y * w + x] < 0)
719 continue; /* known already */
723 for (i = 0; i < nrects; i++)
724 if (overlaps[(i * h + y) * w + x] > 0)
731 * Now we can rule out all placements for
732 * rectangle `index' which _don't_ contain
735 #ifdef SOLVER_DIAGNOSTICS
736 printf("square %d,%d can only be in rectangle %d\n",
739 for (j = 0; j < rectpositions[index].n; j++) {
740 struct rect *r = &rectpositions[index].rects[j];
741 if (x >= r->x && x < r->x + r->w &&
742 y >= r->y && y < r->y + r->h)
743 continue; /* this one is OK */
744 remove_rect_placement(w, h, rectpositions, overlaps,
746 j--; /* don't skip over next placement */
747 done_something = TRUE;
754 * If we've managed to deduce anything by normal means,
755 * loop round again and see if there's more to be done.
756 * Only if normal deduction has completely failed us should
757 * we now move on to narrowing down the possible number
764 * Now we have done everything we can with the current set
765 * of number placements. So we need to winnow the number
766 * placements so as to narrow down the possibilities. We do
767 * this by searching for a candidate placement (of _any_
768 * rectangle) which overlaps a candidate placement of the
769 * number for some other rectangle.
777 size_t nrpns = 0, rpnsize = 0;
780 for (i = 0; i < nrects; i++) {
781 for (j = 0; j < rectpositions[i].n; j++) {
784 for (yy = 0; yy < rectpositions[i].rects[j].h; yy++) {
785 int y = yy + rectpositions[i].rects[j].y;
786 for (xx = 0; xx < rectpositions[i].rects[j].w; xx++) {
787 int x = xx + rectpositions[i].rects[j].x;
789 if (rectbyplace[y * w + x] >= 0 &&
790 rectbyplace[y * w + x] != i) {
792 * Add this to the list of
793 * winnowing possibilities.
795 if (nrpns >= rpnsize) {
796 rpnsize = rpnsize * 3 / 2 + 32;
797 rpns = sresize(rpns, rpnsize, struct rpn);
799 rpns[nrpns].rect = i;
800 rpns[nrpns].placement = j;
801 rpns[nrpns].number = rectbyplace[y * w + x];
810 #ifdef SOLVER_DIAGNOSTICS
811 printf("%d candidate rect placements we could eliminate\n", nrpns);
815 * Now choose one of these unwanted rectangle
816 * placements, and eliminate it.
818 int index = random_upto(rs, nrpns);
820 struct rpn rpn = rpns[index];
827 r = rectpositions[i].rects[j];
830 * We rule out placement j of rectangle i by means
831 * of removing all of rectangle k's candidate
832 * number placements which do _not_ overlap it.
833 * This will ensure that it is eliminated during
834 * the next pass of rectangle-focused deduction.
836 #ifdef SOLVER_DIAGNOSTICS
837 printf("ensuring number for rect %d is within"
838 " rect %d's placement at %d,%d w=%d h=%d\n",
839 k, i, r.x, r.y, r.w, r.h);
842 for (m = 0; m < numbers[k].npoints; m++) {
843 int x = numbers[k].points[m].x;
844 int y = numbers[k].points[m].y;
846 if (x < r.x || x >= r.x + r.w ||
847 y < r.y || y >= r.y + r.h) {
848 #ifdef SOLVER_DIAGNOSTICS
849 printf("eliminating number for rect %d at %d,%d\n",
852 remove_number_placement(w, h, &numbers[k],
854 m--; /* don't skip the next one */
855 done_something = TRUE;
861 if (!done_something) {
862 #ifdef SOLVER_DIAGNOSTICS
863 printf("terminating deduction loop\n");
871 for (i = 0; i < nrects; i++) {
872 #ifdef SOLVER_DIAGNOSTICS
873 printf("rect %d has %d possible placements\n",
874 i, rectpositions[i].n);
876 if (rectpositions[i].n <= 0) {
877 ret = 0; /* inconsistency */
878 } else if (rectpositions[i].n > 1) {
879 ret = 2; /* remaining uncertainty */
880 } else if (hedge && vedge) {
882 * Place the rectangle in its only possible position.
885 struct rect *r = &rectpositions[i].rects[0];
887 for (y = 0; y < r->h; y++) {
889 vedge[(r->y+y) * w + r->x] = 1;
891 vedge[(r->y+y) * w + r->x+r->w] = 1;
893 for (x = 0; x < r->w; x++) {
895 hedge[r->y * w + r->x+x] = 1;
897 hedge[(r->y+r->h) * w + r->x+x] = 1;
903 * Free up all allocated storage.
908 for (i = 0; i < nrects; i++)
909 sfree(rectpositions[i].rects);
910 sfree(rectpositions);
915 /* ----------------------------------------------------------------------
916 * Grid generation code.
920 * This function does one of two things. If passed r==NULL, it
921 * counts the number of possible rectangles which cover the given
922 * square, and returns it in *n. If passed r!=NULL then it _reads_
923 * *n to find an index, counts the possible rectangles until it
924 * reaches the nth, and writes it into r.
926 * `scratch' is expected to point to an array of 2 * params->w
927 * ints, used internally as scratch space (and passed in like this
928 * to avoid re-allocating and re-freeing it every time round a
931 static void enum_rects(game_params *params, int *grid, struct rect *r, int *n,
932 int sx, int sy, int *scratch)
936 int maxarea, realmaxarea;
941 * Maximum rectangle area is 1/6 of total grid size, unless
942 * this means we can't place any rectangles at all in which
943 * case we set it to 2 at minimum.
945 maxarea = params->w * params->h / 6;
950 * Scan the grid to find the limits of the region within which
951 * any rectangle containing this point must fall. This will
952 * save us trawling the inside of every rectangle later on to
953 * see if it contains any used squares.
956 bottom = scratch + params->w;
957 for (dy = -1; dy <= +1; dy += 2) {
958 int *array = (dy == -1 ? top : bottom);
959 for (dx = -1; dx <= +1; dx += 2) {
960 for (x = sx; x >= 0 && x < params->w; x += dx) {
961 array[x] = -2 * params->h * dy;
962 for (y = sy; y >= 0 && y < params->h; y += dy) {
963 if (index(params, grid, x, y) == -1 &&
964 (x == sx || dy*y <= dy*array[x-dx]))
974 * Now scan again to work out the largest rectangles we can fit
975 * in the grid, so that we can terminate the following loops
976 * early once we get down to not having much space left in the
980 for (x = 0; x < params->w; x++) {
983 rh = bottom[x] - top[x] + 1;
985 continue; /* no rectangles can start here */
987 dx = (x > sx ? -1 : +1);
988 for (x2 = x; x2 >= 0 && x2 < params->w; x2 += dx)
989 if (bottom[x2] < bottom[x] || top[x2] > top[x])
993 if (realmaxarea < rw * rh)
994 realmaxarea = rw * rh;
997 if (realmaxarea > maxarea)
998 realmaxarea = maxarea;
1001 * Rectangles which go right the way across the grid are
1002 * boring, although they can't be helped in the case of
1003 * extremely small grids. (Also they might be generated later
1004 * on by the singleton-removal process; we can't help that.)
1011 for (rw = 1; rw <= mw; rw++)
1012 for (rh = 1; rh <= mh; rh++) {
1013 if (rw * rh > realmaxarea)
1017 for (x = max(sx - rw + 1, 0); x <= min(sx, params->w - rw); x++)
1018 for (y = max(sy - rh + 1, 0); y <= min(sy, params->h - rh);
1021 * Check this rectangle against the region we
1024 if (top[x] <= y && top[x+rw-1] <= y &&
1025 bottom[x] >= y+rh-1 && bottom[x+rw-1] >= y+rh-1) {
1026 if (r && index == *n) {
1042 static void place_rect(game_params *params, int *grid, struct rect r)
1044 int idx = INDEX(params, r.x, r.y);
1047 for (x = r.x; x < r.x+r.w; x++)
1048 for (y = r.y; y < r.y+r.h; y++) {
1049 index(params, grid, x, y) = idx;
1051 #ifdef GENERATION_DIAGNOSTICS
1052 printf(" placing rectangle at (%d,%d) size %d x %d\n",
1053 r.x, r.y, r.w, r.h);
1057 static struct rect find_rect(game_params *params, int *grid, int x, int y)
1063 * Find the top left of the rectangle.
1065 idx = index(params, grid, x, y);
1071 return r; /* 1x1 singleton here */
1074 y = idx / params->w;
1075 x = idx % params->w;
1078 * Find the width and height of the rectangle.
1081 (x+w < params->w && index(params,grid,x+w,y)==idx);
1084 (y+h < params->h && index(params,grid,x,y+h)==idx);
1095 #ifdef GENERATION_DIAGNOSTICS
1096 static void display_grid(game_params *params, int *grid, int *numbers, int all)
1098 unsigned char *egrid = snewn((params->w*2+3) * (params->h*2+3),
1101 int r = (params->w*2+3);
1103 memset(egrid, 0, (params->w*2+3) * (params->h*2+3));
1105 for (x = 0; x < params->w; x++)
1106 for (y = 0; y < params->h; y++) {
1107 int i = index(params, grid, x, y);
1108 if (x == 0 || index(params, grid, x-1, y) != i)
1109 egrid[(2*y+2) * r + (2*x+1)] = 1;
1110 if (x == params->w-1 || index(params, grid, x+1, y) != i)
1111 egrid[(2*y+2) * r + (2*x+3)] = 1;
1112 if (y == 0 || index(params, grid, x, y-1) != i)
1113 egrid[(2*y+1) * r + (2*x+2)] = 1;
1114 if (y == params->h-1 || index(params, grid, x, y+1) != i)
1115 egrid[(2*y+3) * r + (2*x+2)] = 1;
1118 for (y = 1; y < 2*params->h+2; y++) {
1119 for (x = 1; x < 2*params->w+2; x++) {
1121 int k = numbers ? index(params, numbers, x/2-1, y/2-1) : 0;
1122 if (k || (all && numbers)) printf("%2d", k); else printf(" ");
1123 } else if (!((y&x)&1)) {
1124 int v = egrid[y*r+x];
1125 if ((y&1) && v) v = '-';
1126 if ((x&1) && v) v = '|';
1129 if (!(x&1)) putchar(v);
1132 if (egrid[y*r+(x+1)]) d |= 1;
1133 if (egrid[(y-1)*r+x]) d |= 2;
1134 if (egrid[y*r+(x-1)]) d |= 4;
1135 if (egrid[(y+1)*r+x]) d |= 8;
1136 c = " ??+?-++?+|+++++"[d];
1138 if (!(x&1)) putchar(c);
1148 static char *new_game_desc(game_params *params, random_state *rs,
1149 char **aux, int interactive)
1151 int *grid, *numbers = NULL;
1152 int x, y, y2, y2last, yx, run, i, nsquares;
1154 int *enum_rects_scratch;
1155 game_params params2real, *params2 = ¶ms2real;
1159 * Set up the smaller width and height which we will use to
1160 * generate the base grid.
1162 params2->w = params->w / (1.0F + params->expandfactor);
1163 if (params2->w < 2 && params->w >= 2) params2->w = 2;
1164 params2->h = params->h / (1.0F + params->expandfactor);
1165 if (params2->h < 2 && params->h >= 2) params2->h = 2;
1167 grid = snewn(params2->w * params2->h, int);
1169 enum_rects_scratch = snewn(2 * params2->w, int);
1172 for (y = 0; y < params2->h; y++)
1173 for (x = 0; x < params2->w; x++) {
1174 index(params2, grid, x, y) = -1;
1179 * Place rectangles until we can't any more. We do this by
1180 * finding a square we haven't yet covered, and randomly
1181 * choosing a rectangle to cover it.
1184 while (nsquares > 0) {
1185 int square = random_upto(rs, nsquares);
1191 for (y = 0; y < params2->h; y++) {
1192 for (x = 0; x < params2->w; x++) {
1193 if (index(params2, grid, x, y) == -1 && square-- == 0)
1199 assert(x < params2->w && y < params2->h);
1202 * Now see how many rectangles fit around this one.
1204 enum_rects(params2, grid, NULL, &n, x, y, enum_rects_scratch);
1208 * There are no possible rectangles covering this
1209 * square, meaning it must be a singleton. Mark it
1210 * -2 so we know not to keep trying.
1212 index(params2, grid, x, y) = -2;
1216 * Pick one at random.
1218 n = random_upto(rs, n);
1219 enum_rects(params2, grid, &r, &n, x, y, enum_rects_scratch);
1224 place_rect(params2, grid, r);
1225 nsquares -= r.w * r.h;
1229 sfree(enum_rects_scratch);
1232 * Deal with singleton spaces remaining in the grid, one by
1235 * We do this by making a local change to the layout. There are
1236 * several possibilities:
1238 * +-----+-----+ Here, we can remove the singleton by
1239 * | | | extending the 1x2 rectangle below it
1240 * +--+--+-----+ into a 1x3.
1248 * +--+--+--+ Here, that trick doesn't work: there's no
1249 * | | | 1 x n rectangle with the singleton at one
1250 * | | | end. Instead, we extend a 1 x n rectangle
1251 * | | | _out_ from the singleton, shaving a layer
1252 * +--+--+ | off the end of another rectangle. So if we
1253 * | | | | extended up, we'd make our singleton part
1254 * | +--+--+ of a 1x3 and generate a 1x2 where the 2x2
1255 * | | | used to be; or we could extend right into
1256 * +--+-----+ a 2x1, turning the 1x3 into a 1x2.
1258 * +-----+--+ Here, we can't even do _that_, since any
1259 * | | | direction we choose to extend the singleton
1260 * +--+--+ | will produce a new singleton as a result of
1261 * | | | | truncating one of the size-2 rectangles.
1262 * | +--+--+ Fortunately, this case can _only_ occur when
1263 * | | | a singleton is surrounded by four size-2s
1264 * +--+-----+ in this fashion; so instead we can simply
1265 * replace the whole section with a single 3x3.
1267 for (x = 0; x < params2->w; x++) {
1268 for (y = 0; y < params2->h; y++) {
1269 if (index(params2, grid, x, y) < 0) {
1272 #ifdef GENERATION_DIAGNOSTICS
1273 display_grid(params2, grid, NULL, FALSE);
1274 printf("singleton at %d,%d\n", x, y);
1278 * Check in which directions we can feasibly extend
1279 * the singleton. We can extend in a particular
1280 * direction iff either:
1282 * - the rectangle on that side of the singleton
1283 * is not 2x1, and we are at one end of the edge
1284 * of it we are touching
1286 * - it is 2x1 but we are on its short side.
1288 * FIXME: we could plausibly choose between these
1289 * based on the sizes of the rectangles they would
1293 if (x < params2->w-1) {
1294 struct rect r = find_rect(params2, grid, x+1, y);
1295 if ((r.w * r.h > 2 && (r.y==y || r.y+r.h-1==y)) || r.h==1)
1296 dirs[ndirs++] = 1; /* right */
1299 struct rect r = find_rect(params2, grid, x, y-1);
1300 if ((r.w * r.h > 2 && (r.x==x || r.x+r.w-1==x)) || r.w==1)
1301 dirs[ndirs++] = 2; /* up */
1304 struct rect r = find_rect(params2, grid, x-1, y);
1305 if ((r.w * r.h > 2 && (r.y==y || r.y+r.h-1==y)) || r.h==1)
1306 dirs[ndirs++] = 4; /* left */
1308 if (y < params2->h-1) {
1309 struct rect r = find_rect(params2, grid, x, y+1);
1310 if ((r.w * r.h > 2 && (r.x==x || r.x+r.w-1==x)) || r.w==1)
1311 dirs[ndirs++] = 8; /* down */
1318 which = random_upto(rs, ndirs);
1323 assert(x < params2->w+1);
1324 #ifdef GENERATION_DIAGNOSTICS
1325 printf("extending right\n");
1327 r1 = find_rect(params2, grid, x+1, y);
1338 #ifdef GENERATION_DIAGNOSTICS
1339 printf("extending up\n");
1341 r1 = find_rect(params2, grid, x, y-1);
1352 #ifdef GENERATION_DIAGNOSTICS
1353 printf("extending left\n");
1355 r1 = find_rect(params2, grid, x-1, y);
1365 assert(y < params2->h+1);
1366 #ifdef GENERATION_DIAGNOSTICS
1367 printf("extending down\n");
1369 r1 = find_rect(params2, grid, x, y+1);
1378 default: /* should never happen */
1379 assert(!"invalid direction");
1381 if (r1.h > 0 && r1.w > 0)
1382 place_rect(params2, grid, r1);
1383 place_rect(params2, grid, r2);
1387 * Sanity-check that there really is a 3x3
1388 * rectangle surrounding this singleton and it
1389 * contains absolutely everything we could
1394 assert(x > 0 && x < params2->w-1);
1395 assert(y > 0 && y < params2->h-1);
1397 for (xx = x-1; xx <= x+1; xx++)
1398 for (yy = y-1; yy <= y+1; yy++) {
1399 struct rect r = find_rect(params2,grid,xx,yy);
1402 assert(r.x+r.w-1 <= x+1);
1403 assert(r.y+r.h-1 <= y+1);
1408 #ifdef GENERATION_DIAGNOSTICS
1409 printf("need the 3x3 trick\n");
1413 * FIXME: If the maximum rectangle area for
1414 * this grid is less than 9, we ought to
1415 * subdivide the 3x3 in some fashion. There are
1416 * five other possibilities:
1419 * - a 4, a 3 and a 2
1421 * - a 3 and three 2s (two different arrangements).
1429 place_rect(params2, grid, r);
1437 * We have now constructed a grid of the size specified in
1438 * params2. Now we extend it into a grid of the size specified
1439 * in params. We do this in two passes: we extend it vertically
1440 * until it's the right height, then we transpose it, then
1441 * extend it vertically again (getting it effectively the right
1442 * width), then finally transpose again.
1444 for (i = 0; i < 2; i++) {
1445 int *grid2, *expand, *where;
1446 game_params params3real, *params3 = ¶ms3real;
1448 #ifdef GENERATION_DIAGNOSTICS
1449 printf("before expansion:\n");
1450 display_grid(params2, grid, NULL, TRUE);
1454 * Set up the new grid.
1456 grid2 = snewn(params2->w * params->h, int);
1457 expand = snewn(params2->h-1, int);
1458 where = snewn(params2->w, int);
1459 params3->w = params2->w;
1460 params3->h = params->h;
1463 * Decide which horizontal edges are going to get expanded,
1466 for (y = 0; y < params2->h-1; y++)
1468 for (y = params2->h; y < params->h; y++) {
1469 x = random_upto(rs, params2->h-1);
1473 #ifdef GENERATION_DIAGNOSTICS
1474 printf("expand[] = {");
1475 for (y = 0; y < params2->h-1; y++)
1476 printf(" %d", expand[y]);
1481 * Perform the expansion. The way this works is that we
1484 * - copy a row from grid into grid2
1486 * - invent some number of additional rows in grid2 where
1487 * there was previously only a horizontal line between
1488 * rows in grid, and make random decisions about where
1489 * among these to place each rectangle edge that ran
1492 for (y = y2 = y2last = 0; y < params2->h; y++) {
1494 * Copy a single line from row y of grid into row y2 of
1497 for (x = 0; x < params2->w; x++) {
1498 int val = index(params2, grid, x, y);
1499 if (val / params2->w == y && /* rect starts on this line */
1500 (y2 == 0 || /* we're at the very top, or... */
1501 index(params3, grid2, x, y2-1) / params3->w < y2last
1502 /* this rect isn't already started */))
1503 index(params3, grid2, x, y2) =
1504 INDEX(params3, val % params2->w, y2);
1506 index(params3, grid2, x, y2) =
1507 index(params3, grid2, x, y2-1);
1511 * If that was the last line, terminate the loop early.
1513 if (++y2 == params3->h)
1519 * Invent some number of additional lines. First walk
1520 * along this line working out where to put all the
1521 * edges that coincide with it.
1524 for (x = 0; x < params2->w; x++) {
1525 if (index(params2, grid, x, y) !=
1526 index(params2, grid, x, y+1)) {
1528 * This is a horizontal edge, so it needs
1532 (index(params2, grid, x-1, y) !=
1533 index(params2, grid, x, y) &&
1534 index(params2, grid, x-1, y+1) !=
1535 index(params2, grid, x, y+1))) {
1537 * Here we have the chance to make a new
1540 yx = random_upto(rs, expand[y]+1);
1543 * Here we just reuse the previous value of
1552 for (yx = 0; yx < expand[y]; yx++) {
1554 * Invent a single row. For each square in the row,
1555 * we copy the grid entry from the square above it,
1556 * unless we're starting the new rectangle here.
1558 for (x = 0; x < params2->w; x++) {
1559 if (yx == where[x]) {
1560 int val = index(params2, grid, x, y+1);
1562 val = INDEX(params3, val, y2);
1563 index(params3, grid2, x, y2) = val;
1565 index(params3, grid2, x, y2) =
1566 index(params3, grid2, x, y2-1);
1576 #ifdef GENERATION_DIAGNOSTICS
1577 printf("after expansion:\n");
1578 display_grid(params3, grid2, NULL, TRUE);
1583 params2->w = params3->h;
1584 params2->h = params3->w;
1586 grid = snewn(params2->w * params2->h, int);
1587 for (x = 0; x < params2->w; x++)
1588 for (y = 0; y < params2->h; y++) {
1589 int idx1 = INDEX(params2, x, y);
1590 int idx2 = INDEX(params3, y, x);
1594 tmp = (tmp % params3->w) * params2->w + (tmp / params3->w);
1603 params->w = params->h;
1607 #ifdef GENERATION_DIAGNOSTICS
1608 printf("after transposition:\n");
1609 display_grid(params2, grid, NULL, TRUE);
1614 * Run the solver to narrow down the possible number
1618 struct numberdata *nd;
1619 int nnumbers, i, ret;
1621 /* Count the rectangles. */
1623 for (y = 0; y < params->h; y++) {
1624 for (x = 0; x < params->w; x++) {
1625 int idx = INDEX(params, x, y);
1626 if (index(params, grid, x, y) == idx)
1631 nd = snewn(nnumbers, struct numberdata);
1633 /* Now set up each number's candidate position list. */
1635 for (y = 0; y < params->h; y++) {
1636 for (x = 0; x < params->w; x++) {
1637 int idx = INDEX(params, x, y);
1638 if (index(params, grid, x, y) == idx) {
1639 struct rect r = find_rect(params, grid, x, y);
1642 nd[i].area = r.w * r.h;
1643 nd[i].npoints = nd[i].area;
1644 nd[i].points = snewn(nd[i].npoints, struct point);
1646 for (j = 0; j < r.h; j++)
1647 for (k = 0; k < r.w; k++) {
1648 nd[i].points[m].x = k + r.x;
1649 nd[i].points[m].y = j + r.y;
1652 assert(m == nd[i].npoints);
1660 ret = rect_solver(params->w, params->h, nnumbers, nd,
1663 ret = 1; /* allow any number placement at all */
1667 * Now place the numbers according to the solver's
1670 numbers = snewn(params->w * params->h, int);
1672 for (y = 0; y < params->h; y++)
1673 for (x = 0; x < params->w; x++) {
1674 index(params, numbers, x, y) = 0;
1677 for (i = 0; i < nnumbers; i++) {
1678 int idx = random_upto(rs, nd[i].npoints);
1679 int x = nd[i].points[idx].x;
1680 int y = nd[i].points[idx].y;
1681 index(params,numbers,x,y) = nd[i].area;
1688 for (i = 0; i < nnumbers; i++)
1689 sfree(nd[i].points);
1693 * If we've succeeded, then terminate the loop.
1700 * Give up and go round again.
1706 * Store the solution in aux.
1712 len = 2 + (params->w-1)*params->h + (params->h-1)*params->w;
1713 ai = snewn(len, char);
1719 for (y = 0; y < params->h; y++)
1720 for (x = 1; x < params->w; x++)
1721 *p++ = (index(params, grid, x, y) !=
1722 index(params, grid, x-1, y) ? '1' : '0');
1724 for (y = 1; y < params->h; y++)
1725 for (x = 0; x < params->w; x++)
1726 *p++ = (index(params, grid, x, y) !=
1727 index(params, grid, x, y-1) ? '1' : '0');
1729 assert(p - ai == len-1);
1735 #ifdef GENERATION_DIAGNOSTICS
1736 display_grid(params, grid, numbers, FALSE);
1739 desc = snewn(11 * params->w * params->h, char);
1742 for (i = 0; i <= params->w * params->h; i++) {
1743 int n = (i < params->w * params->h ? numbers[i] : -1);
1750 int c = 'a' - 1 + run;
1754 run -= c - ('a' - 1);
1758 * If there's a number in the very top left or
1759 * bottom right, there's no point putting an
1760 * unnecessary _ before or after it.
1762 if (p > desc && n > 0)
1766 p += sprintf(p, "%d", n);
1778 static char *validate_desc(game_params *params, char *desc)
1780 int area = params->w * params->h;
1785 if (n >= 'a' && n <= 'z') {
1786 squares += n - 'a' + 1;
1787 } else if (n == '_') {
1789 } else if (n > '0' && n <= '9') {
1791 while (*desc >= '0' && *desc <= '9')
1794 return "Invalid character in game description";
1798 return "Not enough data to fill grid";
1801 return "Too much data to fit in grid";
1806 static unsigned char *get_correct(game_state *state)
1811 ret = snewn(state->w * state->h, unsigned char);
1812 memset(ret, 0xFF, state->w * state->h);
1814 for (x = 0; x < state->w; x++)
1815 for (y = 0; y < state->h; y++)
1816 if (index(state,ret,x,y) == 0xFF) {
1819 int num, area, valid;
1822 * Find a rectangle starting at this point.
1825 while (x+rw < state->w && !vedge(state,x+rw,y))
1828 while (y+rh < state->h && !hedge(state,x,y+rh))
1832 * We know what the dimensions of the rectangle
1833 * should be if it's there at all. Find out if we
1834 * really have a valid rectangle.
1837 /* Check the horizontal edges. */
1838 for (xx = x; xx < x+rw; xx++) {
1839 for (yy = y; yy <= y+rh; yy++) {
1840 int e = !HRANGE(state,xx,yy) || hedge(state,xx,yy);
1841 int ec = (yy == y || yy == y+rh);
1846 /* Check the vertical edges. */
1847 for (yy = y; yy < y+rh; yy++) {
1848 for (xx = x; xx <= x+rw; xx++) {
1849 int e = !VRANGE(state,xx,yy) || vedge(state,xx,yy);
1850 int ec = (xx == x || xx == x+rw);
1857 * If this is not a valid rectangle with no other
1858 * edges inside it, we just mark this square as not
1859 * complete and proceed to the next square.
1862 index(state, ret, x, y) = 0;
1867 * We have a rectangle. Now see what its area is,
1868 * and how many numbers are in it.
1872 for (xx = x; xx < x+rw; xx++) {
1873 for (yy = y; yy < y+rh; yy++) {
1875 if (grid(state,xx,yy)) {
1877 valid = FALSE; /* two numbers */
1878 num = grid(state,xx,yy);
1886 * Now fill in the whole rectangle based on the
1889 for (xx = x; xx < x+rw; xx++) {
1890 for (yy = y; yy < y+rh; yy++) {
1891 index(state, ret, xx, yy) = valid;
1899 static game_state *new_game(midend *me, game_params *params, char *desc)
1901 game_state *state = snew(game_state);
1904 state->w = params->w;
1905 state->h = params->h;
1907 area = state->w * state->h;
1909 state->grid = snewn(area, int);
1910 state->vedge = snewn(area, unsigned char);
1911 state->hedge = snewn(area, unsigned char);
1912 state->completed = state->cheated = FALSE;
1917 if (n >= 'a' && n <= 'z') {
1918 int run = n - 'a' + 1;
1919 assert(i + run <= area);
1921 state->grid[i++] = 0;
1922 } else if (n == '_') {
1924 } else if (n > '0' && n <= '9') {
1926 state->grid[i++] = atoi(desc-1);
1927 while (*desc >= '0' && *desc <= '9')
1930 assert(!"We can't get here");
1935 for (y = 0; y < state->h; y++)
1936 for (x = 0; x < state->w; x++)
1937 vedge(state,x,y) = hedge(state,x,y) = 0;
1939 state->correct = get_correct(state);
1944 static game_state *dup_game(game_state *state)
1946 game_state *ret = snew(game_state);
1951 ret->vedge = snewn(state->w * state->h, unsigned char);
1952 ret->hedge = snewn(state->w * state->h, unsigned char);
1953 ret->grid = snewn(state->w * state->h, int);
1954 ret->correct = snewn(ret->w * ret->h, unsigned char);
1956 ret->completed = state->completed;
1957 ret->cheated = state->cheated;
1959 memcpy(ret->grid, state->grid, state->w * state->h * sizeof(int));
1960 memcpy(ret->vedge, state->vedge, state->w*state->h*sizeof(unsigned char));
1961 memcpy(ret->hedge, state->hedge, state->w*state->h*sizeof(unsigned char));
1963 memcpy(ret->correct, state->correct, state->w*state->h*sizeof(unsigned char));
1968 static void free_game(game_state *state)
1971 sfree(state->vedge);
1972 sfree(state->hedge);
1973 sfree(state->correct);
1977 static char *solve_game(game_state *state, game_state *currstate,
1978 char *ai, char **error)
1980 unsigned char *vedge, *hedge;
1984 struct numberdata *nd;
1990 * Attempt the in-built solver.
1993 /* Set up each number's (very short) candidate position list. */
1994 for (i = n = 0; i < state->h * state->w; i++)
1998 nd = snewn(n, struct numberdata);
2000 for (i = j = 0; i < state->h * state->w; i++)
2001 if (state->grid[i]) {
2002 nd[j].area = state->grid[i];
2004 nd[j].points = snewn(1, struct point);
2005 nd[j].points[0].x = i % state->w;
2006 nd[j].points[0].y = i / state->w;
2012 vedge = snewn(state->w * state->h, unsigned char);
2013 hedge = snewn(state->w * state->h, unsigned char);
2014 memset(vedge, 0, state->w * state->h);
2015 memset(hedge, 0, state->w * state->h);
2017 rect_solver(state->w, state->h, n, nd, hedge, vedge, NULL);
2022 for (i = 0; i < n; i++)
2023 sfree(nd[i].points);
2026 len = 2 + (state->w-1)*state->h + (state->h-1)*state->w;
2027 ret = snewn(len, char);
2031 for (y = 0; y < state->h; y++)
2032 for (x = 1; x < state->w; x++)
2033 *p++ = vedge[y*state->w+x] ? '1' : '0';
2034 for (y = 1; y < state->h; y++)
2035 for (x = 0; x < state->w; x++)
2036 *p++ = hedge[y*state->w+x] ? '1' : '0';
2038 assert(p - ret == len);
2046 static char *game_text_format(game_state *state)
2048 char *ret, *p, buf[80];
2049 int i, x, y, col, maxlen;
2052 * First determine the number of spaces required to display a
2053 * number. We'll use at least two, because one looks a bit
2057 for (i = 0; i < state->w * state->h; i++) {
2058 x = sprintf(buf, "%d", state->grid[i]);
2059 if (col < x) col = x;
2063 * Now we know the exact total size of the grid we're going to
2064 * produce: it's got 2*h+1 rows, each containing w lots of col,
2065 * w+1 boundary characters and a trailing newline.
2067 maxlen = (2*state->h+1) * (state->w * (col+1) + 2);
2069 ret = snewn(maxlen+1, char);
2072 for (y = 0; y <= 2*state->h; y++) {
2073 for (x = 0; x <= 2*state->w; x++) {
2078 int v = grid(state, x/2, y/2);
2080 sprintf(buf, "%*d", col, v);
2082 sprintf(buf, "%*s", col, "");
2083 memcpy(p, buf, col);
2087 * Display a horizontal edge or nothing.
2089 int h = (y==0 || y==2*state->h ? 1 :
2090 HRANGE(state, x/2, y/2) && hedge(state, x/2, y/2));
2096 for (i = 0; i < col; i++)
2100 * Display a vertical edge or nothing.
2102 int v = (x==0 || x==2*state->w ? 1 :
2103 VRANGE(state, x/2, y/2) && vedge(state, x/2, y/2));
2110 * Display a corner, or a vertical edge, or a
2111 * horizontal edge, or nothing.
2113 int hl = (y==0 || y==2*state->h ? 1 :
2114 HRANGE(state, (x-1)/2, y/2) && hedge(state, (x-1)/2, y/2));
2115 int hr = (y==0 || y==2*state->h ? 1 :
2116 HRANGE(state, (x+1)/2, y/2) && hedge(state, (x+1)/2, y/2));
2117 int vu = (x==0 || x==2*state->w ? 1 :
2118 VRANGE(state, x/2, (y-1)/2) && vedge(state, x/2, (y-1)/2));
2119 int vd = (x==0 || x==2*state->w ? 1 :
2120 VRANGE(state, x/2, (y+1)/2) && vedge(state, x/2, (y+1)/2));
2121 if (!hl && !hr && !vu && !vd)
2123 else if (hl && hr && !vu && !vd)
2125 else if (!hl && !hr && vu && vd)
2134 assert(p - ret == maxlen);
2141 * These coordinates are 2 times the obvious grid coordinates.
2142 * Hence, the top left of the grid is (0,0), the grid point to
2143 * the right of that is (2,0), the one _below that_ is (2,2)
2144 * and so on. This is so that we can specify a drag start point
2145 * on an edge (one odd coordinate) or in the middle of a square
2146 * (two odd coordinates) rather than always at a corner.
2148 * -1,-1 means no drag is in progress.
2155 * This flag is set as soon as a dragging action moves the
2156 * mouse pointer away from its starting point, so that even if
2157 * the pointer _returns_ to its starting point the action is
2158 * treated as a small drag rather than a click.
2162 * These are the co-ordinates of the top-left and bottom-right squares
2163 * in the drag box, respectively, or -1 otherwise.
2171 static game_ui *new_ui(game_state *state)
2173 game_ui *ui = snew(game_ui);
2174 ui->drag_start_x = -1;
2175 ui->drag_start_y = -1;
2176 ui->drag_end_x = -1;
2177 ui->drag_end_y = -1;
2178 ui->dragged = FALSE;
2186 static void free_ui(game_ui *ui)
2191 static char *encode_ui(game_ui *ui)
2196 static void decode_ui(game_ui *ui, char *encoding)
2200 static void coord_round(float x, float y, int *xr, int *yr)
2202 float xs, ys, xv, yv, dx, dy, dist;
2205 * Find the nearest square-centre.
2207 xs = (float)floor(x) + 0.5F;
2208 ys = (float)floor(y) + 0.5F;
2211 * And find the nearest grid vertex.
2213 xv = (float)floor(x + 0.5F);
2214 yv = (float)floor(y + 0.5F);
2217 * We allocate clicks in parts of the grid square to either
2218 * corners, edges or square centres, as follows:
2234 * In other words: we measure the square distance (i.e.
2235 * max(dx,dy)) from the click to the nearest corner, and if
2236 * it's within CORNER_TOLERANCE then we return a corner click.
2237 * We measure the square distance from the click to the nearest
2238 * centre, and if that's within CENTRE_TOLERANCE we return a
2239 * centre click. Failing that, we find which of the two edge
2240 * centres is nearer to the click and return that edge.
2244 * Check for corner click.
2246 dx = (float)fabs(x - xv);
2247 dy = (float)fabs(y - yv);
2248 dist = (dx > dy ? dx : dy);
2249 if (dist < CORNER_TOLERANCE) {
2254 * Check for centre click.
2256 dx = (float)fabs(x - xs);
2257 dy = (float)fabs(y - ys);
2258 dist = (dx > dy ? dx : dy);
2259 if (dist < CENTRE_TOLERANCE) {
2260 *xr = 1 + 2 * (int)xs;
2261 *yr = 1 + 2 * (int)ys;
2264 * Failing both of those, see which edge we're closer to.
2265 * Conveniently, this is simply done by testing the relative
2266 * magnitude of dx and dy (which are currently distances from
2267 * the square centre).
2270 /* Vertical edge: x-coord of corner,
2271 * y-coord of square centre. */
2273 *yr = 1 + 2 * (int)floor(ys);
2275 /* Horizontal edge: x-coord of square centre,
2276 * y-coord of corner. */
2277 *xr = 1 + 2 * (int)floor(xs);
2285 * Returns TRUE if it has made any change to the grid.
2287 static int grid_draw_rect(game_state *state,
2288 unsigned char *hedge, unsigned char *vedge,
2290 int x1, int y1, int x2, int y2)
2293 int changed = FALSE;
2296 * Draw horizontal edges of rectangles.
2298 for (x = x1; x < x2; x++)
2299 for (y = y1; y <= y2; y++)
2300 if (HRANGE(state,x,y)) {
2301 int val = index(state,hedge,x,y);
2302 if (y == y1 || y == y2)
2306 changed = changed || (index(state,hedge,x,y) != val);
2308 index(state,hedge,x,y) = val;
2312 * Draw vertical edges of rectangles.
2314 for (y = y1; y < y2; y++)
2315 for (x = x1; x <= x2; x++)
2316 if (VRANGE(state,x,y)) {
2317 int val = index(state,vedge,x,y);
2318 if (x == x1 || x == x2)
2322 changed = changed || (index(state,vedge,x,y) != val);
2324 index(state,vedge,x,y) = val;
2330 static int ui_draw_rect(game_state *state, game_ui *ui,
2331 unsigned char *hedge, unsigned char *vedge, int c,
2334 return grid_draw_rect(state, hedge, vedge, c, really,
2335 ui->x1, ui->y1, ui->x2, ui->y2);
2338 static void game_changed_state(game_ui *ui, game_state *oldstate,
2339 game_state *newstate)
2343 struct game_drawstate {
2346 unsigned long *visible;
2349 static char *interpret_move(game_state *from, game_ui *ui, game_drawstate *ds,
2350 int x, int y, int button)
2353 int startdrag = FALSE, enddrag = FALSE, active = FALSE;
2356 button &= ~MOD_MASK;
2358 if (button == LEFT_BUTTON) {
2360 } else if (button == LEFT_RELEASE) {
2362 } else if (button != LEFT_DRAG) {
2366 coord_round(FROMCOORD((float)x), FROMCOORD((float)y), &xc, &yc);
2369 xc >= 0 && xc <= 2*from->w &&
2370 yc >= 0 && yc <= 2*from->h) {
2372 ui->drag_start_x = xc;
2373 ui->drag_start_y = yc;
2374 ui->drag_end_x = xc;
2375 ui->drag_end_y = yc;
2376 ui->dragged = FALSE;
2380 if (ui->drag_start_x >= 0 &&
2381 (xc != ui->drag_end_x || yc != ui->drag_end_y)) {
2384 ui->drag_end_x = xc;
2385 ui->drag_end_y = yc;
2389 if (xc >= 0 && xc <= 2*from->w &&
2390 yc >= 0 && yc <= 2*from->h) {
2391 ui->x1 = ui->drag_start_x;
2392 ui->x2 = ui->drag_end_x;
2393 if (ui->x2 < ui->x1) { t = ui->x1; ui->x1 = ui->x2; ui->x2 = t; }
2395 ui->y1 = ui->drag_start_y;
2396 ui->y2 = ui->drag_end_y;
2397 if (ui->y2 < ui->y1) { t = ui->y1; ui->y1 = ui->y2; ui->y2 = t; }
2399 ui->x1 = ui->x1 / 2; /* rounds down */
2400 ui->x2 = (ui->x2+1) / 2; /* rounds up */
2401 ui->y1 = ui->y1 / 2; /* rounds down */
2402 ui->y2 = (ui->y2+1) / 2; /* rounds up */
2413 if (enddrag && (ui->drag_start_x >= 0)) {
2414 if (xc >= 0 && xc <= 2*from->w &&
2415 yc >= 0 && yc <= 2*from->h) {
2418 if (ui_draw_rect(from, ui, from->hedge,
2419 from->vedge, 1, FALSE)) {
2420 sprintf(buf, "R%d,%d,%d,%d",
2421 ui->x1, ui->y1, ui->x2 - ui->x1, ui->y2 - ui->y1);
2425 if ((xc & 1) && !(yc & 1) && HRANGE(from,xc/2,yc/2)) {
2426 sprintf(buf, "H%d,%d", xc/2, yc/2);
2429 if ((yc & 1) && !(xc & 1) && VRANGE(from,xc/2,yc/2)) {
2430 sprintf(buf, "V%d,%d", xc/2, yc/2);
2436 ui->drag_start_x = -1;
2437 ui->drag_start_y = -1;
2438 ui->drag_end_x = -1;
2439 ui->drag_end_y = -1;
2444 ui->dragged = FALSE;
2449 return ret; /* a move has been made */
2451 return ""; /* UI activity has occurred */
2456 static game_state *execute_move(game_state *from, char *move)
2459 int x1, y1, x2, y2, mode;
2461 if (move[0] == 'S') {
2465 ret = dup_game(from);
2466 ret->cheated = TRUE;
2468 for (y = 0; y < ret->h; y++)
2469 for (x = 1; x < ret->w; x++) {
2470 vedge(ret, x, y) = (*p == '1');
2473 for (y = 1; y < ret->h; y++)
2474 for (x = 0; x < ret->w; x++) {
2475 hedge(ret, x, y) = (*p == '1');
2479 sfree(ret->correct);
2480 ret->correct = get_correct(ret);
2484 } else if (move[0] == 'R' &&
2485 sscanf(move+1, "%d,%d,%d,%d", &x1, &y1, &x2, &y2) == 4 &&
2486 x1 >= 0 && x2 >= 0 && x1+x2 <= from->w &&
2487 y1 >= 0 && y2 >= 0 && y1+y2 <= from->h) {
2491 } else if ((move[0] == 'H' || move[0] == 'V') &&
2492 sscanf(move+1, "%d,%d", &x1, &y1) == 2 &&
2493 (move[0] == 'H' ? HRANGE(from, x1, y1) :
2494 VRANGE(from, x1, y1))) {
2497 return NULL; /* can't parse move string */
2499 ret = dup_game(from);
2502 grid_draw_rect(ret, ret->hedge, ret->vedge, 1, TRUE, x1, y1, x2, y2);
2503 } else if (mode == 'H') {
2504 hedge(ret,x1,y1) = !hedge(ret,x1,y1);
2505 } else if (mode == 'V') {
2506 vedge(ret,x1,y1) = !vedge(ret,x1,y1);
2509 sfree(ret->correct);
2510 ret->correct = get_correct(ret);
2513 * We've made a real change to the grid. Check to see
2514 * if the game has been completed.
2516 if (!ret->completed) {
2520 for (x = 0; x < ret->w; x++)
2521 for (y = 0; y < ret->h; y++)
2522 if (!index(ret, ret->correct, x, y))
2526 ret->completed = TRUE;
2532 /* ----------------------------------------------------------------------
2536 #define CORRECT (1L<<16)
2538 #define COLOUR(k) ( (k)==1 ? COL_LINE : COL_DRAG )
2539 #define MAX4(x,y,z,w) ( max(max(x,y),max(z,w)) )
2541 static void game_compute_size(game_params *params, int tilesize,
2544 /* Ick: fake up `ds->tilesize' for macro expansion purposes */
2545 struct { int tilesize; } ads, *ds = &ads;
2546 ads.tilesize = tilesize;
2548 *x = params->w * TILE_SIZE + 2*BORDER + 1;
2549 *y = params->h * TILE_SIZE + 2*BORDER + 1;
2552 static void game_set_size(drawing *dr, game_drawstate *ds,
2553 game_params *params, int tilesize)
2555 ds->tilesize = tilesize;
2558 static float *game_colours(frontend *fe, int *ncolours)
2560 float *ret = snewn(3 * NCOLOURS, float);
2562 frontend_default_colour(fe, &ret[COL_BACKGROUND * 3]);
2564 ret[COL_GRID * 3 + 0] = 0.5F * ret[COL_BACKGROUND * 3 + 0];
2565 ret[COL_GRID * 3 + 1] = 0.5F * ret[COL_BACKGROUND * 3 + 1];
2566 ret[COL_GRID * 3 + 2] = 0.5F * ret[COL_BACKGROUND * 3 + 2];
2568 ret[COL_DRAG * 3 + 0] = 1.0F;
2569 ret[COL_DRAG * 3 + 1] = 0.0F;
2570 ret[COL_DRAG * 3 + 2] = 0.0F;
2572 ret[COL_CORRECT * 3 + 0] = 0.75F * ret[COL_BACKGROUND * 3 + 0];
2573 ret[COL_CORRECT * 3 + 1] = 0.75F * ret[COL_BACKGROUND * 3 + 1];
2574 ret[COL_CORRECT * 3 + 2] = 0.75F * ret[COL_BACKGROUND * 3 + 2];
2576 ret[COL_LINE * 3 + 0] = 0.0F;
2577 ret[COL_LINE * 3 + 1] = 0.0F;
2578 ret[COL_LINE * 3 + 2] = 0.0F;
2580 ret[COL_TEXT * 3 + 0] = 0.0F;
2581 ret[COL_TEXT * 3 + 1] = 0.0F;
2582 ret[COL_TEXT * 3 + 2] = 0.0F;
2584 *ncolours = NCOLOURS;
2588 static game_drawstate *game_new_drawstate(drawing *dr, game_state *state)
2590 struct game_drawstate *ds = snew(struct game_drawstate);
2593 ds->started = FALSE;
2596 ds->visible = snewn(ds->w * ds->h, unsigned long);
2597 ds->tilesize = 0; /* not decided yet */
2598 for (i = 0; i < ds->w * ds->h; i++)
2599 ds->visible[i] = 0xFFFF;
2604 static void game_free_drawstate(drawing *dr, game_drawstate *ds)
2610 static void draw_tile(drawing *dr, game_drawstate *ds, game_state *state,
2611 int x, int y, unsigned char *hedge, unsigned char *vedge,
2612 unsigned char *corners, int correct)
2614 int cx = COORD(x), cy = COORD(y);
2617 draw_rect(dr, cx, cy, TILE_SIZE+1, TILE_SIZE+1, COL_GRID);
2618 draw_rect(dr, cx+1, cy+1, TILE_SIZE-1, TILE_SIZE-1,
2619 correct ? COL_CORRECT : COL_BACKGROUND);
2621 if (grid(state,x,y)) {
2622 sprintf(str, "%d", grid(state,x,y));
2623 draw_text(dr, cx+TILE_SIZE/2, cy+TILE_SIZE/2, FONT_VARIABLE,
2624 TILE_SIZE/2, ALIGN_HCENTRE | ALIGN_VCENTRE, COL_TEXT, str);
2630 if (!HRANGE(state,x,y) || index(state,hedge,x,y))
2631 draw_rect(dr, cx, cy, TILE_SIZE+1, 2,
2632 HRANGE(state,x,y) ? COLOUR(index(state,hedge,x,y)) :
2634 if (!HRANGE(state,x,y+1) || index(state,hedge,x,y+1))
2635 draw_rect(dr, cx, cy+TILE_SIZE-1, TILE_SIZE+1, 2,
2636 HRANGE(state,x,y+1) ? COLOUR(index(state,hedge,x,y+1)) :
2638 if (!VRANGE(state,x,y) || index(state,vedge,x,y))
2639 draw_rect(dr, cx, cy, 2, TILE_SIZE+1,
2640 VRANGE(state,x,y) ? COLOUR(index(state,vedge,x,y)) :
2642 if (!VRANGE(state,x+1,y) || index(state,vedge,x+1,y))
2643 draw_rect(dr, cx+TILE_SIZE-1, cy, 2, TILE_SIZE+1,
2644 VRANGE(state,x+1,y) ? COLOUR(index(state,vedge,x+1,y)) :
2650 if (index(state,corners,x,y))
2651 draw_rect(dr, cx, cy, 2, 2,
2652 COLOUR(index(state,corners,x,y)));
2653 if (x+1 < state->w && index(state,corners,x+1,y))
2654 draw_rect(dr, cx+TILE_SIZE-1, cy, 2, 2,
2655 COLOUR(index(state,corners,x+1,y)));
2656 if (y+1 < state->h && index(state,corners,x,y+1))
2657 draw_rect(dr, cx, cy+TILE_SIZE-1, 2, 2,
2658 COLOUR(index(state,corners,x,y+1)));
2659 if (x+1 < state->w && y+1 < state->h && index(state,corners,x+1,y+1))
2660 draw_rect(dr, cx+TILE_SIZE-1, cy+TILE_SIZE-1, 2, 2,
2661 COLOUR(index(state,corners,x+1,y+1)));
2663 draw_update(dr, cx, cy, TILE_SIZE+1, TILE_SIZE+1);
2666 static void game_redraw(drawing *dr, game_drawstate *ds, game_state *oldstate,
2667 game_state *state, int dir, game_ui *ui,
2668 float animtime, float flashtime)
2671 unsigned char *hedge, *vedge, *corners;
2674 hedge = snewn(state->w*state->h, unsigned char);
2675 vedge = snewn(state->w*state->h, unsigned char);
2676 memcpy(hedge, state->hedge, state->w*state->h);
2677 memcpy(vedge, state->vedge, state->w*state->h);
2678 ui_draw_rect(state, ui, hedge, vedge, 2, TRUE);
2680 hedge = state->hedge;
2681 vedge = state->vedge;
2684 corners = snewn(state->w * state->h, unsigned char);
2685 memset(corners, 0, state->w * state->h);
2686 for (x = 0; x < state->w; x++)
2687 for (y = 0; y < state->h; y++) {
2689 int e = index(state, vedge, x, y);
2690 if (index(state,corners,x,y) < e)
2691 index(state,corners,x,y) = e;
2692 if (y+1 < state->h &&
2693 index(state,corners,x,y+1) < e)
2694 index(state,corners,x,y+1) = e;
2697 int e = index(state, hedge, x, y);
2698 if (index(state,corners,x,y) < e)
2699 index(state,corners,x,y) = e;
2700 if (x+1 < state->w &&
2701 index(state,corners,x+1,y) < e)
2702 index(state,corners,x+1,y) = e;
2708 state->w * TILE_SIZE + 2*BORDER + 1,
2709 state->h * TILE_SIZE + 2*BORDER + 1, COL_BACKGROUND);
2710 draw_rect(dr, COORD(0)-1, COORD(0)-1,
2711 ds->w*TILE_SIZE+3, ds->h*TILE_SIZE+3, COL_LINE);
2713 draw_update(dr, 0, 0,
2714 state->w * TILE_SIZE + 2*BORDER + 1,
2715 state->h * TILE_SIZE + 2*BORDER + 1);
2718 for (x = 0; x < state->w; x++)
2719 for (y = 0; y < state->h; y++) {
2720 unsigned long c = 0;
2722 if (HRANGE(state,x,y))
2723 c |= index(state,hedge,x,y);
2724 if (HRANGE(state,x,y+1))
2725 c |= index(state,hedge,x,y+1) << 2;
2726 if (VRANGE(state,x,y))
2727 c |= index(state,vedge,x,y) << 4;
2728 if (VRANGE(state,x+1,y))
2729 c |= index(state,vedge,x+1,y) << 6;
2730 c |= index(state,corners,x,y) << 8;
2732 c |= index(state,corners,x+1,y) << 10;
2734 c |= index(state,corners,x,y+1) << 12;
2735 if (x+1 < state->w && y+1 < state->h)
2736 /* cast to prevent 2<<14 sign-extending on promotion to long */
2737 c |= (unsigned long)index(state,corners,x+1,y+1) << 14;
2738 if (index(state, state->correct, x, y) && !flashtime)
2741 if (index(ds,ds->visible,x,y) != c) {
2742 draw_tile(dr, ds, state, x, y, hedge, vedge, corners,
2743 (c & CORRECT) ? 1 : 0);
2744 index(ds,ds->visible,x,y) = c;
2751 if (ui->x1 >= 0 && ui->y1 >= 0 &&
2752 ui->x2 >= 0 && ui->y2 >= 0) {
2753 sprintf(buf, "%dx%d ",
2761 strcat(buf, "Auto-solved.");
2762 else if (state->completed)
2763 strcat(buf, "COMPLETED!");
2765 status_bar(dr, buf);
2768 if (hedge != state->hedge) {
2776 static float game_anim_length(game_state *oldstate,
2777 game_state *newstate, int dir, game_ui *ui)
2782 static float game_flash_length(game_state *oldstate,
2783 game_state *newstate, int dir, game_ui *ui)
2785 if (!oldstate->completed && newstate->completed &&
2786 !oldstate->cheated && !newstate->cheated)
2791 static int game_timing_state(game_state *state, game_ui *ui)
2796 static void game_print_size(game_params *params, float *x, float *y)
2801 * I'll use 5mm squares by default.
2803 game_compute_size(params, 500, &pw, &ph);
2808 static void game_print(drawing *dr, game_state *state, int tilesize)
2810 int w = state->w, h = state->h;
2811 int ink = print_mono_colour(dr, 0);
2814 /* Ick: fake up `ds->tilesize' for macro expansion purposes */
2815 game_drawstate ads, *ds = &ads;
2816 game_set_size(dr, ds, NULL, tilesize);
2821 print_line_width(dr, TILE_SIZE / 10);
2822 draw_rect_outline(dr, COORD(0), COORD(0), w*TILE_SIZE, h*TILE_SIZE, ink);
2825 * Grid. We have to make the grid lines particularly thin,
2826 * because users will be drawing lines _along_ them and we want
2827 * those lines to be visible.
2829 print_line_width(dr, TILE_SIZE / 256);
2830 for (x = 1; x < w; x++)
2831 draw_line(dr, COORD(x), COORD(0), COORD(x), COORD(h), ink);
2832 for (y = 1; y < h; y++)
2833 draw_line(dr, COORD(0), COORD(y), COORD(w), COORD(y), ink);
2838 print_line_width(dr, TILE_SIZE / 10);
2839 for (y = 0; y <= h; y++)
2840 for (x = 0; x <= w; x++) {
2841 if (HRANGE(state,x,y) && hedge(state,x,y))
2842 draw_line(dr, COORD(x), COORD(y), COORD(x+1), COORD(y), ink);
2843 if (VRANGE(state,x,y) && vedge(state,x,y))
2844 draw_line(dr, COORD(x), COORD(y), COORD(x), COORD(y+1), ink);
2850 for (y = 0; y < h; y++)
2851 for (x = 0; x < w; x++)
2852 if (grid(state,x,y)) {
2854 sprintf(str, "%d", grid(state,x,y));
2855 draw_text(dr, COORD(x)+TILE_SIZE/2, COORD(y)+TILE_SIZE/2,
2856 FONT_VARIABLE, TILE_SIZE/2,
2857 ALIGN_HCENTRE | ALIGN_VCENTRE, ink, str);
2862 #define thegame rect
2865 const struct game thegame = {
2866 "Rectangles", "games.rectangles", "rectangles",
2873 TRUE, game_configure, custom_params,
2881 TRUE, game_text_format,
2889 PREFERRED_TILE_SIZE, game_compute_size, game_set_size,
2892 game_free_drawstate,
2896 TRUE, FALSE, game_print_size, game_print,
2897 TRUE, /* wants_statusbar */
2898 FALSE, game_timing_state,