Search in sources :

Example 11 with HistoryNode

use of games.strategy.engine.history.HistoryNode in project triplea by triplea-game.

the class HistoryLog method printRemainingTurn.

public void printRemainingTurn(final HistoryNode printNode, final boolean verbose, final int diceSides, final Collection<PlayerID> playersAllowed) {
    final PrintWriter logWriter = printWriter;
    final String moreIndent = "    ";
    // print out the parent nodes
    final TreePath parentPath = (new TreePath(printNode.getPath())).getParentPath();
    PlayerID currentPlayer = null;
    if (parentPath != null) {
        final Object[] pathToNode = parentPath.getPath();
        for (final Object pathNode : pathToNode) {
            final HistoryNode node = (HistoryNode) pathNode;
            for (int i = 0; i < node.getLevel(); i++) {
                logWriter.print(moreIndent);
            }
            logWriter.println(node.getTitle());
            if (node.getLevel() == 0) {
                logWriter.println();
            }
            if (node instanceof Step) {
                currentPlayer = ((Step) node).getPlayerId();
            }
        }
    }
    final Collection<PlayerID> players = new HashSet<>();
    if (playersAllowed != null) {
        players.addAll(playersAllowed);
    }
    if (currentPlayer != null) {
        players.add(currentPlayer);
    }
    final List<String> moveList = new ArrayList<>();
    boolean moving = false;
    DefaultMutableTreeNode curNode = printNode;
    final Map<String, Double> hitDifferentialMap = new HashMap<>();
    do {
        // keep track of conquered territory during combat
        StringBuilder conquerStr = new StringBuilder();
        final Enumeration<?> nodeEnum = curNode.preorderEnumeration();
        while (nodeEnum.hasMoreElements()) {
            final HistoryNode node = (HistoryNode) nodeEnum.nextElement();
            final String title = node.getTitle();
            final StringBuilder indent = new StringBuilder();
            for (int i = 0; i < node.getLevel(); i++) {
                indent.append(moreIndent);
            }
            // flush move list
            if (moving && !(node instanceof Renderable)) {
                final Iterator<String> moveIter = moveList.iterator();
                while (moveIter.hasNext()) {
                    logWriter.println(moveIter.next());
                    moveIter.remove();
                }
                moving = false;
            }
            if (node instanceof Renderable) {
                final Object details = ((Renderable) node).getRenderingData();
                if (details instanceof DiceRoll) {
                    if (!verbose) {
                        continue;
                    }
                    final String diceMsg1 = title.substring(0, title.indexOf(':') + 1);
                    if (diceMsg1.isEmpty()) {
                        // tech roll
                        logWriter.println(indent + moreIndent + title);
                    } else {
                        // dice roll
                        // Japanese roll dice for 1 armour in Russia, round 1
                        logWriter.print(indent + moreIndent + diceMsg1);
                        final String player = diceMsg1.split(" roll ")[0];
                        final DiceRoll diceRoll = (DiceRoll) details;
                        final int hits = diceRoll.getHits();
                        int rolls = 0;
                        for (int i = 1; i <= diceSides; i++) {
                            rolls += diceRoll.getRolls(i).size();
                        }
                        final double expectedHits = diceRoll.getExpectedHits();
                        logWriter.println(" " + hits + "/" + rolls + " hits, " + String.format("%.2f", expectedHits) + " expected hits");
                        final double hitDifferential = hits - expectedHits;
                        if (hitDifferentialMap.containsKey(player)) {
                            hitDifferentialMap.put(player, hitDifferentialMap.get(player) + hitDifferential);
                        } else {
                            hitDifferentialMap.put(player, hitDifferential);
                        }
                    }
                } else if (details instanceof MoveDescription) {
                    // movement
                    final Pattern p = Pattern.compile("\\w+ undo move (\\d+).");
                    final Matcher m = p.matcher(title);
                    if (m.matches()) {
                        moveList.remove(Integer.valueOf(m.group(1)) - 1);
                    } else {
                        moveList.add(indent + title);
                        moving = true;
                    }
                } else if (details instanceof Collection) {
                    @SuppressWarnings("unchecked") final Collection<Object> objects = (Collection<Object>) details;
                    final Iterator<Object> objIter = objects.iterator();
                    if (objIter.hasNext()) {
                        final Object obj = objIter.next();
                        if (obj instanceof Unit) {
                            @SuppressWarnings("unchecked") final Collection<Unit> allUnitsInDetails = (Collection<Unit>) details;
                            // purchase/place units - don't need details
                            Unit unit = (Unit) obj;
                            if (title.matches("\\w+ buy .*") || title.matches("\\w+ attack with .*") || title.matches("\\w+ defend with .*")) {
                                logWriter.println(indent + title);
                            } else if (title.matches("\\d+ \\w+ owned by the .*? lost .*") || title.matches("\\d+ \\w+ owned by the .*? lost")) {
                                if (!verbose) {
                                    continue;
                                }
                                logWriter.println(indent + moreIndent + title);
                            } else if (title.startsWith("Battle casualty summary:")) {
                                // logWriter.println(indent+"CAS1: "+title);
                                logWriter.println(indent + conquerStr.toString() + ". Battle score " + title.substring(title.indexOf("for attacker is")));
                                conquerStr = new StringBuilder();
                                // separate units by player and show casualty summary
                                final IntegerMap<PlayerID> unitCount = new IntegerMap<>();
                                unitCount.add(unit.getOwner(), 1);
                                while (objIter.hasNext()) {
                                    unit = (Unit) objIter.next();
                                    unitCount.add(unit.getOwner(), 1);
                                }
                                for (final PlayerID player : unitCount.keySet()) {
                                    logWriter.println(indent + "Casualties for " + player.getName() + ": " + MyFormatter.unitsToTextNoOwner(allUnitsInDetails, player));
                                }
                            } else if (title.matches(".*? placed in .*") || title.matches(".* owned by the \\w+ retreated to .*")) {
                                logWriter.println(indent + title);
                            } else if (title.matches("\\w+ win")) {
                                conquerStr = new StringBuilder(title + conquerStr + " with " + MyFormatter.unitsToTextNoOwner(allUnitsInDetails) + " remaining");
                            } else {
                                logWriter.println(indent + title);
                            }
                        } else {
                            // collection of unhandled objects
                            logWriter.println(indent + title);
                        }
                    } else {
                        // empty collection of something
                        if (title.matches("\\w+ win")) {
                            conquerStr = new StringBuilder(title + conquerStr + " with no units remaining");
                        } else {
                            // empty collection of unhandled objects
                            logWriter.println(indent + title);
                        }
                    }
                } else if (details instanceof Territory) {
                    // territory details
                    logWriter.println(indent + title);
                } else if (details == null) {
                    if (title.equals("Adding original owners") || title.equals(MoveDelegate.CLEANING_UP_DURING_MOVEMENT_PHASE) || title.equals("Game Loaded") || title.contains("now being played by") || title.contains("Turn Summary") || title.contains("Move Summary") || title.contains("Setting uses for triggers used") || title.equals("Resetting and Giving Bonus Movement to Units") || title.equals("Recording Battle Statistics") || title.equals("Preparing Airbases for Possible Scrambling")) {
                    // do nothing
                    } else if (title.matches("\\w+ collect \\d+ PUs?.*")) {
                        logWriter.println(indent + title);
                    } else if (title.matches("\\w+ takes? .*? from \\w+")) {
                        // British take Libya from Germans
                        if (moving) {
                            final String str = moveList.remove(moveList.size() - 1);
                            moveList.add(str + "\n  " + indent + title.replaceAll(" takes ", " take "));
                        } else {
                            conquerStr.append(title.replaceAll("^\\w+ takes ", ", taking "));
                        }
                    } else if (title.matches("\\w+ spend \\d+ on tech rolls")) {
                        logWriter.println(indent + title);
                    } else if (title.startsWith("Rolls to resolve tech hits:")) {
                    // do nothing
                    } else {
                        logWriter.println(indent + title);
                    }
                } else {
                    // unknown details object
                    logWriter.println(indent + title);
                }
            } else if (node instanceof Step) {
                final PlayerID playerId = ((Step) node).getPlayerId();
                if (!title.equals("Initializing Delegates")) {
                    logWriter.println();
                    logWriter.print(indent + title);
                    if (playerId != null) {
                        currentPlayer = playerId;
                        players.add(currentPlayer);
                        logWriter.print(" - " + playerId.getName());
                    }
                    logWriter.println();
                }
            } else if (node instanceof Round) {
                logWriter.println();
                logWriter.println(indent + title);
            } else {
                logWriter.println(indent + title);
            }
        }
        // while (nodeEnum.hasMoreElements())
        curNode = curNode.getNextSibling();
    } while ((curNode instanceof Step) && players.contains(((Step) curNode).getPlayerId()));
    // if we are mid-phase, this might not get flushed
    if (moving && !moveList.isEmpty()) {
        final Iterator<String> moveIter = moveList.iterator();
        while (moveIter.hasNext()) {
            logWriter.println(moveIter.next());
            moveIter.remove();
        }
    }
    logWriter.println();
    if (verbose) {
        logWriter.println("Combat Hit Differential Summary :");
        logWriter.println();
        for (final String player : hitDifferentialMap.keySet()) {
            logWriter.println(moreIndent + player + " : " + String.format("%.2f", hitDifferentialMap.get(player)));
        }
    }
    logWriter.println();
    textArea.setText(stringWriter.toString());
}
Also used : DiceRoll(games.strategy.triplea.delegate.DiceRoll) PlayerID(games.strategy.engine.data.PlayerID) DefaultMutableTreeNode(javax.swing.tree.DefaultMutableTreeNode) HashMap(java.util.HashMap) Matcher(java.util.regex.Matcher) ArrayList(java.util.ArrayList) MoveDescription(games.strategy.triplea.delegate.dataObjects.MoveDescription) Step(games.strategy.engine.history.Step) Unit(games.strategy.engine.data.Unit) Renderable(games.strategy.engine.history.Renderable) Round(games.strategy.engine.history.Round) PrintWriter(java.io.PrintWriter) HashSet(java.util.HashSet) IntegerMap(games.strategy.util.IntegerMap) Pattern(java.util.regex.Pattern) Territory(games.strategy.engine.data.Territory) TreePath(javax.swing.tree.TreePath) HistoryNode(games.strategy.engine.history.HistoryNode) Collection(java.util.Collection)

Example 12 with HistoryNode

use of games.strategy.engine.history.HistoryNode in project triplea by triplea-game.

the class HistoryLog method printFullTurn.

public void printFullTurn(final GameData data, final boolean verbose, final Collection<PlayerID> playersAllowed) {
    HistoryNode curNode = data.getHistory().getLastNode();
    final Collection<PlayerID> players = new HashSet<>();
    if (playersAllowed != null) {
        players.addAll(playersAllowed);
    }
    // find Step node, if exists in this path
    Step stepNode = null;
    while (curNode != null) {
        if (curNode instanceof Step) {
            stepNode = (Step) curNode;
            break;
        }
        curNode = (HistoryNode) curNode.getPreviousNode();
    }
    if (stepNode != null) {
        final PlayerID curPlayer = stepNode.getPlayerId();
        if (players.isEmpty()) {
            players.add(curPlayer);
        }
        // get first step for this turn
        Step turnStartNode = null;
        while (true) {
            turnStartNode = stepNode;
            stepNode = (Step) stepNode.getPreviousSibling();
            if (stepNode == null) {
                break;
            }
            if (stepNode.getPlayerId() == null) {
                break;
            }
            if (!players.contains(stepNode.getPlayerId())) {
                break;
            }
        }
        printRemainingTurn(turnStartNode, verbose, data.getDiceSides(), players);
    } else {
        System.err.println("No Step node found!");
    }
}
Also used : PlayerID(games.strategy.engine.data.PlayerID) HistoryNode(games.strategy.engine.history.HistoryNode) Step(games.strategy.engine.history.Step) HashSet(java.util.HashSet)

Example 13 with HistoryNode

use of games.strategy.engine.history.HistoryNode in project triplea by triplea-game.

the class HistoryPanel method goToEnd.

public void goToEnd() {
    final HistoryNode last;
    try {
        data.acquireWriteLock();
        last = data.getHistory().getLastNode();
    } finally {
        data.releaseWriteLock();
    }
    final TreePath path = new TreePath(last.getPath());
    final TreePath parent = path.getParentPath();
    if (!mouseOverPanel) {
        // make sure we undo our change of the lock property
        gotoNode(last);
        if (lastParent == null) {
            lastParent = tree.getSelectionPath();
        }
        tree.setSelectionPath(path);
        collapseExpanded(path);
        collapseUpFromLastParent(parent);
        final Rectangle rect = tree.getPathBounds(path);
        rect.setRect(0, rect.getY(), rect.getWidth(), rect.getHeight());
        tree.scrollRectToVisible(rect);
    } else {
        if (!mouseWasOverPanel) {
            // save the lock property so that we can undo it
            TreePath root = parent;
            while (root.getPathCount() > 1) {
                root = root.getParentPath();
            }
            final Enumeration<TreePath> expandedDescendants = tree.getExpandedDescendants(root);
            addToStayExpanded(expandedDescendants);
        } else {
            collapseUpFromLastParent(parent);
        }
        tree.expandPath(parent);
    }
    mouseWasOverPanel = mouseOverPanel;
    lastParent = parent;
}
Also used : HistoryNode(games.strategy.engine.history.HistoryNode) TreePath(javax.swing.tree.TreePath) Rectangle(java.awt.Rectangle)

