|
// GameOfLife.java import ch.aplu.util.*; import java.awt.*; public class GameOfLife { private GPanel p; GameOfLife() { p = new GPanel(-0.5, Data.xmax - 0.5, 0.5, Data.ymax - 0.5); p.bgColor(Color.black); Game g = new Game(p); } class Data { final static int xmax = 99; final static int ymax = 99; boolean[][] pop = new boolean[xmax + 1][ymax + 1]; boolean[][] popNew = new boolean[xmax + 1][ymax + 1]; } class Game { private GPanel p; private Data data = new Data(); private int nbGen = 0; private String oldLabel = ""; Game(GPanel panel) { p = panel; initialize(); play(); } private void play() { while (true) { drawPop(); nextGen(); } } private void initialize() { int x, y; for (x = 0; x <= Data.xmax; x++) for (y = 0; y <= Data.ymax; y++) data.popNew[x][y] = data.pop[x][y] = false; for (x = 0; x <= Data.xmax; x++) for (y = 0; y <= Data.ymax; y++) if (x % 3 == y % 7 || (6 * x) % 7 == y % 3) data.popNew[x][y] = true; } private void nextGen() { int x, y; Console.delay(200); nbGen++; for (x = 0; x <= Data.xmax; x++) for (y = 0; y <= Data.ymax; y++) switch (neighbours(x, y)) { case 0 : case 1 : case 4 : case 5 : case 6 : case 7 : case 8 : // Individuum ist oder wird tot data.popNew[x][y] = false; break; case 2 : // Individuum bleibt so, wie es ist data.popNew[x][y] = data.pop[x][y]; break; case 3 : // Individuum ist oder wird lebendig data.popNew[x][y] = true; break; } } private int neighbours(int x, int y) { int count = 0; int xLeft = x > 0 ? x - 1 : Data.xmax; int xRight = x < Data.xmax ? x + 1 : 0; int yBottom = y > 0 ? y - 1 : Data.ymax; int yTop = y < Data.ymax ? y + 1 : 0; count = toInt(data.pop[xLeft][yBottom]) + toInt(data.pop[xLeft][y]) + toInt(data.pop[xLeft][yTop]) + toInt(data.pop[x][yBottom]) + toInt(data.pop[x][yTop]) + toInt(data.pop[xRight][yBottom]) + toInt(data.pop[xRight][y]) + toInt(data.pop[xRight][yTop]); return count; } private int toInt(boolean x) { return x ? 1 : 0; } private void drawPop() { drawTitle(nbGen); for (int x = 0; x <= Data.xmax; x++) for (int y = 0; y <= Data.ymax; y++) if (data.popNew[x][y] != data.pop[x][y]) { if (data.popNew[x][y]) { p.color(Color.green); p.move(x, y); p.fillCircle(0.5); } else { p.color(Color.black); p.move(x, y); p.fillCircle(0.5); } data.pop[x][y] = data.popNew[x][y]; } } private void drawTitle(int n) { String newLabel = "Game of life. Gen #: " + n; Color oldColor = Color.black; p.title(oldLabel); // Erase p.color(Color.white); p.title(newLabel); // Draw oldLabel = newLabel; p.color(oldColor); } } public static void main(String[] args) { new GameOfLife(); } } |