Wednesday, January 31, 2007

Spiral using ncurses

I tried to write a program to draw a spiral using the ncurses library - one which draws slowly in a way which can be seen noticeably. I first analyzed the number of characters to be drawn in each direction - down, right, up and left.

I prepared a table having the number of characters in the outer spiral of the spiral design. I used a variable, m, to hold the number of characters in a particular direction. I programmed m to change according to the mathematical pattern which we can notice in the table.


+----------+----+-----+------+--------+
| n | 1 | 2 | 3 | 4 |
| down | 4 | 8 | 12 | 16 |
| right | 3 | 7 | 11 | 15 |
| up | 2 | 6 | 10 | 14 |
| left | 1 | 5 | 9 | 13 |
+----------+----+-----+------+--------+

I leave the code for the interested reader here. I implemented this using C with the help of the ncurses library for moving the cursor in the relevant directions before printing the character.

#include <curses.h>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>

int main(int argc, char* argv[])
{
int x, y, n, i, m, dx, dy, j;
int ay[] = {1, 0, -1, 0};
int ax[] = {0, 1, 0, -1};
int am[] = {1, 1, 1, 1};

char s[80];

n = atoi(argv[1]);
m = n * 4;

initscr();
cbreak();
noecho();
nonl();
intrflush(stdscr, FALSE);
keypad(stdscr, TRUE);

x = 0;
y = 0;

while (m > 0)
{
for (i = 0; i < 4; ++i)
{
dx = ax[i];
dy = ay[i];
for (j = 0; j < m; ++j)
{
x += dx; y += dy;
mvaddstr(y, x, "X");
}
system("sleep 1");
refresh();
--m;
}
}

system("sleep 1");

endwin();

return 0;
}


The program, when run, should draw the pattern arm by arm or the spiral, i.e, first downward, then rightward, then upward and then leftward. The following is the output for n = 3:



X
X XXXXXXXXXX
X X X
X X XXXXXX X
X X X X X
X X X XX X X
X X X X X X
X X XXXX X X
X X X X
X XXXXXXXX X
X X
XXXXXXXXXXXX