repos / gbc

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

gbc / examples
xplshn  ·  2025-08-13

game_of_life.b

B
  1width;
  2height;
  3W;
  4board1;
  5board2;
  6board;
  7next;
  8
  9mod(n, b) return ((n%b + b)%b);
 10
 11get(b, x, y) {
 12	x = mod(x, width);
 13	y = mod(y, height);
 14	return (b[x+y*width]);
 15}
 16set(b, x, y, v) {
 17	x = mod(x, width);
 18	y = mod(y, height);
 19	b[x+y*width] = v;
 20}
 21
 22count_neighbours(b, x, y) {
 23	auto count; count = 0;
 24	auto dy; dy = -1; while (dy <= 1) {
 25		auto dx; dx = -1; while (dx <= 1) {
 26			if (dx != 0 | dy != 0) count += get(b, x+dx, y+dy);
 27			dx += 1;
 28		}
 29		dy += 1;
 30	}
 31	return (count);
 32}
 33
 34print() {
 35	extrn printf;
 36	auto x, y;
 37
 38	x = 0; while (x <= width) {
 39		printf("##");
 40		x += 1;
 41	}
 42	printf("\n");
 43
 44	y = 0; while (y < height) {
 45		printf("#");
 46		x = 0; while (x < width) {
 47			printf(get(*board, x,y) ? "██" : "  ");
 48			x += 1;
 49		}
 50		printf("#\n");
 51		y += 1;
 52	}
 53
 54	x = 0; while (x <= width) {
 55		printf("##");
 56		x += 1;
 57	}
 58	printf("\n");
 59}
 60
 61step() {
 62	extrn printf;
 63	auto y; y = 0; while (y < height) {
 64		auto x; x = 0; while (x < width) {
 65			auto a, n, r;
 66			n = count_neighbours(*board, x, y);
 67			a = get(*board, x,y);
 68			r = a ? n == 2 | n == 3 : n==3;
 69			set(*next, x, y, r);
 70			x += 1;
 71		}
 72		y += 1;
 73	}
 74
 75	auto tmp;
 76	tmp = board;
 77	board = next;
 78	next = tmp;
 79}
 80
 81main() {
 82	extrn malloc, memset, printf, usleep;
 83	auto size;
 84	width  = 25;
 85	height = 15;
 86	size = width*height*(&0[1]);
 87
 88	board1 = malloc(size);
 89	board2 = malloc(size);
 90	memset(board1, 0, size);
 91	memset(board2,  0, size);
 92	board = &board1;
 93	next = &board2;
 94
 95
 96	set(*board, 3, 2, 1);
 97	set(*board, 4, 3, 1);
 98	set(*board, 2, 4, 1);
 99	set(*board, 3, 4, 1);
100	set(*board, 4, 4, 1);
101
102	set(*board, 11, 1, 1);
103	set(*board, 13, 1, 1);
104	set(*board, 12, 2, 1);
105	set(*board, 13, 2, 1);
106	set(*board, 12, 3, 1);
107
108	set(*board, 6, 12, 1);
109	set(*board, 6, 13, 1);
110	set(*board, 4, 13, 1);
111	set(*board, 5, 14, 1);
112	set(*board, 6, 14, 1);
113
114	set(*board, 16, 8, 1);
115	set(*board, 18, 9, 1);
116	set(*board, 17, 9, 1);
117	set(*board, 16, 10, 1);
118	set(*board, 17, 10, 1);
119
120	while (1) {
121		print();
122		step();
123		printf("%c[%dA", 27, height+2);
124        // TODO: does not work on Windows
125		usleep(150000);
126	}
127}