-
Notifications
You must be signed in to change notification settings - Fork 0
/
game_of_life.c
118 lines (101 loc) · 2.77 KB
/
game_of_life.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
#include <ncurses.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define DELAY 30000
char RandomNumberGenerator(const int nMin, const int nMax, const int nNumOfNumsToGenerate, const int val)
{
int nRandomNumber = 0;
for (int i = 0; i < nNumOfNumsToGenerate; i++)
{
nRandomNumber = rand()%(nMax-nMin) + nMin;
}
if (nRandomNumber > val) return 'X';
else return ' ';
}
int check(char spot){
if (spot == 'X') return 1;
else return 0;
}
int n;
int delay;
int main(int argc, char *argv[]) {
printf("%d\n",argc);
if (argc == 1){
n = 1;
delay = DELAY;
}
else if (argc == 2){
n = atoi(argv[1]);
delay = DELAY;
}
else if (argc == 3){
n = atoi(argv[1]);
delay = atoi(argv[2]);
}
else {
;
}
int x = 0, y = 10;
int max_y = 0, max_x = 0;
int next_x = 0;
int direction = 1;
int rn;
initscr();
curs_set(FALSE);
srand(time(NULL));
getmaxyx(stdscr, max_y, max_x);
char field[max_y][max_x];
char field_next[max_y][max_x];
for (int j = 0;j<max_y;j++){
for (int i = 0;i<max_x;i++){
field[j][i] = RandomNumberGenerator(0,9,1,n);
field_next[j][i] = ' ';
}
}
mvprintw(10,10,"A very simple implementation of Conway's Game of Life");
mvprintw(11,10,"by Christian Johann Sutton");
mvprintw(12,10,"[email protected]");
mvprintw(14,10,"\t\tPress control-c to stop");
mvprintw(16,10,"y: %d\t x: %d",max_y,max_x);
getch();
while(1) {
getmaxyx(stdscr, max_y, max_x);
clear();
for (int x1=0; x1<max_x;x1++){
for (int y1=0; y1<max_y;y1++){
mvprintw(y1,x1,"%c",field[y1][x1]);
refresh();
}
}
for (int x1=0; x1<max_x;x1++){
for (int y1=0; y1<max_y;y1++){
int sum = 0;
int up = y1 - 1;
int down = y1 + 1;
int left = x1 - 1;
int right = x1 + 1;
if (up < 0) up = max_y - 1;
if (down > max_y) down = 0;
if (left < 0) left = max_x - 1;
if (right > max_x) right = 0;
sum = check(field[up][x1]) + check(field[down][x1]) + check(field[y1][left]) + check(field[y1][right]);
sum = check(field[up][right]) + check(field[up][left]) + check(field[down][right]) + check(field[down][left]) + sum;
if ((field[y1][x1] == 'X') && ((sum == 2) || (sum == 3))) field_next[y1][x1] = 'X';
else if ((field[y1][x1] == 'X') && ((sum == 1) || (sum == 4))) field_next[y1][x1] = ' ';
else if ((field[y1][x1] == ' ') && (sum == 3)) field_next[y1][x1] = 'X';
else field[y1][x1] = ' ';
}
}
usleep(delay);
for (int j = 0;j<max_y;j++){
for (int i = 0;i<max_x;i++){
field[j][i] = field_next[j][i];
field_next[j][i] = ' ';
}
}
}
endwin();
return 0;
}