repos / gbc

GBC - Go B Compiler
git clone https://github.com/xplshn/gbc.git

gbc / examples
xplshn  ·  2025-08-13

langtons_ants.b

B
 1/* https://en.wikipedia.org/wiki/Langton%27s_ant */
 2width;
 3height;
 4board;
 5x;
 6y;
 7r;
 8
 9mod(n, b) return ((n%b + b)%b);
10
11get(b, xn, yn) {
12	xn = mod(xn, width);
13	yn = mod(yn, height);
14	return (b[xn+yn*width]);
15}
16set(b, xn, yn, v) {
17	xn = mod(xn, width);
18	yn = mod(yn, height);
19	b[xn+yn*width] = v;
20}
21
22
23print() {
24	extrn printf;
25	auto xn, yn;
26
27	xn = 0; while (xn <= width) {
28		printf("##");
29		xn += 1;
30	}
31	printf("\n");
32
33	yn = 0; while (yn < height) {
34		printf("#");
35		xn = 0; while (xn < width) {
36			if ((xn == mod(x, width)) & (yn == mod(y, height))) {
37				printf("β–’β–’");
38			} else {
39				if (get(board, xn,yn)) {
40					printf("β–ˆβ–ˆ");
41				} else {
42					printf("  ");
43				}
44			}
45			xn += 1;
46		}
47		printf("#\n");
48		yn += 1;
49	}
50
51	xn = 0; while (xn <= width) {
52		printf("##");
53		xn += 1;
54	}
55	printf("\n");
56}
57
58step() {
59	extrn printf;
60	auto c;
61	c = get(board, x, y);
62	if (c) r++; else r--;
63	set(board, x, y, !c);
64	switch mod(r, 4) {
65	case 0: y++; goto out;
66	case 1: x++; goto out;
67	case 2: y--; goto out;
68	case 3: x--; goto out;
69	}
70out:
71}
72
73main() {
74	extrn malloc, memset, printf, usleep;
75	auto size;
76	width  = 25;
77	height = 15;
78	size = width*height*(&0[1]);
79
80	board = malloc(size);
81	memset(board, 0, size);
82
83	r = 0;
84	x = 15;
85	y = 7;
86
87	while (1) {
88		print();
89		step();
90		printf("%c[%dA", 27, height+2);
91		/* TODO: does not work on Windows */
92		usleep(50000);
93	}
94}