diff --git a/ueb08/app/src/main/java/org/example/Game.java b/ueb08/app/src/main/java/org/example/Game.java index 3868a6b0..13b93906 100644 --- a/ueb08/app/src/main/java/org/example/Game.java +++ b/ueb08/app/src/main/java/org/example/Game.java @@ -1,5 +1,6 @@ package org.example; +import java.util.NoSuchElementException; import java.util.Scanner; public class Game { @@ -60,6 +61,9 @@ public class Game { } } catch (NumberFormatException | SelectionException | IllegalStateException e) { System.err.println(e.getMessage()); + } catch (NoSuchElementException e){ + // stdin closed (e.g. by pressing STRG + D) + System.exit(0); } } } diff --git a/ueb08/app/src/main/java/org/example/Player.java b/ueb08/app/src/main/java/org/example/Player.java index af375ef7..6654526b 100644 --- a/ueb08/app/src/main/java/org/example/Player.java +++ b/ueb08/app/src/main/java/org/example/Player.java @@ -1,11 +1,10 @@ package org.example; import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; import java.util.stream.Collectors; -import static org.example.DiceEyes.FIVE; -import static org.example.DiceEyes.ONE; - public class Player implements DiceInteraction{ private final String name; private int totalScore = 0; @@ -99,34 +98,23 @@ public class Player implements DiceInteraction{ return 0; } - int ones = 0; - int fives = 0; + Map diceEyesCount = new HashMap<>(); for (Dice dice : dices) { if (dice.isFixed() || dice.isMarked()) { - switch (dice.getDiceEyes()) { - case ONE: - ones++; - break; - case FIVE: - fives++; - break; - } + Integer count = diceEyesCount.getOrDefault(dice.getDiceEyes(), 0); + count++; + diceEyesCount.put(dice.getDiceEyes(), count); } } int toggledScore = 0; + for (Map.Entry entry : diceEyesCount.entrySet()) { + DiceEyes diceEyes = entry.getKey(); + int count = entry.getValue(); - while (ones >= 3) { - toggledScore += ONE.triplePoints(); - ones -= 3; + toggledScore += diceEyes.triplePoints() * (count / 3); + toggledScore += diceEyes.points() * (count % 3); } - while (fives >= 3) { - toggledScore += FIVE.triplePoints(); - fives -= 3; - } - - toggledScore += ONE.points() * ones; - toggledScore += FIVE.points() * fives; return toggledScore; } @@ -138,11 +126,11 @@ public class Player implements DiceInteraction{ @Override public String toString() { String s2 = toStringHelper(); - int tail = 6 * 3 + 5; - int head = s2.length() - tail; - String s1 = " ".repeat(head); - s1 += " 0 1 2 3 4 5 "; + // Create string `s1` of same length as `s2`. + String tail = " 0 1 2 3 4 5 "; + int headLength = s2.length() - tail.length(); + String s1 = " ".repeat(headLength) + tail; return s1 + "\n" + s2; }