-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlife.c
306 lines (265 loc) · 9.46 KB
/
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
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
#include <ncurses.h>
#include <stdlib.h>
#include <stdio.h>
#include <inttypes.h>
#include <string.h>
#include <errno.h>
#define DEFAULT_MS_FRAME_DELAY 200
#define LIVE_CELL 'o'
#define DEAD_CELL ' '
// Print the menu in which the player adds cells to the grid
void printMenu(const char* buffer, int generation, int population) {
printw("Generation: %d Population: %d\n", generation, population);
addstr(buffer);
attrset(COLOR_PAIR(1));
addstr("\n\nEnter");
attrset(COLOR_PAIR(0));
addstr(" Flip Cell");
attrset(COLOR_PAIR(1));
addstr("\nArrow Keys");
attrset(COLOR_PAIR(0));
addstr(" Move Around");
attrset(COLOR_PAIR(1));
addstr("\nSpace");
attrset(COLOR_PAIR(0));
addstr(" Start Simulation");
attrset(COLOR_PAIR(1));
addstr("\nQ");
attrset(COLOR_PAIR(0));
addstr(" Quit");
}
// Print the current generation of the cellular automata
void printAutomata(const char* buffer, int generation, int population) {
printw("Generation: %d Population: %d\n", generation, population);
addstr(buffer);
attrset(COLOR_PAIR(1));
addstr("\nQ");
attrset(COLOR_PAIR(0));
addstr(" Quit");
}
void calculateNextGeneration(char* bufferRead, char* bufferWrite, int gridWidth, size_t totalChars, int* population) {
memcpy(bufferRead, (void*)bufferWrite, totalChars * sizeof(char));
for (int x = 1; x < gridWidth + 1; x++) {
for (int y = 1; y < gridWidth + 1; y++) {
int idx = x + y * (gridWidth + 3);
// count live neighbors
int live_neighbors = 0;
live_neighbors += (int)(bufferRead[idx - 1] == LIVE_CELL); // left
live_neighbors += (int)(bufferRead[idx + 1] == LIVE_CELL); // right
live_neighbors += (int)(bufferRead[idx - (gridWidth + 3)] == LIVE_CELL); // bottom
live_neighbors += (int)(bufferRead[idx + (gridWidth + 3)] == LIVE_CELL); // top
live_neighbors += (int)(bufferRead[idx - 1 - (gridWidth + 3)] == LIVE_CELL); // bottom left
live_neighbors += (int)(bufferRead[idx - 1 + (gridWidth + 3)] == LIVE_CELL); // bottom right
live_neighbors += (int)(bufferRead[idx + 1 - (gridWidth + 3)] == LIVE_CELL); // top left
live_neighbors += (int)(bufferRead[idx + 1 + (gridWidth + 3)] == LIVE_CELL); // bottom right
if (bufferRead[idx] == LIVE_CELL) {
// if alive and has less than 2 or more than 3 neighbors it dies
if (live_neighbors < 2 || live_neighbors > 3) {
bufferWrite[idx] = DEAD_CELL;
(*population)--;
}
} else if (bufferRead[idx] == DEAD_CELL) {
// if its dead, then if it has three live neighbors it will come back to life
if (live_neighbors == 3) {
bufferWrite[idx] = LIVE_CELL;
(*population)++;
}
}
}
}
}
void nextFrame(char* bufferRead, char* bufferWrite, int gridWidth, size_t totalChars, int generation, int* population) {
calculateNextGeneration(bufferRead, bufferWrite, gridWidth, totalChars, population);
clear();
printAutomata(bufferWrite, generation, *population);
refresh();
}
int main(int argc, char *argv[])
{
/*
Program takes 3 arguments, the width and height of the grid
and an optional argument for the FPS so if we recieve 3 arguments
we interpret it as only width and height
*/
if (argc != 3 && argc != 4) {
fputs("Invalid number of arguments passed! Program usage: ./life (width: int 1 - 255) (height: int 1 - 255) OPTIONAL (FPS: int)\n", stderr);
return EXIT_FAILURE;
}
// Width and height of the playable area in game of life
uint8_t width;
uint8_t height;
int msFrameDelay;
// cellular automata stats
int generation = 0;
int population = 0;
char* endptr;
// If we have a fourth argument, it will be the FPS
if (argc == 4) {
int fps = strtol(argv[3], &endptr, 10);
if (*endptr != '\0') {
fputs("Value provided for optional argument 3 - FPS - is not a valid integer\n", stderr);
return EXIT_FAILURE;
}
msFrameDelay = 1000/fps;
} else {
msFrameDelay = DEFAULT_MS_FRAME_DELAY;
}
{
int lwidth = strtol(argv[1], &endptr, 10);
if (*endptr != '\0') {
fputs("Value provided for argument 1 - width - is not a valid integer\n", stderr);
return EXIT_FAILURE;
}
if (lwidth < 1 || lwidth > 255) {
fputs("Value provided for argument 1 - width - is not in the range 1 - 255\n", stderr);
return EXIT_FAILURE;
}
width = (uint8_t)lwidth;
}
{
int lheight = strtol(argv[2], &endptr, 10);
if (*endptr != '\0') {
fputs("Value provided for argument 2 - height - is not a valid integer\n", stderr);
return EXIT_FAILURE;
}
if (lheight < 1 || lheight > 255) {
fputs("Value provided for argument 2 - height - is not in the range 1 - 255\n", stderr);
return EXIT_FAILURE;
}
height = (uint8_t)lheight;
}
/*
The char buffer needs to store an extra column on the left for a border
and 2 extra column on the right for a border and then newline chars.
There must also be an extra row on the top and bottom for borders above
and below. We also need one extra char for null terminator!
*/
size_t totalChars = ((width + 3) * (height + 2)) + 1;
char* bufferWrite = malloc(sizeof(char) * totalChars);
if (bufferWrite == NULL) {
fputs("Failed to allocate memory for write framebuffer!", stderr);
return EXIT_FAILURE;
}
memset(bufferWrite, DEAD_CELL, sizeof(char) * totalChars);
// TODO: grid setup is messy, must cleanup!
// add newlines to the end of every line
for (int i = 0; i < height + 1; i++) {
bufferWrite[(width + 2) + i * ( width + 3)] = '\n';
}
// top line
bufferWrite[0] = '+';
for (int idx = 1; idx < width + 1; idx++) {
bufferWrite[idx] = '-';
}
bufferWrite[width + 1] = '+';
// middle
for (int i = 1; i < height+1; i++) {
bufferWrite[i * (width + 3)] = '|';
bufferWrite[i * (width + 3) + width + 1] = '|';
}
// top line
bufferWrite[(width + 3) * (height + 1)] = '+';
for (int idx = 1; idx < width + 1; idx++) {
bufferWrite[idx + ((width + 3) * (height + 1))] = '-';
}
bufferWrite[totalChars-3] = '+';
// add null terminator
bufferWrite[totalChars-1] = '\0';
// Init curses screen
initscr();
if (has_colors()) {
use_default_colors();
start_color();
init_pair(1, COLOR_BLACK, COLOR_WHITE);
}
// Draw our char buffer and refresh the screen
printMenu(bufferWrite, generation, population);
refresh();
// Our initial mouse position is (1,2) as to not be on the border
int x = 1;
int y = 1;
move(y+1, x);
// Ncurses input settings
raw();
keypad(stdscr, TRUE);
intrflush(stdscr, FALSE);
noecho();
int inputCode;
do {
inputCode = getch();
switch (inputCode) {
case KEY_LEFT: {
if (x > 1) {
x -= 1;
move(y+1,x);
}
break;
}
case KEY_RIGHT: {
if (x < width) {
x += 1;
move(y+1,x);
}
break;
}
case KEY_UP: {
if (y > 1) {
y -= 1;
move(y+1,x);
}
break;
}
case KEY_DOWN: {
if (y < height) {
y += 1;
move(y+1,x);
}
break;
}
case 10: {
int cellIdx = y * (width + 3) + x;
if (bufferWrite[cellIdx] == LIVE_CELL) {
bufferWrite[cellIdx] = DEAD_CELL;
population--;
}
else if (bufferWrite[cellIdx] == DEAD_CELL) {
bufferWrite[cellIdx] = LIVE_CELL;
population++;
}
clear();
printMenu(bufferWrite, generation, population);
refresh();
move(y+1,x);
break;
}
case 'q': {
endwin();
free(bufferWrite);
return EXIT_SUCCESS;
}
}
} while (inputCode != ' ');
// Start simulation
curs_set(0);
// we will need to copy the buffer for reading in the for loop, so we allocate space for that one too
char* bufferRead = malloc(sizeof(char) * totalChars);
// if we fail to allocate memory for the read framebuffer, free the write framebuffer stop ncurses and return
if (bufferRead == NULL) {
fputs("Failed to allocate memory for read framebuffer!", stderr);
free(bufferWrite);
endwin();
return EXIT_FAILURE;
}
nextFrame(bufferRead, bufferWrite, width, totalChars, generation, &population);
timeout(msFrameDelay);
do {
inputCode = getch();
generation++;
nextFrame(bufferRead, bufferWrite, width, totalChars, generation, &population);
} while (inputCode != 'q');
// Cleanup
endwin();
free(bufferRead);
free(bufferWrite);
return EXIT_SUCCESS;
}