Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Algorytm Conwaya
- // wersja tekstowa, kolorowanie według wątków
- // Gra w życie
- #include <iostream>
- #include <thread>
- #include <chrono>
- #include <cstdlib>
- using namespace std;
- const int height = 16; // wysokość planszy
- const int width = 32; // szerokość planszy
- int state[height][width]; // tablica z komórkami
- int sleep = 300; // czas pomiędzy kolejnymi stanami planszy
- int n = 50; // początkowa ilość żywych komórek
- void init()
- {
- // wypełnienie tablicy martwymi komórkami
- for(int y=0; y<height; y++)
- for(int x=0; x<width; x++)
- state[y][x] = 0;
- // wylosowanie położenia żywych komórek
- srand(time(NULL));
- for(int i=0; i<n; i++)
- state[rand()%height][rand()%width] = 1;
- }
- void print() // wypisuje stan planszy
- {
- this_thread::sleep_for(chrono::milliseconds(sleep));
- cout << "\033[2J\033[1;1H";
- for(int y=0; y<height; y++)
- {
- for(int x=0; x<width; x++)
- if(state[y][x] == 0) cout << ' ';
- else cout << '*';
- cout << endl;
- }
- }
- // LICZENIE KOLEJNEGO STANU
- int neighbors(int y, int x) // liczy ilość sąsiadów dla danej komórki
- {
- int i = 0;
- if(y-1 >= 0 && x-1 >= 0) i += state[y-1][x-1];
- if(y-1 >= 0) i += state[y-1][x];
- if(y-1 >= 0 && x+1 < width) i += state[y-1][x+1];
- if(x-1 >=0) i += state[y][x-1];
- if(x+1 < width) i += state[y][x+1];
- if(y+1 < height && x-1 >= 0) i += state[y+1][x-1];
- if(y+1 < height) i += state[y+1][x];
- if(y+1 < height && x+1 < width) i += state[y+1][x+1];
- return i;
- }
- int count() // oblicza kolejny stan
- {
- int nextState[height][width]; // tablica tymczasowa
- int end = 0; // flaga sprawdzająca czy symulacja została zakończona
- for(int y=0; y<height; y++)
- {
- for(int x=0; x<width; x++)
- {
- int nb = neighbors(y,x);
- if(nb == 3 || (state[y][x] == 1 && nb == 2)) // zasady tworzenia nowego stanu
- {
- nextState[y][x] = 1;
- end = 1;
- }
- else
- nextState[y][x] = 0;
- }
- }
- // przepisanie stanów z tablicy tymczasowej
- for(int y=0; y<height; y++)
- for(int x=0; x<width; x++)
- state[y][x] = nextState[y][x];
- return end;
- }
- int main()
- {
- init();
- while(count() != 0) print();
- cout << endl << "Symulacja zakończona" << endl;
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement