Code:
#include <curses.h>
#include <time.h>
#include <stdlib.h>
#include <ctype.h>
int dirs[6] = {0, 1, 0, -1, 0, 1};
void init () {
srand (time(NULL));
initscr ();
raw (); nodelay(stdscr,1); noecho(); curs_set(0); nonl(); keypad(stdscr,1);
}
void play () {
int x, y, bx, by, c, d, in, bul, lvl, buf[LINES][COLS];
y = x = d = lvl = 0; bul = 10; /* Set up variables for new game. */
do { /* Set up varaibles for new level */
clear ();
lvl++; bul += 15;
mvprintw (LINES - 1, 37, "Round %d", lvl);
for (by = 0; by < LINES; by++) for (bx = 0; bx < COLS; bx++)
buf[by][bx] = 0; /* clear buffer */
for (c = 0; c < 15; c++) { /* Set up enemies. */
do {
by = 1 + rand () % (LINES - 3); bx = 1 + rand () % (COLS - 2);
} while (buf[by][bx]);
buf[by][bx] = 1;
mvaddch (by, bx, 'X');
} /* c will count targets */
/* Draw last few more things on the screen. */
mvaddch (y, x, 'O');
mvprintw (LINES - 1, 0, "Bullets : %d ", bul); /* space after the d */
mvprintw (LINES - 1, 60, "Press SPACE to fire.");
refresh ();
while ((bul > 0) && (c > 0)) { /* The main game loop */
in = getch ();
if (tolower(in) == 'q') return;
if (in == ' ') { /* shoot a bullet */
bul--;
mvprintw (LINES - 1, 0, "Bullets : %d ", bul); /* space after again. */
bx = x; by = y;
do {
bx += dirs[d + 1]; by += dirs[d + 2]; /* move the bullet */
if (buf[by][bx]) { /* a hit */
beep ();
buf[by][bx] = 0;
c--;
}
mvaddch (by, bx, '.');
refresh ();
napms (15);
mvaddch (by, bx, ' ');
} while (!((bx==0) + (by==0) + (bx==COLS - 1) + (by==LINES - 2)));
/* above line is for edge detection. */
}
mvaddch (y, x, ' ');
x += dirs[d]; y += dirs[d + 1];
if (((x == 0) + (y == 0) + (x == COLS - 1) + (y == LINES - 2)) == 2) {
/* if we're at a corner change direction. */
d++; d %= 4;
}
mvaddch (y, x, 'O');
refresh ();
napms (275 - 25 * lvl);
} /* end of level loop if out of bullets or out of enemies. */
} while ((c == 0) && (lvl < 10));
if (c) mvprintw (10, 27, "Out of bullets. Game over.");
else mvprintw (10, 15, "Congratulations! You have defeated every enemy!");
refresh ();
}
int main () {
init ();
play ();
mvprintw (15, 32, "Press any key...");
nodelay(stdscr,0); getch ();
endwin ();
return 0;
}