chiark / gitweb /
Update changelog for 20170923.ff218728-0+iwj2~3.gbpc58e0c release
[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_CURSOR,
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(const 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(const 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(const 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].u.string.sval = dupstr(buf);
152
153     ret[1].name = "Height";
154     ret[1].type = C_STRING;
155     sprintf(buf, "%d", params->h);
156     ret[1].u.string.sval = dupstr(buf);
157
158     ret[2].name = "No. of balls";
159     ret[2].type = C_STRING;
160     if (params->minballs == params->maxballs)
161         sprintf(buf, "%d", params->minballs);
162     else
163         sprintf(buf, "%d-%d", params->minballs, params->maxballs);
164     ret[2].u.string.sval = dupstr(buf);
165
166     ret[3].name = NULL;
167     ret[3].type = C_END;
168
169     return ret;
170 }
171
172 static game_params *custom_params(const config_item *cfg)
173 {
174     game_params *ret = snew(game_params);
175
176     ret->w = atoi(cfg[0].u.string.sval);
177     ret->h = atoi(cfg[1].u.string.sval);
178
179     /* Allow 'a-b' for a range, otherwise assume a single number. */
180     if (sscanf(cfg[2].u.string.sval, "%d-%d",
181                &ret->minballs, &ret->maxballs) < 2)
182         ret->minballs = ret->maxballs = atoi(cfg[2].u.string.sval);
183
184     return ret;
185 }
186
187 static const char *validate_params(const game_params *params, int full)
188 {
189     if (params->w < 2 || params->h < 2)
190         return "Width and height must both be at least two";
191     /* next one is just for ease of coding stuff into 'char'
192      * types, and could be worked around if required. */
193     if (params->w > 255 || params->h > 255)
194         return "Widths and heights greater than 255 are not supported";
195     if (params->minballs > params->maxballs)
196         return "Minimum number of balls may not be greater than maximum";
197     if (params->minballs >= params->w * params->h)
198         return "Too many balls to fit in grid";
199     return NULL;
200 }
201
202 /*
203  * We store: width | height | ball1x | ball1y | [ ball2x | ball2y | [...] ]
204  * all stored as unsigned chars; validate_params has already
205  * checked this won't overflow an 8-bit char.
206  * Then we obfuscate it.
207  */
208
209 static char *new_game_desc(const game_params *params, random_state *rs,
210                            char **aux, int interactive)
211 {
212     int nballs = params->minballs, i;
213     char *grid, *ret;
214     unsigned char *bmp;
215
216     if (params->maxballs > params->minballs)
217         nballs += random_upto(rs, params->maxballs - params->minballs + 1);
218
219     grid = snewn(params->w*params->h, char);
220     memset(grid, 0, params->w * params->h * sizeof(char));
221
222     bmp = snewn(nballs*2 + 2, unsigned char);
223     memset(bmp, 0, (nballs*2 + 2) * sizeof(unsigned char));
224
225     bmp[0] = params->w;
226     bmp[1] = params->h;
227
228     for (i = 0; i < nballs; i++) {
229         int x, y;
230
231         do {
232             x = random_upto(rs, params->w);
233             y = random_upto(rs, params->h);
234         } while (grid[y*params->w + x]);
235
236         grid[y*params->w + x] = 1;
237
238         bmp[(i+1)*2 + 0] = x;
239         bmp[(i+1)*2 + 1] = y;
240     }
241     sfree(grid);
242
243     obfuscate_bitmap(bmp, (nballs*2 + 2) * 8, FALSE);
244     ret = bin2hex(bmp, nballs*2 + 2);
245     sfree(bmp);
246
247     return ret;
248 }
249
250 static const char *validate_desc(const game_params *params, const char *desc)
251 {
252     int nballs, dlen = strlen(desc), i;
253     unsigned char *bmp;
254     const char *ret;
255
256     /* the bitmap is 2+(nballs*2) long; the hex version is double that. */
257     nballs = ((dlen/2)-2)/2;
258
259     if (dlen < 4 || dlen % 4 ||
260         nballs < params->minballs || nballs > params->maxballs)
261         return "Game description is wrong length";
262
263     bmp = hex2bin(desc, nballs*2 + 2);
264     obfuscate_bitmap(bmp, (nballs*2 + 2) * 8, TRUE);
265     ret = "Game description is corrupted";
266     /* check general grid size */
267     if (bmp[0] != params->w || bmp[1] != params->h)
268         goto done;
269     /* check each ball will fit on that grid */
270     for (i = 0; i < nballs; i++) {
271         int x = bmp[(i+1)*2 + 0], y = bmp[(i+1)*2 + 1];
272         if (x < 0 || y < 0 || x >= params->w || y >= params->h)
273             goto done;
274     }
275     ret = NULL;
276
277 done:
278     sfree(bmp);
279     return ret;
280 }
281
282 #define BALL_CORRECT    0x01
283 #define BALL_GUESS      0x02
284 #define BALL_LOCK       0x04
285
286 #define LASER_FLAGMASK  0x1f800
287 #define LASER_OMITTED    0x0800
288 #define LASER_REFLECT    0x1000
289 #define LASER_HIT        0x2000
290 #define LASER_WRONG      0x4000
291 #define LASER_FLASHED    0x8000
292 #define LASER_EMPTY      (~0)
293
294 #define FLAG_CURSOR     0x10000 /* needs to be disjoint from both sets */
295
296 struct game_state {
297     int w, h, minballs, maxballs, nballs, nlasers;
298     unsigned int *grid; /* (w+2)x(h+2), to allow for laser firing range */
299     unsigned int *exits; /* one per laser */
300     int done;           /* user has finished placing his own balls. */
301     int laserno;        /* number of next laser to be fired. */
302     int nguesses, reveal, justwrong, nright, nwrong, nmissed;
303 };
304
305 #define GRID(s,x,y) ((s)->grid[(y)*((s)->w+2) + (x)])
306
307 #define RANGECHECK(s,x) ((x) >= 0 && (x) <= (s)->nlasers)
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(const game_state *state, int rangeno, int *x, int *y,
328                       int *direction)
329 {
330     if (rangeno < 0)
331         return 0;
332
333     if (rangeno < state->w) {
334         /* top row; from (1,0) to (w,0) */
335         *x = rangeno + 1;
336         *y = 0;
337         *direction = DIR_DOWN;
338         return 1;
339     }
340     rangeno -= state->w;
341     if (rangeno < state->h) {
342         /* RHS; from (w+1, 1) to (w+1, h) */
343         *x = state->w+1;
344         *y = rangeno + 1;
345         *direction = DIR_LEFT;
346         return 1;
347     }
348     rangeno -= state->h;
349     if (rangeno < state->w) {
350         /* bottom row; from (1, h+1) to (w, h+1); counts backwards */
351         *x = (state->w - rangeno);
352         *y = state->h+1;
353         *direction = DIR_UP;
354         return 1;
355     }
356     rangeno -= state->w;
357     if (rangeno < state->h) {
358         /* LHS; from (0, 1) to (0, h); counts backwards */
359         *x = 0;
360         *y = (state->h - rangeno);
361         *direction = DIR_RIGHT;
362         return 1;
363     }
364     return 0;
365 }
366
367 static int grid2range(const game_state *state, int x, int y, int *rangeno)
368 {
369     int ret, x1 = state->w+1, y1 = state->h+1;
370
371     if (x > 0 && x < x1 && y > 0 && y < y1) return 0; /* in arena */
372     if (x < 0 || x > x1 || y < 0 || y > y1) return 0; /* outside grid */
373
374     if ((x == 0 || x == x1) && (y == 0 || y == y1))
375         return 0; /* one of 4 corners */
376
377     if (y == 0) {               /* top line */
378         ret = x - 1;
379     } else if (x == x1) {       /* RHS */
380         ret = y - 1 + state->w;
381     } else if (y == y1) {       /* Bottom [and counts backwards] */
382         ret = (state->w - x) + state->w + state->h;
383     } else {                    /* LHS [and counts backwards ] */
384         ret = (state->h-y) + state->w + state->w + state->h;
385     }
386     *rangeno = ret;
387     debug(("grid2range: (%d,%d) rangeno = %d\n", x, y, ret));
388     return 1;
389 }
390
391 static game_state *new_game(midend *me, const game_params *params,
392                             const char *desc)
393 {
394     game_state *state = snew(game_state);
395     int dlen = strlen(desc), i;
396     unsigned char *bmp;
397
398     state->minballs = params->minballs;
399     state->maxballs = params->maxballs;
400     state->nballs = ((dlen/2)-2)/2;
401
402     bmp = hex2bin(desc, state->nballs*2 + 2);
403     obfuscate_bitmap(bmp, (state->nballs*2 + 2) * 8, TRUE);
404
405     state->w = bmp[0]; state->h = bmp[1];
406     state->nlasers = 2 * (state->w + state->h);
407
408     state->grid = snewn((state->w+2)*(state->h+2), unsigned int);
409     memset(state->grid, 0, (state->w+2)*(state->h+2) * sizeof(unsigned int));
410
411     state->exits = snewn(state->nlasers, unsigned int);
412     memset(state->exits, LASER_EMPTY, state->nlasers * sizeof(unsigned int));
413
414     for (i = 0; i < state->nballs; i++) {
415         GRID(state, bmp[(i+1)*2 + 0]+1, bmp[(i+1)*2 + 1]+1) = BALL_CORRECT;
416     }
417     sfree(bmp);
418
419     state->done = state->nguesses = state->reveal = state->justwrong =
420         state->nright = state->nwrong = state->nmissed = 0;
421     state->laserno = 1;
422
423     return state;
424 }
425
426 #define XFER(x) ret->x = state->x
427
428 static game_state *dup_game(const game_state *state)
429 {
430     game_state *ret = snew(game_state);
431
432     XFER(w); XFER(h);
433     XFER(minballs); XFER(maxballs);
434     XFER(nballs); XFER(nlasers);
435
436     ret->grid = snewn((ret->w+2)*(ret->h+2), unsigned int);
437     memcpy(ret->grid, state->grid, (ret->w+2)*(ret->h+2) * sizeof(unsigned int));
438     ret->exits = snewn(ret->nlasers, unsigned int);
439     memcpy(ret->exits, state->exits, ret->nlasers * sizeof(unsigned int));
440
441     XFER(done);
442     XFER(laserno);
443     XFER(nguesses);
444     XFER(reveal);
445     XFER(justwrong);
446     XFER(nright); XFER(nwrong); XFER(nmissed);
447
448     return ret;
449 }
450
451 #undef XFER
452
453 static void free_game(game_state *state)
454 {
455     sfree(state->exits);
456     sfree(state->grid);
457     sfree(state);
458 }
459
460 static char *solve_game(const game_state *state, const game_state *currstate,
461                         const char *aux, const char **error)
462 {
463     return dupstr("S");
464 }
465
466 static int game_can_format_as_text_now(const game_params *params)
467 {
468     return TRUE;
469 }
470
471 static char *game_text_format(const game_state *state)
472 {
473     return NULL;
474 }
475
476 struct game_ui {
477     int flash_laserno;
478     int errors, newmove;
479     int cur_x, cur_y, cur_visible;
480     int flash_laser; /* 0 = never, 1 = always, 2 = if anim. */
481 };
482
483 static game_ui *new_ui(const game_state *state)
484 {
485     game_ui *ui = snew(game_ui);
486     ui->flash_laserno = LASER_EMPTY;
487     ui->errors = 0;
488     ui->newmove = FALSE;
489
490     ui->cur_x = ui->cur_y = 1;
491     ui->cur_visible = 0;
492
493     ui->flash_laser = 0;
494
495     return ui;
496 }
497
498 static void free_ui(game_ui *ui)
499 {
500     sfree(ui);
501 }
502
503 static char *encode_ui(const game_ui *ui)
504 {
505     char buf[80];
506     /*
507      * The error counter needs preserving across a serialisation.
508      */
509     sprintf(buf, "E%d", ui->errors);
510     return dupstr(buf);
511 }
512
513 static void decode_ui(game_ui *ui, const char *encoding)
514 {
515     sscanf(encoding, "E%d", &ui->errors);
516 }
517
518 static void game_changed_state(game_ui *ui, const game_state *oldstate,
519                                const game_state *newstate)
520 {
521     /*
522      * If we've encountered a `justwrong' state as a result of
523      * actually making a move, increment the ui error counter.
524      */
525     if (newstate->justwrong && ui->newmove)
526         ui->errors++;
527     ui->newmove = FALSE;
528 }
529
530 #define OFFSET(gx,gy,o) do {                                    \
531     int off = (4 + (o) % 4) % 4;                                \
532     (gx) += offsets[off].x;                                     \
533     (gy) += offsets[off].y;                                     \
534 } while(0)
535
536 enum { LOOK_LEFT, LOOK_FORWARD, LOOK_RIGHT };
537
538 /* Given a position and a direction, check whether we can see a ball in front
539  * of us, or to our front-left or front-right. */
540 static int isball(game_state *state, int gx, int gy, int direction, int lookwhere)
541 {
542     debug(("isball, (%d, %d), dir %s, lookwhere %s\n", gx, gy, dirstrs[direction],
543            lookwhere == LOOK_LEFT ? "LEFT" :
544            lookwhere == LOOK_FORWARD ? "FORWARD" : "RIGHT"));
545     OFFSET(gx,gy,direction);
546     if (lookwhere == LOOK_LEFT)
547         OFFSET(gx,gy,direction-1);
548     else if (lookwhere == LOOK_RIGHT)
549         OFFSET(gx,gy,direction+1);
550     else if (lookwhere != LOOK_FORWARD)
551         assert(!"unknown lookwhere");
552
553     debug(("isball, new (%d, %d)\n", gx, gy));
554
555     /* if we're off the grid (into the firing range) there's never a ball. */
556     if (gx < 1 || gy < 1 || gx > state->w || gy > state->h)
557         return 0;
558
559     if (GRID(state, gx,gy) & BALL_CORRECT)
560         return 1;
561
562     return 0;
563 }
564
565 static int fire_laser_internal(game_state *state, int x, int y, int direction)
566 {
567     int unused, lno, tmp;
568
569     tmp = grid2range(state, x, y, &lno);
570     assert(tmp);
571
572     /* deal with strange initial reflection rules (that stop
573      * you turning down the laser range) */
574
575     /* I've just chosen to prioritise instant-hit over instant-reflection;
576      * I can't find anywhere that gives me a definite algorithm for this. */
577     if (isball(state, x, y, direction, LOOK_FORWARD)) {
578         debug(("Instant hit at (%d, %d)\n", x, y));
579         return LASER_HIT;              /* hit */
580     }
581
582     if (isball(state, x, y, direction, LOOK_LEFT) ||
583         isball(state, x, y, direction, LOOK_RIGHT)) {
584         debug(("Instant reflection at (%d, %d)\n", x, y));
585         return LASER_REFLECT;          /* reflection */
586     }
587     /* move us onto the grid. */
588     OFFSET(x, y, direction);
589
590     while (1) {
591         debug(("fire_laser: looping at (%d, %d) pointing %s\n",
592                x, y, dirstrs[direction]));
593         if (grid2range(state, x, y, &unused)) {
594             int exitno;
595
596             tmp = grid2range(state, x, y, &exitno);
597             assert(tmp);
598
599             return (lno == exitno ? LASER_REFLECT : exitno);
600         }
601         /* paranoia. This obviously should never happen */
602         assert(!(GRID(state, x, y) & BALL_CORRECT));
603
604         if (isball(state, x, y, direction, LOOK_FORWARD)) {
605             /* we're facing a ball; send back a reflection. */
606             debug(("Ball ahead of (%d, %d)", x, y));
607             return LASER_HIT;          /* hit */
608         }
609
610         if (isball(state, x, y, direction, LOOK_LEFT)) {
611             /* ball to our left; rotate clockwise and look again. */
612             debug(("Ball to left; turning clockwise.\n"));
613             direction += 1; direction %= 4;
614             continue;
615         }
616         if (isball(state, x, y, direction, LOOK_RIGHT)) {
617             /* ball to our right; rotate anti-clockwise and look again. */
618             debug(("Ball to rightl turning anti-clockwise.\n"));
619             direction += 3; direction %= 4;
620             continue;
621         }
622         /* ... otherwise, we have no balls ahead of us so just move one step. */
623         debug(("No balls; moving forwards.\n"));
624         OFFSET(x, y, direction);
625     }
626 }
627
628 static int laser_exit(game_state *state, int entryno)
629 {
630     int tmp, x, y, direction;
631
632     tmp = range2grid(state, entryno, &x, &y, &direction);
633     assert(tmp);
634
635     return fire_laser_internal(state, x, y, direction);
636 }
637
638 static void fire_laser(game_state *state, int entryno)
639 {
640     int tmp, exitno, x, y, direction;
641
642     tmp = range2grid(state, entryno, &x, &y, &direction);
643     assert(tmp);
644
645     exitno = fire_laser_internal(state, x, y, direction);
646
647     if (exitno == LASER_HIT || exitno == LASER_REFLECT) {
648         GRID(state, x, y) = state->exits[entryno] = exitno;
649     } else {
650         int newno = state->laserno++;
651         int xend, yend, unused;
652         tmp = range2grid(state, exitno, &xend, &yend, &unused);
653         assert(tmp);
654         GRID(state, x, y) = GRID(state, xend, yend) = newno;
655         state->exits[entryno] = exitno;
656         state->exits[exitno] = entryno;
657     }
658 }
659
660 /* Checks that the guessed balls in the state match up with the real balls
661  * for all possible lasers (i.e. not just the ones that the player might
662  * have already guessed). This is required because any layout with >4 balls
663  * might have multiple valid solutions. Returns non-zero for a 'correct'
664  * (i.e. consistent) layout. */
665 static int check_guesses(game_state *state, int cagey)
666 {
667     game_state *solution, *guesses;
668     int i, x, y, n, unused, tmp;
669     int ret = 0;
670
671     if (cagey) {
672         /*
673          * First, check that each laser the player has already
674          * fired is consistent with the layout. If not, show them
675          * one error they've made and reveal no further
676          * information.
677          *
678          * Failing that, check to see whether the player would have
679          * been able to fire any laser which distinguished the real
680          * solution from their guess. If so, show them one such
681          * laser and reveal no further information.
682          */
683         guesses = dup_game(state);
684         /* clear out BALL_CORRECT on guess, make BALL_GUESS BALL_CORRECT. */
685         for (x = 1; x <= state->w; x++) {
686             for (y = 1; y <= state->h; y++) {
687                 GRID(guesses, x, y) &= ~BALL_CORRECT;
688                 if (GRID(guesses, x, y) & BALL_GUESS)
689                     GRID(guesses, x, y) |= BALL_CORRECT;
690             }
691         }
692         n = 0;
693         for (i = 0; i < guesses->nlasers; i++) {
694             if (guesses->exits[i] != LASER_EMPTY &&
695                 guesses->exits[i] != laser_exit(guesses, i))
696                 n++;
697         }
698         if (n) {
699             /*
700              * At least one of the player's existing lasers
701              * contradicts their ball placement. Pick a random one,
702              * highlight it, and return.
703              *
704              * A temporary random state is created from the current
705              * grid, so that repeating the same marking will give
706              * the same answer instead of a different one.
707              */
708             random_state *rs = random_new((char *)guesses->grid,
709                                           (state->w+2)*(state->h+2) *
710                                           sizeof(unsigned int));
711             n = random_upto(rs, n);
712             random_free(rs);
713             for (i = 0; i < guesses->nlasers; i++) {
714                 if (guesses->exits[i] != LASER_EMPTY &&
715                     guesses->exits[i] != laser_exit(guesses, i) &&
716                     n-- == 0) {
717                     state->exits[i] |= LASER_WRONG;
718                     tmp = laser_exit(state, i);
719                     if (RANGECHECK(state, tmp))
720                         state->exits[tmp] |= LASER_WRONG;
721                     state->justwrong = TRUE;
722                     free_game(guesses);
723                     return 0;
724                 }
725             }
726         }
727         n = 0;
728         for (i = 0; i < guesses->nlasers; i++) {
729             if (guesses->exits[i] == LASER_EMPTY &&
730                 laser_exit(state, i) != laser_exit(guesses, i))
731                 n++;
732         }
733         if (n) {
734             /*
735              * At least one of the player's unfired lasers would
736              * demonstrate their ball placement to be wrong. Pick a
737              * random one, highlight it, and return.
738              *
739              * A temporary random state is created from the current
740              * grid, so that repeating the same marking will give
741              * the same answer instead of a different one.
742              */
743             random_state *rs = random_new((char *)guesses->grid,
744                                           (state->w+2)*(state->h+2) *
745                                           sizeof(unsigned int));
746             n = random_upto(rs, n);
747             random_free(rs);
748             for (i = 0; i < guesses->nlasers; i++) {
749                 if (guesses->exits[i] == LASER_EMPTY &&
750                     laser_exit(state, i) != laser_exit(guesses, i) &&
751                     n-- == 0) {
752                     fire_laser(state, i);
753                     state->exits[i] |= LASER_OMITTED;
754                     tmp = laser_exit(state, i);
755                     if (RANGECHECK(state, tmp))
756                         state->exits[tmp] |= LASER_OMITTED;
757                     state->justwrong = TRUE;
758                     free_game(guesses);
759                     return 0;
760                 }
761             }
762         }
763         free_game(guesses);
764     }
765
766     /* duplicate the state (to solution) */
767     solution = dup_game(state);
768
769     /* clear out the lasers of solution */
770     for (i = 0; i < solution->nlasers; i++) {
771         tmp = range2grid(solution, i, &x, &y, &unused);
772         assert(tmp);
773         GRID(solution, x, y) = 0;
774         solution->exits[i] = LASER_EMPTY;
775     }
776
777     /* duplicate solution to guess. */
778     guesses = dup_game(solution);
779
780     /* clear out BALL_CORRECT on guess, make BALL_GUESS BALL_CORRECT. */
781     for (x = 1; x <= state->w; x++) {
782         for (y = 1; y <= state->h; y++) {
783             GRID(guesses, x, y) &= ~BALL_CORRECT;
784             if (GRID(guesses, x, y) & BALL_GUESS)
785                 GRID(guesses, x, y) |= BALL_CORRECT;
786         }
787     }
788
789     /* for each laser (on both game_states), fire it if it hasn't been fired.
790      * If one has been fired (or received a hit) and another hasn't, we know
791      * the ball layouts didn't match and can short-circuit return. */
792     for (i = 0; i < solution->nlasers; i++) {
793         if (solution->exits[i] == LASER_EMPTY)
794             fire_laser(solution, i);
795         if (guesses->exits[i] == LASER_EMPTY)
796             fire_laser(guesses, i);
797     }
798
799     /* check each game_state's laser against the other; if any differ, return 0 */
800     ret = 1;
801     for (i = 0; i < solution->nlasers; i++) {
802         tmp = range2grid(solution, i, &x, &y, &unused);
803         assert(tmp);
804
805         if (solution->exits[i] != guesses->exits[i]) {
806             /* If the original state didn't have this shot fired,
807              * and it would be wrong between the guess and the solution,
808              * add it. */
809             if (state->exits[i] == LASER_EMPTY) {
810                 state->exits[i] = solution->exits[i];
811                 if (state->exits[i] == LASER_REFLECT ||
812                     state->exits[i] == LASER_HIT)
813                     GRID(state, x, y) = state->exits[i];
814                 else {
815                     /* add a new shot, incrementing state's laser count. */
816                     int ex, ey, newno = state->laserno++;
817                     tmp = range2grid(state, state->exits[i], &ex, &ey, &unused);
818                     assert(tmp);
819                     GRID(state, x, y) = newno;
820                     GRID(state, ex, ey) = newno;
821                 }
822                 state->exits[i] |= LASER_OMITTED;
823             } else {
824                 state->exits[i] |= LASER_WRONG;
825             }
826             ret = 0;
827         }
828     }
829     if (ret == 0 ||
830         state->nguesses < state->minballs ||
831         state->nguesses > state->maxballs) goto done;
832
833     /* fix up original state so the 'correct' balls end up matching the guesses,
834      * as we've just proved that they were equivalent. */
835     for (x = 1; x <= state->w; x++) {
836         for (y = 1; y <= state->h; y++) {
837             if (GRID(state, x, y) & BALL_GUESS)
838                 GRID(state, x, y) |= BALL_CORRECT;
839             else
840                 GRID(state, x, y) &= ~BALL_CORRECT;
841         }
842     }
843
844 done:
845     /* fill in nright and nwrong. */
846     state->nright = state->nwrong = state->nmissed = 0;
847     for (x = 1; x <= state->w; x++) {
848         for (y = 1; y <= state->h; y++) {
849             int bs = GRID(state, x, y) & (BALL_GUESS | BALL_CORRECT);
850             if (bs == (BALL_GUESS | BALL_CORRECT))
851                 state->nright++;
852             else if (bs == BALL_GUESS)
853                 state->nwrong++;
854             else if (bs == BALL_CORRECT)
855                 state->nmissed++;
856         }
857     }
858     free_game(solution);
859     free_game(guesses);
860     state->reveal = 1;
861     return ret;
862 }
863
864 #define TILE_SIZE (ds->tilesize)
865
866 #define TODRAW(x) ((TILE_SIZE * (x)) + (TILE_SIZE / 2))
867 #define FROMDRAW(x) (((x) - (TILE_SIZE / 2)) / TILE_SIZE)
868
869 #define CAN_REVEAL(state) ((state)->nguesses >= (state)->minballs && \
870                            (state)->nguesses <= (state)->maxballs && \
871                            !(state)->reveal && !(state)->justwrong)
872
873 struct game_drawstate {
874     int tilesize, crad, rrad, w, h; /* w and h to make macros work... */
875     unsigned int *grid;          /* as the game_state grid */
876     int started, reveal;
877     int flash_laserno, isflash;
878 };
879
880 static char *interpret_move(const game_state *state, game_ui *ui,
881                             const game_drawstate *ds,
882                             int x, int y, int button)
883 {
884     int gx = -1, gy = -1, rangeno = -1, wouldflash = 0;
885     enum { NONE, TOGGLE_BALL, TOGGLE_LOCK, FIRE, REVEAL,
886            TOGGLE_COLUMN_LOCK, TOGGLE_ROW_LOCK} action = NONE;
887     char buf[80], *nullret = NULL;
888
889     if (IS_CURSOR_MOVE(button)) {
890         int cx = ui->cur_x, cy = ui->cur_y;
891
892         move_cursor(button, &cx, &cy, state->w+2, state->h+2, 0);
893         if ((cx == 0 && cy == 0 && !CAN_REVEAL(state)) ||
894             (cx == 0 && cy == state->h+1) ||
895             (cx == state->w+1 && cy == 0) ||
896             (cx == state->w+1 && cy == state->h+1))
897             return NULL; /* disallow moving cursor to corners. */
898         ui->cur_x = cx;
899         ui->cur_y = cy;
900         ui->cur_visible = 1;
901         return UI_UPDATE;
902     }
903
904     if (button == LEFT_BUTTON || button == RIGHT_BUTTON) {
905         gx = FROMDRAW(x);
906         gy = FROMDRAW(y);
907         ui->cur_visible = 0;
908         wouldflash = 1;
909     } else if (button == LEFT_RELEASE) {
910         ui->flash_laser = 0;
911         return UI_UPDATE;
912     } else if (IS_CURSOR_SELECT(button)) {
913         if (ui->cur_visible) {
914             gx = ui->cur_x;
915             gy = ui->cur_y;
916             ui->flash_laser = 0;
917             wouldflash = 2;
918         } else {
919             ui->cur_visible = 1;
920             return UI_UPDATE;
921         }
922         /* Fix up 'button' for the below logic. */
923         if (button == CURSOR_SELECT2) button = RIGHT_BUTTON;
924         else button = LEFT_BUTTON;
925     }
926
927     if (gx != -1 && gy != -1) {
928         if (gx == 0 && gy == 0 && button == LEFT_BUTTON)
929             action = REVEAL;
930         if (gx >= 1 && gx <= state->w && gy >= 1 && gy <= state->h) {
931             if (button == LEFT_BUTTON) {
932                 if (!(GRID(state, gx,gy) & BALL_LOCK))
933                     action = TOGGLE_BALL;
934             } else
935                 action = TOGGLE_LOCK;
936         }
937         if (grid2range(state, gx, gy, &rangeno)) {
938             if (button == LEFT_BUTTON)
939                 action = FIRE;
940             else if (gy == 0 || gy > state->h)
941                 action = TOGGLE_COLUMN_LOCK; /* and use gx */
942             else
943                 action = TOGGLE_ROW_LOCK;    /* and use gy */
944         }
945     }
946
947     switch (action) {
948     case TOGGLE_BALL:
949         sprintf(buf, "T%d,%d", gx, gy);
950         break;
951
952     case TOGGLE_LOCK:
953         sprintf(buf, "LB%d,%d", gx, gy);
954         break;
955
956     case TOGGLE_COLUMN_LOCK:
957         sprintf(buf, "LC%d", gx);
958         break;
959
960     case TOGGLE_ROW_LOCK:
961         sprintf(buf, "LR%d", gy);
962         break;
963
964     case FIRE:
965         if (state->reveal && state->exits[rangeno] == LASER_EMPTY)
966             return nullret;
967         ui->flash_laserno = rangeno;
968         ui->flash_laser = wouldflash;
969         nullret = UI_UPDATE;
970         if (state->exits[rangeno] != LASER_EMPTY)
971             return UI_UPDATE;
972         sprintf(buf, "F%d", rangeno);
973         break;
974
975     case REVEAL:
976         if (!CAN_REVEAL(state)) return nullret;
977         if (ui->cur_visible == 1) ui->cur_x = ui->cur_y = 1;
978         sprintf(buf, "R");
979         break;
980
981     default:
982         return nullret;
983     }
984     if (state->reveal) return nullret;
985     ui->newmove = TRUE;
986     return dupstr(buf);
987 }
988
989 static game_state *execute_move(const game_state *from, const char *move)
990 {
991     game_state *ret = dup_game(from);
992     int gx = -1, gy = -1, rangeno = -1;
993
994     if (ret->justwrong) {
995         int i;
996         ret->justwrong = FALSE;
997         for (i = 0; i < ret->nlasers; i++)
998             if (ret->exits[i] != LASER_EMPTY)
999                 ret->exits[i] &= ~(LASER_OMITTED | LASER_WRONG);
1000     }
1001
1002     if (!strcmp(move, "S")) {
1003         check_guesses(ret, FALSE);
1004         return ret;
1005     }
1006
1007     if (from->reveal) goto badmove;
1008     if (!*move) goto badmove;
1009
1010     switch (move[0]) {
1011     case 'T':
1012         sscanf(move+1, "%d,%d", &gx, &gy);
1013         if (gx < 1 || gy < 1 || gx > ret->w || gy > ret->h)
1014             goto badmove;
1015         if (GRID(ret, gx, gy) & BALL_GUESS) {
1016             ret->nguesses--;
1017             GRID(ret, gx, gy) &= ~BALL_GUESS;
1018         } else {
1019             ret->nguesses++;
1020             GRID(ret, gx, gy) |= BALL_GUESS;
1021         }
1022         break;
1023
1024     case 'F':
1025         sscanf(move+1, "%d", &rangeno);
1026         if (ret->exits[rangeno] != LASER_EMPTY)
1027             goto badmove;
1028         if (!RANGECHECK(ret, rangeno))
1029             goto badmove;
1030         fire_laser(ret, rangeno);
1031         break;
1032
1033     case 'R':
1034         if (ret->nguesses < ret->minballs ||
1035             ret->nguesses > ret->maxballs)
1036             goto badmove;
1037         check_guesses(ret, TRUE);
1038         break;
1039
1040     case 'L':
1041         {
1042             int lcount = 0;
1043             if (strlen(move) < 2) goto badmove;
1044             switch (move[1]) {
1045             case 'B':
1046                 sscanf(move+2, "%d,%d", &gx, &gy);
1047                 if (gx < 1 || gy < 1 || gx > ret->w || gy > ret->h)
1048                     goto badmove;
1049                 GRID(ret, gx, gy) ^= BALL_LOCK;
1050                 break;
1051
1052 #define COUNTLOCK do { if (GRID(ret, gx, gy) & BALL_LOCK) lcount++; } while (0)
1053 #define SETLOCKIF(c) do {                                       \
1054     if (lcount > (c)) GRID(ret, gx, gy) &= ~BALL_LOCK;          \
1055     else              GRID(ret, gx, gy) |= BALL_LOCK;           \
1056 } while(0)
1057
1058             case 'C':
1059                 sscanf(move+2, "%d", &gx);
1060                 if (gx < 1 || gx > ret->w) goto badmove;
1061                 for (gy = 1; gy <= ret->h; gy++) { COUNTLOCK; }
1062                 for (gy = 1; gy <= ret->h; gy++) { SETLOCKIF(ret->h/2); }
1063                 break;
1064
1065             case 'R':
1066                 sscanf(move+2, "%d", &gy);
1067                 if (gy < 1 || gy > ret->h) goto badmove;
1068                 for (gx = 1; gx <= ret->w; gx++) { COUNTLOCK; }
1069                 for (gx = 1; gx <= ret->w; gx++) { SETLOCKIF(ret->w/2); }
1070                 break;
1071
1072 #undef COUNTLOCK
1073 #undef SETLOCKIF
1074
1075             default:
1076                 goto badmove;
1077             }
1078         }
1079         break;
1080
1081     default:
1082         goto badmove;
1083     }
1084
1085     return ret;
1086
1087 badmove:
1088     free_game(ret);
1089     return NULL;
1090 }
1091
1092 /* ----------------------------------------------------------------------
1093  * Drawing routines.
1094  */
1095
1096 static void game_compute_size(const game_params *params, int tilesize,
1097                               int *x, int *y)
1098 {
1099     /* Border is ts/2, to make things easier.
1100      * Thus we have (width) + 2 (firing range*2) + 1 (border*2) tiles
1101      * across, and similarly height + 2 + 1 tiles down. */
1102     *x = (params->w + 3) * tilesize;
1103     *y = (params->h + 3) * tilesize;
1104 }
1105
1106 static void game_set_size(drawing *dr, game_drawstate *ds,
1107                           const game_params *params, int tilesize)
1108 {
1109     ds->tilesize = tilesize;
1110     ds->crad = (tilesize-1)/2;
1111     ds->rrad = (3*tilesize)/8;
1112 }
1113
1114 static float *game_colours(frontend *fe, int *ncolours)
1115 {
1116     float *ret = snewn(3 * NCOLOURS, float);
1117     int i;
1118
1119     game_mkhighlight(fe, ret, COL_BACKGROUND, COL_HIGHLIGHT, COL_LOWLIGHT);
1120
1121     ret[COL_BALL * 3 + 0] = 0.0F;
1122     ret[COL_BALL * 3 + 1] = 0.0F;
1123     ret[COL_BALL * 3 + 2] = 0.0F;
1124
1125     ret[COL_WRONG * 3 + 0] = 1.0F;
1126     ret[COL_WRONG * 3 + 1] = 0.0F;
1127     ret[COL_WRONG * 3 + 2] = 0.0F;
1128
1129     ret[COL_BUTTON * 3 + 0] = 0.0F;
1130     ret[COL_BUTTON * 3 + 1] = 1.0F;
1131     ret[COL_BUTTON * 3 + 2] = 0.0F;
1132
1133     ret[COL_CURSOR * 3 + 0] = 1.0F;
1134     ret[COL_CURSOR * 3 + 1] = 0.0F;
1135     ret[COL_CURSOR * 3 + 2] = 0.0F;
1136
1137     for (i = 0; i < 3; i++) {
1138         ret[COL_GRID * 3 + i] = ret[COL_BACKGROUND * 3 + i] * 0.9F;
1139         ret[COL_LOCK * 3 + i] = ret[COL_BACKGROUND * 3 + i] * 0.7F;
1140         ret[COL_COVER * 3 + i] = ret[COL_BACKGROUND * 3 + i] * 0.5F;
1141         ret[COL_TEXT * 3 + i] = 0.0F;
1142     }
1143
1144     ret[COL_FLASHTEXT * 3 + 0] = 0.0F;
1145     ret[COL_FLASHTEXT * 3 + 1] = 1.0F;
1146     ret[COL_FLASHTEXT * 3 + 2] = 0.0F;
1147
1148     *ncolours = NCOLOURS;
1149     return ret;
1150 }
1151
1152 static game_drawstate *game_new_drawstate(drawing *dr, const game_state *state)
1153 {
1154     struct game_drawstate *ds = snew(struct game_drawstate);
1155
1156     ds->tilesize = 0;
1157     ds->w = state->w; ds->h = state->h;
1158     ds->grid = snewn((state->w+2)*(state->h+2), unsigned int);
1159     memset(ds->grid, 0, (state->w+2)*(state->h+2)*sizeof(unsigned int));
1160     ds->started = ds->reveal = 0;
1161     ds->flash_laserno = LASER_EMPTY;
1162     ds->isflash = 0;
1163
1164     return ds;
1165 }
1166
1167 static void game_free_drawstate(drawing *dr, game_drawstate *ds)
1168 {
1169     sfree(ds->grid);
1170     sfree(ds);
1171 }
1172
1173 static void draw_square_cursor(drawing *dr, game_drawstate *ds, int dx, int dy)
1174 {
1175     int coff = TILE_SIZE/8;
1176     draw_rect_outline(dr, dx + coff, dy + coff,
1177                       TILE_SIZE - coff*2,
1178                       TILE_SIZE - coff*2,
1179                       COL_CURSOR);
1180 }
1181
1182
1183 static void draw_arena_tile(drawing *dr, const game_state *gs,
1184                             game_drawstate *ds, const game_ui *ui,
1185                             int ax, int ay, int force, int isflash)
1186 {
1187     int gx = ax+1, gy = ay+1;
1188     int gs_tile = GRID(gs, gx, gy), ds_tile = GRID(ds, gx, gy);
1189     int dx = TODRAW(gx), dy = TODRAW(gy);
1190
1191     if (ui->cur_visible && ui->cur_x == gx && ui->cur_y == gy)
1192         gs_tile |= FLAG_CURSOR;
1193
1194     if (gs_tile != ds_tile || gs->reveal != ds->reveal || force) {
1195         int bcol, ocol, bg;
1196
1197         bg = (gs->reveal ? COL_BACKGROUND :
1198               (gs_tile & BALL_LOCK) ? COL_LOCK : COL_COVER);
1199
1200         draw_rect(dr, dx, dy, TILE_SIZE, TILE_SIZE, bg);
1201         draw_rect_outline(dr, dx, dy, TILE_SIZE, TILE_SIZE, COL_GRID);
1202
1203         if (gs->reveal) {
1204             /* Guessed balls are always black; if they're incorrect they'll
1205              * have a red cross added later.
1206              * Missing balls are red. */
1207             if (gs_tile & BALL_GUESS) {
1208                 bcol = isflash ? bg : COL_BALL;
1209             } else if (gs_tile & BALL_CORRECT) {
1210                 bcol = isflash ? bg : COL_WRONG;
1211             } else {
1212                 bcol = bg;
1213             }
1214         } else {
1215             /* guesses are black/black, all else background. */
1216             if (gs_tile & BALL_GUESS) {
1217                 bcol = COL_BALL;
1218             } else {
1219                 bcol = bg;
1220             }
1221         }
1222         ocol = (gs_tile & FLAG_CURSOR && bcol != bg) ? COL_CURSOR : bcol;
1223
1224         draw_circle(dr, dx + TILE_SIZE/2, dy + TILE_SIZE/2, ds->crad-1,
1225                     ocol, ocol);
1226         draw_circle(dr, dx + TILE_SIZE/2, dy + TILE_SIZE/2, ds->crad-3,
1227                     bcol, bcol);
1228
1229
1230         if (gs_tile & FLAG_CURSOR && bcol == bg)
1231             draw_square_cursor(dr, ds, dx, dy);
1232
1233         if (gs->reveal &&
1234             (gs_tile & BALL_GUESS) &&
1235             !(gs_tile & BALL_CORRECT)) {
1236             int x1 = dx + 3, y1 = dy + 3;
1237             int x2 = dx + TILE_SIZE - 3, y2 = dy + TILE_SIZE-3;
1238             int coords[8];
1239
1240             /* Incorrect guess; draw a red cross over the ball. */
1241             coords[0] = x1-1;
1242             coords[1] = y1+1;
1243             coords[2] = x1+1;
1244             coords[3] = y1-1;
1245             coords[4] = x2+1;
1246             coords[5] = y2-1;
1247             coords[6] = x2-1;
1248             coords[7] = y2+1;
1249             draw_polygon(dr, coords, 4, COL_WRONG, COL_WRONG);
1250             coords[0] = x2+1;
1251             coords[1] = y1+1;
1252             coords[2] = x2-1;
1253             coords[3] = y1-1;
1254             coords[4] = x1-1;
1255             coords[5] = y2-1;
1256             coords[6] = x1+1;
1257             coords[7] = y2+1;
1258             draw_polygon(dr, coords, 4, COL_WRONG, COL_WRONG);
1259         }
1260         draw_update(dr, dx, dy, TILE_SIZE, TILE_SIZE);
1261     }
1262     GRID(ds,gx,gy) = gs_tile;
1263 }
1264
1265 static void draw_laser_tile(drawing *dr, const game_state *gs,
1266                             game_drawstate *ds, const game_ui *ui,
1267                             int lno, int force)
1268 {
1269     int gx, gy, dx, dy, unused;
1270     int wrong, omitted, reflect, hit, laserval, flash = 0, tmp;
1271     unsigned int gs_tile, ds_tile, exitno;
1272
1273     tmp = range2grid(gs, lno, &gx, &gy, &unused);
1274     assert(tmp);
1275     gs_tile = GRID(gs, gx, gy);
1276     ds_tile = GRID(ds, gx, gy);
1277     dx = TODRAW(gx);
1278     dy = TODRAW(gy);
1279
1280     wrong = gs->exits[lno] & LASER_WRONG;
1281     omitted = gs->exits[lno] & LASER_OMITTED;
1282     exitno = gs->exits[lno] & ~LASER_FLAGMASK;
1283
1284     reflect = gs_tile & LASER_REFLECT;
1285     hit = gs_tile & LASER_HIT;
1286     laserval = gs_tile & ~LASER_FLAGMASK;
1287
1288     if (lno == ds->flash_laserno)
1289         gs_tile |= LASER_FLASHED;
1290     else if (!(gs->exits[lno] & (LASER_HIT | LASER_REFLECT))) {
1291         if (exitno == ds->flash_laserno)
1292             gs_tile |= LASER_FLASHED;
1293     }
1294     if (gs_tile & LASER_FLASHED) flash = 1;
1295
1296     gs_tile |= wrong | omitted;
1297
1298     if (ui->cur_visible && ui->cur_x == gx && ui->cur_y == gy)
1299         gs_tile |= FLAG_CURSOR;
1300
1301     if (gs_tile != ds_tile || force) {
1302         draw_rect(dr, dx, dy, TILE_SIZE, TILE_SIZE, COL_BACKGROUND);
1303         draw_rect_outline(dr, dx, dy, TILE_SIZE, TILE_SIZE, COL_GRID);
1304
1305         if (gs_tile &~ (LASER_WRONG | LASER_OMITTED | FLAG_CURSOR)) {
1306             char str[32];
1307             int tcol = flash ? COL_FLASHTEXT : omitted ? COL_WRONG : COL_TEXT;
1308
1309             if (reflect || hit)
1310                 sprintf(str, "%s", reflect ? "R" : "H");
1311             else
1312                 sprintf(str, "%d", laserval);
1313
1314             if (wrong) {
1315                 draw_circle(dr, dx + TILE_SIZE/2, dy + TILE_SIZE/2,
1316                             ds->rrad,
1317                             COL_WRONG, COL_WRONG);
1318                 draw_circle(dr, dx + TILE_SIZE/2, dy + TILE_SIZE/2,
1319                             ds->rrad - TILE_SIZE/16,
1320                             COL_BACKGROUND, COL_WRONG);
1321             }
1322
1323             draw_text(dr, dx + TILE_SIZE/2, dy + TILE_SIZE/2,
1324                       FONT_VARIABLE, TILE_SIZE/2, ALIGN_VCENTRE | ALIGN_HCENTRE,
1325                       tcol, str);
1326         }
1327         if (gs_tile & FLAG_CURSOR)
1328             draw_square_cursor(dr, ds, dx, dy);
1329
1330         draw_update(dr, dx, dy, TILE_SIZE, TILE_SIZE);
1331     }
1332     GRID(ds, gx, gy) = gs_tile;
1333 }
1334
1335 #define CUR_ANIM 0.2F
1336
1337 static void game_redraw(drawing *dr, game_drawstate *ds,
1338                         const game_state *oldstate, const game_state *state,
1339                         int dir, const game_ui *ui,
1340                         float animtime, float flashtime)
1341 {
1342     int i, x, y, ts = TILE_SIZE, isflash = 0, force = 0;
1343
1344     if (flashtime > 0) {
1345         int frame = (int)(flashtime / FLASH_FRAME);
1346         isflash = (frame % 2) == 0;
1347         debug(("game_redraw: flashtime = %f", flashtime));
1348     }
1349
1350     if (!ds->started) {
1351         int x0 = TODRAW(0)-1, y0 = TODRAW(0)-1;
1352         int x1 = TODRAW(state->w+2), y1 = TODRAW(state->h+2);
1353
1354         draw_rect(dr, 0, 0,
1355                   TILE_SIZE * (state->w+3), TILE_SIZE * (state->h+3),
1356                   COL_BACKGROUND);
1357
1358         /* clockwise around the outline starting at pt behind (1,1). */
1359         draw_line(dr, x0+ts, y0+ts, x0+ts, y0,    COL_HIGHLIGHT);
1360         draw_line(dr, x0+ts, y0,    x1-ts, y0,    COL_HIGHLIGHT);
1361         draw_line(dr, x1-ts, y0,    x1-ts, y0+ts, COL_LOWLIGHT);
1362         draw_line(dr, x1-ts, y0+ts, x1,    y0+ts, COL_HIGHLIGHT);
1363         draw_line(dr, x1,    y0+ts, x1,    y1-ts, COL_LOWLIGHT);
1364         draw_line(dr, x1,    y1-ts, x1-ts, y1-ts, COL_LOWLIGHT);
1365         draw_line(dr, x1-ts, y1-ts, x1-ts, y1,    COL_LOWLIGHT);
1366         draw_line(dr, x1-ts, y1,    x0+ts, y1,    COL_LOWLIGHT);
1367         draw_line(dr, x0+ts, y1,    x0+ts, y1-ts, COL_HIGHLIGHT);
1368         draw_line(dr, x0+ts, y1-ts, x0,    y1-ts, COL_LOWLIGHT);
1369         draw_line(dr, x0,    y1-ts, x0,    y0+ts, COL_HIGHLIGHT);
1370         draw_line(dr, x0,    y0+ts, x0+ts, y0+ts, COL_HIGHLIGHT);
1371         /* phew... */
1372
1373         draw_update(dr, 0, 0,
1374                     TILE_SIZE * (state->w+3), TILE_SIZE * (state->h+3));
1375         force = 1;
1376         ds->started = 1;
1377     }
1378
1379     if (isflash != ds->isflash) force = 1;
1380
1381     /* draw the arena */
1382     for (x = 0; x < state->w; x++) {
1383         for (y = 0; y < state->h; y++) {
1384             draw_arena_tile(dr, state, ds, ui, x, y, force, isflash);
1385         }
1386     }
1387
1388     /* draw the lasers */
1389     ds->flash_laserno = LASER_EMPTY;
1390     if (ui->flash_laser == 1)
1391         ds->flash_laserno = ui->flash_laserno;
1392     else if (ui->flash_laser == 2 && animtime > 0)
1393         ds->flash_laserno = ui->flash_laserno;
1394
1395     for (i = 0; i < 2*(state->w+state->h); i++) {
1396         draw_laser_tile(dr, state, ds, ui, i, force);
1397     }
1398
1399     /* draw the 'finish' button */
1400     if (CAN_REVEAL(state)) {
1401         int outline = (ui->cur_visible && ui->cur_x == 0 && ui->cur_y == 0)
1402             ? COL_CURSOR : COL_BALL;
1403         clip(dr, TODRAW(0)-1, TODRAW(0)-1, TILE_SIZE+1, TILE_SIZE+1);
1404         draw_circle(dr, TODRAW(0) + ds->crad, TODRAW(0) + ds->crad, ds->crad,
1405                     outline, outline);
1406         draw_circle(dr, TODRAW(0) + ds->crad, TODRAW(0) + ds->crad, ds->crad-2,
1407                     COL_BUTTON, COL_BUTTON);
1408         unclip(dr);
1409     } else {
1410         draw_rect(dr, TODRAW(0)-1, TODRAW(0)-1,
1411                   TILE_SIZE+1, TILE_SIZE+1, COL_BACKGROUND);
1412     }
1413     draw_update(dr, TODRAW(0), TODRAW(0), TILE_SIZE, TILE_SIZE);
1414     ds->reveal = state->reveal;
1415     ds->isflash = isflash;
1416
1417     {
1418         char buf[256];
1419
1420         if (ds->reveal) {
1421             if (state->nwrong == 0 &&
1422                 state->nmissed == 0 &&
1423                 state->nright >= state->minballs)
1424                 sprintf(buf, "CORRECT!");
1425             else
1426                 sprintf(buf, "%d wrong and %d missed balls.",
1427                         state->nwrong, state->nmissed);
1428         } else if (state->justwrong) {
1429             sprintf(buf, "Wrong! Guess again.");
1430         } else {
1431             if (state->nguesses > state->maxballs)
1432                 sprintf(buf, "%d too many balls marked.",
1433                         state->nguesses - state->maxballs);
1434             else if (state->nguesses <= state->maxballs &&
1435                      state->nguesses >= state->minballs)
1436                 sprintf(buf, "Click button to verify guesses.");
1437             else if (state->maxballs == state->minballs)
1438                 sprintf(buf, "Balls marked: %d / %d",
1439                         state->nguesses, state->minballs);
1440             else
1441                 sprintf(buf, "Balls marked: %d / %d-%d.",
1442                         state->nguesses, state->minballs, state->maxballs);
1443         }
1444         if (ui->errors) {
1445             sprintf(buf + strlen(buf), " (%d error%s)",
1446                     ui->errors, ui->errors > 1 ? "s" : "");
1447         }
1448         status_bar(dr, buf);
1449     }
1450 }
1451
1452 static float game_anim_length(const game_state *oldstate,
1453                               const game_state *newstate, int dir, game_ui *ui)
1454 {
1455     return (ui->flash_laser == 2) ? CUR_ANIM : 0.0F;
1456 }
1457
1458 static float game_flash_length(const game_state *oldstate,
1459                                const game_state *newstate, int dir, game_ui *ui)
1460 {
1461     if (!oldstate->reveal && newstate->reveal)
1462         return 4.0F * FLASH_FRAME;
1463     else
1464         return 0.0F;
1465 }
1466
1467 static int game_status(const game_state *state)
1468 {
1469     if (state->reveal) {
1470         /*
1471          * We return nonzero whenever the solution has been revealed,
1472          * even (on spoiler grounds) if it wasn't guessed correctly.
1473          */
1474         if (state->nwrong == 0 &&
1475             state->nmissed == 0 &&
1476             state->nright >= state->minballs)
1477             return +1;
1478         else
1479             return -1;
1480     }
1481     return 0;
1482 }
1483
1484 static int game_timing_state(const game_state *state, game_ui *ui)
1485 {
1486     return TRUE;
1487 }
1488
1489 static void game_print_size(const game_params *params, float *x, float *y)
1490 {
1491 }
1492
1493 static void game_print(drawing *dr, const game_state *state, int tilesize)
1494 {
1495 }
1496
1497 #ifdef COMBINED
1498 #define thegame blackbox
1499 #endif
1500
1501 const struct game thegame = {
1502     "Black Box", "games.blackbox", "blackbox",
1503     default_params,
1504     game_fetch_preset, NULL,
1505     decode_params,
1506     encode_params,
1507     free_params,
1508     dup_params,
1509     TRUE, game_configure, custom_params,
1510     validate_params,
1511     new_game_desc,
1512     validate_desc,
1513     new_game,
1514     dup_game,
1515     free_game,
1516     TRUE, solve_game,
1517     FALSE, game_can_format_as_text_now, game_text_format,
1518     new_ui,
1519     free_ui,
1520     encode_ui,
1521     decode_ui,
1522     game_changed_state,
1523     interpret_move,
1524     execute_move,
1525     PREFERRED_TILE_SIZE, game_compute_size, game_set_size,
1526     game_colours,
1527     game_new_drawstate,
1528     game_free_drawstate,
1529     game_redraw,
1530     game_anim_length,
1531     game_flash_length,
1532     game_status,
1533     FALSE, FALSE, game_print_size, game_print,
1534     TRUE,                              /* wants_statusbar */
1535     FALSE, game_timing_state,
1536     REQUIRE_RBUTTON,                   /* flags */
1537 };
1538
1539 /* vim: set shiftwidth=4 tabstop=8: */