Example 14 with HistoryNode

use of games.strategy.engine.history.HistoryNode in project triplea by triplea-game.

the class ExportMenu method addSaveScreenshot.

private void addSaveScreenshot() {
    final Action abstractAction = SwingAction.of("Export Map Snapshot", e -> {
        // get current history node. if we are in history view, get the selected node.
        final HistoryPanel historyPanel = frame.getHistoryPanel();
        final HistoryNode curNode;
        if (historyPanel == null) {
            curNode = gameData.getHistory().getLastNode();
        } else {
            curNode = historyPanel.getCurrentNode();
        }
        ScreenshotExporter.exportScreenshot(frame, gameData, curNode);
    });
    add(abstractAction).setMnemonic(KeyEvent.VK_E);
}
Also used : SwingAction(games.strategy.ui.SwingAction) Action(javax.swing.Action) HistoryNode(games.strategy.engine.history.HistoryNode) HistoryPanel(games.strategy.triplea.ui.history.HistoryPanel)

Aggregations

HistoryNode (games.strategy.engine.history.HistoryNode)14 PlayerID (games.strategy.engine.data.PlayerID)9 Step (games.strategy.engine.history.Step)8 GameData (games.strategy.engine.data.GameData)5 Round (games.strategy.engine.history.Round)5 Event (games.strategy.engine.history.Event)3 IOException (java.io.IOException)3 Matcher (java.util.regex.Matcher)3 Pattern (java.util.regex.Pattern)3 TreeNode (javax.swing.tree.TreeNode)3 TreePath (javax.swing.tree.TreePath)3 UnitType (games.strategy.engine.data.UnitType)2 EventChild (games.strategy.engine.history.EventChild)2 UnitAttachment (games.strategy.triplea.attachments.UnitAttachment)2 HistoryPanel (games.strategy.triplea.ui.history.HistoryPanel)2 File (java.io.File)2 HashSet (java.util.HashSet)2 Icon (javax.swing.Icon)2 ImageIcon (javax.swing.ImageIcon)2 BadLocationException (javax.swing.text.BadLocationException)2