Skip to content

Instantly share code, notes, and snippets.

@oguz-ismail
Last active November 30, 2022 16:32
Show Gist options
  • Save oguz-ismail/c78b9ed63d370ffda59f0d76e659ec94 to your computer and use it in GitHub Desktop.
Save oguz-ismail/c78b9ed63d370ffda59f0d76e659ec94 to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#define WIDTH 64
#define HEIGHT 64
#define AREA (WIDTH * HEIGHT)
#define WHITE 255
#define BLACK 0
#define INTERVAL 100
uint8_t grid[WIDTH * HEIGHT];
struct {
size_t x;
size_t y;
enum { UP, RIGHT, DOWN, LEFT, } or;
} ant;
void
dump(void) {
uint8_t *p;
size_t n;
ssize_t w;
p = grid;
n = AREA;
while (n > 0) {
w = write(1, p, n);
if (w == -1)
exit(1);
p += w;
n -= w;
}
}
int
ok(void) {
if (ant.x == 0 && ant.or != RIGHT)
return 0;
if (ant.x == WIDTH-1 && ant.or != LEFT)
return 0;
if (ant.y == 0 && ant.or != DOWN)
return 0;
if (ant.y == HEIGHT-1 && ant.or != UP)
return 0;
return 1;
}
int
main(void) {
size_t c, i;
memset(grid, WHITE, AREA);
ant.x = WIDTH / 2;
ant.y = HEIGHT / 2;
c = 0;
while (ok()) {
if (++c == INTERVAL) {
dump();
c = 0;
}
i = ant.y * WIDTH + ant.x;
if (grid[i] == WHITE) {
grid[i] = BLACK;
ant.or = (ant.or + 1) % 4;
}
else {
grid[i] = WHITE;
ant.or = (ant.or + 3) % 4;
}
switch (ant.or) {
case UP:
ant.y--;
break;
case RIGHT:
ant.x++;
break;
case DOWN:
ant.y++;
break;
case LEFT:
ant.x--;
break;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment