chiark / gitweb /
One more fix from Ben H. Also switched round the arena colour
[sgt-puzzles.git] / blackbox.c
1 /*
2  * blackbox.c: implementation of 'Black Box'.
3  */
4
5 #include <stdio.h>
6 #include <stdlib.h>
7 #include <string.h>
8 #include <assert.h>
9 #include <ctype.h>
10 #include <math.h>
11
12 #include "puzzles.h"
13
14 #define PREFERRED_TILE_SIZE 32
15 #define FLASH_FRAME 0.2F
16
17 /* Terminology, for ease of reading various macros scattered about the place.
18  *
19  * The 'arena' is the inner area where the balls are placed. This is
20  *   indexed from (0,0) to (w-1,h-1) but its offset in the grid is (1,1).
21  *
22  * The 'range' (firing range) is the bit around the edge where
23  *   the lasers are fired from. This is indexed from 0 --> (2*(w+h) - 1),
24  *   starting at the top left ((1,0) on the grid) and moving clockwise.
25  *
26  * The 'grid' is just the big array containing arena and range;
27  *   locations (0,0), (0,w+1), (h+1,w+1) and (h+1,0) are unused.
28  */
29
30 enum {
31     COL_BACKGROUND, COL_COVER, COL_LOCK,
32     COL_TEXT, COL_FLASHTEXT,
33     COL_HIGHLIGHT, COL_LOWLIGHT, COL_GRID,
34     COL_BALL, COL_WRONG, COL_BUTTON,
35     COL_LASER, COL_DIMLASER,
36     NCOLOURS
37 };
38
39 struct game_params {
40     int w, h;
41     int minballs, maxballs;
42 };
43
44 static game_params *default_params(void)
45 {
46     game_params *ret = snew(game_params);
47
48     ret->w = ret->h = 8;
49     ret->minballs = ret->maxballs = 5;
50
51     return ret;
52 }
53
54 static const game_params blackbox_presets[] = {
55     { 5, 5, 3, 3 },
56     { 8, 8, 5, 5 },
57     { 8, 8, 3, 6 },
58     { 10, 10, 5, 5 },
59     { 10, 10, 4, 10 }
60 };
61
62 static int game_fetch_preset(int i, char **name, game_params **params)
63 {
64     char str[80];
65     game_params *ret;
66
67     if (i < 0 || i >= lenof(blackbox_presets))
68         return FALSE;
69
70     ret = snew(game_params);
71     *ret = blackbox_presets[i];
72
73     if (ret->minballs == ret->maxballs)
74         sprintf(str, "%dx%d, %d balls",
75                 ret->w, ret->h, ret->minballs);
76     else
77         sprintf(str, "%dx%d, %d-%d balls",
78                 ret->w, ret->h, ret->minballs, ret->maxballs);
79
80     *name = dupstr(str);
81     *params = ret;
82     return TRUE;
83 }
84
85 static void free_params(game_params *params)
86 {
87     sfree(params);
88 }
89
90 static game_params *dup_params(game_params *params)
91 {
92     game_params *ret = snew(game_params);
93     *ret = *params;                    /* structure copy */
94     return ret;
95 }
96
97 static void decode_params(game_params *params, char const *string)
98 {
99     char const *p = string;
100     game_params *defs = default_params();
101
102     *params = *defs; free_params(defs);
103
104     while (*p) {
105         switch (*p++) {
106         case 'w':
107             params->w = atoi(p);
108             while (*p && isdigit((unsigned char)*p)) p++;
109             break;
110
111         case 'h':
112             params->h = atoi(p);
113             while (*p && isdigit((unsigned char)*p)) p++;
114             break;
115
116         case 'm':
117             params->minballs = atoi(p);
118             while (*p && isdigit((unsigned char)*p)) p++;
119             break;
120
121         case 'M':
122             params->maxballs = atoi(p);
123             while (*p && isdigit((unsigned char)*p)) p++;
124             break;
125
126         default:
127             ;
128         }
129     }
130 }
131
132 static char *encode_params(game_params *params, int full)
133 {
134     char str[256];
135
136     sprintf(str, "w%dh%dm%dM%d",
137             params->w, params->h, params->minballs, params->maxballs);
138     return dupstr(str);
139 }
140
141 static config_item *game_configure(game_params *params)
142 {
143     config_item *ret;
144     char buf[80];
145
146     ret = snewn(4, config_item);
147
148     ret[0].name = "Width";
149     ret[0].type = C_STRING;
150     sprintf(buf, "%d", params->w);
151     ret[0].sval = dupstr(buf);
152     ret[0].ival = 0;
153
154     ret[1].name = "Height";
155     ret[1].type = C_STRING;
156     sprintf(buf, "%d", params->h);
157     ret[1].sval = dupstr(buf);
158     ret[1].ival = 0;
159
160     ret[2].name = "No. of balls";
161     ret[2].type = C_STRING;
162     if (params->minballs == params->maxballs)
163         sprintf(buf, "%d", params->minballs);
164     else
165         sprintf(buf, "%d-%d", params->minballs, params->maxballs);
166     ret[2].sval = dupstr(buf);
167     ret[2].ival = 0;
168
169     ret[3].name = NULL;
170     ret[3].type = C_END;
171     ret[3].sval = NULL;
172     ret[3].ival = 0;
173
174     return ret;
175 }
176
177 static game_params *custom_params(config_item *cfg)
178 {
179     game_params *ret = snew(game_params);
180
181     ret->w = atoi(cfg[0].sval);
182     ret->h = atoi(cfg[1].sval);
183
184     /* Allow 'a-b' for a range, otherwise assume a single number. */
185     if (sscanf(cfg[2].sval, "%d-%d", &ret->minballs, &ret->maxballs) < 2)
186         ret->minballs = ret->maxballs = atoi(cfg[2].sval);
187
188     return ret;
189 }
190
191 static char *validate_params(game_params *params, int full)
192 {
193     if (params->w < 2 || params->h < 2)
194         return "Width and height must both be at least two";
195     /* next one is just for ease of coding stuff into 'char'
196      * types, and could be worked around if required. */
197     if (params->w > 255 || params->h > 255)
198         return "Widths and heights greater than 255 are not supported";
199     if (params->minballs > params->maxballs)
200         return "Minimum number of balls may not be greater than maximum";
201     if (params->minballs >= params->w * params->h)
202         return "Too many balls to fit in grid";
203     return NULL;
204 }
205
206 /*
207  * We store: width | height | ball1x | ball1y | [ ball2x | ball2y | [...] ]
208  * all stored as unsigned chars; validate_params has already
209  * checked this won't overflow an 8-bit char.
210  * Then we obfuscate it.
211  */
212
213 static char *new_game_desc(game_params *params, random_state *rs,
214                            char **aux, int interactive)
215 {
216     int nballs = params->minballs, i;
217     char *grid, *ret;
218     unsigned char *bmp;
219
220     if (params->maxballs > params->minballs)
221         nballs += random_upto(rs, params->maxballs - params->minballs + 1);
222
223     grid = snewn(params->w*params->h, char);
224     memset(grid, 0, params->w * params->h * sizeof(char));
225
226     bmp = snewn(nballs*2 + 2, unsigned char);
227     memset(bmp, 0, (nballs*2 + 2) * sizeof(unsigned char));
228
229     bmp[0] = params->w;
230     bmp[1] = params->h;
231
232     for (i = 0; i < nballs; i++) {
233         int x, y;
234
235         do {
236             x = random_upto(rs, params->w);
237             y = random_upto(rs, params->h);
238         } while (grid[y*params->w + x]);
239
240         grid[y*params->w + x] = 1;
241
242         bmp[(i+1)*2 + 0] = x;
243         bmp[(i+1)*2 + 1] = y;
244     }
245     sfree(grid);
246
247     obfuscate_bitmap(bmp, (nballs*2 + 2) * 8, FALSE);
248     ret = bin2hex(bmp, nballs*2 + 2);
249     sfree(bmp);
250
251     return ret;
252 }
253
254 static char *validate_desc(game_params *params, char *desc)
255 {
256     int nballs, dlen = strlen(desc), i;
257     unsigned char *bmp;
258     char *ret;
259
260     /* the bitmap is 2+(nballs*2) long; the hex version is double that. */
261     nballs = ((dlen/2)-2)/2;
262
263     if (dlen < 4 || dlen % 4 ||
264         nballs < params->minballs || nballs > params->maxballs)
265         return "Game description is wrong length";
266
267     bmp = hex2bin(desc, nballs*2 + 2);
268     obfuscate_bitmap(bmp, (nballs*2 + 2) * 8, TRUE);
269     ret = "Game description is corrupted";
270     /* check general grid size */
271     if (bmp[0] != params->w || bmp[1] != params->h)
272         goto done;
273     /* check each ball will fit on that grid */
274     for (i = 0; i < nballs; i++) {
275         int x = bmp[(i+1)*2 + 0], y = bmp[(i+1)*2 + 1];
276         if (x < 0 || y < 0 || x >= params->w || y >= params->h)
277             goto done;
278     }
279     ret = NULL;
280
281 done:
282     sfree(bmp);
283     return ret;
284 }
285
286 #define BALL_CORRECT    0x01
287 #define BALL_GUESS      0x02
288 #define BALL_LOCK       0x04
289
290 #define LASER_FLAGMASK  0xf800
291 #define LASER_OMITTED   0x0800
292 #define LASER_REFLECT   0x1000
293 #define LASER_HIT       0x2000
294 #define LASER_WRONG     0x4000
295 #define LASER_FLASHED   0x8000
296 #define LASER_EMPTY     (~0)
297
298 struct game_state {
299     int w, h, minballs, maxballs, nballs, nlasers;
300     unsigned int *grid; /* (w+2)x(h+2), to allow for laser firing range */
301     unsigned int *exits; /* one per laser */
302     int done;           /* user has finished placing his own balls. */
303     int laserno;        /* number of next laser to be fired. */
304     int nguesses, reveal, nright, nwrong, nmissed;
305 };
306
307 #define GRID(s,x,y) ((s)->grid[(y)*((s)->w+2) + (x)])
308
309 /* specify numbers because they must match array indexes. */
310 enum { DIR_UP = 0, DIR_RIGHT = 1, DIR_DOWN = 2, DIR_LEFT = 3 };
311
312 struct offset { int x, y; };
313
314 static const struct offset offsets[] = {
315     {  0, -1 }, /* up */
316     {  1,  0 }, /* right */
317     {  0,  1 }, /* down */
318     { -1,  0 }  /* left */
319 };
320
321 #ifdef DEBUGGING
322 static const char *dirstrs[] = {
323     "UP", "RIGHT", "DOWN", "LEFT"
324 };
325 #endif
326
327 static int range2grid(game_state *state, int rangeno, int *x, int *y, int *direction)
328 {
329     if (rangeno < 0)
330         return 0;
331
332     if (rangeno < state->w) {
333         /* top row; from (1,0) to (w,0) */
334         *x = rangeno + 1;
335         *y = 0;
336         *direction = DIR_DOWN;
337         return 1;
338     }
339     rangeno -= state->w;
340     if (rangeno < state->h) {
341         /* RHS; from (w+1, 1) to (w+1, h) */
342         *x = state->w+1;
343         *y = rangeno + 1;
344         *direction = DIR_LEFT;
345         return 1;
346     }
347     rangeno -= state->h;
348     if (rangeno < state->w) {
349         /* bottom row; from (1, h+1) to (w, h+1); counts backwards */
350         *x = (state->w - rangeno);
351         *y = state->h+1;
352         *direction = DIR_UP;
353         return 1;
354     }
355     rangeno -= state->w;
356     if (rangeno < state->h) {
357         /* LHS; from (0, 1) to (0, h); counts backwards */
358         *x = 0;
359         *y = (state->h - rangeno);
360         *direction = DIR_RIGHT;
361         return 1;
362     }
363     return 0;
364 }
365
366 static int grid2range(game_state *state, int x, int y, int *rangeno)
367 {
368     int ret, x1 = state->w+1, y1 = state->h+1;
369
370     if (x > 0 && x < x1 && y > 0 && y < y1) return 0; /* in arena */
371     if (x < 0 || x > y1 || y < 0 || y > y1) return 0; /* outside grid */
372
373     if ((x == 0 || x == x1) && (y == 0 || y == y1))
374         return 0; /* one of 4 corners */
375
376     if (y == 0) {               /* top line */
377         ret = x - 1;
378     } else if (x == x1) {       /* RHS */
379         ret = y - 1 + state->w;
380     } else if (y == y1) {       /* Bottom [and counts backwards] */
381         ret = (state->w - x) + state->w + state->h;
382     } else {                    /* LHS [and counts backwards ] */
383         ret = (state->h-y) + state->w + state->w + state->h;
384     }
385     *rangeno = ret;
386     debug(("grid2range: (%d,%d) rangeno = %d\n", x, y, ret));
387     return 1;
388 }
389
390 static game_state *new_game(midend_data *me, game_params *params, char *desc)
391 {
392     game_state *state = snew(game_state);
393     int dlen = strlen(desc), i;
394     unsigned char *bmp;
395
396     state->minballs = params->minballs;
397     state->maxballs = params->maxballs;
398     state->nballs = ((dlen/2)-2)/2;
399
400     bmp = hex2bin(desc, state->nballs*2 + 2);
401     obfuscate_bitmap(bmp, (state->nballs*2 + 2) * 8, TRUE);
402
403     state->w = bmp[0]; state->h = bmp[1];
404     state->nlasers = 2 * (state->w + state->h);
405
406     state->grid = snewn((state->w+2)*(state->h+2), unsigned int);
407     memset(state->grid, 0, (state->w+2)*(state->h+2) * sizeof(unsigned int));
408
409     state->exits = snewn(state->nlasers, unsigned int);
410     memset(state->exits, LASER_EMPTY, state->nlasers * sizeof(unsigned int));
411
412     for (i = 0; i < state->nballs; i++) {
413         GRID(state, bmp[(i+1)*2 + 0]+1, bmp[(i+1)*2 + 1]+1) = BALL_CORRECT;
414     }
415     sfree(bmp);
416
417     state->done = state->nguesses = state->reveal =
418         state->nright = state->nwrong = state->nmissed = 0;
419     state->laserno = 1;
420
421     return state;
422 }
423
424 #define XFER(x) ret->x = state->x
425
426 static game_state *dup_game(game_state *state)
427 {
428     game_state *ret = snew(game_state);
429
430     XFER(w); XFER(h);
431     XFER(minballs); XFER(maxballs);
432     XFER(nballs); XFER(nlasers);
433
434     ret->grid = snewn((ret->w+2)*(ret->h+2), unsigned int);
435     memcpy(ret->grid, state->grid, (ret->w+2)*(ret->h+2) * sizeof(unsigned int));
436     ret->exits = snewn(ret->nlasers, unsigned int);
437     memcpy(ret->exits, state->exits, ret->nlasers * sizeof(unsigned int));
438
439     XFER(done);
440     XFER(laserno);
441     XFER(nguesses);
442     XFER(reveal);
443     XFER(nright); XFER(nwrong); XFER(nmissed);
444
445     return ret;
446 }
447
448 #undef XFER
449
450 static void free_game(game_state *state)
451 {
452     sfree(state->exits);
453     sfree(state->grid);
454     sfree(state);
455 }
456
457 static char *solve_game(game_state *state, game_state *currstate,
458                         char *aux, char **error)
459 {
460     return dupstr("S");
461 }
462
463 static char *game_text_format(game_state *state)
464 {
465     return NULL;
466 }
467
468 struct game_ui {
469     int flash_laserno;
470 };
471
472 static game_ui *new_ui(game_state *state)
473 {
474     game_ui *ui = snew(struct game_ui);
475     ui->flash_laserno = LASER_EMPTY;
476     return ui;
477 }
478
479 static void free_ui(game_ui *ui)
480 {
481     sfree(ui);
482 }
483
484 static char *encode_ui(game_ui *ui)
485 {
486     return NULL;
487 }
488
489 static void decode_ui(game_ui *ui, char *encoding)
490 {
491 }
492
493 static void game_changed_state(game_ui *ui, game_state *oldstate,
494                                game_state *newstate)
495 {
496 }
497
498 #define OFFSET(gx,gy,o) do {                                    \
499     int off = (4 + (o) % 4) % 4;                                \
500     (gx) += offsets[off].x;                                     \
501     (gy) += offsets[off].y;                                     \
502 } while(0)
503
504 enum { LOOK_LEFT, LOOK_FORWARD, LOOK_RIGHT };
505
506 /* Given a position and a direction, check whether we can see a ball in front
507  * of us, or to our front-left or front-right. */
508 static int isball(game_state *state, int gx, int gy, int direction, int lookwhere)
509 {
510     debug(("isball, (%d, %d), dir %s, lookwhere %s\n", gx, gy, dirstrs[direction],
511            lookwhere == LOOK_LEFT ? "LEFT" :
512            lookwhere == LOOK_FORWARD ? "FORWARD" : "RIGHT"));
513     OFFSET(gx,gy,direction);
514     if (lookwhere == LOOK_LEFT)
515         OFFSET(gx,gy,direction-1);
516     else if (lookwhere == LOOK_RIGHT)
517         OFFSET(gx,gy,direction+1);
518     else if (lookwhere != LOOK_FORWARD)
519         assert(!"unknown lookwhere");
520
521     debug(("isball, new (%d, %d)\n", gx, gy));
522
523     /* if we're off the grid (into the firing range) there's never a ball. */
524     if (gx < 1 || gy < 1 || gx > state->h || gy > state->w)
525         return 0;
526
527     if (GRID(state, gx,gy) & BALL_CORRECT)
528         return 1;
529
530     return 0;
531 }
532
533 static void fire_laser(game_state *state, int x, int y, int direction)
534 {
535     int xstart = x, ystart = y, unused, lno, tmp;
536
537     tmp = grid2range(state, x, y, &lno);
538     assert(tmp);
539
540     /* deal with strange initial reflection rules (that stop
541      * you turning down the laser range) */
542
543     /* I've just chosen to prioritise instant-hit over instant-reflection;
544      * I can't find anywhere that gives me a definite algorithm for this. */
545     if (isball(state, x, y, direction, LOOK_FORWARD)) {
546         debug(("Instant hit at (%d, %d)\n", x, y));
547         GRID(state, x, y) = LASER_HIT;
548         state->exits[lno] = LASER_HIT;
549         return;
550     }
551
552     if (isball(state, x, y, direction, LOOK_LEFT) ||
553         isball(state, x, y, direction, LOOK_RIGHT)) {
554         debug(("Instant reflection at (%d, %d)\n", x, y));
555         GRID(state, x, y) = LASER_REFLECT;
556         state->exits[lno] = LASER_REFLECT;
557         return;
558     }
559     /* move us onto the grid. */
560     OFFSET(x, y, direction);
561
562     while (1) {
563         debug(("fire_laser: looping at (%d, %d) pointing %s\n",
564                x, y, dirstrs[direction]));
565         if (grid2range(state, x, y, &unused)) {
566             int newno = state->laserno++, exitno;
567             debug(("Back on range; (%d, %d) --> (%d, %d)\n",
568                    xstart, ystart, x, y));
569             /* We're back out of the grid; the move is complete. */
570             if (xstart == x && ystart == y) {
571                 GRID(state, x, y) = LASER_REFLECT;
572                 state->exits[lno] = LASER_REFLECT;
573             } else {
574                 /* it wasn't a reflection */
575                 GRID(state, xstart, ystart) = newno;
576                 GRID(state, x, y) = newno;
577
578                 tmp = grid2range(state, x, y, &exitno);
579                 assert(tmp);
580                 state->exits[lno] = exitno;
581                 state->exits[exitno] = lno;
582             }
583             return;
584         }
585         /* paranoia. This obviously should never happen */
586         assert(!(GRID(state, x, y) & BALL_CORRECT));
587
588         if (isball(state, x, y, direction, LOOK_FORWARD)) {
589             /* we're facing a ball; send back a reflection. */
590             GRID(state, xstart, ystart) = LASER_HIT;
591             state->exits[lno] = LASER_HIT;
592             debug(("Ball ahead of (%d, %d); HIT at (%d, %d), new grid 0x%x\n",
593                    x, y, xstart, ystart, GRID(state, xstart, ystart)));
594             return;
595         }
596
597         if (isball(state, x, y, direction, LOOK_LEFT)) {
598             /* ball to our left; rotate clockwise and look again. */
599             debug(("Ball to left; turning clockwise.\n"));
600             direction += 1; direction %= 4;
601             continue;
602         }
603         if (isball(state, x, y, direction, LOOK_RIGHT)) {
604             /* ball to our right; rotate anti-clockwise and look again. */
605             debug(("Ball to rightl turning anti-clockwise.\n"));
606             direction += 3; direction %= 4;
607             continue;
608         }
609         /* ... otherwise, we have no balls ahead of us so just move one step. */
610         debug(("No balls; moving forwards.\n"));
611         OFFSET(x, y, direction);
612     }
613 }
614
615 /* Checks that the guessed balls in the state match up with the real balls
616  * for all possible lasers (i.e. not just the ones that the player might
617  * have already guessed). This is required because any layout with >4 balls
618  * might have multiple valid solutions. Returns non-zero for a 'correct'
619  * (i.e. consistent) layout. */
620 static int check_guesses(game_state *state)
621 {
622     game_state *solution, *guesses;
623     int i, x, y, dir, unused, tmp;
624     int ret = 0;
625
626     /* duplicate the state (to solution) */
627     solution = dup_game(state);
628
629     /* clear out the lasers of solution */
630     for (i = 0; i < solution->nlasers; i++) {
631         tmp = range2grid(solution, i, &x, &y, &unused);
632         assert(tmp);
633         GRID(solution, x, y) = 0;
634         solution->exits[i] = LASER_EMPTY;
635     }
636
637     /* duplicate solution to guess. */
638     guesses = dup_game(solution);
639
640     /* clear out BALL_CORRECT on guess, make BALL_GUESS BALL_CORRECT. */
641     for (x = 1; x <= state->w; x++) {
642         for (y = 1; y <= state->h; y++) {
643             GRID(guesses, x, y) &= ~BALL_CORRECT;
644             if (GRID(guesses, x, y) & BALL_GUESS)
645                 GRID(guesses, x, y) |= BALL_CORRECT;
646         }
647     }
648
649     /* for each laser (on both game_states), fire it if it hasn't been fired.
650      * If one has been fired (or received a hit) and another hasn't, we know
651      * the ball layouts didn't match and can short-circuit return. */
652     for (i = 0; i < solution->nlasers; i++) {
653         tmp = range2grid(solution, i, &x, &y, &dir);
654         assert(tmp);
655         if (solution->exits[i] == LASER_EMPTY)
656             fire_laser(solution, x, y, dir);
657         if (guesses->exits[i] == LASER_EMPTY)
658             fire_laser(guesses, x, y, dir);
659     }
660
661     /* check each game_state's laser against the other; if any differ, return 0 */
662     ret = 1;
663     for (i = 0; i < solution->nlasers; i++) {
664         tmp = range2grid(solution, i, &x, &y, &unused);
665         assert(tmp);
666
667         if (solution->exits[i] != guesses->exits[i]) {
668             /* If the original state didn't have this shot fired,
669              * and it would be wrong between the guess and the solution,
670              * add it. */
671             if (state->exits[i] == LASER_EMPTY) {
672                 state->exits[i] = solution->exits[i];
673                 if (state->exits[i] == LASER_REFLECT ||
674                     state->exits[i] == LASER_HIT)
675                     GRID(state, x, y) = state->exits[i];
676                 else {
677                     /* add a new shot, incrementing state's laser count. */
678                     int ex, ey, newno = state->laserno++;
679                     tmp = range2grid(state, state->exits[i], &ex, &ey, &unused);
680                     assert(tmp);
681                     GRID(state, x, y) = newno;
682                     GRID(state, ex, ey) = newno;
683                 }
684                 state->exits[i] |= LASER_OMITTED;
685             } else {
686                 state->exits[i] |= LASER_WRONG;
687             }
688             ret = 0;
689         }
690     }
691     if (ret == 0) goto done;
692
693     /* fix up original state so the 'correct' balls end up matching the guesses,
694      * as we've just proved that they were equivalent. */
695     for (x = 1; x <= state->w; x++) {
696         for (y = 1; y <= state->h; y++) {
697             if (GRID(state, x, y) & BALL_GUESS)
698                 GRID(state, x, y) |= BALL_CORRECT;
699             else
700                 GRID(state, x, y) &= ~BALL_CORRECT;
701         }
702     }
703
704 done:
705     /* fill in nright and nwrong. */
706     state->nright = state->nwrong = state->nmissed = 0;
707     for (x = 1; x <= state->w; x++) {
708         for (y = 1; y <= state->h; y++) {
709             int bs = GRID(state, x, y) & (BALL_GUESS | BALL_CORRECT);
710             if (bs == (BALL_GUESS | BALL_CORRECT))
711                 state->nright++;
712             else if (bs == BALL_GUESS)
713                 state->nwrong++;
714             else if (bs == BALL_CORRECT)
715                 state->nmissed++;
716         }
717     }
718     free_game(solution);
719     free_game(guesses);
720     return ret;
721 }
722
723 #define TILE_SIZE (ds->tilesize)
724
725 #define TODRAW(x) ((TILE_SIZE * (x)) + (TILE_SIZE / 2))
726 #define FROMDRAW(x) (((x) - (TILE_SIZE / 2)) / TILE_SIZE)
727
728 struct game_drawstate {
729     int tilesize, crad, rrad, w, h; /* w and h to make macros work... */
730     unsigned int *grid;          /* as the game_state grid */
731     int started, canreveal, reveal;
732     int flash_laserno;
733 };
734
735 static char *interpret_move(game_state *state, game_ui *ui, game_drawstate *ds,
736                             int x, int y, int button)
737 {
738     int gx = -1, gy = -1, rangeno = -1;
739     enum { NONE, TOGGLE_BALL, TOGGLE_LOCK, FIRE, REVEAL,
740            TOGGLE_COLUMN_LOCK, TOGGLE_ROW_LOCK} action = NONE;
741     char buf[80], *nullret = NULL;
742
743     if (button == LEFT_BUTTON || button == RIGHT_BUTTON) {
744         gx = FROMDRAW(x);
745         gy = FROMDRAW(y);
746         if (gx == 0 && gy == 0 && button == LEFT_BUTTON)
747             action = REVEAL;
748         if (gx >= 1 && gx <= state->w && gy >= 1 && gy <= state->h) {
749             if (button == LEFT_BUTTON) {
750                 if (!(GRID(state, gx,gy) & BALL_LOCK))
751                     action = TOGGLE_BALL;
752             } else
753                 action = TOGGLE_LOCK;
754         }
755         if (grid2range(state, gx, gy, &rangeno)) {
756             if (button == LEFT_BUTTON)
757                 action = FIRE;
758             else if (gy == 0 || gy > state->h)
759                 action = TOGGLE_COLUMN_LOCK; /* and use gx */
760             else
761                 action = TOGGLE_ROW_LOCK;    /* and use gy */
762         }
763     } else if (button == LEFT_RELEASE) {
764         ui->flash_laserno = LASER_EMPTY;
765         return "";
766     }
767
768     switch (action) {
769     case TOGGLE_BALL:
770         sprintf(buf, "T%d,%d", gx, gy);
771         break;
772
773     case TOGGLE_LOCK:
774         sprintf(buf, "LB%d,%d", gx, gy);
775         break;
776
777     case TOGGLE_COLUMN_LOCK:
778         sprintf(buf, "LC%d", gx);
779         break;
780
781     case TOGGLE_ROW_LOCK:
782         sprintf(buf, "LR%d", gy);
783         break;
784
785     case FIRE:
786         if (state->reveal && state->exits[rangeno] == LASER_EMPTY)
787             return nullret;
788         ui->flash_laserno = rangeno;
789         nullret = "";
790         if (state->exits[rangeno] != LASER_EMPTY)
791             return "";
792         sprintf(buf, "F%d", rangeno);
793         break;
794
795     case REVEAL:
796         if (!ds->canreveal) return nullret;
797         sprintf(buf, "R");
798         break;
799
800     default:
801         return nullret;
802     }
803     if (state->reveal) return nullret;
804     return dupstr(buf);
805 }
806
807 static game_state *execute_move(game_state *from, char *move)
808 {
809     game_state *ret = dup_game(from);
810     int gx = -1, gy = -1, rangeno = -1, direction;
811
812     if (!strcmp(move, "S")) {
813         ret->reveal = 1;
814         return ret;
815     }
816
817     if (from->reveal) goto badmove;
818     if (!*move) goto badmove;
819
820     switch (move[0]) {
821     case 'T':
822         sscanf(move+1, "%d,%d", &gx, &gy);
823         if (gx < 1 || gy < 1 || gx > ret->w || gy > ret->h)
824             goto badmove;
825         if (GRID(ret, gx, gy) & BALL_GUESS) {
826             ret->nguesses--;
827             GRID(ret, gx, gy) &= ~BALL_GUESS;
828         } else {
829             ret->nguesses++;
830             GRID(ret, gx, gy) |= BALL_GUESS;
831         }
832         break;
833
834     case 'F':
835         sscanf(move+1, "%d", &rangeno);
836         if (ret->exits[rangeno] != LASER_EMPTY)
837             goto badmove;
838         if (!range2grid(ret, rangeno, &gx, &gy, &direction))
839             goto badmove;
840         fire_laser(ret, gx, gy, direction);
841         break;
842
843     case 'R':
844         if (ret->nguesses < ret->minballs ||
845             ret->nguesses > ret->maxballs)
846             goto badmove;
847         check_guesses(ret);
848         ret->reveal = 1;
849         break;
850
851     case 'L':
852         {
853             int lcount = 0;
854             if (strlen(move) < 2) goto badmove;
855             switch (move[1]) {
856             case 'B':
857                 sscanf(move+2, "%d,%d", &gx, &gy);
858                 if (gx < 1 || gy < 1 || gx > ret->w || gy > ret->h)
859                     goto badmove;
860                 GRID(ret, gx, gy) ^= BALL_LOCK;
861                 break;
862
863 #define COUNTLOCK do { if (GRID(ret, gx, gy) & BALL_LOCK) lcount++; } while (0)
864 #define SETLOCKIF(c) do {                                       \
865     if (lcount > (c)) GRID(ret, gx, gy) &= ~BALL_LOCK;          \
866     else              GRID(ret, gx, gy) |= BALL_LOCK;           \
867 } while(0)
868
869             case 'C':
870                 sscanf(move+2, "%d", &gx);
871                 if (gx < 1 || gx > ret->w) goto badmove;
872                 for (gy = 1; gy <= ret->h; gy++) { COUNTLOCK; }
873                 for (gy = 1; gy <= ret->h; gy++) { SETLOCKIF(ret->h/2); }
874                 break;
875
876             case 'R':
877                 sscanf(move+2, "%d", &gy);
878                 if (gy < 1 || gy > ret->h) goto badmove;
879                 for (gx = 1; gx <= ret->w; gx++) { COUNTLOCK; }
880                 for (gx = 1; gx <= ret->w; gx++) { SETLOCKIF(ret->w/2); }
881                 break;
882
883 #undef COUNTLOCK
884 #undef SETLOCKIF
885
886             default:
887                 goto badmove;
888             }
889         }
890         break;
891
892     default:
893         goto badmove;
894     }
895
896     return ret;
897
898 badmove:
899     free_game(ret);
900     return NULL;
901 }
902
903 /* ----------------------------------------------------------------------
904  * Drawing routines.
905  */
906
907 static void game_compute_size(game_params *params, int tilesize,
908                               int *x, int *y)
909 {
910     /* Border is ts/2, to make things easier.
911      * Thus we have (width) + 2 (firing range*2) + 1 (border*2) tiles
912      * across, and similarly height + 2 + 1 tiles down. */
913     *x = (params->w + 3) * tilesize;
914     *y = (params->h + 3) * tilesize;
915 }
916
917 static void game_set_size(game_drawstate *ds, game_params *params,
918                           int tilesize)
919 {
920     ds->tilesize = tilesize;
921     ds->crad = (tilesize-1)/2;
922     ds->rrad = (3*tilesize)/8;
923 }
924
925 static float *game_colours(frontend *fe, game_state *state, int *ncolours)
926 {
927     float *ret = snewn(3 * NCOLOURS, float);
928     int i;
929
930     game_mkhighlight(fe, ret, COL_BACKGROUND, COL_HIGHLIGHT, COL_LOWLIGHT);
931
932     ret[COL_BALL * 3 + 0] = 0.0F;
933     ret[COL_BALL * 3 + 1] = 0.0F;
934     ret[COL_BALL * 3 + 2] = 0.0F;
935
936     ret[COL_WRONG * 3 + 0] = 1.0F;
937     ret[COL_WRONG * 3 + 1] = 0.0F;
938     ret[COL_WRONG * 3 + 2] = 0.0F;
939
940     ret[COL_BUTTON * 3 + 0] = 0.0F;
941     ret[COL_BUTTON * 3 + 1] = 1.0F;
942     ret[COL_BUTTON * 3 + 2] = 0.0F;
943
944     ret[COL_LASER * 3 + 0] = 1.0F;
945     ret[COL_LASER * 3 + 1] = 0.0F;
946     ret[COL_LASER * 3 + 2] = 0.0F;
947
948     ret[COL_DIMLASER * 3 + 0] = 0.5F;
949     ret[COL_DIMLASER * 3 + 1] = 0.0F;
950     ret[COL_DIMLASER * 3 + 2] = 0.0F;
951
952     for (i = 0; i < 3; i++) {
953         ret[COL_GRID * 3 + i] = ret[COL_BACKGROUND * 3 + i] * 0.9F;
954         ret[COL_LOCK * 3 + i] = ret[COL_BACKGROUND * 3 + i] * 0.7F;
955         ret[COL_COVER * 3 + i] = ret[COL_BACKGROUND * 3 + i] * 0.5F;
956         ret[COL_TEXT * 3 + i] = 0.0F;
957     }
958
959     ret[COL_FLASHTEXT * 3 + 0] = 0.0F;
960     ret[COL_FLASHTEXT * 3 + 1] = 1.0F;
961     ret[COL_FLASHTEXT * 3 + 2] = 0.0F;
962
963     *ncolours = NCOLOURS;
964     return ret;
965 }
966
967 static game_drawstate *game_new_drawstate(game_state *state)
968 {
969     struct game_drawstate *ds = snew(struct game_drawstate);
970
971     ds->tilesize = 0;
972     ds->w = state->w; ds->h = state->h;
973     ds->grid = snewn((state->w+2)*(state->h+2), unsigned int);
974     memset(ds->grid, 0, (state->w+2)*(state->h+2)*sizeof(unsigned int));
975     ds->started = 0;
976     ds->flash_laserno = LASER_EMPTY;
977
978     return ds;
979 }
980
981 static void game_free_drawstate(game_drawstate *ds)
982 {
983     sfree(ds->grid);
984     sfree(ds);
985 }
986
987 static void draw_arena_tile(frontend *fe, game_state *gs, game_drawstate *ds,
988                             int ax, int ay, int force, int isflash)
989 {
990     int gx = ax+1, gy = ay+1;
991     int gs_tile = GRID(gs, gx, gy), ds_tile = GRID(ds, gx, gy);
992     int dx = TODRAW(gx), dy = TODRAW(gy);
993
994     if (gs_tile != ds_tile || gs->reveal != ds->reveal || force) {
995         int bcol, bg;
996
997         bg = (gs->reveal ? COL_BACKGROUND :
998               (gs_tile & BALL_LOCK) ? COL_LOCK : COL_COVER);
999
1000         draw_rect(fe, dx, dy, TILE_SIZE, TILE_SIZE, bg);
1001         draw_rect_outline(fe, dx, dy, TILE_SIZE, TILE_SIZE, COL_GRID);
1002
1003         if (gs->reveal) {
1004             /* Guessed balls are always black; if they're incorrect they'll
1005              * have a red cross added later.
1006              * Missing balls are red. */
1007             if (gs_tile & BALL_GUESS) {
1008                 bcol = isflash ? bg : COL_BALL;
1009             } else if (gs_tile & BALL_CORRECT) {
1010                 bcol = isflash ? bg : COL_WRONG;
1011             } else {
1012                 bcol = bg;
1013             }
1014         } else {
1015             /* guesses are black/black, all else background. */
1016             if (gs_tile & BALL_GUESS) {
1017                 bcol = COL_BALL;
1018             } else {
1019                 bcol = bg;
1020             }
1021         }
1022
1023         draw_circle(fe, dx + TILE_SIZE/2, dy + TILE_SIZE/2, ds->crad-1,
1024                     bcol, bcol);
1025
1026         if (gs->reveal &&
1027             (gs_tile & BALL_GUESS) &&
1028             !(gs_tile & BALL_CORRECT)) {
1029             int x1 = dx + 3, y1 = dy + 3;
1030             int x2 = dx + TILE_SIZE - 3, y2 = dy + TILE_SIZE-3;
1031             int coords[8];
1032
1033             /* Incorrect guess; draw a red cross over the ball. */
1034             coords[0] = x1-1;
1035             coords[1] = y1+1;
1036             coords[2] = x1+1;
1037             coords[3] = y1-1;
1038             coords[4] = x2+1;
1039             coords[5] = y2-1;
1040             coords[6] = x2-1;
1041             coords[7] = y2+1;
1042             draw_polygon(fe, coords, 4, COL_WRONG, COL_WRONG);
1043             coords[0] = x2+1;
1044             coords[1] = y1+1;
1045             coords[2] = x2-1;
1046             coords[3] = y1-1;
1047             coords[4] = x1-1;
1048             coords[5] = y2-1;
1049             coords[6] = x1+1;
1050             coords[7] = y2+1;
1051             draw_polygon(fe, coords, 4, COL_WRONG, COL_WRONG);
1052         }
1053         draw_update(fe, dx, dy, TILE_SIZE, TILE_SIZE);
1054     }
1055     GRID(ds,gx,gy) = gs_tile;
1056 }
1057
1058 static void draw_laser_tile(frontend *fe, game_state *gs, game_drawstate *ds,
1059                             game_ui *ui, int lno, int force)
1060 {
1061     int gx, gy, dx, dy, unused;
1062     int wrong, omitted, reflect, hit, laserval, flash = 0, tmp;
1063     unsigned int gs_tile, ds_tile, exitno;
1064
1065     tmp = range2grid(gs, lno, &gx, &gy, &unused);
1066     assert(tmp);
1067     gs_tile = GRID(gs, gx, gy);
1068     ds_tile = GRID(ds, gx, gy);
1069     dx = TODRAW(gx);
1070     dy = TODRAW(gy);
1071
1072     wrong = gs->exits[lno] & LASER_WRONG;
1073     omitted = gs->exits[lno] & LASER_OMITTED;
1074     exitno = gs->exits[lno] & ~LASER_FLAGMASK;
1075
1076     reflect = gs_tile & LASER_REFLECT;
1077     hit = gs_tile & LASER_HIT;
1078     laserval = gs_tile & ~LASER_FLAGMASK;
1079
1080     if (lno == ui->flash_laserno)
1081         gs_tile |= LASER_FLASHED;
1082     else if (!(gs->exits[lno] & (LASER_HIT | LASER_REFLECT))) {
1083         if (exitno == ui->flash_laserno)
1084             gs_tile |= LASER_FLASHED;
1085     }
1086     if (gs_tile & LASER_FLASHED) flash = 1;
1087
1088     gs_tile |= wrong | omitted;
1089
1090     if (gs_tile != ds_tile || force) {
1091         draw_rect(fe, dx, dy, TILE_SIZE, TILE_SIZE, COL_BACKGROUND);
1092         draw_rect_outline(fe, dx, dy, TILE_SIZE, TILE_SIZE, COL_GRID);
1093
1094         if (gs_tile &~ (LASER_WRONG | LASER_OMITTED)) {
1095             char str[10];
1096             int tcol = flash ? COL_FLASHTEXT : omitted ? COL_WRONG : COL_TEXT;
1097
1098             if (reflect || hit)
1099                 sprintf(str, "%s", reflect ? "R" : "H");
1100             else
1101                 sprintf(str, "%d", laserval);
1102
1103             if (wrong) {
1104                 draw_circle(fe, dx + TILE_SIZE/2, dy + TILE_SIZE/2,
1105                             ds->rrad,
1106                             COL_WRONG, COL_WRONG);
1107                 draw_circle(fe, dx + TILE_SIZE/2, dy + TILE_SIZE/2,
1108                             ds->rrad - TILE_SIZE/16,
1109                             COL_BACKGROUND, COL_WRONG);
1110             }
1111
1112             draw_text(fe, dx + TILE_SIZE/2, dy + TILE_SIZE/2,
1113                       FONT_VARIABLE, TILE_SIZE/2, ALIGN_VCENTRE | ALIGN_HCENTRE,
1114                       tcol, str);
1115         }
1116         draw_update(fe, dx, dy, TILE_SIZE, TILE_SIZE);
1117     }
1118     GRID(ds, gx, gy) = gs_tile;
1119 }
1120
1121
1122 static void game_redraw(frontend *fe, game_drawstate *ds, game_state *oldstate,
1123                         game_state *state, int dir, game_ui *ui,
1124                         float animtime, float flashtime)
1125 {
1126     int i, x, y, ts = TILE_SIZE, isflash = 0, force = 0;
1127
1128     if (flashtime > 0) {
1129         int frame = (int)(flashtime / FLASH_FRAME);
1130         isflash = (frame % 2) == 0;
1131         force = 1;
1132         debug(("game_redraw: flashtime = %f", flashtime));
1133     }
1134
1135     if (!ds->started) {
1136         int x0 = TODRAW(0)-1, y0 = TODRAW(0)-1;
1137         int x1 = TODRAW(state->w+2), y1 = TODRAW(state->h+2);
1138
1139         draw_rect(fe, 0, 0,
1140                   TILE_SIZE * (state->w+3), TILE_SIZE * (state->h+3),
1141                   COL_BACKGROUND);
1142
1143         /* clockwise around the outline starting at pt behind (1,1). */
1144         draw_line(fe, x0+ts, y0+ts, x0+ts, y0,    COL_HIGHLIGHT);
1145         draw_line(fe, x0+ts, y0,    x1-ts, y0,    COL_HIGHLIGHT);
1146         draw_line(fe, x1-ts, y0,    x1-ts, y0+ts, COL_LOWLIGHT);
1147         draw_line(fe, x1-ts, y0+ts, x1,    y0+ts, COL_HIGHLIGHT);
1148         draw_line(fe, x1,    y0+ts, x1,    y1-ts, COL_LOWLIGHT);
1149         draw_line(fe, x1,    y1-ts, x1-ts, y1-ts, COL_LOWLIGHT);
1150         draw_line(fe, x1-ts, y1-ts, x1-ts, y1,    COL_LOWLIGHT);
1151         draw_line(fe, x1-ts, y1,    x0+ts, y1,    COL_LOWLIGHT);
1152         draw_line(fe, x0+ts, y1,    x0+ts, y1-ts, COL_HIGHLIGHT);
1153         draw_line(fe, x0+ts, y1-ts, x0,    y1-ts, COL_LOWLIGHT);
1154         draw_line(fe, x0,    y1-ts, x0,    y0+ts, COL_HIGHLIGHT);
1155         draw_line(fe, x0,    y0+ts, x0+ts, y0+ts, COL_HIGHLIGHT);
1156         /* phew... */
1157
1158         draw_update(fe, 0, 0,
1159                     TILE_SIZE * (state->w+3), TILE_SIZE * (state->h+3));
1160         force = 1;
1161         ds->started = 1;
1162     }
1163
1164     /* draw the arena */
1165     for (x = 0; x < state->w; x++) {
1166         for (y = 0; y < state->h; y++) {
1167             draw_arena_tile(fe, state, ds, x, y, force, isflash);
1168         }
1169     }
1170
1171     /* draw the lasers */
1172     for (i = 0; i < 2*(state->w+state->h); i++) {
1173         draw_laser_tile(fe, state, ds, ui, i, force);
1174     }
1175
1176     /* draw the 'finish' button */
1177     if (state->nguesses >= state->minballs &&
1178         state->nguesses <= state->maxballs &&
1179         !state->reveal) {
1180         clip(fe, TODRAW(0), TODRAW(0), TILE_SIZE-1, TILE_SIZE-1);
1181         draw_circle(fe, TODRAW(0) + ds->crad, TODRAW(0) + ds->crad, ds->crad,
1182                     COL_BUTTON, COL_BALL);
1183         unclip(fe);
1184         ds->canreveal = 1;
1185     } else {
1186         draw_rect(fe, TODRAW(0), TODRAW(0),
1187                   TILE_SIZE-1, TILE_SIZE-1, COL_BACKGROUND);
1188         ds->canreveal = 0;
1189     }
1190     draw_update(fe, TODRAW(0), TODRAW(0), TILE_SIZE, TILE_SIZE);
1191     ds->reveal = state->reveal;
1192     ds->flash_laserno = ui->flash_laserno;
1193
1194     {
1195         char buf[256];
1196
1197         if (ds->reveal) {
1198             if (state->nwrong == 0 &&
1199                 state->nmissed == 0 &&
1200                 state->nright >= state->minballs)
1201                 sprintf(buf, "CORRECT!");
1202             else
1203                 sprintf(buf, "%d wrong and %d missed balls.",
1204                         state->nwrong, state->nmissed);
1205         } else {
1206             if (state->nguesses > state->maxballs)
1207                 sprintf(buf, "%d too many balls marked.",
1208                         state->nguesses - state->maxballs);
1209             else if (state->nguesses <= state->maxballs &&
1210                      state->nguesses >= state->minballs)
1211                 sprintf(buf, "Click button to verify guesses.");
1212             else if (state->maxballs == state->minballs)
1213                 sprintf(buf, "Balls marked: %d / %d",
1214                         state->nguesses, state->minballs);
1215             else
1216                 sprintf(buf, "Balls marked: %d / %d-%d.",
1217                         state->nguesses, state->minballs, state->maxballs);
1218         }
1219         status_bar(fe, buf);
1220     }
1221 }
1222
1223 static float game_anim_length(game_state *oldstate, game_state *newstate,
1224                               int dir, game_ui *ui)
1225 {
1226     return 0.0F;
1227 }
1228
1229 static float game_flash_length(game_state *oldstate, game_state *newstate,
1230                                int dir, game_ui *ui)
1231 {
1232     if (!oldstate->reveal && newstate->reveal)
1233         return 4.0F * FLASH_FRAME;
1234     else
1235         return 0.0F;
1236 }
1237
1238 static int game_wants_statusbar(void)
1239 {
1240     return TRUE;
1241 }
1242
1243 static int game_timing_state(game_state *state, game_ui *ui)
1244 {
1245     return TRUE;
1246 }
1247
1248 #ifdef COMBINED
1249 #define thegame blackbox
1250 #endif
1251
1252 const struct game thegame = {
1253     "Black Box", "games.blackbox",
1254     default_params,
1255     game_fetch_preset,
1256     decode_params,
1257     encode_params,
1258     free_params,
1259     dup_params,
1260     TRUE, game_configure, custom_params,
1261     validate_params,
1262     new_game_desc,
1263     validate_desc,
1264     new_game,
1265     dup_game,
1266     free_game,
1267     TRUE, solve_game,
1268     FALSE, game_text_format,
1269     new_ui,
1270     free_ui,
1271     encode_ui,
1272     decode_ui,
1273     game_changed_state,
1274     interpret_move,
1275     execute_move,
1276     PREFERRED_TILE_SIZE, game_compute_size, game_set_size,
1277     game_colours,
1278     game_new_drawstate,
1279     game_free_drawstate,
1280     game_redraw,
1281     game_anim_length,
1282     game_flash_length,
1283     game_wants_statusbar,
1284     FALSE, game_timing_state,
1285     0,                                 /* mouse_priorities */
1286 };
1287
1288 /* vim: set shiftwidth=4 tabstop=8: */