Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.ArrayList;
- public class Life {
- private LifeBoard board;
- private int neighbours;
- private int rows, cols;
- // Skapar ett Life-spel med spelplanen board
- public Life(LifeBoard board) {
- this.board = board;
- }
- // Skapar en ny generation
- public void newGeneration() {
- rows = board.getRows();
- cols = board.getCols();
- LifeBoard tempBoard = new LifeBoard(rows, cols);
- for (int i=0; i < rows; i++ ) {
- for (int k=0; k< cols; k++) {
- getNeighbours(board, i, k);
- if (neighbours < 2 || neighbours > 3) {
- tempBoard.put(i, k, false);
- }
- if ( neighbours == 2 && (board.get(i, k) == true)){
- tempBoard.put(i, k, true);
- }
- if (neighbours == 3) {
- tempBoard.put(i, k, true);
- }
- }
- }
- for (int y=0; y < rows; y++ ) {
- for (int x=0; x< cols; x++) {
- board.put(y, x, tempBoard.get(y, x));
- }
- }
- board.increaseGeneration();
- }
- // Ändrar innehållet i rutan med index row, col från individ till tom eller
- // tvärtom
- public void flip(int row, int col) {
- if (board.get(row, col) == true) {
- board.put(row, col, false);
- } else
- board.put(row, col, true);
- }
- private int getNeighbours(LifeBoard board, int row, int col) {
- neighbours = 0;
- //for (int i=-1;i <=1; i++) {
- //for(int k = -1; k<=1; k++) {
- //if ((board.get(row + i, col + k)) && (i !=0 && k!=0)) {
- //neighbours++;
- //}
- //}
- //}
- if (board.get(row -1, col)) {//N
- neighbours++;
- }
- if (board.get(row -1, col+1)) {//NE
- neighbours++;
- }
- if (board.get(row , col+1)) {//E
- neighbours++;
- }
- if (board.get(row +1, col+1)) {//SE
- neighbours++;
- }
- if (board.get(row +1, col)) {//S
- neighbours++;
- }
- if (board.get(row +1, col-1)) {//SW
- neighbours++;
- }
- if (board.get(row , col-1)) {//W
- neighbours++;
- }
- if (board.get(row -1, col-1)) {//NW
- neighbours++;
- }
- return neighbours;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement