Skip to content

Commit

Permalink
added selected animal
Browse files Browse the repository at this point in the history
  • Loading branch information
PiotrMakarewicz committed Dec 23, 2020
1 parent 90b3603 commit d427f64
Show file tree
Hide file tree
Showing 10 changed files with 183 additions and 54 deletions.
2 changes: 0 additions & 2 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,4 +1,2 @@
.idea/*
*.iml
test/*
out/*
30 changes: 30 additions & 0 deletions EvolutionSimulator.iml
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="JAVA_MODULE" version="4">
<component name="NewModuleRootManager" inherit-compiler-output="true">
<exclude-output />
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/test" isTestSource="true" />
<sourceFolder url="file://$MODULE_DIR$/resources" type="java-resource" />
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
<orderEntry type="library" name="lib" level="project" />
<orderEntry type="module-library" scope="TEST">
<library name="JUnit5.4">
<CLASSES>
<root url="jar://$MAVEN_REPOSITORY$/org/junit/jupiter/junit-jupiter/5.4.2/junit-jupiter-5.4.2.jar!/" />
<root url="jar://$MAVEN_REPOSITORY$/org/junit/jupiter/junit-jupiter-api/5.4.2/junit-jupiter-api-5.4.2.jar!/" />
<root url="jar://$MAVEN_REPOSITORY$/org/apiguardian/apiguardian-api/1.0.0/apiguardian-api-1.0.0.jar!/" />
<root url="jar://$MAVEN_REPOSITORY$/org/opentest4j/opentest4j/1.1.1/opentest4j-1.1.1.jar!/" />
<root url="jar://$MAVEN_REPOSITORY$/org/junit/platform/junit-platform-commons/1.4.2/junit-platform-commons-1.4.2.jar!/" />
<root url="jar://$MAVEN_REPOSITORY$/org/junit/jupiter/junit-jupiter-params/5.4.2/junit-jupiter-params-5.4.2.jar!/" />
<root url="jar://$MAVEN_REPOSITORY$/org/junit/jupiter/junit-jupiter-engine/5.4.2/junit-jupiter-engine-5.4.2.jar!/" />
<root url="jar://$MAVEN_REPOSITORY$/org/junit/platform/junit-platform-engine/1.4.2/junit-platform-engine-1.4.2.jar!/" />
</CLASSES>
<JAVADOC />
<SOURCES />
</library>
</orderEntry>
</component>
</module>
Binary file modified resources/images/highlight-animal.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added resources/images/selected-animal.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
27 changes: 25 additions & 2 deletions src/sample/SimulationCanvas.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,24 +2,39 @@

import javafx.scene.image.Image;
import javafx.scene.canvas.Canvas;
import simulation.Animal;
import simulation.AnimalEnergyComparator;
import simulation.Location;
import simulation.Simulation;


import java.util.List;
import java.util.Optional;

public class SimulationCanvas extends Canvas {
private final Simulation simulation;
private final TerrainTileFactory terrainTileFactory;
private final AnimalTileFactory animalTileFactory;
private final int tileSize = 10;
private final Image highlightAnimalImage = new Image("images/highlight-animal.png");
// private final Image selectedAnimalImage = new Image("images/selected-animal.png");
public Animal selectedAnimal;

SimulationCanvas(Simulation simulation){
super(simulation.getWidth()*10,simulation.getHeight()*10);
this.simulation = simulation;
this.terrainTileFactory = new TerrainTileFactory(simulation);
this.animalTileFactory = new AnimalTileFactory(simulation);
this.setOnMouseClicked(mouseEvent -> {
int x = (int) (mouseEvent.getX()/10);
int y = (int) (mouseEvent.getY()/10);
Optional<Animal> selectedAnimalOptional = simulation.animalBoard.get(x,y)
.stream()
.max(new AnimalEnergyComparator());
selectedAnimalOptional
.ifPresentOrElse(
animal -> this.selectedAnimal = animal,
() -> {selectedAnimal = null;});
});
}
public void drawBackground(){
for (int i = 0; i<simulation.getWidth(); i++){
Expand Down Expand Up @@ -54,14 +69,22 @@ public void update(){
int y = location.getY();
drawTile(x,y,animalTileFactory.getTile(x,y));
}

//drawSelectedAnimal();
}
private void drawTile(int x, int y, Tile tile){
int drawX = x* tileSize;
int drawY = y* tileSize;
this.getGraphicsContext2D().drawImage(tile.getImage(),drawX,drawY);
}

// public void drawSelectedAnimal(){
//// if(selectedAnimal != null && selectedAnimal.isAlive()) {
//// int drawX = selectedAnimal.getLocation().getX() * tileSize;
//// int drawY = selectedAnimal.getLocation().getY() * tileSize;
//// this.getGraphicsContext2D().drawImage(selectedAnimalImage, drawX, drawY);
//// }
// }

public void highlightLocations(List<Location> locations){
for (Location location :locations){
int x = location.getX()*tileSize;
Expand Down
89 changes: 53 additions & 36 deletions src/sample/SimulationThread.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,12 @@

import javafx.application.Platform;
import javafx.concurrent.Task;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.input.MouseEvent;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
import simulation.Animal;
Expand All @@ -20,47 +19,30 @@
import java.util.stream.Collectors;

public class SimulationThread extends Thread{
private final Stage stage = new Stage();

private final Simulation simulation;
private final Scene scene;
private final Group root = new Group();
private final StatsWatcher statsWatcher;
private final SimulationCanvas canvas;
private final Label statsLabel = new Label();
private final Button pauseButton;
private final Button highlightButton;
private SimulationCanvas canvas;
private final AtomicBoolean paused = new AtomicBoolean(false);
private final AtomicBoolean dominatingAnimalsHighlighted = new AtomicBoolean(false);

private final Label statsLabel = new Label();
private final Label selectedAnimalLabel = new Label();

private final Button pauseButton = createPauseButton();
private final Button highlightButton = createHighlightButton();

public void run() {
Platform.runLater(this::displaySimulation);
}

public SimulationThread(Simulation simulation){
this.simulation = simulation;
this.scene = new Scene(root, simulation.getWidth()*10+400, Math.max(simulation.getHeight()*10,185), Color.BLACK);
this.statsWatcher = new StatsWatcher(simulation);
this.canvas = new SimulationCanvas(simulation);
this.highlightButton = createHighlightButton();
this.pauseButton = createPauseButton();
}
public void displaySimulation() {
canvas.setLayoutX(400);
statsLabel.setTextFill(Color.web("#FFFFFF"));
statsLabel.setPadding(new Insets(5.0));

root.getChildren().add(statsLabel);
root.getChildren().add(canvas);
root.getChildren().add(pauseButton);
root.getChildren().add(highlightButton);

stage.setScene(scene);
stage.setTitle("Evolution Simulator");
stage.setResizable(false);

simulation.start();
canvas.drawBackground();
canvas.update();
stage.show();
public void displaySimulation() {
loadWindow();
SimulationThread simulationThread = this;
Task<Integer> task = new Task<>() {
@Override protected Integer call() throws Exception {
Expand All @@ -69,6 +51,10 @@ public void displaySimulation() {
if (isCancelled()) {
break;
}
Platform.runLater(()-> {
selectedAnimalLabel.setText(canvas.selectedAnimal == null ? "No selected animals." : "Selected animal:\n" + canvas.selectedAnimal.toString());
// canvas.drawSelectedAnimal();
});
Thread.sleep(100);
if(simulationThread.paused.get()){
continue;
Expand All @@ -80,18 +66,47 @@ public void displaySimulation() {
} catch (SimulationErrorException e) {
e.printStackTrace();
}
canvas.update(); statsLabel.setText(statsWatcher.getSummary());});
canvas.update();
statsLabel.setText(statsWatcher.getSummary());
});
}
return iterations;
}
};
Thread th = new Thread(task);
th.start();
}

private void loadWindow() {
final Group root = new Group();
final Scene scene = new Scene(root, simulation.getWidth()*10+400, Math.max(simulation.getHeight()*10,350), Color.BLACK);
final Stage stage = new Stage();

canvas = new SimulationCanvas(simulation);
canvas.setLayoutX(400);
statsLabel.setTextFill(Color.web("#FFFFFF"));
statsLabel.setLayoutX(5);
statsLabel.setLayoutY(5);

selectedAnimalLabel.setLayoutX(5);
selectedAnimalLabel.setLayoutY(210);
selectedAnimalLabel.setTextFill(Color.web("#FFFFFF"));
root.getChildren().addAll(statsLabel,selectedAnimalLabel,canvas,pauseButton,highlightButton);

stage.setScene(scene);
stage.setTitle("Evolution Simulator");
stage.setResizable(false);

simulation.start();
canvas.drawBackground();
canvas.update();
stage.show();
}

private Button createHighlightButton(){
Button button = new Button("Highlight dominating Genome");
button.setLayoutX(90);
button.setLayoutY(150);
button.setLayoutX(5);
button.setLayoutY(180);
button.setVisible(false);
button.setOnMouseClicked(mouseEvent -> {
if(dominatingAnimalsHighlighted.get()){
Expand All @@ -104,17 +119,19 @@ private Button createHighlightButton(){
statsWatcher.getAnimalsWithDominatingGenome()
.stream().map(Animal::getLocation)
.collect(Collectors.toList()));
this.dominatingAnimalsHighlighted.set(true);
dominatingAnimalsHighlighted.set(true);
}
});
return button;
}

private Button createPauseButton(){
Button button = new Button("RUN/PAUSE");
button.setLayoutX(5);
button.setLayoutY(150);
button.setOnMouseClicked(mouseEvent -> { paused.set(!paused.get());
this.highlightButton.setVisible(!this.highlightButton.isVisible());
button.setOnMouseClicked(mouseEvent -> {
paused.set(!paused.get());
highlightButton.setVisible(!this.highlightButton.isVisible());
});
return button;
}
Expand Down
42 changes: 34 additions & 8 deletions src/simulation/Animal.java
Original file line number Diff line number Diff line change
@@ -1,25 +1,23 @@
package simulation;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.*;

public class Animal{
public class Animal implements Comparable<Animal>{
private final int birthDay;
private int deathDay = -1;
private final Genome genome;
private Direction direction;
private double energy;
private Location location;
private List<Animal> children = new ArrayList<>();
private final List<Animal> children = new ArrayList<>();

Animal(double energy, int birthDay, Location location){
this.birthDay = birthDay;
this.energy = energy;
this.genome = new Genome();
this.location = location;
this.direction = Direction.values()[(new Random(System.nanoTime()).nextInt(8))];
};
}

Animal(Animal parent1, Animal parent2, int birthDay, Location location){
this.genome = new Genome(parent1.getGenome(), parent2.getGenome());
Expand Down Expand Up @@ -81,11 +79,39 @@ public void setEnergy(double energy) {

@Override
public String toString() {
return genome.toString() +
"-" + birthDay;
return "Genome: " + genome + "\n"
+ "Location: " + location + "\n"
+ "Born on day: " + birthDay + "\n"
+ (this.isAlive() ? "Energy: " + energy : "Died on day: " + deathDay) + "\n"
+ "Children: " + getChildrenNumber() +"\n"
+ "Ancestors: " + getAncestorsNumber();
}

public List<Animal> getChildren() {
return children;
}

public int compareTo(Animal a){
return this.hashCode() - a.hashCode();
}

public int getChildrenNumber(){
return this.children.size();
}

public int getAncestorsNumber(){
Set<Animal> visited = new TreeSet<>();
this.traverse(visited);
return visited.size() - 1;
}

public void traverse(Set<Animal> visited){
if(!visited.contains(this)){
visited.add(this);
for (Animal child : this.children){
child.traverse(visited);
}
}
}

}
7 changes: 5 additions & 2 deletions src/simulation/Genome.java
Original file line number Diff line number Diff line change
Expand Up @@ -108,8 +108,11 @@ public boolean equals(Genome g){
public int hashCode(){
int hash = 0;
int multiplier = 1;
for (int gene : genes){
hash += multiplier*gene;
for (int i = 0; i < 31; i++){
if (genes.get(i)!=genes.get(i+1)){
multiplier*=8;
}
hash+=multiplier;
}
return hash;
}
Expand Down
6 changes: 2 additions & 4 deletions src/simulation/Location.java
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ public class Location implements Comparable<Location>{
private final int x;
private final int y;

Location(int x,int y){
public Location(int x, int y){
this.x = x;
this.y = y;
}
Expand Down Expand Up @@ -52,8 +52,6 @@ public Location stepTo(Direction direction){

@Override
public String toString() {
return "("+ x + " "
+ y +
')';
return x + ", " + y;
}
}
Loading

0 comments on commit d427f64

Please sign in to comment.