Snippets

Burdzi0 Game Of Life

Created by Burdzi0 last modified
package gra;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;

public class Life {
	
	private char[][] gameBoard = new char[12][20];
	private int numberOfRounds = 0;
	
	public boolean readDataFromFile(File file) {
		try (BufferedReader br = new BufferedReader(new FileReader(file))) {
			String line;
			int arrayIndex = 0;
			while ((line = br.readLine()) != null) {
				for (int i = 0; i < 20; i++) {
					gameBoard[arrayIndex][i] = line.charAt(i);
				}
				arrayIndex++;
			}
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}
	
	public void printGameBoard() {
		for (int i = 0; i < gameBoard.length; i++) {
			for (int j = 0; j < gameBoard[i].length; j++) {
				System.out.print(gameBoard[i][j]);
			}
			System.out.println();
		}
	}
	
	public int getNumberOfNeighbours(int row, int column) {
		int neighboursCount = 0;
		for (int i = -1; i < 2; i++) {
			for (int j = -1; j < 2; j++) {
				if (gameBoard[row + i][column + j] == 'X') neighboursCount++;
			}
		}
		return neighboursCount;
	}
	
	public boolean hasTwoOrThreeNeighbours(int row, int column) {
		int numberOfNeighbours = getNumberOfNeighbours(row, column);
		return numberOfNeighbours == 2 || numberOfNeighbours == 3;
	}
	
	public boolean hasThreeNeighbours(int row, int column) {
		return getNumberOfNeighbours(row, column) == 3;
	}
	
	public void nextRound() {
		// Starts from 1 because number of neighbours add -1
		// to row and to column in the first place
		for (int i = 1; i < gameBoard.length - 1; i++) {
			for (int j = 1; j < gameBoard[i].length - 1; j++) {
				if (gameBoard[i][j] == 'X' && hasTwoOrThreeNeighbours(i, j)) {
					gameBoard[i][j] = 'X';
				} else if (gameBoard[i][j] == '.' && hasThreeNeighbours(i, j)) {
					gameBoard[i][j] = 'X';
				} else {
					gameBoard[i][j] = '.';
				}
			}
		}
		numberOfRounds++;
	}
	
	public int getNumberOfRounds() {
		return numberOfRounds;
	}
}

Comments (0)

HTTPS SSH

You can clone a snippet to your computer for local editing. Learn more.