Created
November 16, 2019 07:54
-
-
Save y0t4/21f54a6b5054b8e1705b8a5b58ae7ffd to your computer and use it in GitHub Desktop.
[初C++]coderetreatで作ったlifegame
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <vector> | |
#include <map> | |
#include <string> | |
#include <unistd.h> | |
using namespace std; | |
class Lifegame | |
{ | |
private: | |
vector<pair<int, int> > living_cells; | |
int col; | |
int row; | |
map<pair<int, int>, int> calculate_alive_counts() { | |
map<pair<int, int>, int> alive_counts; | |
for (pair<int, int> living_cell : living_cells) { | |
int _col = living_cell.first; | |
int _row = living_cell.second; | |
for (int i = -1; i <= 1; i++) { | |
for (int j = -1; j <= 1; j++) { | |
if (i == 0 && j == 0) continue; | |
pair<int, int> cood = make_pair(_col + i, _row + j); | |
alive_counts[cood] = alive_counts[cood] + 1; | |
} | |
} | |
} | |
return alive_counts; | |
} | |
public: | |
void initialize(int x, int y) { | |
col = x; | |
row = y; | |
living_cells = {}; | |
} | |
bool is_alive(int col, int row) { | |
for (pair<int, int> living_cell : living_cells) { | |
if (living_cell == make_pair(col, row)) | |
return true; | |
} | |
return false; | |
} | |
void set_alives(vector<pair<int, int> > alives) { | |
living_cells = alives; | |
} | |
void next() { | |
map<pair<int, int>, int> alive_counts = calculate_alive_counts(); | |
vector<pair<int, int> > next_livings; | |
for (int row = 0; row < this->row; row++) { | |
for (int col = 0; col < this->col; col++) { | |
pair<int, int> cood = make_pair(col,row); | |
if (is_alive(col, row)) { | |
if (alive_counts[cood] == 2 || alive_counts[cood] == 3) { | |
next_livings.push_back(cood); | |
} | |
} else { | |
if (alive_counts[cood] == 3) { | |
next_livings.push_back(cood); | |
} | |
} | |
} | |
} | |
set_alives(next_livings); | |
} | |
void pretty_print() { | |
string result; | |
for (int row = 0; row < this->row; row++) { | |
for (int col = 0; col < this->col; col++) { | |
if (is_alive(col, row)) { | |
result += "1"; | |
} else { | |
result += "0"; | |
} | |
} | |
result += "\n"; | |
} | |
cout << result; | |
cout<<"\e[" << this->row << "A"; | |
} | |
}; | |
int main() { | |
Lifegame lifegame; | |
vector<pair<int, int> > data = {make_pair(0, 1), make_pair(1, 1), make_pair(2, 1)}; | |
//vector<pair<int, int> > grider = {make_pair(0, 0), make_pair(1, 0), make_pair(2, 0), make_pair(0, 1), make_pair(1, 2)}; | |
lifegame.initialize(3, 3); | |
lifegame.set_alives(data); | |
while (1) { | |
lifegame.pretty_print(); | |
lifegame.next(); | |
sleep(1); | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment