From c82ab689d42d4eb75b59f01d9c688325e515e8e3 Mon Sep 17 00:00:00 2001 From: Arne Keller Date: Fri, 21 Feb 2020 08:30:30 +0100 Subject: [PATCH] Write comments --- .../kit/informatik/model/TrainManager.java | 24 +++++++++++++++++-- 1 file changed, 22 insertions(+), 2 deletions(-) diff --git a/src/edu/kit/informatik/model/TrainManager.java b/src/edu/kit/informatik/model/TrainManager.java index 9a6c4aa..6ef1fec 100644 --- a/src/edu/kit/informatik/model/TrainManager.java +++ b/src/edu/kit/informatik/model/TrainManager.java @@ -277,21 +277,40 @@ public final class TrainManager { return collisions; } + /** + * Calculate train collisions, removing crashing trains in the process. + * + * @param collisions list of collisions to expand + * @param occupiedRails map of occupied rails before the step + * @param nextOccupiedRails map of occupied rails after the step + */ private void checkForBlockCollisions(List> collisions, Map> occupiedRails, Map> nextOccupiedRails) { - trains.values().stream().filter(train -> train.isPlaced() - && collisions.stream().noneMatch(x -> x.contains(train))).forEach(train -> { + trains.values().stream() + // only process placed trains + .filter(Train::isPlaced) + // if already in a collision, do not process again + .filter(train -> collisions.stream().noneMatch(x -> x.contains(train))) + .forEach(train -> { Set occupiedByThisTrain = nextOccupiedRails.get(train); + // check each other train trains.values().stream().filter(x -> x != train).forEach(otherTrain -> { Set occupiedByOtherTrainPreviously = occupiedRails.get(otherTrain); Set occupiedByOtherTrain = nextOccupiedRails.get(otherTrain); + // if train did not occupy any rails (it is not placed) if (occupiedByOtherTrain == null) { + // skip return; } + // first check if train is on the same rails boolean anyIntersection = Stream.concat( occupiedByOtherTrain.stream(), occupiedByOtherTrainPreviously.stream()) + // only search in currently occupied rails, previously occupied rails + // will be checked once the other train is processed in the outer loop .anyMatch(occupiedByThisTrain::contains); + // or simply touches the other train if (anyIntersection || train.touches(otherTrain)) { + // remove crashing trains train.removeFromRails(); otherTrain.removeFromRails(); // try to find/merge existing collisions @@ -312,6 +331,7 @@ public final class TrainManager { } } if (existingCollision == null) { + // create a new collision collisions.add(Stream.of(train, otherTrain).collect(Collectors.toSet())); } }