From b6abba86d33e1fc124c3f0eb99aebf9e5dcc4ffe Mon Sep 17 00:00:00 2001 From: Mathias <mathias.faure@univ-amu.fr> Date: Mon, 5 Oct 2020 15:11:05 +0200 Subject: [PATCH] First part of the TP. --- Grid.java | 69 +++++++++++++++++++++++++++++++++++++++++++++---------- 1 file changed, 57 insertions(+), 12 deletions(-) diff --git a/Grid.java b/Grid.java index 939e05f..4fcdfd3 100644 --- a/Grid.java +++ b/Grid.java @@ -1,7 +1,4 @@ -import java.util.Arrays; -import java.util.Iterator; -import java.util.List; -import java.util.Random; +import java.util.*; /** * {@code Grid} instances represent the grid in <i>The Game of Life</i>. @@ -98,29 +95,68 @@ public class Grid implements Iterable<Cell> { } private boolean[][] calculateNextStates() { - return null; + boolean[][] newState = new boolean[getNumberOfRows()][getNumberOfColumns()]; + for (int r=0; r<numberOfRows; r++) { + for (int c=0; c<numberOfColumns; c++) { + newState[r][c] = this.calculateNextState(r,c,this.getCell(r,c)); + } + } + + return newState; + } + + private void goToNextState(boolean[][] nextState) { + for (int r=0; r<numberOfRows; r++) { + for (int c=0; c<numberOfColumns; c++) { + if (nextState[r][c]) { + this.getCell(r,c).setAlive(); + } + else { + this.getCell(r,c).setDead(); + } + } + } } private boolean calculateNextState(int rowIndex, int columnIndex, Cell cell) { - return false; + return cell.isAliveInNextState(this.countAliveNeighbours(rowIndex, columnIndex)); } private int countAliveNeighbours(int rowIndex, int columnIndex) { - return 0; + int CounterAliveCell = 0; + for (Cell NeighboursCell : this.getNeighbours(rowIndex, columnIndex)) { + if (NeighboursCell.isAlive()) { + CounterAliveCell+=1; + } + } + return CounterAliveCell; } private List<Cell> getNeighbours(int rowIndex, int columnIndex) { - return null; - } + List<Cell> Neighbours = new ArrayList<>(); + for (int r=-1; r<=1; r++) { + for (int c=-1; c<=1; c++) { + if ((r != 0) || (c != 0)) { + Neighbours.add(this.getCell(rowIndex + r, columnIndex + c)); + } + } + } - private void goToNextState(boolean[][] nextState) { + return Neighbours; } + + /** * Sets all {@link Cell}s in this {@code Grid} as dead. */ void clear() { + + for (Iterator<Cell> it = this.iterator(); it.hasNext(); ) { + Cell cell = it.next(); + cell.setDead(); + } } /** @@ -129,8 +165,17 @@ public class Grid implements Iterable<Cell> { * @param random {@link Random} instance used to decide if each {@link Cell} is alive or dead * @throws NullPointerException if {@code random} is {@code null} */ - + void randomGeneration(Random random) { + for (Iterator<Cell> it = this.iterator(); it.hasNext(); ) { + Cell cell = it.next(); + if (random.nextBoolean()) { + cell.setAlive(); + } + else { + cell.setDead(); + } + } } -} +} \ No newline at end of file -- GitLab