Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdlib.h>
- #include <stdio.h>
- #include <string.h>
- #include <stdint.h>
- #include <sys/time.h>
- #include <conio.h>
- #define NOMINMAX
- #define WIN32_LEAN_AND_MEAN
- #include <Windows.h>
- #define COLS 60
- #define ROWS COLS
- #define START_X COLS/2
- #define START_Y ROWS/2
- #define STEPS_MAX 20000
- #define ANIMATE 1
- #define WRAP 0
- #define FRAMERATE 600
- int ToIndex(int x, int y){ return y * COLS + x; }
- char buffer[(COLS+1)*ROWS] = {0};
- void PrintASCII(uint8_t *w);
- void setCursorPosition(int x, int y);
- void setCursorVisibility(int isShown);
- uint16_t antPath[20000] = {0};
- uint8_t world[COLS*ROWS] = {0};
- //up, right, down, left
- int dirs[] = {-COLS,+1,+COLS,-1};
- int heading = 0;
- int stepCounter = 0;
- int main(void){
- system("cls");
- setCursorVisibility(FALSE);
- for(int i = 0; i < COLS*ROWS; ++i){
- fprintf(stdout, ".");
- if(i % COLS == COLS-1){
- fprintf(stdout, "\n");
- }
- }
- //Place the ant
- uint8_t *ant = &world[ToIndex(START_X, START_Y)];
- *ant = 1;
- while(stepCounter < STEPS_MAX){
- //Ant walks forward
- ant += dirs[heading];
- #if WRAP
- //Wrap around to avoid crash from out of bounds
- if(ant - world < 0){ ant = &world[COLS*ROWS]; }
- if(ant - world > COLS*ROWS){ ant = &world[0]; }
- #else
- //Quit when the ant reaches the edge of the board
- if(ant - world < 0 || ant - world > COLS*ROWS){ break; }
- #endif
- //Update the ant
- if(*ant == 0) {
- heading = (heading + 1) % 4;
- *ant = 1;
- } else {
- heading = (heading == 0) ? 3 : heading - 1;
- *ant = 0;
- }
- antPath[stepCounter] = (ant - world);
- #if ANIMATE
- Sleep(1000 / FRAMERATE);
- PrintASCII(world);
- #endif
- stepCounter++;
- }
- PrintASCII(world);
- printf("\nSteps: %i\n", stepCounter);
- FILE *fp = fopen("data.txt", "w+");
- if (fp == NULL)
- {
- printf("Error opening file!\n");
- exit(1);
- }
- for(int i = 0; i < stepCounter; ++i){
- fprintf(fp, "%i\n", antPath[i]);
- }
- fclose(fp);
- return 0;
- }
- void PrintASCII(uint8_t *w){
- setCursorPosition(0,0);
- for(int i = 0; i < (COLS+1)*ROWS; ++i){
- if(w[i]){
- buffer[i] = '#';
- } else {
- buffer[i] = '.';
- }
- if(i % (COLS) == (COLS-1)){
- buffer[i] = '\n';
- }
- }
- buffer[COLS*ROWS] = '\0';
- fprintf(stdout, "%s", buffer);
- }
- void setCursorPosition(int x, int y){
- const HANDLE hOut = GetStdHandle(STD_OUTPUT_HANDLE);
- fflush(stdout);
- COORD coord = { (SHORT)x, (SHORT)y };
- SetConsoleCursorPosition(hOut, coord);
- }
- void setCursorVisibility(int isShown){
- HANDLE consoleHandle = GetStdHandle(STD_OUTPUT_HANDLE);
- CONSOLE_CURSOR_INFO info;
- info.dwSize = 100;
- info.bVisible = isShown;
- SetConsoleCursorInfo(consoleHandle, &info);
- }
Add Comment
Please, Sign In to add comment