Search in sources :

Example 1 with AlphanumComparator

use of games.strategy.util.AlphanumComparator in project triplea by triplea-game.

the class ConnectionFinder method runInternal.

private void runInternal(final String[] args) {
    handleCommandLineArgs(args);
    JOptionPane.showMessageDialog(null, new JLabel("<html>" + "This is the ConnectionFinder. " + "<br>It will create a file containing the connections between territories, and optionally the territory " + "definitions as well. " + "<br>Copy and paste everything from this file into your game xml file (the 'map' section). " + "<br>The connections file can and Should Be Deleted when finished, because it is Not Needed and not read " + "by the engine. " + "</html>"));
    ToolLogger.info("Select polygons.txt");
    File polyFile = null;
    if (mapFolderLocation != null && mapFolderLocation.exists()) {
        polyFile = new File(mapFolderLocation, "polygons.txt");
    }
    if (polyFile != null && polyFile.exists() && JOptionPane.showConfirmDialog(null, "A polygons.txt file was found in the map's folder, do you want to use it?", "File Suggestion", JOptionPane.YES_NO_CANCEL_OPTION) == 0) {
    // yay
    } else {
        polyFile = new FileOpen("Select The polygons.txt file", mapFolderLocation, ".txt").getFile();
    }
    if (polyFile == null || !polyFile.exists()) {
        ToolLogger.info("No polygons.txt Selected. Shutting down.");
        return;
    }
    if (mapFolderLocation == null && polyFile != null) {
        mapFolderLocation = polyFile.getParentFile();
    }
    final Map<String, List<Area>> territoryAreas = new HashMap<>();
    Map<String, List<Polygon>> mapOfPolygons = null;
    try (InputStream in = new FileInputStream(polyFile)) {
        mapOfPolygons = PointFileReaderWriter.readOneToManyPolygons(in);
        for (final String territoryName : mapOfPolygons.keySet()) {
            final List<Polygon> listOfPolygons = mapOfPolygons.get(territoryName);
            final List<Area> listOfAreas = new ArrayList<>();
            for (final Polygon p : listOfPolygons) {
                listOfAreas.add(new Area(p));
            }
            territoryAreas.put(territoryName, listOfAreas);
        }
    } catch (final IOException e) {
        ToolLogger.error("Failed to load polygons: " + polyFile.getAbsolutePath(), e);
        return;
    }
    if (!dimensionsSet) {
        final String lineWidth = JOptionPane.showInputDialog(null, "Enter the width of territory border lines on your map? \r\n(eg: 1, or 2, etc.)");
        try {
            final int lineThickness = Integer.parseInt(lineWidth);
            scalePixels = lineThickness * 4;
            minOverlap = scalePixels * 4;
            dimensionsSet = true;
        } catch (final NumberFormatException ex) {
        // ignore malformed input
        }
    }
    if (JOptionPane.showConfirmDialog(null, "Scale set to " + scalePixels + " pixels larger, and minimum overlap set to " + minOverlap + " pixels. \r\n" + "Do you wish to continue with this? \r\n" + "Select Yes to continue, Select No to override and change the size.", "Scale and Overlap Size", JOptionPane.YES_NO_OPTION) == 1) {
        final String scale = JOptionPane.showInputDialog(null, "Enter the number of pixels larger each territory should become? \r\n" + "(Normally 4x bigger than the border line width. eg: 4, or 8, etc)");
        try {
            scalePixels = Integer.parseInt(scale);
        } catch (final NumberFormatException ex) {
        // ignore malformed input
        }
        final String overlap = JOptionPane.showInputDialog(null, "Enter the minimum number of overlapping pixels for a connection? \r\n" + "(Normally 16x bigger than the border line width. eg: 16, or 32, etc.)");
        try {
            minOverlap = Integer.parseInt(overlap);
        } catch (final NumberFormatException ex) {
        // ignore malformed input
        }
    }
    ToolLogger.info("Now Scanning for Connections");
    // sort so that they are in alphabetic order (makes xml's prettier and easier to update in future)
    final List<String> allTerritories = mapOfPolygons == null ? new ArrayList<>() : new ArrayList<>(mapOfPolygons.keySet());
    allTerritories.sort(new AlphanumComparator());
    final List<String> allAreas = new ArrayList<>(territoryAreas.keySet());
    allAreas.sort(new AlphanumComparator());
    final Map<String, Collection<String>> connections = new HashMap<>();
    for (final String territory : allTerritories) {
        final Set<String> thisTerritoryConnections = new LinkedHashSet<>();
        final List<Polygon> currentPolygons = mapOfPolygons.get(territory);
        for (final Polygon currentPolygon : currentPolygons) {
            final Shape scaledShape = scale(currentPolygon, scalePixels);
            for (final String otherTerritory : allAreas) {
                if (otherTerritory.equals(territory)) {
                    continue;
                }
                if (thisTerritoryConnections.contains(otherTerritory)) {
                    continue;
                }
                if (connections.get(otherTerritory) != null && connections.get(otherTerritory).contains(territory)) {
                    continue;
                }
                for (final Area otherArea : territoryAreas.get(otherTerritory)) {
                    final Area testArea = new Area(scaledShape);
                    testArea.intersect(otherArea);
                    if (!testArea.isEmpty() && sizeOfArea(testArea) > minOverlap) {
                        thisTerritoryConnections.add(otherTerritory);
                    }
                }
            }
            connections.put(territory, thisTerritoryConnections);
        }
    }
    if (JOptionPane.showConfirmDialog(null, "Do you also want to create the Territory Definitions?", "Territory Definitions", JOptionPane.YES_NO_CANCEL_OPTION) == 0) {
        final String waterString = JOptionPane.showInputDialog(null, "Enter a string or regex that determines if the territory is Water? \r\n(e.g.: " + Util.TERRITORY_SEA_ZONE_INFIX + ")", Util.TERRITORY_SEA_ZONE_INFIX);
        territoryDefinitions = doTerritoryDefinitions(allTerritories, waterString);
    }
    try {
        final String fileName = new FileSave("Where To Save connections.txt ? (cancel to print to console)", "connections.txt", mapFolderLocation).getPathString();
        final StringBuilder connectionsString = convertToXml(connections);
        if (fileName == null) {
            if (territoryDefinitions != null) {
                ToolLogger.info(territoryDefinitions.toString());
            }
            ToolLogger.info(connectionsString.toString());
        } else {
            try (OutputStream out = new FileOutputStream(fileName)) {
                if (territoryDefinitions != null) {
                    out.write(String.valueOf(territoryDefinitions).getBytes(StandardCharsets.UTF_8));
                }
                out.write(String.valueOf(connectionsString).getBytes(StandardCharsets.UTF_8));
            }
            ToolLogger.info("Data written to :" + new File(fileName).getCanonicalPath());
        }
    } catch (final Exception e) {
        ToolLogger.error("Failed to write connections", e);
    }
}
Also used : LinkedHashSet(java.util.LinkedHashSet) Shape(java.awt.Shape) HashMap(java.util.HashMap) FileOpen(tools.image.FileOpen) OutputStream(java.io.OutputStream) FileOutputStream(java.io.FileOutputStream) ArrayList(java.util.ArrayList) ArrayList(java.util.ArrayList) List(java.util.List) Polygon(java.awt.Polygon) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) JLabel(javax.swing.JLabel) IOException(java.io.IOException) FileInputStream(java.io.FileInputStream) IOException(java.io.IOException) Area(java.awt.geom.Area) AlphanumComparator(games.strategy.util.AlphanumComparator) FileOutputStream(java.io.FileOutputStream) Collection(java.util.Collection) FileSave(tools.image.FileSave) File(java.io.File)

