Write comments

This commit is contained in:
Arne Keller 2020-02-21 08:30:30 +01:00
parent 122193300d
commit c82ab689d4

View File

@ -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<Set<Train>> collisions, Map<Train, Set<Rail>> occupiedRails,
Map<Train, Set<Rail>> 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<Rail> occupiedByThisTrain = nextOccupiedRails.get(train);
// check each other train
trains.values().stream().filter(x -> x != train).forEach(otherTrain -> {
Set<Rail> occupiedByOtherTrainPreviously = occupiedRails.get(otherTrain);
Set<Rail> 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()));
}
}