-
Notifications
You must be signed in to change notification settings - Fork 0
/
game_of_life.c
96 lines (84 loc) · 1.95 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
#include <stdio.h>
#include <stdlib.h>
void start(int width, int height, char *T);
void run();
void stop();
char *T;
int width, height;
int load_data(char *filename) {
FILE *f;
f = fopen(filename, "r");
if (f == NULL) {
perror("couldn't open input file");
return 1;
}
if (fscanf(f, "%d %d\n", &width, &height) <= 0) {
printf("couldn't parse width or height in the first line\n");
fclose(f);
return 1;
}
T = malloc(sizeof(char)*width*height);
if (T == NULL) {
perror("couldn't allocate memory for the board");
fclose(f);
return 1;
}
int x, y;
for (y = 0; y < height; y++) {
for (x = 0; x < width; x++) {
if (fscanf(f, "%c ", &T[y*width + x]) <= 0) {
printf("couldn't parse board, allowed values (0,1)\n");
fclose(f);
free(T);
return 1;
}
if (fscanf(f, "\n") < 0) {
perror("couldn't parse board");
fclose(f);
free(T);
return 1;
}
}
}
return 0;
}
void unload_data() {
free(T);
}
void print_T() {
int x, y;
for (y = 0; y < height; y++) {
for (x = 0; x < width; x++) {
if (T[y*width + x] == '1') {
printf("\e[1;32m1\e[0m ");
} else {
printf("0 ");
}
}
printf("\n");
}
printf("\n");
}
int main(int argc, char **argv) {
if (argc != 3) {
printf("Usage: game_of_life ./input steps\n");
return 1;
}
int steps = atoi(argv[2]);
if (steps <= 0) {
printf("Number of steps must be positive.\n");
return 1;
}
if (load_data(argv[1]) != 0) {
return 2;
}
start(width, height, T);
int i;
for (i = 0; i < steps; i++) {
run();
print_T();
}
stop();
unload_data(T);
return 0;
}