/
monahov
/
learningcplusplus
Обзор
Документация
Войти
/
monahov
/
learningcplusplus
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
Безопасность
master
Lesson Space.cpp
146 строк
3 KB
monahov
update Lesson Space.cpp
03 сен 2025, 17:45
03 сен 2025, 17:45
a0e7b24
Код
Авторство
О чём код?
#include <iostream> #include <fstream> #include <vector> #include <cstdlib> #include <Windows.h> using namespace std; using Grid = vector<vector<int>>; bool loadUniverse(const string& filename, Grid& grid, int& rows, int& cols) { ifstream file(filename); if (!file.is_open()) { cerr << "Ошибка: не удалось открыть файл " << filename << endl; return false; } file >> rows >> cols; grid.assign(rows, vector<int>(cols, 0)); int row, col; while (file >> row >> col) { if (row >= 0 && row < rows && col >= 0 && col < cols) { grid[row][col] = 1; } } file.close(); return true; } void printUniverse(const Grid& grid, int generation, int liveCount) { system("cls"); for (const auto& row : grid) { for (int cell : row) { cout << (cell ? '*' : '-') << ' '; } cout << endl; } cout << "Поколение: " << generation << ", Живых клеток: " << liveCount << endl; } int countNeighbors(const Grid& grid, int i, int j) { int rows = grid.size(); int cols = grid[0].size(); int count = 0; for (int di = -1; di <= 1; ++di) { for (int dj = -1; dj <= 1; ++dj) { if (di == 0 && dj == 0) continue; int ni = i + di; int nj = j + dj; if (ni >= 0 && ni < rows && nj >= 0 && nj < cols) { count += grid[ni][nj]; } } } return count; } int countLiveCells(const Grid& grid) { int count = 0; for (const auto& row : grid) { for (int cell : row) { count += cell; } } return count; } bool gridsEqual(const Grid& a, const Grid& b) { return a == b; } int main() { setlocale(LC_ALL, "rus"); const string filename = "info.txt"; int rows, cols; Grid current; if (!loadUniverse(filename, current, rows, cols)) { return 1; } int generation = 1; int liveCount = countLiveCells(current); printUniverse(current, generation, liveCount); while (true) { Sleep(300); Grid previous = current; Grid next = current; for (int i = 0; i < rows; ++i) { for (int j = 0; j < cols; ++j) { int neighbors = countNeighbors(current, i, j); if (current[i][j] == 0) { next[i][j] = (neighbors == 3) ? 1 : 0; } else { next[i][j] = (neighbors == 2 || neighbors == 3) ? 1 : 0; } } } current = move(next); generation++; liveCount = countLiveCells(current); printUniverse(current, generation, liveCount); if (liveCount == 0) { cout << "Игра окончена: все клетки мертвы." << endl; break; } if (gridsEqual(current, previous)) { cout << "Игра окончена: стабильная конфигурация." << endl; break; } } return 0; }