package kata.gameoflife.a20110208;
import java.awt.BorderLayout;
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Graphics;
import java.io.FileReader;
import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;
import javax.swing.JFrame;
import javax.swing.WindowConstants;
public class View extends JFrame {
private static final Color DEAD = Color.BLACK;
private static final Color DIED = Color.getHSBColor(0f, 0f, 0.2f);
private static final Color ALIFE = Color.getHSBColor(0f, 0f, 0.9f);
private static final Color BORN = Color.WHITE;
public View(final Game game) {
super("Game of Life");
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
final Canvas drawing = new Canvas() {
@Override
public void update(Graphics g) {
paint(g);
}
@Override
public void paint(Graphics g) {
paintGame(g, game);
}
};
drawing.setBackground(DEAD);
getContentPane().setLayout(new BorderLayout());
getContentPane().add(drawing, BorderLayout.CENTER);
Timer timer = new Timer("Game of Life Ticker");
timer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
game.tick();
drawing.repaint();
}
}, 100, 100);
}
private void paintGame(Graphics g, Game game) {
final int maxx = game.getMaxx();
final int maxy = game.getMaxy();
final double cellWidth = getSize().getWidth() * 1.0 / maxx;
final double cellHeight = getSize().getHeight() * 1.0 / maxy;
for (int x = 0; x < maxx; x++) {
for (int y = 0; y < maxy; y++) {
Cell cell = game.getField().getCell(x, y);
if (cell.wasStateChanged()) {
if (cell.isAlive()) {
g.setColor(BORN);
} else {
g.setColor(DIED);
}
} else {
if (cell.isAlive()) {
g.setColor(ALIFE);
} else {
g.setColor(DEAD);
}
}
g.fillOval((int) (x * cellWidth), (int) (y * cellHeight), (int) cellWidth, (int) cellHeight);
}
}
}
private static Game parseGame(String[] args) throws IOException {
Game game = new Game(Integer.parseInt(args[0]), Integer.parseInt(args[1]));
for (int i = 2; i < args.length; i++) {
game.seed(new FileReader(args[i]));
}
return game;
}
public static void main(String[] args) throws IOException {
if (args.length < 2) {
System.out.println("Game of Live maxx maxy [initial Seed] [...]");
System.exit(1);
}
Game game = parseGame(args);
View v = new View(game);
v.setSize(1024, 768);
v.setVisible(true);
}
}