main.c

1#include <ncurses.h>
2#include <unistd.h> // For usleep function
3
4#define GRID_SIZE 40
5#define DELAY 50000 // Delay in microseconds
6
7typedef enum { WHITE, BLACK } Color;
8typedef enum { UP, RIGHT, DOWN, LEFT } Direction;
9
10typedef struct {
11    int x;
12    int y;
13    Direction direction;
14} Ant;
15
16void turn_right(Ant *ant) {
17    ant->direction = (ant->direction + 1) % 4;
18}
19
20void turn_left(Ant *ant) {
21    ant->direction = (ant->direction + 3) % 4; // Adding 3 is equivalent to subtracting 1 mod 4
22}
23
24void move_forward(Ant *ant) {
25    switch (ant->direction) {
26        case UP:
27            ant->y--;
28            break;
29        case RIGHT:
30            ant->x++;
31            break;
32        case DOWN:
33            ant->y++;
34            break;
35        case LEFT:
36            ant->x--;
37            break;
38    }
39}
40
41void draw_grid(Color grid[GRID_SIZE][GRID_SIZE], Ant *ant) {
42    for (int y = 0; y < GRID_SIZE; y++) {
43        for (int x = 0; x < GRID_SIZE; x++) {
44            if (x == ant->x && y == ant->y) {
45                mvaddch(y, x, 'A');
46            } else {
47                mvaddch(y, x, grid[y][x] == WHITE ? '.' : '#');
48            }
49        }
50    }
51}
52
53int main() {
54    Color grid[GRID_SIZE][GRID_SIZE] = { WHITE };
55    Ant ant = { GRID_SIZE / 2, GRID_SIZE / 2, UP };
56
57    initscr();
58    cbreak();
59    noecho();
60    curs_set(FALSE);
61
62    while (1) {
63        clear();
64        if (grid[ant.y][ant.x] == WHITE) {
65            turn_right(&ant);
66            grid[ant.y][ant.x] = BLACK;
67        } else {
68            turn_left(&ant);
69            grid[ant.y][ant.x] = WHITE;
70        }
71        move_forward(&ant);
72
73        // Ensure the ant stays within the bounds of the grid
74        if (ant.x < 0) ant.x = GRID_SIZE - 1;
75        if (ant.x >= GRID_SIZE) ant.x = 0;
76        if (ant.y < 0) ant.y = GRID_SIZE - 1;
77        if (ant.y >= GRID_SIZE) ant.y = 0;
78
79        draw_grid(grid, &ant);
80        refresh();
81        usleep(DELAY);
82    }
83
84    endwin();
85    return 0;
86}
87
88