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 on singleton removal by making an aesthetic choice
13 * about which of the options to take.
15 * - When doing the 3x3 trick in singleton removal, limit the size
16 * of the generated rectangles in accordance with the max
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
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)
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)
63 #define PREFERRED_TILE_SIZE 24
64 #define TILE_SIZE (ds->tilesize)
65 #define BORDER (TILE_SIZE * 3 / 4)
67 #define CORNER_TOLERANCE 0.15F
68 #define CENTRE_TOLERANCE 0.15F
70 #define FLASH_TIME 0.13F
72 #define COORD(x) ( (x) * TILE_SIZE + BORDER )
73 #define FROMCOORD(x) ( ((x) - BORDER) / TILE_SIZE )
77 int *grid; /* contains the numbers */
78 unsigned char *vedge; /* (w+1) x h */
79 unsigned char *hedge; /* w x (h+1) */
80 int completed, cheated;
83 static game_params *default_params(void)
85 game_params *ret = snew(game_params);
88 ret->expandfactor = 0.0F;
94 static int game_fetch_preset(int i, char **name, game_params **params)
101 case 0: w = 7, h = 7; break;
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;
107 case 5: w = 17, h = 17; break;
108 case 6: w = 19, h = 19; break;
110 default: return FALSE;
113 sprintf(buf, "%dx%d", w, h);
115 *params = ret = snew(game_params);
118 ret->expandfactor = 0.0F;
123 static void free_params(game_params *params)
128 static game_params *dup_params(game_params *params)
130 game_params *ret = snew(game_params);
131 *ret = *params; /* structure copy */
135 static void decode_params(game_params *ret, char const *string)
137 ret->w = ret->h = atoi(string);
138 while (*string && isdigit((unsigned char)*string)) string++;
139 if (*string == 'x') {
141 ret->h = atoi(string);
142 while (*string && isdigit((unsigned char)*string)) string++;
144 if (*string == 'e') {
146 ret->expandfactor = atof(string);
148 (*string == '.' || isdigit((unsigned char)*string))) string++;
150 if (*string == 'a') {
156 static char *encode_params(game_params *params, int full)
160 sprintf(data, "%dx%d", params->w, params->h);
161 if (full && params->expandfactor)
162 sprintf(data + strlen(data), "e%g", params->expandfactor);
163 if (full && !params->unique)
169 static config_item *game_configure(game_params *params)
174 ret = snewn(5, config_item);
176 ret[0].name = "Width";
177 ret[0].type = C_STRING;
178 sprintf(buf, "%d", params->w);
179 ret[0].sval = dupstr(buf);
182 ret[1].name = "Height";
183 ret[1].type = C_STRING;
184 sprintf(buf, "%d", params->h);
185 ret[1].sval = dupstr(buf);
188 ret[2].name = "Expansion factor";
189 ret[2].type = C_STRING;
190 sprintf(buf, "%g", params->expandfactor);
191 ret[2].sval = dupstr(buf);
194 ret[3].name = "Ensure unique solution";
195 ret[3].type = C_BOOLEAN;
197 ret[3].ival = params->unique;
207 static game_params *custom_params(config_item *cfg)
209 game_params *ret = snew(game_params);
211 ret->w = atoi(cfg[0].sval);
212 ret->h = atoi(cfg[1].sval);
213 ret->expandfactor = atof(cfg[2].sval);
214 ret->unique = cfg[3].ival;
219 static char *validate_params(game_params *params)
221 if (params->w <= 0 || params->h <= 0)
222 return "Width and height must both be greater than zero";
223 if (params->w*params->h < 2)
224 return "Grid area must be greater than one";
225 if (params->expandfactor < 0.0F)
226 return "Expansion factor may not be negative";
247 struct point *points;
250 /* ----------------------------------------------------------------------
251 * Solver for Rectangles games.
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
261 static void remove_rect_placement(int w, int h,
262 struct rectlist *rectpositions,
264 int rectnum, int placement)
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);
277 * Decrement each entry in the overlaps array to reflect the
278 * removal of this rectangle placement.
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;
285 assert(overlaps[(rectnum * h + y) * w + x] != 0);
287 if (overlaps[(rectnum * h + y) * w + x] > 0)
288 overlaps[(rectnum * h + y) * w + x]--;
293 * Remove the placement from the list of positions for that
294 * rectangle, by interchanging it with the one on the end.
296 if (placement < rectpositions[rectnum].n - 1) {
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;
304 rectpositions[rectnum].n--;
307 static void remove_number_placement(int w, int h, struct numberdata *number,
308 int index, int *rectbyplace)
311 * Remove the entry from the rectbyplace array.
313 rectbyplace[number->points[index].y * w + number->points[index].x] = -1;
316 * Remove the placement from the list of candidates for that
317 * number, by interchanging it with the one on the end.
319 if (index < number->npoints - 1) {
322 t = number->points[number->npoints - 1];
323 number->points[number->npoints - 1] = number->points[index];
324 number->points[index] = t;
329 static int rect_solver(int w, int h, int nrects, struct numberdata *numbers,
330 game_state *result, random_state *rs)
332 struct rectlist *rectpositions;
333 int *overlaps, *rectbyplace, *workspace;
337 * Start by setting up a list of candidate positions for each
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;
345 int rlistn, rlistsize;
348 * For each rectangle, begin by finding the bounding
349 * rectangle of its candidate number placements.
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;
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.
368 rlistn = rlistsize = 0;
370 for (rw = 1; rw <= area && rw <= w; rw++) {
379 for (y = miny - rh + 1; y <= maxy; y++) {
380 if (y < 0 || y+rh > h)
383 for (x = minx - rw + 1; x <= maxx; x++) {
384 if (x < 0 || x+rw > w)
388 * See if we can find a candidate number
389 * placement within this rectangle.
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)
398 if (j < numbers[i].npoints) {
400 * Add this to the list of candidate
401 * placements for this rectangle.
403 if (rlistn >= rlistsize) {
404 rlistsize = rlistn + 32;
405 rlist = sresize(rlist, rlistsize, struct rect);
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);
422 rectpositions[i].rects = rlist;
423 rectpositions[i].n = rlistn;
427 * Next, construct a multidimensional array tracking how many
428 * candidate positions for each rectangle overlap each square.
430 * Indexing of this array is by the formula
432 * overlaps[(rectindex * h + y) * w + x]
434 overlaps = snewn(nrects * w * h, int);
435 memset(overlaps, 0, nrects * w * h * sizeof(int));
436 for (i = 0; i < nrects; i++) {
439 for (j = 0; j < rectpositions[i].n; j++) {
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]++;
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.)
462 rectbyplace = snewn(w * h, int);
463 for (i = 0; i < w*h; i++)
466 for (i = 0; i < nrects; i++) {
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;
473 assert(rectbyplace[y * w + x] == -1);
474 rectbyplace[y * w + x] = i;
478 workspace = snewn(nrects, int);
481 * Now run the actual deduction loop.
484 int done_something = FALSE;
486 #ifdef SOLVER_DIAGNOSTICS
487 printf("starting deduction loop\n");
489 for (i = 0; i < nrects; i++) {
490 printf("rect %d overlaps:\n", i);
493 for (y = 0; y < h; y++) {
494 for (x = 0; x < w; x++) {
495 printf("%3d", overlaps[(i * h + y) * w + x]);
501 printf("rectbyplace:\n");
504 for (y = 0; y < h; y++) {
505 for (x = 0; x < w; x++) {
506 printf("%3d", rectbyplace[y * w + x]);
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.
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) {
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);
531 for (j = 0; j < nrects; j++)
532 overlaps[(j * h + y) * w + x] = -1;
534 overlaps[(i * h + y) * w + x] = -2;
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
545 for (i = 0; i < nrects; i++) {
546 int minx, miny, maxx, maxy, xx, yy, j;
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;
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;
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",
574 for (j = 0; j < nrects; j++)
575 overlaps[(j * h + yy) * w + xx] = -1;
577 overlaps[(i * h + yy) * w + xx] = -2;
582 * Rectangle-focused deduction. Look at each rectangle in
583 * turn and try to rule out some of its candidate
586 for (i = 0; i < nrects; i++) {
589 for (j = 0; j < rectpositions[i].n; j++) {
593 for (k = 0; k < nrects; k++)
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;
601 if (overlaps[(i * h + y) * w + x] == -1) {
603 * This placement overlaps a square
604 * which is _known_ to be part of
605 * another rectangle. Therefore we must
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,
620 if (rectbyplace[y * w + x] != -1) {
622 * This placement overlaps one of the
623 * candidate number placements for some
624 * rectangle. Count it.
626 workspace[rectbyplace[y * w + x]]++;
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.
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",
644 rectpositions[i].rects[j].x,
645 rectpositions[i].rects[j].y,
646 rectpositions[i].rects[j].w,
647 rectpositions[i].rects[j].h,
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
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",
666 rectpositions[i].rects[j].x,
667 rectpositions[i].rects[j].y,
668 rectpositions[i].rects[j].w,
669 rectpositions[i].rects[j].h);
676 remove_rect_placement(w, h, rectpositions, overlaps, i, j);
678 j--; /* don't skip over next placement */
680 done_something = TRUE;
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.
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 */
700 for (i = 0; i < nrects; i++)
701 if (overlaps[(i * h + y) * w + x] > 0)
708 * Now we can rule out all placements for
709 * rectangle `index' which _don't_ contain
712 #ifdef SOLVER_DIAGNOSTICS
713 printf("square %d,%d can only be in rectangle %d\n",
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,
723 j--; /* don't skip over next placement */
724 done_something = TRUE;
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
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.
754 int nrpns = 0, rpnsize = 0;
757 for (i = 0; i < nrects; i++) {
758 for (j = 0; j < rectpositions[i].n; j++) {
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;
766 if (rectbyplace[y * w + x] >= 0 &&
767 rectbyplace[y * w + x] != i) {
769 * Add this to the list of
770 * winnowing possibilities.
772 if (nrpns >= rpnsize) {
773 rpnsize = rpnsize * 3 / 2 + 32;
774 rpns = sresize(rpns, rpnsize, struct rpn);
776 rpns[nrpns].rect = i;
777 rpns[nrpns].placement = j;
778 rpns[nrpns].number = rectbyplace[y * w + x];
787 #ifdef SOLVER_DIAGNOSTICS
788 printf("%d candidate rect placements we could eliminate\n", nrpns);
792 * Now choose one of these unwanted rectangle
793 * placements, and eliminate it.
795 int index = random_upto(rs, nrpns);
797 struct rpn rpn = rpns[index];
804 r = rectpositions[i].rects[j];
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.
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);
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;
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",
829 remove_number_placement(w, h, &numbers[k],
831 m--; /* don't skip the next one */
832 done_something = TRUE;
838 if (!done_something) {
839 #ifdef SOLVER_DIAGNOSTICS
840 printf("terminating deduction loop\n");
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);
852 assert(rectpositions[i].n > 0);
853 if (rectpositions[i].n > 1) {
857 * Place the rectangle in its only possible position.
860 struct rect *r = &rectpositions[i].rects[0];
862 for (y = 0; y < r->h; y++) {
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;
868 for (x = 0; x < r->w; x++) {
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;
878 * Free up all allocated storage.
883 for (i = 0; i < nrects; i++)
884 sfree(rectpositions[i].rects);
885 sfree(rectpositions);
890 /* ----------------------------------------------------------------------
891 * Grid generation code.
894 static struct rectlist *get_rectlist(game_params *params, int *grid)
899 struct rect *rects = NULL;
900 int nrects = 0, rectsize = 0;
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.
907 maxarea = params->w * params->h / 6;
911 for (rw = 1; rw <= params->w; rw++)
912 for (rh = 1; rh <= params->h; rh++) {
913 if (rw * rh > maxarea)
917 for (x = 0; x <= params->w - rw; x++)
918 for (y = 0; y <= params->h - rh; y++) {
919 if (nrects >= rectsize) {
920 rectsize = nrects + 256;
921 rects = sresize(rects, rectsize, struct rect);
926 rects[nrects].w = rw;
927 rects[nrects].h = rh;
933 struct rectlist *ret;
934 ret = snew(struct rectlist);
939 assert(rects == NULL); /* hence no need to free */
944 static void free_rectlist(struct rectlist *list)
950 static void place_rect(game_params *params, int *grid, struct rect r)
952 int idx = INDEX(params, r.x, r.y);
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;
959 #ifdef GENERATION_DIAGNOSTICS
960 printf(" placing rectangle at (%d,%d) size %d x %d\n",
965 static struct rect find_rect(game_params *params, int *grid, int x, int y)
971 * Find the top left of the rectangle.
973 idx = index(params, grid, x, y);
979 return r; /* 1x1 singleton here */
986 * Find the width and height of the rectangle.
989 (x+w < params->w && index(params,grid,x+w,y)==idx);
992 (y+h < params->h && index(params,grid,x,y+h)==idx);
1003 #ifdef GENERATION_DIAGNOSTICS
1004 static void display_grid(game_params *params, int *grid, int *numbers, int all)
1006 unsigned char *egrid = snewn((params->w*2+3) * (params->h*2+3),
1009 int r = (params->w*2+3);
1011 memset(egrid, 0, (params->w*2+3) * (params->h*2+3));
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;
1026 for (y = 1; y < 2*params->h+2; y++) {
1027 for (x = 1; x < 2*params->w+2; x++) {
1029 int k = numbers ? index(params, numbers, x/2-1, y/2-1) : 0;
1030 if (k || (all && numbers)) printf("%2d", k); else printf(" ");
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 = '|';
1037 if (!(x&1)) putchar(v);
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];
1046 if (!(x&1)) putchar(c);
1056 struct game_aux_info {
1058 unsigned char *vedge; /* (w+1) x h */
1059 unsigned char *hedge; /* w x (h+1) */
1062 static char *new_game_desc(game_params *params, random_state *rs,
1063 game_aux_info **aux, int interactive)
1065 int *grid, *numbers = NULL;
1066 struct rectlist *list;
1067 int x, y, y2, y2last, yx, run, i;
1069 game_params params2real, *params2 = ¶ms2real;
1073 * Set up the smaller width and height which we will use to
1074 * generate the base grid.
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;
1081 grid = snewn(params2->w * params2->h, int);
1083 for (y = 0; y < params2->h; y++)
1084 for (x = 0; x < params2->w; x++) {
1085 index(params2, grid, x, y) = -1;
1088 list = get_rectlist(params2, grid);
1089 assert(list != NULL);
1092 * Place rectangles until we can't any more.
1094 while (list->n > 0) {
1099 * Pick a random rectangle.
1101 i = random_upto(rs, list->n);
1107 place_rect(params2, grid, r);
1110 * Winnow the list by removing any rectangles which
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;
1123 free_rectlist(list);
1126 * Deal with singleton spaces remaining in the grid, one by
1129 * We do this by making a local change to the layout. There are
1130 * several possibilities:
1132 * +-----+-----+ Here, we can remove the singleton by
1133 * | | | extending the 1x2 rectangle below it
1134 * +--+--+-----+ into a 1x3.
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.
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.
1161 for (x = 0; x < params2->w; x++) {
1162 for (y = 0; y < params2->h; y++) {
1163 if (index(params2, grid, x, y) < 0) {
1166 #ifdef GENERATION_DIAGNOSTICS
1167 display_grid(params2, grid, NULL, FALSE);
1168 printf("singleton at %d,%d\n", x, y);
1172 * Check in which directions we can feasibly extend
1173 * the singleton. We can extend in a particular
1174 * direction iff either:
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
1180 * - it is 2x1 but we are on its short side.
1182 * FIXME: we could plausibly choose between these
1183 * based on the sizes of the rectangles they would
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 */
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 */
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 */
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 */
1212 which = random_upto(rs, ndirs);
1217 assert(x < params2->w+1);
1218 #ifdef GENERATION_DIAGNOSTICS
1219 printf("extending right\n");
1221 r1 = find_rect(params2, grid, x+1, y);
1232 #ifdef GENERATION_DIAGNOSTICS
1233 printf("extending up\n");
1235 r1 = find_rect(params2, grid, x, y-1);
1246 #ifdef GENERATION_DIAGNOSTICS
1247 printf("extending left\n");
1249 r1 = find_rect(params2, grid, x-1, y);
1259 assert(y < params2->h+1);
1260 #ifdef GENERATION_DIAGNOSTICS
1261 printf("extending down\n");
1263 r1 = find_rect(params2, grid, x, y+1);
1273 if (r1.h > 0 && r1.w > 0)
1274 place_rect(params2, grid, r1);
1275 place_rect(params2, grid, r2);
1279 * Sanity-check that there really is a 3x3
1280 * rectangle surrounding this singleton and it
1281 * contains absolutely everything we could
1286 assert(x > 0 && x < params2->w-1);
1287 assert(y > 0 && y < params2->h-1);
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);
1294 assert(r.x+r.w-1 <= x+1);
1295 assert(r.y+r.h-1 <= y+1);
1300 #ifdef GENERATION_DIAGNOSTICS
1301 printf("need the 3x3 trick\n");
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:
1311 * - a 4, a 3 and a 2
1313 * - a 3 and three 2s (two different arrangements).
1321 place_rect(params2, grid, r);
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.
1336 for (i = 0; i < 2; i++) {
1337 int *grid2, *expand, *where;
1338 game_params params3real, *params3 = ¶ms3real;
1340 #ifdef GENERATION_DIAGNOSTICS
1341 printf("before expansion:\n");
1342 display_grid(params2, grid, NULL, TRUE);
1346 * Set up the new grid.
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;
1355 * Decide which horizontal edges are going to get expanded,
1358 for (y = 0; y < params2->h-1; y++)
1360 for (y = params2->h; y < params->h; y++) {
1361 x = random_upto(rs, params2->h-1);
1365 #ifdef GENERATION_DIAGNOSTICS
1366 printf("expand[] = {");
1367 for (y = 0; y < params2->h-1; y++)
1368 printf(" %d", expand[y]);
1373 * Perform the expansion. The way this works is that we
1376 * - copy a row from grid into grid2
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
1384 for (y = y2 = y2last = 0; y < params2->h; y++) {
1386 * Copy a single line from row y of grid into row y2 of
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);
1398 index(params3, grid2, x, y2) =
1399 index(params3, grid2, x, y2-1);
1403 * If that was the last line, terminate the loop early.
1405 if (++y2 == params3->h)
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.
1416 for (x = 0; x < params2->w; x++) {
1417 if (index(params2, grid, x, y) !=
1418 index(params2, grid, x, y+1)) {
1420 * This is a horizontal edge, so it needs
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))) {
1429 * Here we have the chance to make a new
1432 yx = random_upto(rs, expand[y]+1);
1435 * Here we just reuse the previous value of
1444 for (yx = 0; yx < expand[y]; yx++) {
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.
1450 for (x = 0; x < params2->w; x++) {
1451 if (yx == where[x]) {
1452 int val = index(params2, grid, x, y+1);
1454 val = INDEX(params3, val, y2);
1455 index(params3, grid2, x, y2) = val;
1457 index(params3, grid2, x, y2) =
1458 index(params3, grid2, x, y2-1);
1468 #ifdef GENERATION_DIAGNOSTICS
1469 printf("after expansion:\n");
1470 display_grid(params3, grid2, NULL, TRUE);
1475 params2->w = params3->h;
1476 params2->h = params3->w;
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);
1486 tmp = (tmp % params3->w) * params2->w + (tmp / params3->w);
1495 params->w = params->h;
1499 #ifdef GENERATION_DIAGNOSTICS
1500 printf("after transposition:\n");
1501 display_grid(params2, grid, NULL, TRUE);
1506 * Run the solver to narrow down the possible number
1510 struct numberdata *nd;
1511 int nnumbers, i, ret;
1513 /* Count the rectangles. */
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)
1523 nd = snewn(nnumbers, struct numberdata);
1525 /* Now set up each number's candidate position list. */
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);
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);
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;
1544 assert(m == nd[i].npoints);
1552 ret = rect_solver(params->w, params->h, nnumbers, nd,
1555 ret = TRUE; /* allow any number placement at all */
1559 * Now place the numbers according to the solver's
1562 numbers = snewn(params->w * params->h, int);
1564 for (y = 0; y < params->h; y++)
1565 for (x = 0; x < params->w; x++) {
1566 index(params, numbers, x, y) = 0;
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;
1580 for (i = 0; i < nnumbers; i++)
1581 sfree(nd[i].points);
1585 * If we've succeeded, then terminate the loop.
1592 * Give up and go round again.
1598 * Store the rectangle data in the game_aux_info.
1601 game_aux_info *ai = snew(game_aux_info);
1605 ai->vedge = snewn(ai->w * ai->h, unsigned char);
1606 ai->hedge = snewn(ai->w * ai->h, unsigned char);
1608 for (y = 0; y < params->h; y++)
1609 for (x = 1; x < params->w; x++) {
1611 index(params, grid, x, y) != index(params, grid, x-1, y);
1613 for (y = 1; y < params->h; y++)
1614 for (x = 0; x < params->w; x++) {
1616 index(params, grid, x, y) != index(params, grid, x, y-1);
1622 #ifdef GENERATION_DIAGNOSTICS
1623 display_grid(params, grid, numbers, FALSE);
1626 desc = snewn(11 * params->w * params->h, char);
1629 for (i = 0; i <= params->w * params->h; i++) {
1630 int n = (i < params->w * params->h ? numbers[i] : -1);
1637 int c = 'a' - 1 + run;
1641 run -= c - ('a' - 1);
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.
1649 if (p > desc && n > 0)
1653 p += sprintf(p, "%d", n);
1665 static void game_free_aux_info(game_aux_info *ai)
1672 static char *validate_desc(game_params *params, char *desc)
1674 int area = params->w * params->h;
1679 if (n >= 'a' && n <= 'z') {
1680 squares += n - 'a' + 1;
1681 } else if (n == '_') {
1683 } else if (n > '0' && n <= '9') {
1685 while (*desc >= '0' && *desc <= '9')
1688 return "Invalid character in game description";
1692 return "Not enough data to fill grid";
1695 return "Too much data to fit in grid";
1700 static game_state *new_game(midend_data *me, game_params *params, char *desc)
1702 game_state *state = snew(game_state);
1705 state->w = params->w;
1706 state->h = params->h;
1708 area = state->w * state->h;
1710 state->grid = snewn(area, int);
1711 state->vedge = snewn(area, unsigned char);
1712 state->hedge = snewn(area, unsigned char);
1713 state->completed = state->cheated = FALSE;
1718 if (n >= 'a' && n <= 'z') {
1719 int run = n - 'a' + 1;
1720 assert(i + run <= area);
1722 state->grid[i++] = 0;
1723 } else if (n == '_') {
1725 } else if (n > '0' && n <= '9') {
1727 state->grid[i++] = atoi(desc-1);
1728 while (*desc >= '0' && *desc <= '9')
1731 assert(!"We can't get here");
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;
1743 static game_state *dup_game(game_state *state)
1745 game_state *ret = snew(game_state);
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);
1754 ret->completed = state->completed;
1755 ret->cheated = state->cheated;
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));
1764 static void free_game(game_state *state)
1767 sfree(state->vedge);
1768 sfree(state->hedge);
1772 static game_state *solve_game(game_state *state, game_aux_info *ai,
1779 struct numberdata *nd;
1782 * Attempt the in-built solver.
1785 /* Set up each number's (very short) candidate position list. */
1786 for (i = n = 0; i < state->h * state->w; i++)
1790 nd = snewn(n, struct numberdata);
1792 for (i = j = 0; i < state->h * state->w; i++)
1793 if (state->grid[i]) {
1794 nd[j].area = state->grid[i];
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;
1804 ret = dup_game(state);
1805 ret->cheated = TRUE;
1807 rect_solver(state->w, state->h, n, nd, ret, NULL);
1812 for (i = 0; i < n; i++)
1813 sfree(nd[i].points);
1819 assert(state->w == ai->w);
1820 assert(state->h == ai->h);
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;
1830 static char *game_text_format(game_state *state)
1832 char *ret, *p, buf[80];
1833 int i, x, y, col, maxlen;
1836 * First determine the number of spaces required to display a
1837 * number. We'll use at least two, because one looks a bit
1841 for (i = 0; i < state->w * state->h; i++) {
1842 x = sprintf(buf, "%d", state->grid[i]);
1843 if (col < x) col = x;
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.
1851 maxlen = (2*state->h+1) * (state->w * (col+1) + 2);
1853 ret = snewn(maxlen+1, char);
1856 for (y = 0; y <= 2*state->h; y++) {
1857 for (x = 0; x <= 2*state->w; x++) {
1862 int v = grid(state, x/2, y/2);
1864 sprintf(buf, "%*d", col, v);
1866 sprintf(buf, "%*s", col, "");
1867 memcpy(p, buf, col);
1871 * Display a horizontal edge or nothing.
1873 int h = (y==0 || y==2*state->h ? 1 :
1874 HRANGE(state, x/2, y/2) && hedge(state, x/2, y/2));
1880 for (i = 0; i < col; i++)
1884 * Display a vertical edge or nothing.
1886 int v = (x==0 || x==2*state->w ? 1 :
1887 VRANGE(state, x/2, y/2) && vedge(state, x/2, y/2));
1894 * Display a corner, or a vertical edge, or a
1895 * horizontal edge, or nothing.
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)
1907 else if (hl && hr && !vu && !vd)
1909 else if (!hl && !hr && vu && vd)
1918 assert(p - ret == maxlen);
1923 static unsigned char *get_correct(game_state *state)
1928 ret = snewn(state->w * state->h, unsigned char);
1929 memset(ret, 0xFF, state->w * state->h);
1931 for (x = 0; x < state->w; x++)
1932 for (y = 0; y < state->h; y++)
1933 if (index(state,ret,x,y) == 0xFF) {
1936 int num, area, valid;
1939 * Find a rectangle starting at this point.
1942 while (x+rw < state->w && !vedge(state,x+rw,y))
1945 while (y+rh < state->h && !hedge(state,x,y+rh))
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.
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);
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);
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.
1979 index(state, ret, x, y) = 0;
1984 * We have a rectangle. Now see what its area is,
1985 * and how many numbers are in it.
1989 for (xx = x; xx < x+rw; xx++) {
1990 for (yy = y; yy < y+rh; yy++) {
1992 if (grid(state,xx,yy)) {
1994 valid = FALSE; /* two numbers */
1995 num = grid(state,xx,yy);
2003 * Now fill in the whole rectangle based on the
2006 for (xx = x; xx < x+rw; xx++) {
2007 for (yy = y; yy < y+rh; yy++) {
2008 index(state, ret, xx, yy) = valid;
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.
2025 * -1,-1 means no drag is in progress.
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.
2039 * These are the co-ordinates of the top-left and bottom-right squares
2040 * in the drag box, respectively, or -1 otherwise.
2048 static game_ui *new_ui(game_state *state)
2050 game_ui *ui = snew(game_ui);
2051 ui->drag_start_x = -1;
2052 ui->drag_start_y = -1;
2053 ui->drag_end_x = -1;
2054 ui->drag_end_y = -1;
2055 ui->dragged = FALSE;
2063 static void free_ui(game_ui *ui)
2068 static void coord_round(float x, float y, int *xr, int *yr)
2070 float xs, ys, xv, yv, dx, dy, dist;
2073 * Find the nearest square-centre.
2075 xs = (float)floor(x) + 0.5F;
2076 ys = (float)floor(y) + 0.5F;
2079 * And find the nearest grid vertex.
2081 xv = (float)floor(x + 0.5F);
2082 yv = (float)floor(y + 0.5F);
2085 * We allocate clicks in parts of the grid square to either
2086 * corners, edges or square centres, as follows:
2102 * In other words: we measure the square distance (i.e.
2103 * max(dx,dy)) from the click to the nearest corner, and if
2104 * it's within CORNER_TOLERANCE then we return a corner click.
2105 * We measure the square distance from the click to the nearest
2106 * centre, and if that's within CENTRE_TOLERANCE we return a
2107 * centre click. Failing that, we find which of the two edge
2108 * centres is nearer to the click and return that edge.
2112 * Check for corner click.
2114 dx = (float)fabs(x - xv);
2115 dy = (float)fabs(y - yv);
2116 dist = (dx > dy ? dx : dy);
2117 if (dist < CORNER_TOLERANCE) {
2122 * Check for centre click.
2124 dx = (float)fabs(x - xs);
2125 dy = (float)fabs(y - ys);
2126 dist = (dx > dy ? dx : dy);
2127 if (dist < CENTRE_TOLERANCE) {
2128 *xr = 1 + 2 * (int)xs;
2129 *yr = 1 + 2 * (int)ys;
2132 * Failing both of those, see which edge we're closer to.
2133 * Conveniently, this is simply done by testing the relative
2134 * magnitude of dx and dy (which are currently distances from
2135 * the square centre).
2138 /* Vertical edge: x-coord of corner,
2139 * y-coord of square centre. */
2141 *yr = 1 + 2 * (int)floor(ys);
2143 /* Horizontal edge: x-coord of square centre,
2144 * y-coord of corner. */
2145 *xr = 1 + 2 * (int)floor(xs);
2152 static void ui_draw_rect(game_state *state, game_ui *ui,
2153 unsigned char *hedge, unsigned char *vedge, int c)
2162 * Draw horizontal edges of rectangles.
2164 for (x = x1; x < x2; x++)
2165 for (y = y1; y <= y2; y++)
2166 if (HRANGE(state,x,y)) {
2167 int val = index(state,hedge,x,y);
2168 if (y == y1 || y == y2)
2172 index(state,hedge,x,y) = val;
2176 * Draw vertical edges of rectangles.
2178 for (y = y1; y < y2; y++)
2179 for (x = x1; x <= x2; x++)
2180 if (VRANGE(state,x,y)) {
2181 int val = index(state,vedge,x,y);
2182 if (x == x1 || x == x2)
2186 index(state,vedge,x,y) = val;
2190 static void game_changed_state(game_ui *ui, game_state *oldstate,
2191 game_state *newstate)
2195 struct game_drawstate {
2198 unsigned long *visible;
2201 static game_state *make_move(game_state *from, game_ui *ui, game_drawstate *ds,
2202 int x, int y, int button) {
2204 int startdrag = FALSE, enddrag = FALSE, active = FALSE;
2207 button &= ~MOD_MASK;
2209 if (button == LEFT_BUTTON) {
2211 } else if (button == LEFT_RELEASE) {
2213 } else if (button != LEFT_DRAG) {
2217 coord_round(FROMCOORD((float)x), FROMCOORD((float)y), &xc, &yc);
2220 ui->drag_start_x = xc;
2221 ui->drag_start_y = yc;
2222 ui->drag_end_x = xc;
2223 ui->drag_end_y = yc;
2224 ui->dragged = FALSE;
2228 if (xc != ui->drag_end_x || yc != ui->drag_end_y) {
2231 ui->drag_end_x = xc;
2232 ui->drag_end_y = yc;
2236 if (xc >= 0 && xc <= 2*from->w &&
2237 yc >= 0 && yc <= 2*from->h) {
2238 ui->x1 = ui->drag_start_x;
2239 ui->x2 = ui->drag_end_x;
2240 if (ui->x2 < ui->x1) { t = ui->x1; ui->x1 = ui->x2; ui->x2 = t; }
2242 ui->y1 = ui->drag_start_y;
2243 ui->y2 = ui->drag_end_y;
2244 if (ui->y2 < ui->y1) { t = ui->y1; ui->y1 = ui->y2; ui->y2 = t; }
2246 ui->x1 = ui->x1 / 2; /* rounds down */
2247 ui->x2 = (ui->x2+1) / 2; /* rounds up */
2248 ui->y1 = ui->y1 / 2; /* rounds down */
2249 ui->y2 = (ui->y2+1) / 2; /* rounds up */
2261 if (xc >= 0 && xc <= 2*from->w &&
2262 yc >= 0 && yc <= 2*from->h) {
2263 ret = dup_game(from);
2266 ui_draw_rect(ret, ui, ret->hedge, ret->vedge, 1);
2268 if ((xc & 1) && !(yc & 1) && HRANGE(from,xc/2,yc/2)) {
2269 hedge(ret,xc/2,yc/2) = !hedge(ret,xc/2,yc/2);
2271 if ((yc & 1) && !(xc & 1) && VRANGE(from,xc/2,yc/2)) {
2272 vedge(ret,xc/2,yc/2) = !vedge(ret,xc/2,yc/2);
2276 if (!memcmp(ret->hedge, from->hedge, from->w*from->h) &&
2277 !memcmp(ret->vedge, from->vedge, from->w*from->h)) {
2283 * We've made a real change to the grid. Check to see
2284 * if the game has been completed.
2286 if (ret && !ret->completed) {
2288 unsigned char *correct = get_correct(ret);
2291 for (x = 0; x < ret->w; x++)
2292 for (y = 0; y < ret->h; y++)
2293 if (!index(ret, correct, x, y))
2299 ret->completed = TRUE;
2303 ui->drag_start_x = -1;
2304 ui->drag_start_y = -1;
2305 ui->drag_end_x = -1;
2306 ui->drag_end_y = -1;
2311 ui->dragged = FALSE;
2316 return ret; /* a move has been made */
2318 return from; /* UI activity has occurred */
2323 /* ----------------------------------------------------------------------
2327 #define CORRECT (1L<<16)
2329 #define COLOUR(k) ( (k)==1 ? COL_LINE : COL_DRAG )
2330 #define MAX4(x,y,z,w) ( max(max(x,y),max(z,w)) )
2332 static void game_size(game_params *params, game_drawstate *ds,
2333 int *x, int *y, int expand)
2337 * Each window dimension equals the tile size times 1.5 more
2338 * than the grid dimension (the border is 3/4 the width of the
2341 * We must cast to unsigned before multiplying by two, because
2342 * *x might be INT_MAX.
2344 tsx = 2 * (unsigned)*x / (2 * params->w + 3);
2345 tsy = 2 * (unsigned)*y / (2 * params->h + 3);
2350 ds->tilesize = min(ts, PREFERRED_TILE_SIZE);
2352 *x = params->w * TILE_SIZE + 2*BORDER + 1;
2353 *y = params->h * TILE_SIZE + 2*BORDER + 1;
2356 static float *game_colours(frontend *fe, game_state *state, int *ncolours)
2358 float *ret = snewn(3 * NCOLOURS, float);
2360 frontend_default_colour(fe, &ret[COL_BACKGROUND * 3]);
2362 ret[COL_GRID * 3 + 0] = 0.5F * ret[COL_BACKGROUND * 3 + 0];
2363 ret[COL_GRID * 3 + 1] = 0.5F * ret[COL_BACKGROUND * 3 + 1];
2364 ret[COL_GRID * 3 + 2] = 0.5F * ret[COL_BACKGROUND * 3 + 2];
2366 ret[COL_DRAG * 3 + 0] = 1.0F;
2367 ret[COL_DRAG * 3 + 1] = 0.0F;
2368 ret[COL_DRAG * 3 + 2] = 0.0F;
2370 ret[COL_CORRECT * 3 + 0] = 0.75F * ret[COL_BACKGROUND * 3 + 0];
2371 ret[COL_CORRECT * 3 + 1] = 0.75F * ret[COL_BACKGROUND * 3 + 1];
2372 ret[COL_CORRECT * 3 + 2] = 0.75F * ret[COL_BACKGROUND * 3 + 2];
2374 ret[COL_LINE * 3 + 0] = 0.0F;
2375 ret[COL_LINE * 3 + 1] = 0.0F;
2376 ret[COL_LINE * 3 + 2] = 0.0F;
2378 ret[COL_TEXT * 3 + 0] = 0.0F;
2379 ret[COL_TEXT * 3 + 1] = 0.0F;
2380 ret[COL_TEXT * 3 + 2] = 0.0F;
2382 *ncolours = NCOLOURS;
2386 static game_drawstate *game_new_drawstate(game_state *state)
2388 struct game_drawstate *ds = snew(struct game_drawstate);
2391 ds->started = FALSE;
2394 ds->visible = snewn(ds->w * ds->h, unsigned long);
2395 ds->tilesize = 0; /* not decided yet */
2396 for (i = 0; i < ds->w * ds->h; i++)
2397 ds->visible[i] = 0xFFFF;
2402 static void game_free_drawstate(game_drawstate *ds)
2408 static void draw_tile(frontend *fe, game_drawstate *ds, game_state *state,
2409 int x, int y, unsigned char *hedge, unsigned char *vedge,
2410 unsigned char *corners, int correct)
2412 int cx = COORD(x), cy = COORD(y);
2415 draw_rect(fe, cx, cy, TILE_SIZE+1, TILE_SIZE+1, COL_GRID);
2416 draw_rect(fe, cx+1, cy+1, TILE_SIZE-1, TILE_SIZE-1,
2417 correct ? COL_CORRECT : COL_BACKGROUND);
2419 if (grid(state,x,y)) {
2420 sprintf(str, "%d", grid(state,x,y));
2421 draw_text(fe, cx+TILE_SIZE/2, cy+TILE_SIZE/2, FONT_VARIABLE,
2422 TILE_SIZE/2, ALIGN_HCENTRE | ALIGN_VCENTRE, COL_TEXT, str);
2428 if (!HRANGE(state,x,y) || index(state,hedge,x,y))
2429 draw_rect(fe, cx, cy, TILE_SIZE+1, 2,
2430 HRANGE(state,x,y) ? COLOUR(index(state,hedge,x,y)) :
2432 if (!HRANGE(state,x,y+1) || index(state,hedge,x,y+1))
2433 draw_rect(fe, cx, cy+TILE_SIZE-1, TILE_SIZE+1, 2,
2434 HRANGE(state,x,y+1) ? COLOUR(index(state,hedge,x,y+1)) :
2436 if (!VRANGE(state,x,y) || index(state,vedge,x,y))
2437 draw_rect(fe, cx, cy, 2, TILE_SIZE+1,
2438 VRANGE(state,x,y) ? COLOUR(index(state,vedge,x,y)) :
2440 if (!VRANGE(state,x+1,y) || index(state,vedge,x+1,y))
2441 draw_rect(fe, cx+TILE_SIZE-1, cy, 2, TILE_SIZE+1,
2442 VRANGE(state,x+1,y) ? COLOUR(index(state,vedge,x+1,y)) :
2448 if (index(state,corners,x,y))
2449 draw_rect(fe, cx, cy, 2, 2,
2450 COLOUR(index(state,corners,x,y)));
2451 if (x+1 < state->w && index(state,corners,x+1,y))
2452 draw_rect(fe, cx+TILE_SIZE-1, cy, 2, 2,
2453 COLOUR(index(state,corners,x+1,y)));
2454 if (y+1 < state->h && index(state,corners,x,y+1))
2455 draw_rect(fe, cx, cy+TILE_SIZE-1, 2, 2,
2456 COLOUR(index(state,corners,x,y+1)));
2457 if (x+1 < state->w && y+1 < state->h && index(state,corners,x+1,y+1))
2458 draw_rect(fe, cx+TILE_SIZE-1, cy+TILE_SIZE-1, 2, 2,
2459 COLOUR(index(state,corners,x+1,y+1)));
2461 draw_update(fe, cx, cy, TILE_SIZE+1, TILE_SIZE+1);
2464 static void game_redraw(frontend *fe, game_drawstate *ds, game_state *oldstate,
2465 game_state *state, int dir, game_ui *ui,
2466 float animtime, float flashtime)
2469 unsigned char *correct;
2470 unsigned char *hedge, *vedge, *corners;
2472 correct = get_correct(state);
2475 hedge = snewn(state->w*state->h, unsigned char);
2476 vedge = snewn(state->w*state->h, unsigned char);
2477 memcpy(hedge, state->hedge, state->w*state->h);
2478 memcpy(vedge, state->vedge, state->w*state->h);
2479 ui_draw_rect(state, ui, hedge, vedge, 2);
2481 hedge = state->hedge;
2482 vedge = state->vedge;
2485 corners = snewn(state->w * state->h, unsigned char);
2486 memset(corners, 0, state->w * state->h);
2487 for (x = 0; x < state->w; x++)
2488 for (y = 0; y < state->h; y++) {
2490 int e = index(state, vedge, x, y);
2491 if (index(state,corners,x,y) < e)
2492 index(state,corners,x,y) = e;
2493 if (y+1 < state->h &&
2494 index(state,corners,x,y+1) < e)
2495 index(state,corners,x,y+1) = e;
2498 int e = index(state, hedge, x, y);
2499 if (index(state,corners,x,y) < e)
2500 index(state,corners,x,y) = e;
2501 if (x+1 < state->w &&
2502 index(state,corners,x+1,y) < e)
2503 index(state,corners,x+1,y) = e;
2509 state->w * TILE_SIZE + 2*BORDER + 1,
2510 state->h * TILE_SIZE + 2*BORDER + 1, COL_BACKGROUND);
2511 draw_rect(fe, COORD(0)-1, COORD(0)-1,
2512 ds->w*TILE_SIZE+3, ds->h*TILE_SIZE+3, COL_LINE);
2514 draw_update(fe, 0, 0,
2515 state->w * TILE_SIZE + 2*BORDER + 1,
2516 state->h * TILE_SIZE + 2*BORDER + 1);
2519 for (x = 0; x < state->w; x++)
2520 for (y = 0; y < state->h; y++) {
2521 unsigned long c = 0;
2523 if (HRANGE(state,x,y))
2524 c |= index(state,hedge,x,y);
2525 if (HRANGE(state,x,y+1))
2526 c |= index(state,hedge,x,y+1) << 2;
2527 if (VRANGE(state,x,y))
2528 c |= index(state,vedge,x,y) << 4;
2529 if (VRANGE(state,x+1,y))
2530 c |= index(state,vedge,x+1,y) << 6;
2531 c |= index(state,corners,x,y) << 8;
2533 c |= index(state,corners,x+1,y) << 10;
2535 c |= index(state,corners,x,y+1) << 12;
2536 if (x+1 < state->w && y+1 < state->h)
2537 /* cast to prevent 2<<14 sign-extending on promotion to long */
2538 c |= (unsigned long)index(state,corners,x+1,y+1) << 14;
2539 if (index(state, correct, x, y) && !flashtime)
2542 if (index(ds,ds->visible,x,y) != c) {
2543 draw_tile(fe, ds, state, x, y, hedge, vedge, corners,
2544 (c & CORRECT) ? 1 : 0);
2545 index(ds,ds->visible,x,y) = c;
2552 if (ui->x1 >= 0 && ui->y1 >= 0 &&
2553 ui->x2 >= 0 && ui->y2 >= 0) {
2554 sprintf(buf, "%dx%d ",
2562 strcat(buf, "Auto-solved.");
2563 else if (state->completed)
2564 strcat(buf, "COMPLETED!");
2566 status_bar(fe, buf);
2569 if (hedge != state->hedge) {
2578 static float game_anim_length(game_state *oldstate,
2579 game_state *newstate, int dir, game_ui *ui)
2584 static float game_flash_length(game_state *oldstate,
2585 game_state *newstate, int dir, game_ui *ui)
2587 if (!oldstate->completed && newstate->completed &&
2588 !oldstate->cheated && !newstate->cheated)
2593 static int game_wants_statusbar(void)
2598 static int game_timing_state(game_state *state)
2604 #define thegame rect
2607 const struct game thegame = {
2608 "Rectangles", "games.rectangles",
2615 TRUE, game_configure, custom_params,
2624 TRUE, game_text_format,
2632 game_free_drawstate,
2636 game_wants_statusbar,
2637 FALSE, game_timing_state,
2638 0, /* mouse_priorities */