Example 2 with AlphanumComparator

use of games.strategy.util.AlphanumComparator in project triplea by triplea-game.

the class ConnectionFinder method doTerritoryDefinitions.

// end main
/**
 * Creates the xml territory definitions.
 *
 * @param waterString
 *        a substring contained in a TerritoryName to define a Sea Zone or a regex expression that indicates that a
 *        territory is water
 * @return StringBuffer containing XML representing these connections
 */
private static StringBuilder doTerritoryDefinitions(final List<String> allTerritoryNames, final String waterString) {
    // sort for pretty xml's
    allTerritoryNames.sort(new AlphanumComparator());
    final StringBuilder output = new StringBuilder();
    output.append("<!-- Territory Definitions -->\r\n");
    final Pattern waterPattern = Pattern.compile(waterString);
    for (final String t : allTerritoryNames) {
        final Matcher matcher = waterPattern.matcher(t);
        if (matcher.find()) {
            // <territory name="sea zone 1" water="true"/>
            output.append("<territory name=\"").append(t).append("\" water=\"true\"/>\r\n");
        } else {
            // <territory name="neutral territory 2"/>
            output.append("<territory name=\"").append(t).append("\"/>\r\n");
        }
    }
    output.append("\r\n");
    return output;
}
Also used : Pattern(java.util.regex.Pattern) Matcher(java.util.regex.Matcher) AlphanumComparator(games.strategy.util.AlphanumComparator)

Example 3 with AlphanumComparator

use of games.strategy.util.AlphanumComparator in project triplea by triplea-game.

the class ConnectionFinder method convertToXml.

/**
 * Converts a map of connections to XML formatted text with the connections.
 *
 * @param connections
 *        a map of connections between Territories
 * @return a StringBuffer containing XML representing these connections
 */
private static StringBuilder convertToXml(final Map<String, Collection<String>> connections) {
    final StringBuilder output = new StringBuilder();
    output.append("<!-- Territory Connections -->\r\n");
    // sort for pretty xml's
    final List<String> allTerritories = new ArrayList<>(connections.keySet());
    allTerritories.sort(new AlphanumComparator());
    for (final String t1 : allTerritories) {
        for (final String t2 : connections.get(t1)) {
            output.append("<connection t1=\"").append(t1).append("\" t2=\"").append(t2).append("\"/>\r\n");
        }
    }
    return output;
}
Also used : AlphanumComparator(games.strategy.util.AlphanumComparator) ArrayList(java.util.ArrayList)

Aggregations

AlphanumComparator (games.strategy.util.AlphanumComparator)3 ArrayList (java.util.ArrayList)2 Polygon (java.awt.Polygon)1 Shape (java.awt.Shape)1 Area (java.awt.geom.Area)1 File (java.io.File)1 FileInputStream (java.io.FileInputStream)1 FileOutputStream (java.io.FileOutputStream)1 IOException (java.io.IOException)1 InputStream (java.io.InputStream)1 OutputStream (java.io.OutputStream)1 Collection (java.util.Collection)1 HashMap (java.util.HashMap)1 LinkedHashSet (java.util.LinkedHashSet)1 List (java.util.List)1 Matcher (java.util.regex.Matcher)1 Pattern (java.util.regex.Pattern)1 JLabel (javax.swing.JLabel)1 FileOpen (tools.image.FileOpen)1 FileSave (tools.image.FileSave)1