Langston's Ant, animated for POSIX
Jump to navigation
Jump to search
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 #include <time.h>
10 #include <errno.h>
11
12 /* msleep(): Sleep for the requested number of milliseconds. */
13 int msleep(long msec)
14 {
15 struct timespec ts;
16 int res;
17
18 if (msec < 0)
19 {
20 errno = EINVAL;
21 return -1;
22 }
23
24 ts.tv_sec = msec / 1000;
25 ts.tv_nsec = (msec % 1000) * 1000000;
26
27 do
28 {
29 res = nanosleep(&ts, &ts);
30 }
31 while (res && errno == EINTR);
32 return res;
33 }
34
35 void main(void)
36 {
37 char world[X][Y];
38 unsigned short x, y, c, d, h, s;
39 //init
40 x=X/2; y=Y/2; h=0;
41 for(c=0;c<Y;c++)
42 {
43 for(d=0;d<X;d++)
44 {
45 world[d][c] = '.';
46 }
47 }
48
49 //loop
50 for(s=0;s<S;s++)
51 {
52 #ifdef D
53 msleep(D);
54 #endif
55 printf("\e[1;1H\e[2J");
56 //print current state
57 printf("S=%d\n\n",s+1);
58 printf("%c", '/');
59 for(c=0;c<X;c++)
60 {
61 printf("%c", '-');
62 }
63 printf("%c\n", '\\');
64 for(c=0;c<Y;c++)
65 {
66 printf("%c", '|');
67 for(d=0;d<X;d++)
68 {
69 if(d==x && c==y)
70 printf("A");
71 else
72 printf("%c",world[d][c]);
73 }
74 printf("%c\n", '|');
75 }
76 printf("%c", '\\');
77 for(c=0;c<X;c++)
78 {
79 printf("%c", '-');
80 }
81 printf("/\n\n");
82 //turn logic
83 if(world[x][y]=='.')
84 {
85 h++; //CW
86 h = h % 4;
87 world[x][y]='*';
88 }
89 else
90 {
91 h--; //CCW
92 h= h % 4;
93 world[x][y]='.';
94 }
95 //move forward
96 if(h==0)
97 {if(y==0) y=Y-1; else y--;}
98 if(h==2)
99 {if(y==Y-1) y=0; else y++;}
100 if(h==1)
101 {if(x==X-1) x=0; else x++;}
102 if(h==3)
103 {if(x==0) x=X-1; else x--;}
104 }
105
106 //terminate
107 printf("\nEOS \n");
108 return;
109 }