[データ構造]Life_ゲーム
2702 ワード
//main.cpp
#include"Life.h"
#include
#include
using namespace std;
void main() {
cout << "********************************* Life Game**********************************" << endl;
cout << "please enter the location you want live, just like \"m n\"" << endl;
cout << "enter \"-1 -1\" to end enter" << endl;
Life example;
example.Initialize();
example.Print();
while (1) {
cout << "enter \"yes\" to the next generation" << endl;
string s;
cin >> s;
if (s == "yes") {
example.UpDate();
example.Print();
}
else break;
}
system("pause");
}
//Life.h
#pragma once
#include
using namespace std;
const int maxrow = 20, maxcol = 60;//
class Life
{
public:
void Initialize();//
void UpDate();//
void Print();//
Life() {
for (int i = 1; i <= maxrow; i++)
for (int j = 0; j <= maxcol; j++)
arr[i][j] = 0;
}
private:
int arr[maxrow + 2][maxcol + 2];
int neighbour_count(int row,int col);
};
Life.cpp
#include"Life.h"
#include
#include
using namespace std;
void Life::Initialize() {
int row, col;
do {
cin >> row >> col;
if (row >= 1 && row <= maxrow)
if (col >= 1 && col <= maxcol)
arr[row][col] = 1;
else {
cout << "out of range" << endl;
break;
}
} while (row != -1 && col != -1);
}
void Life::Print() {
system("cls");
int row, col;
for (row = 1; row <= maxrow; row++) {
for (col = 1; col <= maxcol; col++) {
if (arr[row][col] == 0)cout << "□";
else cout << "●";
}
cout << endl;
}
}
void Life::UpDate() {
int new_arr[maxrow + 2][maxcol + 2];
for (int i = 1; i <= maxrow; i++)
for (int j = 0; j <= maxcol; j++)
new_arr[i][j] = 0;
for (int row = 1; row <= maxrow; row++) {
for (int col = 1; col <= maxcol; col++) {
switch (neighbour_count(row,col))
{
case 2:
new_arr[row][col] = arr[row][col];
break;
case 3:
new_arr[row][col] = 1;
break;
default:
new_arr[row][col] = 0;
break;
}
}
}
for (int i = 0; i <= maxrow; i++)
for (int j = 0; j <= maxcol; j++)
arr[i][j] = new_arr[i][j];
}
int Life::neighbour_count(int row, int col) {
int sum = 0;
for (int i = row - 1; i <= row + 1; i++)
for (int j = col - 1; j <= col + 1; j++)
if (arr[i][j] == 1)sum++;
return (sum - arr[row][col]);
}