home *** CD-ROM | disk | FTP | other *** search
- /* LIFE.C -- C. Reace, May 1993 */
-
- #include <stdlib.h>
- #include <stdio.h>
- #include <string.h>
- #include <conio.h>
- #include <time.h>
-
- int life[25][42];
- int cur_row, cur_col;
- int life_color[3] = {BLUE, YELLOW, WHITE};
- char life_char[3] = {' ', '*', '*'};
- int generation = 1, population = 0;
- char done = '';
-
- main(void)
- {
- do {
- /* Initialize all cells to 0 (no life) */
- randomize();
- for (cur_row = 0; cur_row < 25; cur_row ++) {
- for (cur_col = 0; cur_col < 42; cur_col ++) {
- life[cur_row][cur_col] = 0;
- }
- }
- setcbrk(1); /* Test for break each system call */
- textmode(C40);
- textbackground(life_color[0]);
- clrscr();
-
- /* Randomly set some central cells to '1' (new life) */
- for (cur_row = 12; cur_row < 15; cur_row ++) {
- for (cur_col = 19; cur_col < 23; cur_col ++) {
- life[cur_row][cur_col] = random(2);
- if (life[cur_row][cur_col] == 1) {
- population = population + 1;
- }
- }
- }
- _setcursortype(_NOCURSOR);
- show_life();
- for (generation = 2;population > 0 && generation < 200 && !kbhit();
- generation ++) {
- calc_life();
- show_life();
- }
- }
- while (!kbhit());
- textmode(C80);
- clrscr();
- return;
- }
-
- calc_life(void)
- {
- int new_life[25][42];
- int n_row, n_col;
- int neighbors;
-
- population = 0;
- for (cur_row = 0; cur_row < 25; cur_row ++) {
- for (cur_col = 0; cur_col < 42; cur_col ++) {
- new_life[cur_row][cur_col] = life[cur_row][cur_col];
- }
- }
- for (cur_row = 1; cur_row < 24; cur_row ++) {
- for (cur_col = 1; cur_col < 41; cur_col ++) {
- neighbors = 0;
- for (n_col = cur_col - 1; n_col < cur_col + 2; n_col ++) {
- if (life[cur_row - 1][n_col] > 0) {
- neighbors = neighbors + 1;
- }
- }
- for (n_col = cur_col -1; n_col < cur_col +2; n_col = n_col + 2) {
- if (life[cur_row][n_col] > 0) {
- neighbors = neighbors + 1;
- }
- }
- for (n_col = cur_col - 1; n_col < cur_col + 2; n_col ++) {
- if (life[cur_row + 1][n_col] > 0) {
- neighbors = neighbors + 1;
- }
- }
- if (life[cur_row][cur_col] == 0) {
- if (neighbors == 3) {
- new_life[cur_row][cur_col] = 1;
- population = population + 1;
- }
- }
- else {
- if (neighbors < 2 || neighbors > 4) {
- new_life[cur_row][cur_col] = 0;
- }
- else {
- new_life[cur_row][cur_col] = 2;
- population = population + 1;
- }
- }
- }
- }
- for (cur_row = 0; cur_row < 25; cur_row ++) {
- for (cur_col = 0; cur_col < 42; cur_col ++) {
- life[cur_row][cur_col] = new_life[cur_row][cur_col];
- }
- }
- return;
- }
-
- show_life(void)
- {
- gotoxy(1,1);
- textcolor(WHITE);
- textbackground(GREEN);
- cprintf("Generation: %i %s %i",generation,"Population: ",population);
- clreol();
- gotoxy(1,2);
- textbackground(BLUE);
- for (cur_row = 1; cur_row < 24; cur_row ++) {
- gotoxy(1, cur_row + 1);
- for (cur_col = 1; cur_col < 41; cur_col ++) {
- textcolor(life_color[life[cur_row][cur_col]]);
- putch(life_char[life[cur_row][cur_col]]);
- }
- }
- return;
- }
-