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