Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <vector>
- struct point
- {
- int first;
- int second;
- };
- class game
- {
- typedef std::vector<std::vector<bool>> field_t;
- int height, width;
- field_t field;
- mutable field_t mask;
- int count_neighbours(int posx, int posy) const
- {
- int count = 0;
- for(int i = -1; i<=1; ++i)
- for(int j = -1; j<=1; ++j)
- {
- if(!i && !j ) continue;
- try
- {
- count += field.at(posx+i).at(posy+j);
- }
- catch(std::out_of_range) {}
- }
- return count;
- }
- void construct_mask() const
- {
- for(int i = 0; i<height; ++i)
- for(int j = 0; j<width ; ++j)
- {
- int count = count_neighbours(i, j);
- mask[i][j] = (field[i][j] && (count < 2 || count > 3))
- || (!field[i][j] && count == 3); //uhum uhum
- }
- }
- void apply_mask()
- {
- for(int i = 0; i<height; ++i)
- for(int j = 0; j<width ; ++j)
- {
- field[i][j] = field[i][j] ^ mask[i][j];
- // field[i][j] ^= mask[i][j] does not work
- }
- }
- public:
- game(int h, int w): height{h}, width{w}
- {
- field = std::vector<std::vector<bool>>(height);
- for(auto &x: field)
- {
- x = std::vector<bool>(width);
- }
- mask = field;
- }
- void set_alive(std::vector<point> &points)
- {
- for(auto [i, j]: points)
- field.at(i).at(j) = true;
- }
- inline void next_iteration()
- {
- construct_mask();
- apply_mask();
- }
- void print() const
- {
- for(auto &x: field)
- {
- for(auto y: x)
- std::cout << (y ? '#' : '`') << ' ';
- std::cout << '\n';
- }
- std::cout << '\n';
- }
- };
- #include <thread>
- int main()
- {
- int h, w;
- std::cout << "enter height, width\n";
- std::cin >> h >> w;
- game G(h, w);
- G.print();
- setup:
- std::cout << "\nenter amount of live cells\n";
- int amount; std::cin >> amount;
- std::cout << "\nenter points\n";
- std::vector<point> points(amount);
- for(auto &x: points)
- std::cin >> x.first >> x.second;
- try
- {
- G.set_alive(points);
- }
- catch(std::out_of_range &e)
- {
- std::cout << "\npoint out of bounds!\n";
- goto setup;
- }
- std::cout << "\nsetup complete!\n";
- G.print();
- for(int i = 0; i<100; ++i)
- {
- G.next_iteration();
- G.print();
- std::this_thread::sleep_for(std::chrono::milliseconds(100));
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment