Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //code is cc0
- #include <stdio.h>
- #include <stdlib.h>
- #include <unistd.h>
- //size of torus (odd by odd for weird bridges)
- #define MAP_X 9999
- #define MAP_Y 9999
- //NOTE: change this to fit your terminal size (or smaller)
- #define SCR_WIDTH 1906
- #define SCR_HEIGHT 501
- //rules are defines for testing other rules if needed, should clean this
- #define TURN_R switch(ant.dir) {\
- case UP: ant.dir = RIGHT; break;\
- case DOWN: ant.dir = LEFT; break;\
- case LEFT: ant.dir = UP; break;\
- case RIGHT: ant.dir = DOWN; break;\
- }
- #define TURN_L switch(ant.dir) {\
- case UP: ant.dir = LEFT; break;\
- case DOWN: ant.dir = RIGHT; break;\
- case LEFT: ant.dir = DOWN; break;\
- case RIGHT: ant.dir = UP; break;\
- }
- //directions and the ant type
- enum t_dir {UP, DOWN, LEFT, RIGHT};
- struct t_ant {
- int x;
- int y;
- enum t_dir dir;
- };
- main() {
- //clear screen
- printf("\x1b[48;2;0;0;0m\x1b[2J");
- struct t_ant ant;
- //center in the visible part of screen and initialize
- ant.x = SCR_WIDTH/2;
- ant.y = SCR_HEIGHT/2;
- ant.dir = UP;
- //allocate memory
- char *map = calloc(MAP_X * MAP_Y, sizeof(char));
- while(1) {
- if(ant.x < SCR_WIDTH && ant.y < SCR_HEIGHT) printf("\x1b[%d;%dH", ant.y, ant.x);
- //check current cell then accordingly; flip cell, print new cell, and change direction
- //this also checks if the ant is offscreen in order to save time in order to decide to print or not, it will just process it way faster until the ant reappears
- switch(map[ant.x + (ant.y * MAP_X)]) {
- case 0:
- map[ant.x + (ant.y * MAP_X)] = 1;
- TURN_R
- if(ant.x < SCR_WIDTH && ant.y < SCR_HEIGHT) printf("\x1b[48;2;255;255;255m "); break;
- case 1:
- map[ant.x + (ant.y * MAP_X)] = 0;
- TURN_L
- if(ant.x < SCR_WIDTH && ant.y < SCR_HEIGHT) printf("\x1b[48;2;0;0;0m "); break;
- }
- //move forward in direction
- switch(ant.dir) {
- case UP: ant.y = ant.y + 1; if(ant.y == MAP_Y) ant.y = 0; break;
- case DOWN: ant.y = ant.y - 1; if(ant.y == -1) ant.y = MAP_Y - 1; break;
- case LEFT: ant.x = ant.x - 1; if(ant.x == -1) ant.x = MAP_X - 1; break;
- case RIGHT: ant.x = ant.x + 1; if(ant.x == MAP_X) ant.x = 0; break;
- }
- fflush(stdout); //flush output to screen
- //usleep(50); //dont need this, especially for larger maps
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement