W
Hab das vor Jahren mal für die Konsole programmieren müssen. Schau's Dir an, vielleicht hilft es ja. Das so abzugeben ohne es verstanden zu haben wäre hingegen unklug befürchte ich . Ist evtl. nicht der beste Code, habe es wie gesagt vor einigen Jahren programmiert.
#include <cstdlib>
#include <ctime>
#include <cstring>
#include <iostream>
const int xMove[8] = { -1, 0, 1, 1, 1, 0,-1,-1 };
const int yMove[8] = { -1,-1,-1, 0, 1, 1, 1, 0 };
const int width = 79, height = 23;
class GameOfLife {
bool cells[width][height];
unsigned long generation;
static bool seed;
unsigned fit(int value, unsigned maximum) {
return (value + maximum) % maximum;
}
public:
GameOfLife() : generation(0) {
if(!seed) {
std::srand(static_cast<unsigned>(time(0)));
seed = true;
}
memset(cells, 0, sizeof(cells) * sizeof(bool));
for(unsigned i = 0; i < 200; ++i)
cells[rand() % width][rand() % height] = true;
}
void generateNext();
friend std::ostream& operator <<(std::ostream&, const GameOfLife&);
};
bool GameOfLife::seed = false;
void GameOfLife::generateNext() {
bool nextCells[width][height];
for(unsigned y = 0; y < height; ++y) {
for(unsigned x = 0; x < width; ++x) {
unsigned neighbours = 0;
for(int i = 0; i < 8; ++i)
if(cells[fit(x + xMove[i], width)][fit(y + yMove[i], height)])
++neighbours;
switch(neighbours) {
case 2: // passiert nix
nextCells[x][y] = cells[x][y];
break;
case 3: // Geburt
nextCells[x][y] = true;
break;
default: // sterben
nextCells[x][y] = false;
break;
}
}
}
memcpy(cells, nextCells, sizeof(cells) * sizeof(bool));
}
std::ostream& operator <<(std::ostream& os, const GameOfLife& game) {
os << "Generation: " << game.generation << "\n";
for(unsigned y = 0; y < height; ++y) {
for(unsigned x = 0; x < width; ++x)
os << (game.cells[x][y] ? "O" : " ");
os << "\n";
}
return os;
}
void wait () {
std::cin.clear();
std::cin.ignore(std::cin.rdbuf()->in_avail());
std::cin.get();
}
int main() {
GameOfLife game;
for(;;) {
std::cout << game << std::endl;
game.generateNext();
wait();
}
}