Difference between revisions of "Langston's Ant, animated for POSIX"
Jump to navigation
Jump to search
(Created page with "==Synopsis== Performs a simulation of Langston's Ant as an animation for Linux, Un*x systems. ==Notes== There are no borders, the map wraps edge to edge. Define statements...") |
(→Code) |
||
Line 20: | Line 20: | ||
#define Y 20 | #define Y 20 | ||
#define S 1000 | #define S 1000 | ||
− | #define D 20 | + | #define D 20 |
− | |||
− | |||
/* msleep(): Sleep for the requested number of milliseconds. */ | /* msleep(): Sleep for the requested number of milliseconds. */ |
Latest revision as of 19:08, 27 May 2021
Contents
Synopsis
Performs a simulation of Langston's Ant as an animation for Linux, Un*x systems.
Notes
There are no borders, the map wraps edge to edge. Define statements have a 20x20 grid, 1000 steps and a delay of 20ms. The ANT always starts at, or near, the center. The ant defaults being oriented towards north as an initial condition.
Compilation
gcc -o Ant Ant.c
Code
1 #include<stdio.h>
2 #include<stdlib.h>
3 #include <time.h>
4 #include <errno.h>
5 #define X 20
6 #define Y 20
7 #define S 1000
8 #define D 20
9
10 /* msleep(): Sleep for the requested number of milliseconds. */
11 int msleep(long msec)
12 {
13 struct timespec ts;
14 int res;
15
16 if (msec < 0)
17 {
18 errno = EINVAL;
19 return -1;
20 }
21
22 ts.tv_sec = msec / 1000;
23 ts.tv_nsec = (msec % 1000) * 1000000;
24
25 do
26 {
27 res = nanosleep(&ts, &ts);
28 }
29 while (res && errno == EINTR);
30 return res;
31 }
32
33 void main(void)
34 {
35 char world[X][Y];
36 unsigned short x, y, c, d, h, s;
37 //init
38 x=X/2; y=Y/2; h=0;
39 for(c=0;c<Y;c++)
40 {
41 for(d=0;d<X;d++)
42 {
43 world[d][c] = '.';
44 }
45 }
46
47 //loop
48 for(s=0;s<S;s++)
49 {
50 #ifdef D
51 msleep(D);
52 #endif
53 printf("\e[1;1H\e[2J");
54 //print current state
55 printf("S=%d\n\n",s+1);
56 printf("%c", '/');
57 for(c=0;c<X;c++)
58 {
59 printf("%c", '-');
60 }
61 printf("%c\n", '\\');
62 for(c=0;c<Y;c++)
63 {
64 printf("%c", '|');
65 for(d=0;d<X;d++)
66 {
67 if(d==x && c==y)
68 printf("A");
69 else
70 printf("%c",world[d][c]);
71 }
72 printf("%c\n", '|');
73 }
74 printf("%c", '\\');
75 for(c=0;c<X;c++)
76 {
77 printf("%c", '-');
78 }
79 printf("/\n\n");
80 //turn logic
81 if(world[x][y]=='.')
82 {
83 h++; //CW
84 h = h % 4;
85 world[x][y]='*';
86 }
87 else
88 {
89 h--; //CCW
90 h= h % 4;
91 world[x][y]='.';
92 }
93 //move forward
94 if(h==0)
95 {if(y==0) y=Y-1; else y--;}
96 if(h==2)
97 {if(y==Y-1) y=0; else y++;}
98 if(h==1)
99 {if(x==X-1) x=0; else x++;}
100 if(h==3)
101 {if(x==0) x=X-1; else x--;}
102 }
103
104 //terminate
105 printf("\nEOS \n");
106 return;
107 }