daily pastebin goal
46%
SHARE
TWEET

Untitled

a guest Sep 14th, 2018 49 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. package me.lukecarr.gameoflife;
  2.  
  3. import javax.swing.*;
  4. import java.awt.*;
  5. import java.util.Timer;
  6. import java.util.List;
  7. import java.util.ArrayList;
  8. import java.util.TimerTask;
  9. import java.util.stream.Stream;
  10.  
  11. public class GameOfLife {
  12.  
  13.     private static final JPanel[][] cells = new JPanel[40][40];
  14.  
  15.     public static void main(String[] args) {
  16.         JFrame frame = new JFrame("Game of Life");
  17.         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  18.         frame.setSize(800, 800);
  19.         frame.setLayout(new GridLayout(40, 40));
  20.         Container container = frame.getContentPane();
  21.         for(int x = 0; x < 40; x++) {
  22.             for(int y = 0; y < 40; y++) {
  23.                 cells[x][y] = new JPanel();
  24.                 cells[x][y].setBackground(Color.WHITE);
  25.             }
  26.         }
  27.  
  28.         Timer timer = new Timer();
  29.         timer.schedule(new TimerTask() {
  30.             @Override
  31.             public void run() {
  32.                 for(int x = 0; x < 40; x++) {
  33.                     for(int y = 0; y < 40; y++) {
  34.                         JPanel cell = cells[x][y];
  35.                         Stream<JPanel> neighbours = getNeighbours(x, y);
  36.                         long aliveNeighbours = neighbours.filter(neighbour -> neighbour.getBackground() == Color.BLACK).count();
  37.                     }
  38.                 }
  39.             }
  40.         }, 0, 500);
  41.  
  42.         frame.pack();
  43.         frame.setLocationByPlatform(true);
  44.         frame.setVisible(true);
  45.     }
  46.  
  47.     public static boolean isAlive(int x, int y) {
  48.         return cells[x][y].getBackground() == Color.BLACK;
  49.     }
  50.  
  51.     public static Stream<JPanel> getNeighbours(int x, int y) {
  52.         List<JPanel> neighbours = new ArrayList<>();
  53.         for(int x1 = x-1; x1 < x+2; x1++) {
  54.             for(int y1 = y-1; y1< y+2; y1++) {
  55.                 if(x1 < 0 || x1 > 39 || y1 < 0 || y1 > 39) {
  56.                     continue;
  57.                 }
  58.                 neighbours.add(cells[x1][y1]);
  59.             }
  60.         }
  61.         return neighbours.stream();
  62.     }
  63.  
  64. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top