Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.jnumerical.gameoflife;
- import java.awt.Canvas;
- import java.awt.Dimension;
- import java.awt.Graphics;
- import java.awt.image.BufferStrategy;
- import javax.swing.JFrame;
- public class Main extends Canvas implements Runnable {
- static String title = "Game of Life";
- private boolean running = false;
- private Thread thread;
- private JFrame frame;
- private Board board;
- static int width = 1900; // pixels width of board
- static int height = 1000; // pixels height of board
- private int cellPixels = 8; // pixels across a cell plus the gap
- private int gridPixels = 2; // pixels between each cell
- private int tick = 500; // milliseconds between ticks
- private int chance = 13; // percent chance each cell will start alive
- private int boardLife = 50; // number of ticks until board randomization
- private int colorLife = 10; // number of ticks until new color chosen
- public Main(){
- setPreferredSize(new Dimension(width, height));
- frame = new JFrame();
- board = new Board(chance, cellPixels, gridPixels, boardLife, colorLife);
- }
- public synchronized void start(){
- running = true;
- thread = new Thread(this, "Thread");
- thread.start();
- }
- public synchronized void stop(){
- running = false;
- try{
- thread.join();
- }catch(InterruptedException e){
- e.printStackTrace();
- }
- }
- public void run(){
- requestFocus();
- long lastTime = 0;
- while(running){
- long time = System.currentTimeMillis();
- if(time - lastTime >= tick){
- lastTime = time;
- update();
- render();
- }
- }
- stop();
- }
- public void update(){
- board.update();
- }
- public void render(){
- BufferStrategy bs = getBufferStrategy();
- if(bs == null){
- createBufferStrategy(3);
- return;
- }
- Graphics g = bs.getDrawGraphics();
- board.render(g);
- g.dispose();
- bs.show();
- }
- public static void main(String[] args){
- Main main = new Main();
- main.frame.setResizable(false);
- main.frame.setTitle(title);
- main.frame.add(main);
- main.frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
- main.frame.setLocation(7, 0);
- main.frame.setVisible(true);
- main.frame.requestFocus();
- main.frame.pack();
- main.start();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment