Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //============================================================================
- // Name : Game.cpp
- // Author : Hasan Rasulov
- // Version :
- // Copyright : Your copyright notice
- // Description : Hello World in C++, Ansi-style
- //============================================================================
- #include <iostream>
- #include<random>
- #include<array>
- #include<SFML/Graphics.hpp>
- using namespace std;
- enum class State
- :size_t {
- dead = 0, alive = 1
- };
- constexpr size_t w = 600;
- constexpr size_t h = 400;
- constexpr size_t res = 5;
- constexpr size_t cols = w / res;
- constexpr size_t rows = h / res;
- using Grid=array<array<State,rows>,cols>;
- size_t get_count(Grid& grid, size_t x, size_t y) {
- size_t count = 0;
- for (int i = -1; i < 2; ++i)
- for (int j = -1; j < 2; j++)
- count += static_cast<size_t>(grid[(x + i + cols) % cols][(y + j
- + rows) % rows]);
- count -= static_cast<size_t>(grid[x][y]);
- return count;
- }
- Grid generate(Grid& old_grid) {
- Grid new_grid;
- for (size_t i = 0; i < cols; ++i) {
- for (size_t j = 0; j < rows; j++) {
- size_t count_neighbours = get_count(old_grid, i, j);
- if (old_grid[i][j] == State::dead && count_neighbours == 3) {
- new_grid[i][j] = State::alive;
- } else if (old_grid[i][j] == State::alive
- && (count_neighbours < 2 || count_neighbours > 3)) {
- new_grid[i][j] = State::dead;
- } else {
- new_grid[i][j] = old_grid[i][j];
- }
- }
- }
- return new_grid;
- }
- int main() {
- sf::RenderWindow window(sf::VideoMode(w, h), "Game of Life",
- sf::Style::Default);
- sf::RectangleShape zero(sf::Vector2f(res, res));
- zero.setFillColor(sf::Color::White);
- sf::RectangleShape one(sf::Vector2f(res, res));
- one.setFillColor(sf::Color::Black);
- Grid grid;
- std::random_device rd;
- mt19937 gen(rd());
- std::bernoulli_distribution dist(0.1);
- for (size_t i = 0; i < cols; ++i) {
- for (size_t j = 0; j < rows; j++) {
- grid[i][j] = dist(gen) ? State::alive : State::dead;
- }
- }
- while (window.isOpen()) {
- sf::Event e;
- while (window.pollEvent(e)) {
- if (e.type == sf::Event::Closed)
- window.close();
- }
- for (size_t i = 0; i < cols; ++i) {
- for (size_t j = 0; j < rows; j++) {
- if (grid[i][j] == State::alive) {
- one.setPosition(i * res, j * res);
- window.draw(one);
- } else {
- zero.setPosition(i * res, j * res);
- window.draw(zero);
- }
- }
- }
- grid = generate(grid);
- window.display();
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment