Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class Main {
- // booleans in place of string, resolve boolean in print method
- // global variables are unnecessary
- public static final int size = 10;
- public static void main(String [] args) throws Exception {
- boolean[][] board = createBoard();
- while (true) {
- printBoard(board);
- board = updateBoard(board);
- Thread.sleep(500);
- System.out.println();
- }
- }
- public static boolean[][] createBoard() {
- boolean[][] board = new boolean[size][size];
- for (int x = 0; x < size; x++) {
- for (int y = 0; y < size; y++) {
- if (x == 0 && y == 2) {
- board[x][y] = true;
- }
- if (x == 1 && y == 3) {
- board[x][y] = true;
- }
- if (x == 2 && y == 1) {
- board[x][y] = true;
- }
- if (x == 2 && y == 2) {
- board[x][y] = true;
- }
- if (x == 2 && y == 3) {
- board[x][y] = true;
- }
- }
- }
- return board;
- }
- public static void printBoard(boolean[][] board) {
- for (int x = 0; x < size; x++) {
- for (int y = 0; y < size; y++) {
- if (board[x][y]) {
- System.out.print("[X]");
- } else {
- System.out.print("[ ]");
- }
- }
- System.out.println();
- }
- }
- public static boolean[][] updateBoard(boolean[][] board) {
- boolean[][] newBoard = new boolean[size][size];
- for (int x = 0; x < size; x++) {
- for (int y = 0; y < size; y++) {
- int neighbors = getNeighbors(board, x, y);
- boolean cell = board[x][y];
- if (cell && neighbors < 2) {
- newBoard[x][y] = false;
- } else if (cell && (neighbors == 2 || neighbors ==3)) {
- newBoard[x][y] = true;
- } else if (cell && neighbors > 3) {
- newBoard[x][y] = false;
- } else if (!cell && neighbors == 3) {
- newBoard[x][y] = true;
- }
- }
- }
- return newBoard;
- }
- public static int getNeighbors(boolean[][] board, int x, int y) {
- int count = 0;
- for (int i = -1; i <2; i++) {
- for (int j = -1; j <2; j++) {
- if (x == x - i && y == y - j) {
- continue;
- }
- if (x - i < 0 || y - j < 0 || x - i > size - 1 || y - j > size - 1) {
- continue;
- }
- if (board[x - i][y - j]) {
- count++;
- }
- }
- }
- return count;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement