#include #include #include #include int x = 15, y = 10, c = 4, score, total; ulong rgb[] = {DRed, DGreen, DBlue, DYellow, DCyan, DMagenta, 0x777777FF, DWhite}; Image **hue; char *a; void eresized(int i) { Point o; if(i && getwindow(display, Refnone) < 0) sysfatal("can't reattach to window"); if((!i || Dx(screen->r) != x * 48 || Dy(screen->r) != y * 48) && (i = open("/dev/wctl", OWRITE)) >= 0){ fprint(i, "resize -dx %d -dy %d", x * 48 + 2 * Borderwidth, y * 48 + 2 * Borderwidth); close(i); } draw(screen, screen->r, display->black, nil, ZP); o = Pt(screen->r.min.x + 24, screen->r.max.y - 24); for(i = 0; i < x * y;){ if(a[i] >= 0) fillellipse(screen, o, 20, 20, hue[a[i]], ZP); if(++i % y) o.y -= 48; else o = Pt(o.x + 48, screen->r.max.y - 24); } } void flood(int i, int t){ a[i] = -2; if((i + 1) % y && a[i + 1] == t) flood(i + 1, t); if(i + y < x * y && a[i + y] == t) flood(i + y, t); if(i % y && a[i - 1] == t) flood(i - 1, t); if(i >= y && a[i - y] == t) flood(i - y, t); } void usage(void){ sysfatal("usage: %s [-c colours] [-x width] [-y height]", argv0); } void main(int argc, char **argv){ Mouse m; int i, j; ARGBEGIN{ default: usage(); case 'c': c = atoi(EARGF(usage())); if(c < 2) sysfatal("%d colours not enough!", x); break; case 'x': x = atoi(EARGF(usage())); if(x < 2) sysfatal("width %d too small!", x); break; case 'y': y = atoi(EARGF(usage())); if(y < 2) sysfatal("height %d too small!", y); break; }ARGEND if((hue = calloc(c, sizeof(Image*))) == nil) sysfatal("calloc: %r"); if((a = malloc(x * y)) == nil) sysfatal("malloc: %r"); srand(truerand()); for(i = 0; i < x * y; i++) a[i] = nrand(c); if(initdraw(nil, nil, argv0) < 0) sysfatal("initdraw: %r"); for(i = 0; i < c; i++) if((hue[i] = allocimage(display, Rect(0,0,1,1), screen->chan, 1, rgb[i])) == nil) sysfatal("allocimage: %r"); einit(Emouse); eresized(0); for(;;){ m = emouse(); if(m.buttons){ do m = emouse(); while(m.buttons); i = (m.xy.x - screen->r.min.x) / 48 * y + (screen->r.max.y - m.xy.y) / 48 ; if(ptinrect(m.xy, screen->r) && a[i] != -1 && ((i + 1) % y && a[i + 1] == a[i] || i + y < x * y && a[i + y] == a[i] || i % y && a[i - 1] == a[i] || i >= y && a[i - y] == a[i])){ score = 0; flood(i, a[i]); for(i = x * y - 1; i >= 0; i--) if(a[i] == -2){ score++; for(j = i; (j + 1) % y; j++) a[j] = a[j + 1]; a[j] = -1; } total += score * (score - 1); for(i = (x - 2) * y; i >= 0; i -= y) if(a[i] == -1){ for(j = i; j < x * y - y; j++) a[j] = a[j + y]; while(j < x * y) a[j++] = -1; } for(i = 0; i < x * y; i++) if(a[i] >= 0 && ((i + 1) % y && a[i + 1] == a[i] || i + y < x * y && a[i + y] == a[i] || i % y && a[i - 1] == a[i] || i >= y && a[i - y] == a[i])) break; if(i == x * y){ fprint(1, "Dimensions: %d x %d\nColours: %d\nScore: %d\n", x, y, c, total); exits(nil); } eresized(0); } } } }