Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package me.lukecarr.gameoflife;
- import javax.swing.*;
- import java.awt.*;
- import java.util.Timer;
- import java.util.List;
- import java.util.ArrayList;
- import java.util.TimerTask;
- import java.util.stream.Stream;
- public class GameOfLife {
- private static final JPanel[][] cells = new JPanel[40][40];
- public static void main(String[] args) {
- JFrame frame = new JFrame("Game of Life");
- frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
- frame.setSize(800, 800);
- frame.setLayout(new GridLayout(40, 40));
- Container container = frame.getContentPane();
- for(int x = 0; x < 40; x++) {
- for(int y = 0; y < 40; y++) {
- cells[x][y] = new JPanel();
- cells[x][y].setBackground(Color.WHITE);
- }
- }
- Timer timer = new Timer();
- timer.schedule(new TimerTask() {
- @Override
- public void run() {
- for(int x = 0; x < 40; x++) {
- for(int y = 0; y < 40; y++) {
- JPanel cell = cells[x][y];
- Stream<JPanel> neighbours = getNeighbours(x, y);
- long aliveNeighbours = neighbours.filter(neighbour -> neighbour.getBackground() == Color.BLACK).count();
- }
- }
- }
- }, 0, 500);
- frame.pack();
- frame.setLocationByPlatform(true);
- frame.setVisible(true);
- }
- public static boolean isAlive(int x, int y) {
- return cells[x][y].getBackground() == Color.BLACK;
- }
- public static Stream<JPanel> getNeighbours(int x, int y) {
- List<JPanel> neighbours = new ArrayList<>();
- for(int x1 = x-1; x1 < x+2; x1++) {
- for(int y1 = y-1; y1< y+2; y1++) {
- if(x1 < 0 || x1 > 39 || y1 < 0 || y1 > 39) {
- continue;
- }
- neighbours.add(cells[x1][y1]);
- }
- }
- return neighbours.stream();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement