-
Notifications
You must be signed in to change notification settings - Fork 2
/
Game.cpp
127 lines (114 loc) · 2.8 KB
/
Game.cpp
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
#include "Utility/PPMFile.h"
#include "Utility/RLEFile.h"
#include <iostream>
#include <vector>
#include <string>
#include <array>
#include <unistd.h>
class Game
{
public:
Game():width(0), height(0), time(0), born(), survive(), now(), past(){}
void read(const std::string &path)
{
RLEFile::read(path, width, height, born, survive, now);
past.resize(width * height);
}
void run()
{
for(int i = 1; i <= time; ++ i)
{
std::cout << "Starting: " << i << std::endl;
swap(now, past);
std::cout << "Saving" << std::endl;
save(i);
std::cout << "Calcing" << std::endl;
calc();
}
}
private:
void save(int t)
{
std::string path = "Output/";
path += std::to_string(t);
path += ".ppm";
PPMFile::save(path, width, height, past);
}
void calc()
{
for(int i = 0; i < height; ++ i)
{
for(int j = 0; j < width; ++ j)
{
now[index(i, j)] = count(i, j);
}
}
}
int index(int x, int y)
{
return x * width + y;
}
bool count(int x, int y)
{
int count = past[index((x + 1) % height, (y + 1) % width)]
+ past[index(x, (y + 1) % width)]
+ past[index((x - 1 + height) % height, (y + 1) % width)]
+ past[index((x + 1) % height, y)]
+ past[index((x - 1 + height) % height, y)]
+ past[index((x + 1) % height, (y - 1 + width) % width)]
+ past[index(x, (y - 1 + width) % width)]
+ past[index((x - 1 + height) % height, (y - 1 + width) % width)];
if(past[index(x, y)] == true)
{
return survive[count];
}
else
{
return born[count];
}
}
public:
int time;
private:
int width, height;
std::array<bool, 9> born, survive;
std::vector<bool> now, past;
};
void usage()
{
std::cout << "Usage: Game.out -p [PATTERN FILE] -t [SIMULATE TIMES]" << std::endl;
std::cout << "Example: Game.out -p Pattern/otcametapixel.rle -t 100" << std::endl;
}
int main(int argc, char* argv[])
{
int ret;
bool time = false, pattern = false;
Game g;
while((ret = getopt(argc, argv, "hp:t:")) != -1)
{
switch(ret)
{
case 't':
time = true;
g.time = atoi(optarg);
break;
case 'p':
pattern = true;
g.read(optarg);
break;
case 'h':
default:
usage();
return 0;
}
}
if(time && pattern)
{
g.run();
}
else
{
usage();
}
return 0;
}