|
| 1 | +package io.suhan.ladder.model; |
| 2 | + |
| 3 | +import io.suhan.ladder.model.ladder.Connection; |
| 4 | +import io.suhan.ladder.model.ladder.Ladder; |
| 5 | +import io.suhan.ladder.model.ladder.LadderFactory; |
| 6 | +import io.suhan.ladder.model.ladder.Line; |
| 7 | +import io.suhan.ladder.view.OutputView; |
| 8 | +import java.util.LinkedHashMap; |
| 9 | +import java.util.List; |
| 10 | +import java.util.Map; |
| 11 | +import java.util.Optional; |
| 12 | + |
| 13 | +public class Game { |
| 14 | + private final Ladder ladder; |
| 15 | + private final GameConfiguration configuration; |
| 16 | + |
| 17 | + private Game(GameConfiguration configuration, Ladder ladder) { |
| 18 | + this.configuration = configuration; |
| 19 | + this.ladder = ladder; |
| 20 | + } |
| 21 | + |
| 22 | + public static Game of(GameConfiguration configuration) { |
| 23 | + return new Game(configuration, LadderFactory.createLadder(configuration.width(), configuration.height())); |
| 24 | + } |
| 25 | + |
| 26 | + public static Game of(GameConfiguration configuration, Ladder ladder) { |
| 27 | + return new Game(configuration, ladder); |
| 28 | + } |
| 29 | + |
| 30 | + public GameResult execute() { |
| 31 | + List<Participant> participants = configuration.participants(); |
| 32 | + List<Outcome> outcomes = configuration.outcomes(); |
| 33 | + Map<Participant, Outcome> result = new LinkedHashMap<>(); |
| 34 | + |
| 35 | + for (int start = 0; start < configuration.width(); start++) { |
| 36 | + int end = traverse(start); |
| 37 | + Participant participant = participants.get(start); |
| 38 | + Outcome outcome = outcomes.get(end); |
| 39 | + |
| 40 | + result.put(participant, outcome); |
| 41 | + } |
| 42 | + |
| 43 | + return new GameResult(result); |
| 44 | + } |
| 45 | + |
| 46 | + private int traverse(int start) { |
| 47 | + int col = start; |
| 48 | + |
| 49 | + for (Line line : ladder.lines()) { |
| 50 | + col = findNextColumn(line, col); |
| 51 | + } |
| 52 | + |
| 53 | + return col; |
| 54 | + } |
| 55 | + |
| 56 | + private int findNextColumn(Line line, int col) { |
| 57 | + Optional<Connection> connected = line.connections().stream() |
| 58 | + .filter((connection) -> connection.left() == col || connection.right() == col) |
| 59 | + .findFirst(); |
| 60 | + |
| 61 | + return connected |
| 62 | + .map((connection) -> getConnectedColumn(connection, col)) |
| 63 | + .orElse(col); |
| 64 | + } |
| 65 | + |
| 66 | + private int getConnectedColumn(Connection connection, int col) { |
| 67 | + if (connection.left() == col) { |
| 68 | + return connection.right(); |
| 69 | + } |
| 70 | + |
| 71 | + return connection.left(); |
| 72 | + } |
| 73 | + |
| 74 | + public Ladder getLadder() { |
| 75 | + return ladder; |
| 76 | + } |
| 77 | + |
| 78 | + public GameConfiguration getConfiguration() { |
| 79 | + return configuration; |
| 80 | + } |
| 81 | +} |
0 commit comments