repo
stringlengths
1
191
file
stringlengths
23
351
code
stringlengths
0
5.32M
file_length
int64
0
5.32M
avg_line_length
float64
0
2.9k
max_line_length
int64
0
288k
extension_type
stringclasses
1 value
Ludii
Ludii-master/PlayerDesktop/src/app/display/dialogs/visual_editor/view/components/ludemenodecomponent/inputs/LInputArea.java
package app.display.dialogs.visual_editor.view.components.ludemenodecomponent.inputs; import app.display.dialogs.visual_editor.handler.Handler; import app.display.dialogs.visual_editor.model.LudemeNode; import app.display.dialogs.visual_editor.model.NodeArgument; import app.display.dialogs.visual_editor.view.components.ludemenodecomponent.LudemeNodeComponent; import app.display.dialogs.visual_editor.view.designPalettes.DesignPalette; import main.grammar.ClauseArg; import main.grammar.Symbol; import javax.swing.*; import java.awt.*; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.List; /** * Generates and stores LInputFields for the current Clause of a LudemeNodeComponent * Procedure (re-executed when the selected Clause is changed) * 1. Generate a list of NodeArguments for the current Clause * 2. Generate a list of lists of NodeArgument * - Each list of NodeArgument is for one LInputField * - Consequent optional NodeArguments are grouped together in one List * 3. Construct a list of LInputFields * 4. Add and display the LInputFields * @author Filipp Dokienko */ public class LInputArea extends JPanel { /** * */ private static final long serialVersionUID = -7019971564269120999L; /** LudemeNodeComponent that this LInputAreaNew is associated with */ private final LudemeNodeComponent LNC; /** List of NodeArguments for the current Clause of the associated LudemeNodeComponent */ private List<NodeArgument> currentNodeArguments; /** List of lists of NodeArguments for the current Clause of the associated LudemeNodeComponent */ private List<List<NodeArgument>> currentNodeArgumentsLists; /** List of LInputFields for the current Clause of the associated LudemeNodeComponent */ public List<LInputField> currentInputFields; private final boolean DEBUG = true; /** * Constructor * @param LNC LudemeNodeComponent that this LInputAreaNew is associated with */ public LInputArea(LudemeNodeComponent LNC) { this.LNC = LNC; currentNodeArguments = LNC.node().currentNodeArguments(); currentNodeArgumentsLists = generateNodeArgumentsLists(currentNodeArguments); currentInputFields = generateInputFields(currentNodeArgumentsLists); drawInputFields(); setOpaque(false); setVisible(true); } /** * Groups consequent optional NodeArguments together in one list * Only if the NodeArgument is not provided with input by the user * @param nodeArguments List of NodeArguments to group into lists * @return List of lists of NodeArguments where each list corresponds to a LInputField */ private List<List<NodeArgument>> generateNodeArgumentsLists(List<NodeArgument> nodeArguments) { List<List<NodeArgument>> nodeArgumentsLists = new ArrayList<>(); List<NodeArgument> currentNodeArgumentsList = new ArrayList<>(); // List of NodeArguments currently being added to the current list for (NodeArgument nodeArgument : nodeArguments) { // If optional and not filled, add it to the current list if(nodeArgument.optional() && !isArgumentProvided(nodeArgument)) currentNodeArgumentsList.add(nodeArgument); else // If not optional, add it to a new empty list and add it to the list of lists { // if the current list is not empty, add it to the list of lists and clear it (happens when previous nodeArguments were optional) if (!currentNodeArgumentsList.isEmpty()) { nodeArgumentsLists.add(currentNodeArgumentsList); currentNodeArgumentsList = new ArrayList<>(); } List<NodeArgument> list = new ArrayList<>(); list.add(nodeArgument); nodeArgumentsLists.add(list); } } // if the current list is not empty, add it to the list of lists and clear it (happens when previous nodeArguments were optional) if(!currentNodeArgumentsList.isEmpty()) nodeArgumentsLists.add(currentNodeArgumentsList); return nodeArgumentsLists; } /** * * @param nodeArgument * @return Whether this NodeArgument was provided with input by the user */ private boolean isArgumentProvided(NodeArgument nodeArgument) { return LNC.node().providedInputsMap().get(nodeArgument) != null; //return LNC.node().providedInputs()[nodeArgument.index()] != null; } /** * Generates a list of LInputFields for every list of NodeArguments in the current list of lists of NodeArguments * @return List of LInputFields for the current list of lists of NodeArguments */ private List<LInputField> generateInputFields(List<List<NodeArgument>> nodeArgumentsLists) { List<LInputField> inputFields = new ArrayList<>(); for(List<NodeArgument> nodeArgumentsList : nodeArgumentsLists) { LInputField inputField = new LInputField(this, nodeArgumentsList); inputFields.add(inputField); } return inputFields; } /** * Draws the HashMap of LInputFields * Handles the merging/singling out of LInputFields of the dynamic constructor */ public void drawInputFields() { removeAll(); setLayout(new BoxLayout(this, BoxLayout.Y_AXIS)); setAlignmentX(LEFT_ALIGNMENT); removeEmptyFields(); for (LInputField inputField : currentInputFields) { inputField.setAlignmentX(LEFT_ALIGNMENT); add(inputField); } int preferredHeight = getPreferredSize().height; setSize(new Dimension(LNC.width(), preferredHeight)); LNC.updateComponentDimension(); LNC.updatePositions(); repaint(); } private void removeEmptyFields() { for(LInputField lif : new ArrayList<>(currentInputFields)) if(lif.nodeArguments().size() == 0) removeInputField(lif); } /** * If the selected clause is changed, this method is called to update the current list of NodeArguments and list of lists of NodeArguments and redraw the InputArea */ public void changedSelectedClause() { LNC.graphPanel().connectionHandler().cancelNewConnection(); LNC.graphPanel().connectionHandler().removeAllConnections(LNC.node()); LNC.graphPanel().setBusy(true); removeAll(); LNC.graphPanel().setBusy(false); currentNodeArguments = currentNodeArguments(); currentNodeArgumentsLists = generateNodeArgumentsLists(currentNodeArguments); currentInputFields = generateInputFields(currentNodeArgumentsLists); drawInputFields(); setOpaque(false); setVisible(true); } /** * Method which syncs the Ludeme Node Component with provided inputs (stored in the Ludeme Node). * Called when drawing a graph. */ public void updateProvidedInputs() { // Fill existing inputs Object[] providedInputs = LNC.node().providedInputsMap().values().toArray(new Object[0]); for(int input_index = 0; input_index < providedInputs.length; input_index++) { Object providedInput = providedInputs[input_index]; if(providedInput != null){ // find the inputfield with same index LInputField inputField = null; for(LInputField lInputField : currentInputFields) if(lInputField.inputIndices().contains(Integer.valueOf(input_index))) { inputField = lInputField; break; } assert inputField != null; inputField.setUserInput(providedInput); if(providedInput instanceof LudemeNode) { if (((LudemeNode) providedInput).collapsed()) { inputField.notifyCollapsed(); } } else if(providedInput instanceof Object[]) for(int i = 0; i < ((Object[]) providedInput).length; i++) { Object o = ((Object[])providedInput)[i]; if(!(o instanceof LudemeNode)) { continue; } LudemeNode ln = (LudemeNode) o; if(!ln.collapsed()) { continue; } // find according input field to notify it about the collapse if(i == 0) { inputField.notifyCollapsed(); } else { inputField.children().get(i-1).notifyCollapsed(); } } } } repaint(); revalidate(); setVisible(true); } /** * Notifies the Input Area that the user has provided non-terminal input for a NodeArgument * @param lnc The LudemeNodeComponent that the user connected to * @param inputField LInputField that the user has provided input for * @return The LInputField associated with the NodeArgument that the user provided input for */ public LInputField addedConnection(LudemeNodeComponent lnc, LInputField inputField) { // Find the NodeArgument that the user provided input for NodeArgument providedNodeArgument = null; for(NodeArgument nodeArgument : inputField.nodeArguments()) { for(Symbol s : nodeArgument.possibleSymbolInputsExpanded()) if(s.equals(lnc.node().symbol()) || s.returnType().equals(lnc.node().symbol()) || (lnc.node().isDefineNode() && s.equals(lnc.node().macroNode().symbol()))) { providedNodeArgument = nodeArgument; break; } if(providedNodeArgument != null) break; } // if the nodeArgument is choice, we need to find the correct one if(providedNodeArgument.choice()) { for(ClauseArg ca : providedNodeArgument.args()) { if(ca.symbol() == lnc.node().symbol()) { providedNodeArgument.setActiveChoiceArg(ca); break; } } } // Update active and inactive variables for dynamic nodes // if(dynamic()) providedNodeArgument(providedNodeArgument); // If the input field only contains one NodeArgument, it is the one that the user provided input for if(!inputField.isMerged()) { // if the field is a choice, update its label if(inputField.choice()) inputField.setLabelText(providedNodeArgument.arg().actualParameterName()); // if the field is hybrid, deactivate the terminal component if(inputField.isHybrid()) inputField.activateHybrid(false); return inputField; } // Otherwise it is a merged one. // Therefore, the NodeArgument which corresponds to the NodeArgument that the user provided input for is removed from the merged InputField // Single out the NodeArgument that the user provided input for and return the new InputField return singleOutInputField(providedNodeArgument, inputField); } /** * Notifies the Input Area that the user has provided terminal input for a NodeArgument * @param nodeArgument The NodeArgument that the user provided input for * @param inputField LInputField that the user has provided input for * @return The LInputField associated with the NodeArgument that the user provided input for */ public LInputField addedConnection(NodeArgument nodeArgument, LInputField inputField) { // Update active and inactive variables for dynamic nodes // if(dynamic()) providedNodeArgument(nodeArgument); // Single out the NodeArgument that the user provided input for and return the new InputField return singleOutInputField(nodeArgument, inputField); } /** * Notifies the Input Area that the user has provided terminal input for a NodeArgument * @param symbol The symbol of the NodeArgument that the user provided input for * @param inputField LInputField that the user has provided input for * @return The LInputField associated with the NodeArgument that the user provided input for */ public LInputField addedConnection(Symbol symbol, LInputField inputField) { System.out.println("Adding connection " + symbol + " -> " + inputField); // Find the NodeArgument that the user provided input for NodeArgument providedNodeArgument = null; for(NodeArgument nodeArgument : inputField.nodeArguments()) { for(ClauseArg arg : nodeArgument.args()) if(arg.symbol().equals(symbol)) { providedNodeArgument = nodeArgument; break; } if(providedNodeArgument != null) break; } return addedConnection(providedNodeArgument, inputField); } /** * Removes the NodeArgument from a merged InputField, and creates a new InputField for the remaining NodeArguments and for the NodeArgument that was removed * 3 Cases: * 1. The removed NodeArgument has the highest index in the merged InputField * -> The new InputField is above the merged InputField * 2. The removed NodeArgument has the lowest index in the merged InputField * -> The new InputField is below the merged InputField * 3. The removed NodeArgument is in the middle of the merged InputField * -> The merged InputField is split into two InputFields * -> The new InputField is centered between the two InputFields * @param nodeArgument The NodeArgument to remove from the merged InputField * @param inputField The merged InputField to remove the NodeArgument from * @return The new InputField for the removed NodeArgument */ private LInputField singleOutInputField(NodeArgument nodeArgument, LInputField inputField) { // Create the new InputField for the removed NodeArgument List<NodeArgument> nodeArguments = new ArrayList<>(); nodeArguments.add(nodeArgument); LInputField newInputField = new LInputField(this, nodeArguments); // Case 1 if(nodeArgument.index() == inputField.nodeArguments().get(0).index()) addInputFieldAbove(newInputField, inputField); // Case 2 else if(nodeArgument.index() == inputField.nodeArguments().get(inputField.nodeArguments().size() - 1).index()) addInputFieldBelow(newInputField, inputField); // Case 3 else splitAndAddBetween(newInputField, inputField); // Remove the NodeArgument from the merged InputField inputField.removeNodeArgument(nodeArgument); // If the merged InputField now only contains one NodeArgument, notify it to update it accordingly if(inputField.nodeArguments().size() == 1) inputField.reconstruct(); newInputField.activate(); // Redraw drawInputFields(); return newInputField; } public static void addCollectionItem(LInputField inputField) { inputField.addCollectionItem(); } /** * Adds an InputField to the current input fields * @param inputField InputField to add * @param index Index to add the InputField to */ private void addInputField(LInputField inputField, int index) { currentNodeArgumentsLists.add(index, inputField.nodeArguments()); currentInputFields.add(index, inputField); } /** * Removes an InputField from the current input fields * @param inputField InputField to remove */ protected void removeInputField(LInputField inputField) { int index = inputFieldIndex(inputField); if(inputField.parent() != null) inputField.parent().children().remove(inputField); currentNodeArgumentsLists.remove(index); currentInputFields.remove(index); } public void updateCurrentInputFields(List<NodeArgument> newNodeArguments) { // first remove all inputfields no longer contained (to first remove collection children, and then parent) List<LInputField> reversedInputFields = new ArrayList<>(currentInputFields); Collections.reverse(reversedInputFields); for(LInputField inputField : reversedInputFields) { if(!new HashSet<>(newNodeArguments).containsAll(inputField.nodeArguments())) { // remove connection Handler.recordUserActions = false; Object input = inputField.getUserInput(); if(input instanceof LudemeNode) { if(inputField.nodeArgument(0).collection()) { Handler.removeEdge(LNC().graphPanel().graph(), LNC().node(), ((LudemeNode) input), inputField.elementIndex(), true); } else { Handler.removeEdge(LNC().graphPanel().graph(), LNC().node(), ((LudemeNode) input)); } } else if(input != null) { Handler.updateInput(LNC().graphPanel().graph(), LNC().node(), inputField.nodeArgument(0), null); } Handler.recordUserActions = true; // remove inputfield removeInputField(inputField); } } // now add all inputfields that are new for(int i = 0; i < newNodeArguments.size(); i++) { NodeArgument na = newNodeArguments.get(i); // if exists, continue if(containsNodeArgument(na)) { continue; } // otherwise add it LInputField newInputField = new LInputField(this, na); addInputField(newInputField, i); } drawInputFields(); } /** * Checks whether an input field in the input area contains a given node argument. * @param na * @return */ private boolean containsNodeArgument(NodeArgument na) { for(List<NodeArgument> lna : currentNodeArgumentsLists) if(lna.contains(na)) return true; return false; } /** * Adds a new InputField above another InputField * @param inputFieldNew The InputField to add above the other InputField * @param inputField The InputField to add the new InputField above */ public void addInputFieldAbove(LInputField inputFieldNew, LInputField inputField) { if(DEBUG) System.out.println("Adding InputField " + inputFieldNew + " above " + inputField); int index = inputFieldIndex(inputField); addInputField(inputFieldNew, index); } /** * Adds a new InputField below another InputField * @param inputFieldNew The InputField to add below the other InputField * @param inputField The InputField to add the new InputField below */ public void addInputFieldBelow(LInputField inputFieldNew, LInputField inputField) { if(DEBUG) System.out.println("Adding InputField " + inputFieldNew + " below " + inputField); int index = inputFieldIndex(inputField) + 1; addInputField(inputFieldNew, index); } /** * Splits a merged InputField into two InputFields and singles out the NodeArgument that the user provided input for * @param inputFieldNew The new single InputField * @param inputField The merged InputField to split */ private void splitAndAddBetween(LInputField inputFieldNew, LInputField inputField) { // Find the NodeArgument that the user provided input for // Split the merged InputField into two InputFields List<NodeArgument> nodeArguments1 = new ArrayList<>(); List<NodeArgument> nodeArguments2 = new ArrayList<>(); for(NodeArgument nodeArgument : inputField.nodeArguments()) if(nodeArgument.index() < inputFieldNew.nodeArguments().get(0).index()) nodeArguments1.add(nodeArgument); else if(nodeArgument.index() > inputFieldNew.nodeArguments().get(0).index()) nodeArguments2.add(nodeArgument); // Create the new InputFields LInputField inputField1 = new LInputField(this, nodeArguments1); LInputField inputField2 = new LInputField(this, nodeArguments2); // Add inputField1 above the old merged InputField if(!nodeArguments1.isEmpty()) addInputFieldAbove(inputField1, inputField); // Add the new single InputField between the two InputFields addInputFieldAbove(inputFieldNew, inputField); // Add inputField2 below the new single InputField if(!nodeArguments2.isEmpty()) addInputFieldAbove(inputField2, inputField); // Remove the old merged InputField if(DEBUG) System.out.println("Removing old InputField " + inputField); removeInputField(inputField); } /** * Called when the connection of a input field is removed * Attempts to merge the input field into the input field above or below (or both) * @param inputField the input field which connection is removed * @return whether the input field was merged */ public boolean removedConnection(LInputField inputField) { if(DEBUG) System.out.println("removedConnection: " + inputField); if(!inputField.isMerged() && inputField.isHybrid()) inputField.activateHybrid(true); // if the inputfield is single and optional, check whether it can be merged into another inputfield if(!inputField.isMerged() && inputField.optional() && inputField.children().isEmpty()) { // get input fields above and below (null if there is no input field above or below) LInputField inputFieldAbove = inputFieldAbove(inputField); //boolean canBeMergedIntoAbove = inputFieldAbove != null && !isArgumentProvided(inputFieldAbove.nodeArgument(0)) && (inputFieldAbove.optional() || dynamic()); LInputField inputFieldBelow = inputFieldBelow(inputField); //boolean canBeMergedIntoBelow = inputFieldBelow != null && !isArgumentProvided(inputFieldBelow.nodeArgument(0)) && (inputFieldBelow.optional() || dynamic()); // check where the input field can be merged into // for optional: field above/below must be unfilled & optional boolean canBeMergedIntoAbove = inputFieldAbove != null && !isArgumentProvided(inputFieldAbove.nodeArgument(0)) && inputFieldAbove.optional(); boolean canBeMergedIntoBelow = inputFieldBelow != null && !isArgumentProvided(inputFieldBelow.nodeArgument(0)) && inputFieldBelow.optional(); // if cannot be merged into above or below field, then find suitable LInputField to merge into if(!canBeMergedIntoBelow && !canBeMergedIntoAbove) { // check whether this is a block of subsequent symbols (e.g. int) if((inputFieldAbove != null && inputFieldAbove.nodeArgument(0).arg().symbol().equals(inputField.nodeArgument(0).arg().symbol()) && inputFieldAbove.nodeArgument(0).collection() == inputField.nodeArgument(0).collection() && inputFieldAbove.nodeArgument(0).optional()) || (inputFieldBelow != null && inputFieldBelow.nodeArgument(0).arg().symbol().equals(inputField.nodeArgument(0).arg().symbol()) && inputFieldBelow.nodeArgument(0).collection() == inputField.nodeArgument(0).collection() && inputFieldBelow.nodeArgument(0).optional())) { // find this block List<LInputField> block = new ArrayList<>(); // find first element LInputField e = inputFieldAbove; if(e == null) { e = inputField; } while(inputFieldAbove!=null && !inputFieldAbove.isMerged() && inputFieldAbove.nodeArgument(0).arg().symbol().equals(inputField.nodeArgument(0).arg().symbol()) && inputFieldAbove.nodeArgument(0).collection() == inputField.nodeArgument(0).collection()) { e = inputFieldAbove; inputFieldAbove = inputFieldAbove(inputFieldAbove); } // add remaining elements to list block.add(e); LInputField current = inputFieldBelow(e); while(current != null && !current.isMerged() && current.nodeArgument(0).arg().symbol().equals(e.nodeArgument(0).arg().symbol()) && current.nodeArgument(0).collection() == inputField.nodeArgument(0).collection()) { block.add(current); current = inputFieldBelow(current); } // find whether there is another unprovided input field in the block. if yes, then merge them together LInputField newMerged = inputField; for(LInputField lif : block) { if(lif == inputField) { continue; } if(!isArgumentProvided(lif.nodeArgument(0))) { newMerged = mergeInputFields(new LInputField[]{lif, inputField}); break; } } // check whether the (maybe merged) input field can be merged into a field above/below the block LInputField lif_b_block = inputFieldBelow(block.get(block.size()-1)); LInputField lif_a_block = inputFieldAbove(block.get(0)); canBeMergedIntoAbove = lif_a_block != null && !isArgumentProvided(lif_a_block.nodeArgument(0)) && lif_a_block.optional() && lif_a_block.nodeArgument(0).collection() == inputField.nodeArgument(0).collection(); canBeMergedIntoBelow = lif_b_block != null && !isArgumentProvided(lif_b_block.nodeArgument(0)) && lif_b_block.optional() && lif_b_block.nodeArgument(0).collection() == inputField.nodeArgument(0).collection(); if(canBeMergedIntoAbove && canBeMergedIntoBelow) { // check whether one of those contains the symbol already for(NodeArgument na : lif_a_block.nodeArguments()) { if(na.arg().symbol().equals(inputField.nodeArgument(0).arg().symbol())) { canBeMergedIntoBelow = false; break; } } if(canBeMergedIntoBelow) for (NodeArgument na : lif_b_block.nodeArguments()) { if (na.arg().symbol().equals(inputField.nodeArgument(0).arg().symbol())) { canBeMergedIntoAbove = false; break; } } } if(canBeMergedIntoBelow) { mergeInputFields(new LInputField[]{newMerged, lif_b_block}); } else if(canBeMergedIntoAbove) { mergeInputFields(new LInputField[]{lif_a_block, newMerged}); } drawInputFields(); setOpaque(false); setVisible(true); return true; } else { return false; } } // if can be merged into both, combine the three inputfields into one if(canBeMergedIntoAbove && canBeMergedIntoBelow) { mergeInputFields(new LInputField[]{inputFieldAbove, inputField, inputFieldBelow}); } // if can be merged into above, merge into above else if(canBeMergedIntoAbove) { mergeInputFields(new LInputField[]{inputFieldAbove, inputField}); } // if can be merged into below, merge into below else { mergeInputFields(new LInputField[]{inputField, inputFieldBelow}); } } drawInputFields(); setOpaque(false); setVisible(true); return true; } /** * Merges multiple InputFields into one InputField and updates the currentInputFields map * @param inputFields The InputFields to merge * @return The merged InputField */ private LInputField mergeInputFields(LInputField[] inputFields) { List<NodeArgument> nodeArguments = new ArrayList<>(); for(LInputField inputField : inputFields) nodeArguments.addAll(inputField.nodeArguments()); LInputField mergedInputField = new LInputField(this, nodeArguments); // Update the currentNodeArgumentsLists list and the currentInputFields map // add the new nodeArguments to the currentNodeArgumentsLists list int index = inputFieldIndex(inputFields[0]); addInputField(mergedInputField, index); // remove the old nodeArguments from the currentNodeArgumentsLists list for(LInputField inputField : inputFields) { if(DEBUG) System.out.println("Removing old InputField " + inputField); removeInputField(inputField); } return mergedInputField; } /** * * @param inputField * @return The index of an inputfield in the currentInputFields list */ public int inputFieldIndex(LInputField inputField) { return currentInputFields.indexOf(inputField); } /** * Returns the inputfield above the given inputfield * @param inputField The inputfield to get the above inputfield of * @return The inputfield above the given inputfield */ private LInputField inputFieldAbove(LInputField inputField) { int index = inputFieldIndex(inputField)-1; if(index < 0) return null; return currentInputFields.get(index); } /** * Returns the inputfield below the given inputfield * @param inputField The inputfield to get the below inputfield of * @return The inputfield below the given inputfield */ private LInputField inputFieldBelow(LInputField inputField) { // this is inefficient, but the one below doesn't work. Maybe because the ArrayList is altered in the process before (but id stays the same!) int index = inputFieldIndex(inputField) + 1; if(index >= currentInputFields.size()) return null; return currentInputFields.get(index); } /** * Updates the positions of all LInputFields' connection components */ public void updateConnectionPointPositions() { for(LInputField inputField : currentInputFields) if(inputField.connectionComponent() != null) inputField.connectionComponent().updatePosition(); } /** * * @return the List of NodeArguments for the current Clause of the associated LudemeNodeComponent */ public List<NodeArgument> currentNodeArguments() { return LNC().node().currentNodeArguments(); } /** * * @return the LudemeNodeComponent that this LInputAreaNew is associated with */ public LudemeNodeComponent LNC() { return LNC; } @Override public void paintComponent(Graphics g) { super.paintComponent(g); setBorder(DesignPalette.INPUT_AREA_PADDING_BORDER); // just space between this and bottom of LNC } // // UNUSED DYNAMIC-CONSTRUCTOR VARIABLES & METHODS // /* // Variables for a dynamic node // How it works: Initially the user can provide node arguments / inputs for any clause the node has. // Whenever an argument is provided, clauses that do not include that argument are removed from the list of active clauses. // The list of possible arguments is updated whenever an argument is provided. // // Clauses that satisfy currently provided inputs private List<Clause> activeClauses; // Clauses that do not satisfy currently provided inputs private List<Clause> inactiveClauses; // NodeArguments that are currently provided private List<NodeArgument> providedNodeArguments; // NodeArguments that can be provided to satisfy active clauses private List<NodeArgument> activeNodeArguments; // NodeArguments that cannot be provided to satisfy active clauses private List<NodeArgument> inactiveNodeArguments; // Whether there is an active clause (only one active clause left) private boolean activeClause = false; In constructor: if(dynamic()) { activeClauses = LNC.node().activeClauses(); if(activeClauses.size() == 1) activeClause = true; inactiveClauses = LNC.node().inactiveClauses(); providedNodeArguments = LNC.node().providedNodeArguments(); activeNodeArguments = LNC.node().activeNodeArguments(); //for(List<NodeArgument> nas: nodeArguments.values()) activeNodeArguments.addAll(nas); inactiveNodeArguments = LNC.node().inactiveNodeArguments(); currentNodeArguments = activeNodeArguments; } In generateNodeArgumentsList() first line: if(dynamic()) return generateDynamicNodeArgumentsLists(nodeArguments); // Groups consequent NodeArguments together in one list // Only if the NodeArgument is not provided with input by the user // @param nodeArguments List of NodeArguments to group into lists // @return List of lists of NodeArguments where each list corresponds to a LInputField // private List<List<NodeArgument>> generateDynamicNodeArgumentsLists(List<NodeArgument> nodeArguments) { List<List<NodeArgument>> nodeArgumentsLists = new ArrayList<>(); List<NodeArgument> currentNodeArgumentsList = new ArrayList<>(); // List of NodeArguments currently being added to the current list for (NodeArgument nodeArgument : nodeArguments) { // Only if not provided with input by the user if(!providedNodeArguments.contains(nodeArgument)) { currentNodeArgumentsList.add(nodeArgument); } else // If not optional, add it to a new empty list and add it to the list of lists { // if the current list is not empty, add it to the list of lists and clear it (happens when previous nodeArguments were optional) if (!currentNodeArgumentsList.isEmpty()) { nodeArgumentsLists.add(currentNodeArgumentsList); currentNodeArgumentsList = new ArrayList<>(); } List<NodeArgument> list = new ArrayList<>(); list.add(nodeArgument); nodeArgumentsLists.add(list); } } // if the current list is not empty, add it to the list of lists and clear it (happens when previous nodeArguments were optional) if(!currentNodeArgumentsList.isEmpty()) { nodeArgumentsLists.add(currentNodeArgumentsList); } return nodeArgumentsLists; } in drawInputFields before any other method calls: if(dynamic() && activeClauses.size() == 1 && !activeClause) { addRemainingInputFields(); } else if(dynamic() && activeClauses.size() > 1 && activeClause) { removeUnprovidedInputFields(); mergeUnprovidedMergedInputFields(); } // @return Whether the node is dynamic or not private boolean dynamic() { return LNC.node().dynamic(); } In singleOutInputField() before Case 1 // Dynamic nodes have a special case, only case 3 if(dynamic()) { splitAndAddBetween(newInputField, inputField); // Remove the NodeArgument from the merged InputField inputField.removeNodeArgument(nodeArgument); // If the merged InputField now only contains one NodeArgument, notify it to update it accordingly if(inputField.nodeArguments().size() == 1) { inputField.reconstruct(); } if(inputField.nodeArguments().size() == 0) { removeInputField(inputField); } // Redraw drawInputFields(); return newInputField; } In SplitAndAddBetween first line // different for dynamic nodes if(dynamic()) { splitAndAddBetweenDynamic(inputFieldNew, inputField); return; } In removedConnection() first line if(!inputField.isMerged() && dynamic()) { removedConnectionDynamic(inputField); drawInputFields(); setOpaque(false); setVisible(true); return true; } // Splits a merged InputField into two InputFields and singles out the NodeArgument that the user provided input for // @param inputFieldNew The new single InputField // @param inputField The merged InputField to split private void splitAndAddBetweenDynamic(LInputField inputFieldNew, LInputField inputField) { // Find the NodeArgument that the user provided input for // Split the merged InputField into two InputFields List<NodeArgument> nodeArguments1 = new ArrayList<>(); // nodeArguments1 contains active node arguments which index is smaller than the max_index of provided node arguments excluding provided arguments List<NodeArgument> nodeArguments2 = new ArrayList<>(); // nodeArguments2 contains active node arguments which index is greater than the max_index of provided node arguments excluding provided arguments int min_index = 100000; int max_index = 0; for(NodeArgument providedNA : providedNodeArguments) { if(!inputField.nodeArguments().contains(providedNA)) continue; min_index = Math.min(min_index, providedNA.index()); max_index = Math.max(max_index, providedNA.index()); } for(NodeArgument nodeArgument : inputField.nodeArguments()) { if(nodeArgument.index() <= min_index && !providedNodeArguments.contains(nodeArgument)) { nodeArguments1.add(nodeArgument); } else if(nodeArgument.index() >= max_index && !providedNodeArguments.contains(nodeArgument)) { nodeArguments2.add(nodeArgument); } } if(DEBUG) { System.out.println("---------"); System.out.println("ABOVE: " + nodeArguments1); System.out.println("BETWEEN: " + inputFieldNew.nodeArguments()); System.out.println("BELOW: " + nodeArguments2); System.out.println("---------"); } // Create the new InputFields LInputField inputField1 = new LInputField(this, nodeArguments1); LInputField inputField2 = new LInputField(this, nodeArguments2); // Add inputField1 above the old merged InputField if(!nodeArguments1.isEmpty()) addInputFieldAbove(inputField1, inputField); // Add the new single InputField between the two InputFields addInputFieldAbove(inputFieldNew, inputField); // Add inputField2 below the new single InputField if(!nodeArguments2.isEmpty()) addInputFieldAbove(inputField2, inputField); // Remove the old merged InputField if(DEBUG) System.out.println("Removing old InputField " + inputField); removeInputField(inputField); } // // For Dynamic Nodes. // Called when the connection of a input field is removed // Attempts to merge the input field into the input field above or below (or both) // @param inputField the input field which connection is removed private void removedConnectionDynamic(LInputField inputField) { // get input fields above and below (null if there is no input field above or below) LInputField inputFieldAbove = inputFieldAbove(inputField); LInputField inputFieldBelow = inputFieldBelow(inputField); // check where the input field can be merged into // for dynamic: field above/below must be unfilled boolean canBeMergedIntoAbove = inputFieldAbove != null && !providedNodeArguments.contains(inputFieldAbove.nodeArgument(0)); boolean canBeMergedIntoBelow = inputFieldBelow != null && !providedNodeArguments.contains(inputFieldBelow.nodeArgument(0)); // update active node arguments etc. // get freed up node arguments (now active, before inactive) List<List<NodeArgument>> freedUpArguments = removedProvidedNodeArgument(inputField.nodeArgument(0)); List<NodeArgument> freedUpAbove = freedUpArguments.get(0); List<NodeArgument> freedUpBelow = freedUpArguments.get(1); if(activeClauses.size() == 1) return; if(!canBeMergedIntoBelow && !canBeMergedIntoAbove) { System.err.println("Cannot remove connection, because there is no place to merge the input field! [dynamic]"); return; } // if can be merged into both, combine the three inputfields into one if(canBeMergedIntoAbove && canBeMergedIntoBelow) { LInputField inputFieldNew = mergeInputFields(new LInputField[]{inputFieldAbove, inputField, inputFieldBelow}); for(NodeArgument na : freedUpAbove) if(!providedNodeArguments.contains(na)) inputFieldNew.addNodeArgument(na); for(NodeArgument na : freedUpBelow) if(!providedNodeArguments.contains(na)) inputFieldNew.addNodeArgument(na); } // if can be merged into above, merge into above else if(canBeMergedIntoAbove) { LInputField inputFieldNew = mergeInputFields(new LInputField[]{inputFieldAbove, inputField}); // add freed up node arguments to input field for(NodeArgument na : freedUpAbove) if(!providedNodeArguments.contains(na)) inputFieldNew.addNodeArgument(na); // get input field below LInputField inputFieldBelowMerged = inputFieldBelow(inputFieldNew); if(inputFieldBelowMerged != null) { // add freed up node arguments to input field for(NodeArgument na : freedUpBelow) if(!providedNodeArguments.contains(na)) inputFieldBelowMerged.addNodeArgument(na); } else { // add freed up node arguments to input field for(NodeArgument na : freedUpBelow) if(!providedNodeArguments.contains(na)) inputFieldNew.addNodeArgument(na); } } // if can be merged into below, merge into below else if(canBeMergedIntoBelow) { LInputField inputFieldNew = mergeInputFields(new LInputField[]{inputField, inputFieldBelow}); // add freed up node arguments to input field for(NodeArgument na : freedUpBelow) if(!providedNodeArguments.contains(na)) inputFieldNew.addNodeArgument(na); // get input field below LInputField inputFieldAboveMerged = inputFieldAbove(inputFieldNew); if(inputFieldAboveMerged != null) { // add freed up node arguments to input field for(NodeArgument na : freedUpAbove) if(!providedNodeArguments.contains(na)) inputFieldAboveMerged.addNodeArgument(na); } else { // add freed up node arguments to input field for(NodeArgument na : freedUpAbove) if(!providedNodeArguments.contains(na)) inputFieldNew.addNodeArgument(na); } } } // For Dynamic Nodes. // When a new NodeArgument is provided by the user, update the list of available node arguments to input // @param nodeArgument NodeArgument that was provided by the user private void providedNodeArgument(NodeArgument nodeArgument) { // add all node arguments with the same symbol to the providedNodeArguments list for(NodeArgument activeNA : new ArrayList<>(activeNodeArguments)) { if(activeNA.arg().symbol().equals(nodeArgument.arg().symbol())) { providedNodeArguments.add(activeNA); } } // check whether all active clauses satisfy the provided node argument List<Clause> notSatisfiedClauses = new ArrayList<>(); for(Clause activeClause : activeClauses) { if(!clauseSatisfiesArgument(activeClause, nodeArgument)) { notSatisfiedClauses.add(activeClause); } } // remove the not satisfied clauses from the active clauses and add them to the inactive clauses activeClauses.removeAll(notSatisfiedClauses); inactiveClauses.addAll(notSatisfiedClauses); // update the list of active and inactive node arguments for(Clause notSatisfiedClause : notSatisfiedClauses) { // Get NodeArguments from notSatisfiedClause List<NodeArgument> notSatisfiedClauseArguments = nodeArguments.get(notSatisfiedClause); // Add all previously activeNodeArguments that are in the list of notSatisfiedClauseArguments to the list of inactiveNodeArguments for (NodeArgument notSatisfiedClauseArgument : notSatisfiedClauseArguments) { if (activeNodeArguments.contains(notSatisfiedClauseArgument)) removeActiveNodeArgument(notSatisfiedClauseArgument); // remove the argument from the active list and updates input fields accordingly } } } // For Dynamic Nodes. // When the remaining NodeArguments to be provided by the user are known, add a inputfield for each private void addRemainingInputFields() { activeClause = true; // expand all input fields that are not yet expanded List<NodeArgument> addedNodeArguments = new ArrayList<>(); // NodeArguments for which a LInputFieldNew was added for(LInputField inputField : new ArrayList<>(currentInputFields)) { if(!inputField.isMerged()) continue; List<NodeArgument> lif_arguments = inputField.nodeArguments(); lif_arguments.sort(Comparator.comparingInt(NodeArgument::index)); // sort ascending by index for(NodeArgument na: lif_arguments) { LInputField lif = new LInputField(this, na); addedNodeArguments.add(na); // add this field above the current input field addInputFieldAbove(lif, inputField); } // remove the current input field if(DEBUG) System.out.println("Removing old InputField " + inputField); removeInputField(inputField); } LNC().node().setSelectedClause(activeClauses.get(0)); } // For Dynamic Nodes. // Empty single InputFields should be merged together // Called when there is no more single active clause anymore. // Every automatically singled-out inputfields that are not provided with input should be merged together // private void removeUnprovidedInputFields() { activeClause = false; // try to merge empty input fields for(LInputField inputField : new ArrayList<>(currentInputFields)) { if(!currentInputFields.contains(inputField)) continue; if(inputField.isMerged()) continue; // check whether can be merged LInputField inputFieldAbove = inputFieldAbove(inputField); LInputField inputFieldBelow = inputFieldBelow(inputField); if((inputFieldAbove == null || providedNodeArguments.contains(inputFieldAbove.nodeArgument(0))) && (inputFieldBelow == null || providedNodeArguments.contains(inputFieldBelow.nodeArgument(0)))) continue; if(!providedNodeArguments.contains(inputField.nodeArgument(0))) { removedConnectionDynamic(inputField); removeUnprovidedInputFields(); break; } } } // If merged inputfields are both unprovided for, they can be merged together private void mergeUnprovidedMergedInputFields() { List<LInputField> consequentInputFields = new ArrayList<>(); for(LInputField inputField : new ArrayList<>(currentInputFields)) { if (!inputField.isMerged()) { if(consequentInputFields.size() > 1) { // convert consequentInputFields to an array LInputField[] consequentInputFieldsArray = new LInputField[consequentInputFields.size()]; for(int i = 0; i < consequentInputFields.size(); i++) consequentInputFieldsArray[i] = consequentInputFields.get(i); mergeInputFields(consequentInputFieldsArray); mergeUnprovidedMergedInputFields(); consequentInputFields.clear(); break; } } else { consequentInputFields.add(inputField); } } } // // @param clause Clause to check // @param nodeArgument NodeArgument that was added // @return whether the provided node argument satisfies a clause, i.e. whether this clause satisfies the newly added node argument // private boolean clauseSatisfiesArgument(Clause clause, NodeArgument nodeArgument) { // check whether the clause contains the node argument's symbol for (ClauseArg clauseArg : clause.args()) { Symbol argSymbol = clauseArg.symbol(); if (argSymbol.equals(nodeArgument.arg().symbol())) { return true; } } return false; } // // // @param clause // @param nodeArguments // @return Whether a clause satisfies a list of node arguments // private boolean clauseSatisfiesArguments(Clause clause, List<NodeArgument> nodeArguments) { for(NodeArgument na : nodeArguments) { if(!clauseSatisfiesArgument(clause, na)) { return false; } } return true; } // // For Dynamic Nodes. // A NodeArgument was removed from the active node arguments list. // @param nodeArgument NodeArgument that was removed from the active node arguments list // private void removeActiveNodeArgument(NodeArgument nodeArgument) { // find inputfield for argument LInputField inputField = null; for(LInputField lif : currentInputFields) { if(lif.isMerged() && lif.nodeArguments().contains(nodeArgument)) { inputField = lif; break; } } // Remove the NodeArgument from the merged InputField if(inputField != null) { inputField.removeNodeArgument(nodeArgument); // If the merged InputField now only contains one NodeArgument, notify it to update it accordingly (shouldn't happen) if (inputField.nodeArguments().size() == 0) { for(LInputField lif : currentInputFields) { if(lif == inputField) { if(DEBUG) System.out.println("Removing old InputField " + inputField); removeInputField(inputField); } } } } activeNodeArguments.remove(nodeArgument); inactiveNodeArguments.add(nodeArgument); } // // For Dynamic Nodes. // Called when a provided node argument was deleted (connection was removed) // @param nodeArgument NodeArgument that was deleted // @return A list of two lists of NodeArguments. They contain node arguments that are now active but previously were inactive. The first list contains node arguments with an index // lower than the index of the deleted node argument. The second list contains node arguments with an index higher than the index of the deleted node argument. // private List<List<NodeArgument>> removedProvidedNodeArgument(NodeArgument nodeArgument) { // find which node arguments to remove from the provided node arguments list List<NodeArgument> nodeArgumentsToRemove = new ArrayList<>(); List<NodeArgument> freedNodeArgumentsBelow = new ArrayList<>(); List<NodeArgument> freedNodeArgumentsAbove = new ArrayList<>(); // get max index from inputfield above, and min index from inputfield below // all node arguments with the same symbol as the removed node argument and between the min and max index are removed from the provided node arguments list for(NodeArgument providedNA : providedNodeArguments) { if(providedNA.arg().symbol().equals(nodeArgument.arg().symbol())) { if(providedNA.index() >= nodeArgument.index()) { nodeArgumentsToRemove.add(providedNA); freedNodeArgumentsAbove.add(providedNA); } else if(providedNA.index() <= nodeArgument.index()) { nodeArgumentsToRemove.add(providedNA); freedNodeArgumentsBelow.add(providedNA); } } } // update the list of provided node arguments providedNodeArguments.removeAll(nodeArgumentsToRemove); // check which clauses are now satisfied by the provided arguments List<Clause> satisfiedClauses = new ArrayList<>(); for(Clause inactiveClause : inactiveClauses) { if(clauseSatisfiesArguments(inactiveClause, providedNodeArguments)) { satisfiedClauses.add(inactiveClause); } } // add their nodearguments to the active node arguments list for(Clause satisfiedClause : satisfiedClauses) { for(NodeArgument na: nodeArguments.get(satisfiedClause)) { activeNodeArguments.add(na); inactiveNodeArguments.remove(na); if(na == nodeArgument) continue; if(na.index() <= nodeArgument.index()) { freedNodeArgumentsBelow.add(na); } else { freedNodeArgumentsAbove.add(na); } } } // add the satisfied clauses to the active clauses and remove them from the inactive clauses activeClauses.addAll(satisfiedClauses); inactiveClauses.removeAll(satisfiedClauses); List<List<NodeArgument>> freedNodeArguments = new ArrayList<>(); freedNodeArguments.add(freedNodeArgumentsBelow); freedNodeArguments.add(freedNodeArgumentsAbove); return freedNodeArguments; } */ }
56,778
42.642583
270
java
Ludii
Ludii-master/PlayerDesktop/src/app/display/dialogs/visual_editor/view/components/ludemenodecomponent/inputs/LInputButton.java
package app.display.dialogs.visual_editor.view.components.ludemenodecomponent.inputs; import app.display.dialogs.visual_editor.view.designPalettes.DesignPalette; import javax.swing.*; import java.awt.*; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; public class LInputButton extends JButton { /** * */ private static final long serialVersionUID = -6627034885726770235L; public Color ACTIVE_COLOR; private final Color HOVER_COLOR = new Color(127,191,255); public ImageIcon ACTIVE_ICON; private ImageIcon HOVER_ICON; private boolean active = true; public LInputButton(ImageIcon activeIcon, ImageIcon hoverIcon) { super(activeIcon); this.ACTIVE_COLOR = DesignPalette.FONT_LUDEME_INPUTS_COLOR(); this.ACTIVE_ICON = activeIcon; this.HOVER_ICON = hoverIcon; setFont(new Font("Roboto Bold", 0, 12)); // make transparent setBorder(BorderFactory.createEmptyBorder()); setFocusPainted(false); setOpaque(false); setContentAreaFilled(false); setBorderPainted(false); addMouseListener(hoverMouseListener); } public void updateDP() { if(active) setActive(); } public void setActive(){ active = true; setForeground(ACTIVE_COLOR); setIcon(ACTIVE_ICON); repaint(); } public void setHover(){ active = false; setForeground(HOVER_COLOR); setIcon(HOVER_ICON); repaint(); } final MouseListener hoverMouseListener = new MouseAdapter() { @Override public void mouseEntered(MouseEvent e) { setHover(); } @Override public void mouseExited(MouseEvent e) { setActive(); } }; @Override public void setSize(int width, int height) { super.setSize(width, height); ACTIVE_ICON = new ImageIcon(ACTIVE_ICON.getImage().getScaledInstance(width, height, Image.SCALE_SMOOTH)); HOVER_ICON = new ImageIcon(HOVER_ICON.getImage().getScaledInstance(width, height, Image.SCALE_SMOOTH)); if(active) setIcon(ACTIVE_ICON); else setIcon(HOVER_ICON); } }
2,253
25.209302
113
java
Ludii
Ludii-master/PlayerDesktop/src/app/display/dialogs/visual_editor/view/components/ludemenodecomponent/inputs/LInputField.java
package app.display.dialogs.visual_editor.view.components.ludemenodecomponent.inputs; import app.display.dialogs.visual_editor.handler.Handler; import app.display.dialogs.visual_editor.model.LudemeNode; import app.display.dialogs.visual_editor.model.NodeArgument; import app.display.dialogs.visual_editor.view.designPalettes.DesignPalette; import app.display.dialogs.visual_editor.view.panels.IGraphPanel; import main.grammar.ClauseArg; import main.grammar.Symbol; import javax.swing.*; import javax.swing.border.Border; import javax.swing.border.LineBorder; import javax.swing.event.ChangeListener; import javax.swing.text.DefaultFormatter; import java.awt.*; import java.awt.event.*; import java.beans.PropertyChangeListener; import java.util.ArrayList; import java.util.List; /** * A component representing one or more NodeArguments * @author Filipp dokienko */ public class LInputField extends JComponent { /** * */ private static final long serialVersionUID = -2836300174342385636L; /** LInputAreaNew that this LInputFieldNew is associated with */ private final LInputArea LIA; /** NodeArguments that this LInputField is associated with */ private final List<NodeArgument> nodeArguments; /** The JComponent the user interacts with to provide input */ private JComponent fieldComponent; /** If the LInputField is not terminal, it has a connection point which is used to connect to other Nodes */ private LConnectionComponent connectionComponent = null; /** If the LInputField is part of a collection (its element), the root/first element of that collection is the parent */ private LInputField parent = null; /** If the LInputField is the root of a collection, store its elements/children in a list */ private final List<LInputField> children = new ArrayList<>(); /** Label of the InputField */ private final JLabel label = new JLabel(); private final JLabel optionalLabel = new JLabel("(optional)"); private final JLabel terminalOptionalLabel = new JLabel("+"); private final LInputButton expandButton = new LInputButton(DesignPalette.UNCOLLAPSE_ICON(), DesignPalette.UNCOLLAPSE_ICON_HOVER()); private final LInputButton addItemButton = new LInputButton(DesignPalette.COLLECTION_ICON_ACTIVE(), DesignPalette.COLLECTION_ICON_HOVER()); private final LInputButton removeItemButton = new LInputButton(DesignPalette.COLLECTION_REMOVE_ICON_ACTIVE(), DesignPalette.COLLECTION_REMOVE_ICON_HOVER()); private final LInputButton choiceButton = new LInputButton(DesignPalette.CHOICE_ICON_ACTIVE(), DesignPalette.CHOICE_ICON_HOVER()); private static final float buttonWidthPercentage = 1f; private boolean active = true; /** * Constructor for a single or merged input field * @param LIA Input Area this field belongs to * @param nodeArguments NodeArgument(s) this field represents */ public LInputField(LInputArea LIA, List<NodeArgument> nodeArguments) { this.LIA = LIA; this.nodeArguments = nodeArguments; loadButtons(); construct(); } /** * Constructor for a single input field * @param LIA * @param nodeArgument */ public LInputField(LInputArea LIA, NodeArgument nodeArgument) { this.LIA = LIA; this.nodeArguments = new ArrayList<>(); this.nodeArguments.add(nodeArgument); loadButtons(); construct(); } /** * Constructor for an input field which is part of a collection * @param parentCollectionInputField Parent InputField of collection */ public LInputField(LInputField parentCollectionInputField) { this.LIA = parentCollectionInputField.inputArea(); this.parent = parentCollectionInputField; this.nodeArguments = new ArrayList<>(parentCollectionInputField.nodeArguments()); loadButtons(); parent.addChildren(this); construct(nodeArgument(0)); } /** * Loads all buttons their listeners */ private void loadButtons() { optionalLabel.setFont(DesignPalette.LUDEME_INPUT_FONT_ITALIC); optionalLabel.setForeground(DesignPalette.FONT_LUDEME_INPUTS_COLOR()); optionalLabel.setText("(optional)"); terminalOptionalLabel.setFont(DesignPalette.LUDEME_INPUT_FONT); if(terminalOptionalLabel.getMouseListeners().length == 0) terminalOptionalLabel.addMouseListener(terminalOptionalLabelListener); expandButton.setSize(expandButton.getPreferredSize()); expandButton.setActive(); expandButton.addActionListener(expandButtonListener); addItemButton.addActionListener(addItemButtonListener); removeItemButton.addActionListener(removeItemButtonListener); choiceButton.addActionListener(choiceButtonListener); } private final ActionListener expandButtonListener = e -> { remove(expandButton); add(connectionComponent); Handler.collapseNode(inputArea().LNC().graphPanel().graph(), connectionComponent().connectedTo().node(), false); }; private final ActionListener addItemButtonListener = e -> addCollectionItem(); private final ActionListener removeItemButtonListener = e -> removeCollectionItem(); private final ActionListener choiceButtonListener = e -> { JPopupMenu popup = new JPopupMenu(); JMenuItem[] items = new JMenuItem[nodeArgument(0).size()]; for(int i = 0; i < nodeArgument(0).size(); i++) { items[i] = new JMenuItem(nodeArgument(0).args().get(i).toString()); int finalI = i; items[i].addActionListener(e1 -> { // ask user for confirmation if(children.size()+1 >= Handler.SENSITIVITY_COLLECTION_REMOVAL && Handler.sensitivityToChanges) { int userChoice = JOptionPane.showConfirmDialog(null, "When changing the argument " + (children.size() + 1) + " collection elements will be reset.", "Remove nodes", JOptionPane.OK_CANCEL_OPTION); if(userChoice != JOptionPane.OK_OPTION) { return; } } inputArea().LNC().graphPanel().setBusy(true); // if was collection, remove all children if(children.size() > 0) removeAllChildren(); nodeArgument(0).setActiveChoiceArg(nodeArgument(0).args().get(finalI)); notifyActivated(); if (getUserInput() != null) if(getUserInput() instanceof LudemeNode) Handler.removeEdge(inputArea().LNC().graphPanel().graph(), inputArea().LNC().node(),(LudemeNode) getUserInput()); else Handler.updateInput(inputArea().LNC().graphPanel().graph(), inputArea().LNC().node(), nodeArgument(0), null); reconstruct(); inputArea().LNC().graphPanel().setBusy(false); inputArea().repaint(); }); popup.add(items[i]); } popup.show(choiceButton, 0, 0); }; private void removeAllChildren() { boolean handlerRecording = Handler.recordUserActions; if(handlerRecording) Handler.recordUserActions = false; for (LInputField child : new ArrayList<>(children)) removeChildrenEdge(child); for(LInputField child : new ArrayList<>(children)) try { inputArea().removeInputField(child); } catch (Exception ignored) { // Nothing to do } children.clear(); inputArea().drawInputFields(); if(handlerRecording) Handler.recordUserActions = true; } private void removeChildrenEdge(LInputField child) { if(child.connectionComponent != null && child.connectionComponent.connectedTo() != null) Handler.removeEdge(inputArea().LNC().graphPanel().graph(), inputArea().LNC().node(), child.connectionComponent.connectedTo().node(), child.elementIndex()); } /** * Constructs the JComponent representing the LInputField for a single NodeArgument * @param nodeArgument */ private void construct(NodeArgument nodeArgument) { // reset the component removeAll(); // set label text if(nodeArgument.arg().actualParameterName() != null) label.setText(nodeArgument.arg().actualParameterName()); else label.setText(nodeArgument.arg().symbol().name()); label.setFont(DesignPalette.LUDEME_INPUT_FONT); label.setForeground(DesignPalette.FONT_LUDEME_INPUTS_COLOR()); label.setToolTipText(nodeArgument(0).parameterDescription()); optionalLabel.setToolTipText(nodeArgument(0).parameterDescription()); if(nodeArgument.optional()) active = false; // If collection if(parent != null) constructCollection(parent); else if(nodeArgument.collection2D()) constructNonTerminal(nodeArgument); else if(nodeArgument.canBePredefined()) constructHybrid(nodeArgument); else if(nodeArgument.isTerminal()) // If the selected NodeArgument is a terminal NodeArgument stemming from a merged input field (i.e. optional or dynamic) // (nodeArguments.get(0).separateNode()) // Add an option to remove this argument again constructTerminal(nodeArgument, nodeArgument.optional()); else constructNonTerminal(nodeArgument); } /** * Construct the input field for a list of node arguments (optional or dynamic) */ private void construct() { if(nodeArguments.size() == 1) { construct(nodeArgument(0)); return; } // reset the component removeAll(); setLayout(new FlowLayout(FlowLayout.RIGHT)); // add optional label if(optional()) add(optionalLabel); label.setText("Arguments"); label.setFont(DesignPalette.LUDEME_INPUT_FONT); label.setForeground(DesignPalette.FONT_LUDEME_INPUTS_COLOR()); add(label); add(Box.createHorizontalStrut(DesignPalette.INPUTFIELD_PADDING_RIGHT_NONTERMINAL)); connectionComponent = new LConnectionComponent(this, false); fieldComponent = connectionComponent; add(connectionComponent); } /** * Constructs a LInputField for a terminal NodeArgument * @param nodeArgument NodeArgument to construct a LInputField for * @param removable Whether the LInputField can be removed */ private void constructTerminal(NodeArgument nodeArgument, boolean removable) { // check whether a input already exists to auto-fill it Object input = inputArea().LNC().node().providedInputsMap().get(nodeArgument); fieldComponent = generateTerminalComponent(nodeArgument); if(input == null) updateUserInputs(); initializeFieldComponent(); setLayout(new FlowLayout(FlowLayout.LEFT)); add(Box.createHorizontalStrut(DesignPalette.INPUTFIELD_PADDING_LEFT_TERMINAL)); // padding to the left add(label); add(fieldComponent); if(nodeArgument.choice()) { choiceButton.setPreferredSize(buttonSize()); choiceButton.setSize(choiceButton.getPreferredSize()); // resize terminal field accordingly to fit fieldComponent.setPreferredSize(new Dimension(fieldComponent.getPreferredSize().width-choiceButton.getPreferredSize().width, fieldComponent.getPreferredSize().height)); fieldComponent.setSize(fieldComponent.getPreferredSize()); add(choiceButton); //adjustFieldComponentSize(choiceButton); } if(nodeArgument.collection()) { addItemButton.setPreferredSize(buttonSize()); addItemButton.setSize(addItemButton.getPreferredSize()); add(addItemButton); //adjustFieldComponentSize(addItemButton); } if(removable) { add(terminalOptionalLabel); //adjustFieldComponentSize(terminalOptionalLabel); if(inputArea().LNC().node().providedInputsMap().get(nodeArgument(0)) != null) { notifyActivated(); } else { fieldComponent.setEnabled(false); terminalOptionalLabel.setText("+"); } } updateTerminalComponentSize(); adjustFieldComponentSize(Box.createHorizontalStrut(DesignPalette.INPUTFIELD_PADDING_LEFT_TERMINAL)); if(input != null) { if(nodeArgument.collection()) { Object[] inputArray = (Object[]) input; int elementIndex = 0; if(parent != null) { elementIndex = parent.children.indexOf(this) + 1; } if(inputArray[elementIndex] != null) { setUserInput(inputArray[elementIndex]); } } else { setUserInput(input); } } if(input == null && removable) { fieldComponent.setEnabled(false); addItemButton.setEnabled(false); active = false; } } private void initializeFieldComponent() { // set size updateTerminalComponentSize(); // add listeners to update provided inputs when modified if(fieldComponent instanceof JTextField) { for(KeyListener listener : fieldComponent.getKeyListeners().clone()) { fieldComponent.removeKeyListener(listener); } fieldComponent.addKeyListener(userInputListener_keyListener); } else if(fieldComponent instanceof JSpinner) { for(ChangeListener listener : ((JSpinner)fieldComponent).getChangeListeners().clone()) { ((JSpinner) fieldComponent).removeChangeListener(listener); } ((JSpinner) fieldComponent).addChangeListener(userInputListener_change); } else if(fieldComponent instanceof JComboBox) { for(ActionListener listener : ((JComboBox<?>)fieldComponent).getActionListeners().clone()) { ((JComboBox<?>) fieldComponent).removeActionListener(listener); } ((JComboBox<?>) fieldComponent).addActionListener(userInputListener_dropdown); } else { for(PropertyChangeListener listener : fieldComponent.getPropertyChangeListeners().clone()) { fieldComponent.removePropertyChangeListener(listener); } fieldComponent.addPropertyChangeListener(userInputListener_propertyChange); } loadFieldComponentColours(); } private void loadFieldComponentColours() { if(fieldComponent == connectionComponent) { return; } if(fieldComponent instanceof JTextField) { fieldComponent.setBackground(DesignPalette.INPUT_FIELD_BACKGROUND()); fieldComponent.setForeground(DesignPalette.INPUT_FIELD_FOREGROUND()); } else if(fieldComponent instanceof JSpinner) { ((JSpinner) fieldComponent).getEditor().getComponent(0).setBackground(DesignPalette.INPUT_FIELD_BACKGROUND()); ((JSpinner) fieldComponent).getEditor().getComponent(0).setForeground(DesignPalette.INPUT_FIELD_FOREGROUND()); } else if(fieldComponent instanceof JComboBox) { ((JComboBox<?>) fieldComponent).getEditor().getEditorComponent().setBackground(DesignPalette.INPUT_FIELD_BACKGROUND()); ((JComboBox<?>) fieldComponent).getEditor().getEditorComponent().setForeground(DesignPalette.INPUT_FIELD_FOREGROUND()); } else { fieldComponent.setBackground(DesignPalette.INPUT_FIELD_BACKGROUND()); fieldComponent.setForeground(DesignPalette.INPUT_FIELD_FOREGROUND()); } Border b = new LineBorder(DesignPalette.INPUT_FIELD_BORDER_COLOUR(), 1); fieldComponent.setBorder(b); } /** * Constructs a LInputField for a non-terminal NodeArgument * @param nodeArgument NodeArgument to construct a LInputField for */ private void constructNonTerminal(NodeArgument nodeArgument) { // create connection component if(connectionComponent == null) connectionComponent = new LConnectionComponent(this, false); fieldComponent = connectionComponent; // user interacts with the connection component setLayout(new FlowLayout(FlowLayout.RIGHT)); if(nodeArgument.optional()) add(optionalLabel); add(label); if(nodeArgument.choice()) { choiceButton.setPreferredSize(buttonSize()); choiceButton.setSize(choiceButton.getPreferredSize()); add(choiceButton); } if(nodeArgument.collection()) { addItemButton.setPreferredSize(buttonSize()); addItemButton.setSize(addItemButton.getPreferredSize()); add(Box.createHorizontalStrut(DesignPalette.INPUTFIELD_PADDING_RIGHT_NONTERMINAL)); add(addItemButton); } add(Box.createHorizontalStrut(DesignPalette.INPUTFIELD_PADDING_RIGHT_NONTERMINAL)); // padding to the right, distance between label and connection component if(collapsed()) { expandButton.setActive(); expandButton.setPreferredSize(buttonSize()); expandButton.setSize(expandButton.getPreferredSize()); add(expandButton); } else { add(connectionComponent); } if(nodeArgument.optional() && nodeArgument.collection()) { add(Box.createHorizontalStrut(DesignPalette.INPUTFIELD_PADDING_RIGHT_NONTERMINAL)); add(terminalOptionalLabel); if(inputArea().LNC().node().providedInputsMap().get(nodeArgument(0)) != null) { notifyActivated(); } else { fieldComponent.setEnabled(false); terminalOptionalLabel.setText("+"); } } } public void constructHybrid(NodeArgument nodeArgument) { Object input = inputArea().LNC().node().providedInputsMap().get(nodeArgument); // create connection component if(connectionComponent == null) connectionComponent = new LConnectionComponent(this, false); fieldComponent = generateTerminalComponent(nodeArgument); if(input == null) updateUserInputs(); initializeFieldComponent(); setLayout(new FlowLayout(FlowLayout.RIGHT)); add(label); add(fieldComponent); if(nodeArgument.choice()) { choiceButton.setPreferredSize(buttonSize()); choiceButton.setSize(choiceButton.getPreferredSize()); add(choiceButton); //adjustFieldComponentSize(choiceButton); } if(nodeArgument.collection()) { addItemButton.setPreferredSize(buttonSize()); addItemButton.setSize(addItemButton.getPreferredSize()); add(addItemButton); //adjustFieldComponentSize(addItemButton); } if(collapsed()) { expandButton.setActive(); expandButton.setPreferredSize(buttonSize()); expandButton.setSize(expandButton.getPreferredSize()); add(expandButton); //adjustFieldComponentSize(expandButton); } else { add(connectionComponent); if(nodeArgument.optional()) { add(terminalOptionalLabel); if(inputArea().LNC().node().providedInputsMap().get(nodeArgument(0)) != null) { notifyActivated(); } else { fieldComponent.setEnabled(false); terminalOptionalLabel.setText("+"); } } } updateTerminalComponentSize(); if(input != null) { if(nodeArgument.collection()) { Object[] inputArray = (Object[]) input; int elementIndex = 0; if(parent != null) { elementIndex = parent.children.indexOf(this) + 1; } if(inputArray[elementIndex] != null) { setUserInput(inputArray[elementIndex]); } } else { setUserInput(input); } } if(input == null && nodeArgument.optional()) { fieldComponent.setEnabled(false); addItemButton.setEnabled(false); active = false; } } private void adjustFieldComponentSize(Component otherComponent) { fieldComponent.setPreferredSize(new Dimension(fieldComponent.getPreferredSize().width - otherComponent.getPreferredSize().width, fieldComponent.getPreferredSize().height)); fieldComponent.setSize(fieldComponent.getPreferredSize()); } /** * Constructs a new collection child/element input field , below the last child of the collection root/parent * @param parent1 */ private void constructCollection(LInputField parent1) { NodeArgument nodeArgument = parent1.nodeArgument(0); if(nodeArgument.canBePredefined() && !nodeArgument.collection2D()) constructHybridCollection(nodeArgument); else if(!nodeArgument.isTerminal() || nodeArgument.collection2D()) constructCollectionNonTerminal(nodeArgument); else constructCollectionTerminal(nodeArgument); } private void constructCollectionNonTerminal(NodeArgument nodeArgument) { if(connectionComponent == null) connectionComponent = new LConnectionComponent(this, false); fieldComponent = connectionComponent; // user interacts with the connection component setLayout(new FlowLayout(FlowLayout.RIGHT)); add(label); removeItemButton.setPreferredSize(buttonSize()); removeItemButton.setSize(removeItemButton.getPreferredSize()); add(Box.createHorizontalStrut(DesignPalette.INPUTFIELD_PADDING_LEFT_TERMINAL)); add(removeItemButton); add(Box.createHorizontalStrut(DesignPalette.INPUTFIELD_PADDING_RIGHT_NONTERMINAL)); // padding to the right, distance between label and connection component if(collapsed()) { expandButton.setActive(); expandButton.setPreferredSize(buttonSize()); expandButton.setSize(expandButton.getPreferredSize()); add(expandButton); } add(connectionComponent); } private void constructCollectionTerminal(NodeArgument nodeArgument) { // check whether a input already exists to auto-fill it Object input = inputArea().LNC().node().providedInputsMap().get(nodeArgument); fieldComponent = generateTerminalComponent(nodeArgument); if(input == null) updateUserInputs(); initializeFieldComponent(); setLayout(new FlowLayout(FlowLayout.LEFT)); add(Box.createHorizontalStrut(DesignPalette.INPUTFIELD_PADDING_LEFT_TERMINAL)); // padding to the left add(label); add(fieldComponent); removeItemButton.setPreferredSize(buttonSize()); removeItemButton.setSize(removeItemButton.getPreferredSize()); add(removeItemButton); updateTerminalComponentSize(); adjustFieldComponentSize(Box.createHorizontalStrut(DesignPalette.INPUTFIELD_PADDING_LEFT_TERMINAL)); if(input != null) { if(nodeArgument.collection()) { Object[] inputArray = (Object[]) input; int elementIndex = 0; if(parent != null) elementIndex = parent.children.indexOf(this) + 1; if(inputArray[elementIndex] != null) setUserInput(inputArray[elementIndex]); } else { setUserInput(input); } } } public void constructHybridCollection(NodeArgument nodeArgument) { Object input = inputArea().LNC().node().providedInputsMap().get(nodeArgument); // create connection component if(connectionComponent == null) connectionComponent = new LConnectionComponent(this, false); fieldComponent = generateTerminalComponent(nodeArgument); if(input == null) updateUserInputs(); initializeFieldComponent(); setLayout(new FlowLayout(FlowLayout.RIGHT)); add(label); add(fieldComponent); removeItemButton.setPreferredSize(buttonSize()); removeItemButton.setSize(removeItemButton.getPreferredSize()); add(removeItemButton); //adjustFieldComponentSize(removeItemButton); if(collapsed()) { expandButton.setActive(); expandButton.setPreferredSize(buttonSize()); expandButton.setSize(expandButton.getPreferredSize()); add(expandButton); //adjustFieldComponentSize(expandButton); } else { add(connectionComponent); //adjustFieldComponentSize(connectionComponent); } updateTerminalComponentSize(); } /** * Adds a children collection input field */ public void addCollectionItem() { Handler.addCollectionElement(inputArea().LNC().graphPanel().graph(), inputArea().LNC().node(), nodeArgument(0)); } public void notifyCollectionAdded() { LInputField last; // get last children/element of collection if(children.isEmpty()) last = this; else last = children.get(children.size()-1); inputArea().addInputFieldBelow(new LInputField(this), last); // add children field below last element inputArea().drawInputFields(); } /** * Removes this LInputField (children/element of a collection) */ private void removeCollectionItem() { Handler.removeCollectionElement(inputArea().LNC().graphPanel().graph(), inputArea().LNC().node(), nodeArgument(0), parent.children().indexOf(this) + 1); } public void notifyCollectionRemoved() { inputArea().LNC().inputArea().removeInputField(this); parent.children.remove(this); inputArea().drawInputFields(); } /** * * @param nodeArgument * @return a JComponent representing the terminal NodeArgument */ private JComponent generateTerminalComponent(NodeArgument nodeArgument) { ClauseArg arg = nodeArgument.arg(); // A DropDown menu of constant symbols if(nodeArgument.terminalDropdown()) { JComboBox<Symbol> dropdown = new JComboBox<>(); if(inputArea().LNC().isPartOfDefine()) dropdown.addItem(Handler.PARAMETER_SYMBOL); for(Symbol symbol : nodeArgument.constantInputs()) dropdown.addItem(symbol); return dropdown; } // A TextField if(arg.symbol().name().equals("String")) { JTextField field = new JTextField(); if(inputArea().LNC().isPartOfDefine() && !inputArea().LNC().node().isDefineRoot()) { field.setText("<PARAMETER>"); } return field; } // A Integer Spinner if(arg.symbol().name().equals("Integer") || arg.symbol().name().equals("int") || arg.symbol().token().equals("dim")) { JSpinner spinner = new JSpinner(new SpinnerNumberModel(1, 1, Integer.MAX_VALUE, 1)); ((DefaultFormatter) ((JFormattedTextField) spinner.getEditor().getComponent(0)).getFormatter()).setCommitsOnValidEdit(true); return spinner; } // A floating point Spinner if(arg.symbol().token().equals("float")) { JSpinner spinner = new JSpinner(new SpinnerNumberModel(1, 0.01, Float.MAX_VALUE, 0.1)); ((DefaultFormatter) ((JFormattedTextField) spinner.getEditor().getComponent(0)).getFormatter()).setCommitsOnValidEdit(true); return spinner; } if(arg.symbol().token().equals("boolean")) { JComboBox<Symbol> dropdown = new JComboBox<>(); if(inputArea().LNC().isPartOfDefine()) dropdown.addItem(Handler.PARAMETER_SYMBOL); dropdown.addItem(new Symbol(Symbol.LudemeType.Constant, "True", "True", null)); dropdown.addItem(new Symbol(Symbol.LudemeType.Constant, "False", "False", null)); return dropdown; } return new JTextField("Could not generate component: " + arg.symbol().name()); } /** * Removes a NodeArgument from the list of NodeArguments * @param nodeArgument NodeArgument to remove */ public void removeNodeArgument(NodeArgument nodeArgument) { nodeArguments.remove(nodeArgument); if(nodeArguments.size() == 1) reconstruct(); } /** * Reconstructs the InputField * Used when the NodeArgument list changes from merged to single or vice versa */ public void reconstruct() { if(nodeArguments.size() == 1) construct(nodeArguments.get(0)); else construct(); } /** * Notifies the InputField that the Node it is connected to was collapsed */ public void notifyCollapsed() { reconstruct(); } public boolean isActive() { return active; } public void activate() { if(!isTerminal()) return; Handler.activateOptionalTerminalField(inputArea().LNC().graphPanel().graph(), inputArea().LNC().node(), nodeArgument(0), true); } public void notifyActivated() { active = true; fieldComponent.setEnabled(true); fieldComponent.repaint(); addItemButton.setEnabled(true); terminalOptionalLabel.setText("x"); if(!nodeArgument(0).collection()) { Handler.updateInput(inputArea().LNC().graphPanel().graph(), inputArea().LNC().node(), nodeArgument(0), getUserInput()); } repaint(); } public void activateHybrid(boolean activate) { if(!isHybrid()) return; fieldComponent.setEnabled(activate); fieldComponent.setVisible(activate); if(activate) { LudemeNode node = inputArea().LNC().node(); if(node.providedInputsMap().get(nodeArgument(0)) == null) Handler.updateInput(inputArea().LNC().graphPanel().graph(), inputArea().LNC().node(), nodeArgument(0), getUserInput()); else if(node.providedInputsMap().get(nodeArgument(0)) instanceof Object[]) Handler.updateCollectionInput(inputArea().LNC().graphPanel().graph(), inputArea().LNC().node(), nodeArgument(0), getUserInput(), elementIndex()); } repaint(); } public void deactivate() { if(!isTerminal()) return; Handler.activateOptionalTerminalField(inputArea().LNC().graphPanel().graph(), inputArea().LNC().node(), nodeArgument(0), false); } public void notifyDeactivated() { active = false; inputArea().LNC().graphPanel().setBusy(true); fieldComponent.setEnabled(false); addItemButton.setEnabled(false); terminalOptionalLabel.setText("+"); inputArea().removedConnection(LInputField.this); boolean hasChildren = children.size() > 0; for(LInputField child : new ArrayList<>(children)) inputArea().removeInputField(child); // notify handler Handler.updateInput(inputArea().LNC().graphPanel().graph(), inputArea().LNC().node(), nodeArgument(0), null); inputArea().LNC().graphPanel().setBusy(false); children.clear(); if(hasChildren) inputArea().drawInputFields(); repaint(); } public int elementIndex() { if(!nodeArgument(0).collection()) return -1; if(nodeArgument(0).collection() && parent() == null) return 0; return parent().children.indexOf(this)+1; } /** * Listens for changes to a terminal component and updates the model accordingly */ final PropertyChangeListener userInputListener_propertyChange = evt -> updateUserInputs(); final ChangeListener userInputListener_change = evt -> { ((JFormattedTextField) ((JSpinner) fieldComponent).getEditor().getComponent(0)).setValue(((JSpinner) fieldComponent).getValue()); updateUserInputs(); }; final ActionListener userInputListener_dropdown = evt -> updateUserInputs(); /** * Listens for changes via keys to a terminal component and updates the model accordingly */ final KeyListener userInputListener_keyListener = new KeyListener() { @Override public void keyTyped(KeyEvent e) { updateUserInputs(); } @Override public void keyPressed(KeyEvent e) { // Nothing to do } @Override public void keyReleased(KeyEvent e) { updateUserInputs(); } }; final MouseAdapter terminalOptionalLabelListener = new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { super.mouseClicked(e); if(isActive()) deactivate(); else activate(); } }; /** * Sets the input field to the given value * @param input input to set the input field to */ public void setUserInput(Object input) { if(input == null) return; if(nodeArgument(0).collection() && input instanceof Object[]) { IGraphPanel graphPanel = inputArea().LNC().graphPanel(); Object[] inputs = (Object[]) input; for(int i = 1; i < inputs.length; i++) addCollectionItem(); for(int i = 0; i < inputs.length; i++) { Object input_i = inputs[i]; if(input_i == null) { continue; } if(input_i instanceof LudemeNode) { // get correct collection component LConnectionComponent connectionComponentChild; if (i == 0) { connectionComponentChild = connectionComponent; } else { connectionComponentChild = children.get(i-1).connectionComponent(); } Handler.addEdge(graphPanel.graph(), connectionComponentChild.inputField().inputArea().LNC().node(), (LudemeNode) input_i, connectionComponentChild.inputField().nodeArgument(0)); } else { if (i == 0) { setUserInput(input_i); } else { children().get(i-1).setUserInput(input_i); } } } } else if(fieldComponent == connectionComponent) { // then its ludeme input Handler.addEdge(inputArea().LNC().graphPanel().graph(), inputArea().LNC().node(), (LudemeNode) input, nodeArgument(0)); if(((LudemeNode) input).collapsed()) { notifyCollapsed(); } } else { if (fieldComponent instanceof JTextField) { if (input instanceof String) { ((JTextField) fieldComponent).setText((String) input); } else { ((JTextField) fieldComponent).setText(""); } } if (fieldComponent instanceof JSpinner) { if(input instanceof Integer) { ((JSpinner) fieldComponent).setValue(input); } } if (fieldComponent instanceof JComboBox<?> && input instanceof Symbol) { ((JComboBox<?>) fieldComponent).setSelectedItem(input); } } } /** * Updates the model with the current user input * Only works for single input fields */ public void updateUserInputs() { if(inputArea().LNC().graphPanel().isBusy()) return; if(nodeArguments.get(0).collection() && parent() == null && !isActive()) return; if(nodeArguments.get(0).collection() && parent() != null && !parent().isActive()) return; if(nodeArguments.get(0).collection()) { if (inputArea().LNC().node().providedInputsMap().get(nodeArgument(0)) == null) { Object[] in = new Object[1]; in[0] = getUserInput(); Handler.updateInput(LIA.LNC().graphPanel().graph(), LIA.LNC().node(), nodeArgument(0), in); } else { int index = 0; if(parent != null) index = parent.children.indexOf(this)+1; Handler.updateCollectionInput(inputArea().LNC().graphPanel().graph(), inputArea().LNC().node(), nodeArgument(0), getUserInput(), index); } } else Handler.updateInput(LIA.LNC().graphPanel().graph(), LIA.LNC().node(), nodeArgument(0), getUserInput()); } /** * * @return the user supplied input for an input field */ public Object getUserInput() { if(isMerged()) return null; if(parent() == null && optional() && !isActive()) return null; if(fieldComponent == connectionComponent) // Ludeme Input { if(connectionComponent.connectedTo() == null) return null; return connectionComponent.connectedTo().node(); } // Terminal Inputs if(fieldComponent instanceof JTextField) return ((JTextField)fieldComponent).getText(); if(fieldComponent instanceof JSpinner) return ((JSpinner)fieldComponent).getValue(); if(fieldComponent instanceof JComboBox) return ((JComboBox<?>)fieldComponent).getSelectedItem(); return null; } /** * Updates the terminal component size */ private void updateTerminalComponentSize() { fieldComponent.setPreferredSize(null); fieldComponent.setFont(DesignPalette.LUDEME_INPUT_FONT); int preferredWidth = (int) ((DesignPalette.NODE_WIDTH-label.getWidth()) * 0.75); fieldComponent.setPreferredSize(new Dimension(preferredWidth, fieldComponent.getPreferredSize().height)); fieldComponent.setSize(new Dimension(preferredWidth, fieldComponent.getPreferredSize().height)); if(fieldComponent instanceof JComboBox<?>) { fieldComponent.setPreferredSize(new Dimension(preferredWidth, DesignPalette.TERMINAL_INPUT_HEIGHT)); fieldComponent.setSize(new Dimension(preferredWidth, DesignPalette.TERMINAL_INPUT_HEIGHT)); } if(parent!=null && fieldComponent != connectionComponent) adjustFieldComponentSize(removeItemButton); if(nodeArgument(0).collection() && parent() == null && fieldComponent != connectionComponent) adjustFieldComponentSize(addItemButton); if(nodeArgument(0).choice()) adjustFieldComponentSize(choiceButton); if(nodeArgument(0).optional() && fieldComponent == connectionComponent) adjustFieldComponentSize(optionalLabel); if(nodeArgument(0).optional()) adjustFieldComponentSize(terminalOptionalLabel); if(collapsed()) adjustFieldComponentSize(expandButton); if(isHybrid()) adjustFieldComponentSize(connectionComponent); } private Dimension buttonSize() { if(label != null && !label.getText().equals((""))) return new Dimension((int) (label().getPreferredSize().height*buttonWidthPercentage), (int) (label().getPreferredSize().height*buttonWidthPercentage)); if(fieldComponent != null) return new Dimension((int) (fieldComponent.getPreferredSize().height*buttonWidthPercentage), (int) (fieldComponent.getPreferredSize().height*buttonWidthPercentage)); else if(connectionComponent != null) return new Dimension((int) (connectionComponent.getSize().width*buttonWidthPercentage), (int) (connectionComponent.getSize().height*buttonWidthPercentage)); else return null; } /** * * @return Whether this input field is a terminal input field */ public boolean isTerminal() { if(isMerged()) return false; // merged input fields cannot be terminals return nodeArgument(0).isTerminal(); } /** * * @return the list of NodeArguments that this LInputField is associated with */ public List<NodeArgument> nodeArguments() { return nodeArguments; } /** * @param i index of the NodeArgument that this LInputField is associated with * @return the NodeArgument that this LInputField is associated with at index i */ public NodeArgument nodeArgument(int i) { return nodeArguments.get(i); } /** * * @return Whether this LInputFieldNew is associated with more than one NodeArgument */ public boolean isMerged() { return nodeArguments.size() > 1; } public boolean isHybrid() { return nodeArguments.get(0).canBePredefined(); } /** * * @return whether this input field is optional */ public boolean optional() { for(NodeArgument nodeArgument : nodeArguments) if(!nodeArgument.optional()) return false; return true; } /** * * @return whether this input field is a choice */ public boolean choice() { return nodeArgument(0).choice(); } /** * * @return the connection component used to provide an input to a non-terminal input field * or null if this input field represents a terminal input field */ public LConnectionComponent connectionComponent() { return connectionComponent; } /** * * @return the input area that this LInputField is associated with */ public LInputArea inputArea() { return LIA; } /** * * @return list of all node argument indices */ public List<Integer> inputIndices() { List<Integer> indices = new ArrayList<>(); for (NodeArgument nodeArgument : nodeArguments) indices.add(Integer.valueOf(nodeArgument.index())); return indices; } /** * * @return a list of Symbols that can be provided as input to this LInputField */ public List<Symbol> possibleSymbolInputs() { if(isTerminal()) return null; if(!isMerged()) return nodeArgument(0).possibleSymbolInputsExpanded(); List<Symbol> possibleSymbolInputs = new ArrayList<>(); for(NodeArgument nodeArgument : nodeArguments) possibleSymbolInputs.addAll(nodeArgument.possibleSymbolInputsExpanded()); return possibleSymbolInputs; } /** * * @return The parent/root input field of a collection */ public LInputField parent() { return parent; } /** * * @return The list of elements/children of a collection */ public List<LInputField> children() { return children; } /** * Adds a children/element input field to the collection * @param child Element to add */ private void addChildren(LInputField child) { children.add(child); } private boolean collapsed() { if(connectionComponent() == null) return false; else if(connectionComponent().connectedTo() == null) return false; return connectionComponent().connectedTo().node().collapsed(); } /** * * @return the label of this LInputField */ public JLabel label() { return label; } public void setLabelText(String text) { label.setText(text); } @Override protected void paintComponent(Graphics g) { super.paintComponent(g); if(label.getForeground() != DesignPalette.FONT_LUDEME_INPUTS_COLOR()) { label.setForeground(DesignPalette.FONT_LUDEME_INPUTS_COLOR()); optionalLabel.setForeground(DesignPalette.FONT_LUDEME_INPUTS_COLOR()); terminalOptionalLabel.setForeground(DesignPalette.FONT_LUDEME_INPUTS_COLOR()); } if(label.getFont() != DesignPalette.LUDEME_INPUT_FONT) { label.setFont(DesignPalette.LUDEME_INPUT_FONT); optionalLabel.setFont(DesignPalette.LUDEME_INPUT_FONT_ITALIC); terminalOptionalLabel.setFont(DesignPalette.LUDEME_INPUT_FONT); } if(fieldComponent != null && fieldComponent != connectionComponent) updateTerminalComponentSize(); if(fieldComponent != null && fieldComponent.getBackground() != DesignPalette.INPUT_FIELD_BACKGROUND() && !(fieldComponent instanceof JComboBox)) // JComboBox background does not work loadFieldComponentColours(); if(addItemButton.ACTIVE_COLOR != DesignPalette.FONT_LUDEME_INPUTS_COLOR()) { addItemButton.ACTIVE_COLOR = DesignPalette.FONT_LUDEME_INPUTS_COLOR(); addItemButton.ACTIVE_ICON = DesignPalette.COLLECTION_ICON_ACTIVE(); addItemButton.updateDP(); removeItemButton.ACTIVE_COLOR = DesignPalette.FONT_LUDEME_INPUTS_COLOR(); removeItemButton.ACTIVE_ICON = DesignPalette.COLLECTION_REMOVE_ICON_ACTIVE(); removeItemButton.updateDP(); choiceButton.ACTIVE_COLOR = DesignPalette.FONT_LUDEME_INPUTS_COLOR(); choiceButton.ACTIVE_ICON = DesignPalette.CHOICE_ICON_ACTIVE(); choiceButton.updateDP(); expandButton.ACTIVE_COLOR = DesignPalette.FONT_LUDEME_INPUTS_COLOR(); expandButton.ACTIVE_ICON = DesignPalette.UNCOLLAPSE_ICON(); expandButton.updateDP(); } } @Override public String toString() { return "LIF: " + label.getText() + ", " + nodeArguments; } }
47,589
33.838946
214
java
Ludii
Ludii-master/PlayerDesktop/src/app/display/dialogs/visual_editor/view/designPalettes/DesignPalette.java
package app.display.dialogs.visual_editor.view.designPalettes; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Dimension; import java.awt.Font; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.URL; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Objects; import javax.swing.BorderFactory; import javax.swing.ImageIcon; import javax.swing.border.Border; import javax.swing.border.EmptyBorder; import org.json.JSONException; import org.json.JSONObject; import org.json.JSONTokener; /** * Stores colors and fonts for objects in the visual editor * @author Filipp Dokienko */ public class DesignPalette { private static String name = ""; private static DesignPalette instance = null; public static final Dimension DEFAULT_FRAME_SIZE = new Dimension(1200,800); public static final Dimension DEFAULT_GRAPHPANEL_SIZE = new Dimension(10000,10000); public static float SCALAR = 1f; // SIZES ================================================================ private static int DEFAULT_NODE_WIDTH = 220; // small: 200, default: 220, bigger: 250 big: 250 private static int DEFAULT_TERMINAL_INPUT_HEIGHT = 20; // small: 17, default, bigger: 20, big: 24 private static int DEFAULT_LUDEME_TITLE_FONT_SIZE = 14; // small: 10, default, bigger 14, big: 18 private static int DEFAULT_LUDEME_INPUT_FONT_SIZE = 13; // small: 10, default, bigger: 13, big: 16 public static void makeSizeSmall() { DEFAULT_NODE_WIDTH = 180; DEFAULT_TERMINAL_INPUT_HEIGHT = 17; DEFAULT_LUDEME_TITLE_FONT_SIZE = 10; DEFAULT_LUDEME_INPUT_FONT_SIZE = 10; SCALAR = 1f; scale(SCALAR); } public static void makeSizeMedium() { DEFAULT_NODE_WIDTH = 220; DEFAULT_TERMINAL_INPUT_HEIGHT = 20; DEFAULT_LUDEME_TITLE_FONT_SIZE = 14; DEFAULT_LUDEME_INPUT_FONT_SIZE = 13; SCALAR = 1f; scale(SCALAR); } public static void makeSizeLarge() { DEFAULT_NODE_WIDTH = 250; DEFAULT_TERMINAL_INPUT_HEIGHT = 24; DEFAULT_LUDEME_TITLE_FONT_SIZE = 18; DEFAULT_LUDEME_INPUT_FONT_SIZE = 16; SCALAR = 1f; scale(SCALAR); } public static int NODE_WIDTH = (int) (DEFAULT_NODE_WIDTH * SCALAR); public static int TERMINAL_INPUT_HEIGHT = (int) (DEFAULT_TERMINAL_INPUT_HEIGHT * SCALAR); private static int LUDEME_INPUT_FONT_SIZE = (int) (DEFAULT_LUDEME_INPUT_FONT_SIZE * (1.0/SCALAR)); public static int LUDEME_TITLE_FONT_SIZE = (int) (DEFAULT_LUDEME_TITLE_FONT_SIZE * SCALAR); // COLOURS ================================================================ private static final String PALETTE_FILE_PATH = "/lve_palettes/"; private static final String DEFAULT_PALETTE_FILE_NAME = "Pastel"; // PANELS // private static Color BACKGROUND_EDITOR; private static Color BACKGROUND_VISUAL_HELPER; private static Color BACKGROUND_HEADER_PANEL; // NODE BACKGROUNDS // private static Color BACKGROUND_LUDEME_BODY; private static Color BACKGROUND_LUDEME_BODY_EQUIPMENT; private static Color BACKGROUND_LUDEME_BODY_FUNCTIONS; private static Color BACKGROUND_LUDEME_BODY_RULES; private static Color BACKGROUND_LUDEME_BODY_DEFINE; private static Color INPUT_FIELD_BACKGROUND; // NODE BORDERS // private static Color LUDEME_BORDER_COLOR; private static Color LUDEME_SELECTION_COLOR; private static Color LUDEME_UNCOMPILABLE_COLOR; private static Color INPUT_FIELD_BORDER_COLOUR; // CONNECTIONS private static Color LUDEME_CONNECTION_POINT; private static Color LUDEME_CONNECTION_POINT_INACTIVE; private static Color LUDEME_CONNECTION_EDGE; // FONTS private static Color FONT_LUDEME_TITLE_COLOR; private static Color FONT_LUDEME_INPUTS_COLOR; private static Color INPUT_FIELD_FOREGROUND; // PLAY BUTTON private static Color PLAY_BUTTON_FOREGROUND ; private static Color COMPILABLE_COLOR; private static Color NOT_COMPILABLE_COLOR; // TOOL PANEL private static Color HEADER_BUTTON_ACTIVE_COLOR; private static Color HEADER_BUTTON_INACTIVE_COLOR; private static final Color HEADER_BUTTON_HOVER_COLOR = new Color(127,191,255); public DesignPalette() { loadPalette(DEFAULT_PALETTE_FILE_NAME); } public static DesignPalette instance() { if (instance == null) instance = new DesignPalette(); return instance; } @SuppressWarnings("resource") public static List<String> palettes() { final List<String> names = new ArrayList<>(); try { try (BufferedReader br = new BufferedReader(new InputStreamReader(Objects.requireNonNull(DesignPalette.class.getResourceAsStream(PALETTE_FILE_PATH))))) { System.out.println("Loading palettes..."); br.lines().forEach(line -> { System.out.println(line); if(line.endsWith(".json")) { names.add(line.replace(".json", "")); } }); br.close(); } } catch(final Exception e) { e.printStackTrace(); } return names; } public static void loadPalette(final String paletteName) { System.out.println("Loading palette: " + paletteName); // read json final JSONObject palette = readPaletteJSON(paletteName); if(palette == null) { System.out.println("Palette not found"); return; } // set colours setColours(palette.toMap()); } private static JSONObject readPaletteJSON(final String paletteName) { try (InputStream is = DesignPalette.class.getResourceAsStream(PALETTE_FILE_PATH + paletteName + ".json")) { if(is == null) return null; final JSONObject obj = new JSONObject(new JSONTokener(is)); try { is.close(); } catch (final IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return obj; } catch (JSONException | IOException e) { // TODO Auto-generated catch block e.printStackTrace(); return null; } } private static void setColours(final Map<String, Object> palette) { for(final Map.Entry<String, Object> entry : palette.entrySet()) { final String key = entry.getKey(); final String value = (String) entry.getValue(); if(key.equals("name")) { name = value; } else if(key.equals("icons")) { setIcons(value); } else { setColour(key, Color.decode(value)); } } } private static void setColour(final String name, final Color colour) { switch(name.toLowerCase()) { case "editor_background": BACKGROUND_EDITOR = colour; break; case "background_grid_colour": BACKGROUND_VISUAL_HELPER = colour; break; case "header_background": BACKGROUND_HEADER_PANEL = colour; break; case "default_node_background": BACKGROUND_LUDEME_BODY = colour; break; case "rule_node_background": BACKGROUND_LUDEME_BODY_RULES = colour; break; case "equipment_node_background": BACKGROUND_LUDEME_BODY_EQUIPMENT = colour; break; case "functions_node_background": BACKGROUND_LUDEME_BODY_FUNCTIONS = colour; break; case "define_node_background": BACKGROUND_LUDEME_BODY_DEFINE = colour; break; case "input_field_background": INPUT_FIELD_BACKGROUND = colour; break; case "connection_point_colour": LUDEME_CONNECTION_POINT = colour; break; case "connection_point_inactive_colour": LUDEME_CONNECTION_POINT_INACTIVE = colour; break; case "edge_colour": LUDEME_CONNECTION_EDGE = colour; break; case "play_button_background": COMPILABLE_COLOR = colour; break; case "uncompilable_button_background": NOT_COMPILABLE_COLOR = colour; break; case "play_button_font": PLAY_BUTTON_FOREGROUND = colour; break; case "node_border": LUDEME_BORDER_COLOR = colour; LUDEME_NODE_BORDER = BorderFactory.createLineBorder(LUDEME_BORDER_COLOR(), NODE_BORDER_WIDTH); break; case "node_selected_border": LUDEME_SELECTION_COLOR = colour; LUDEME_NODE_BORDER_SELECTED = BorderFactory.createLineBorder(LUDEME_SELECTION_COLOR(), NODE_BORDER_WIDTH); break; case "node_uncompilable_border": LUDEME_UNCOMPILABLE_COLOR = colour; LUDEME_NODE_BORDER_UNCOMPILABLE = BorderFactory.createLineBorder(LUDEME_UNCOMPILABLE_COLOR(), NODE_BORDER_WIDTH); break; case "node_title_font": FONT_LUDEME_TITLE_COLOR = colour; break; case "node_body_font": FONT_LUDEME_INPUTS_COLOR = colour; break; case "input_field_border": INPUT_FIELD_BORDER_COLOUR = colour; break; case "input_field_font": INPUT_FIELD_FOREGROUND = colour; break; case "tool_panel_active_font": HEADER_BUTTON_ACTIVE_COLOR = colour; break; case "tool_panel_inactive_font": HEADER_BUTTON_INACTIVE_COLOR = colour; break; default: System.out.println("Colour not found : " + name); break; } } private static void setIcons(final String style) { switch(style) { case "dark": CHOICE_ICON_ACTIVE = getIcon("node/dark/active/choice.png"); COLLECTION_ICON_ACTIVE = getIcon("node/dark/active/collection_add.png"); COLLECTION_REMOVE_ICON_ACTIVE = getIcon("node/dark/active/collection_remove.png"); DOWN_ICON = getIcon("node/dark/active/down.png"); UNCOLLAPSE_ICON = getIcon("node/dark/active/uncollapse.png"); COLLAPSE_ICON = getIcon("node/dark/active/collapse.png"); GAME_EDITOR_INACTIVE = getIcon("editor/active/game_editor.png"); GAME_EDITOR_ACTIVE = getIcon("editor/inactive/game_editor.png"); DEFINE_EDITOR_INACTIVE = getIcon("editor/active/define_editor.png"); DEFINE_EDITOR_ACTIVE = getIcon("editor/inactive/define_editor.png"); TEXT_EDITOR_INACTIVE = getIcon("editor/active/text_editor.png"); TEXT_EDITOR_ACTIVE = getIcon("editor/inactive/text_editor.png"); SELECT_INACTIVE = getIcon("editor/active/select.png"); SELECT_ACTIVE = getIcon("editor/inactive/select.png"); UNDO_INACTIVE = getIcon("editor/active/undo.png"); UNDO_ACTIVE = getIcon("editor/inactive/undo.png"); REDO_INACTIVE = getIcon("editor/active/redo.png"); REDO_ACTIVE = getIcon("editor/inactive/redo.png"); break; case "light": default: CHOICE_ICON_ACTIVE = getIcon("node/active/choice.png"); COLLECTION_ICON_ACTIVE = getIcon("node/active/collection_add.png"); COLLECTION_REMOVE_ICON_ACTIVE = getIcon("node/active/collection_remove.png"); DOWN_ICON = getIcon("node/active/down.png"); UNCOLLAPSE_ICON = getIcon("node/active/uncollapse.png"); COLLAPSE_ICON = getIcon("node/active/collapse.png"); GAME_EDITOR_ACTIVE = getIcon("editor/active/game_editor.png"); GAME_EDITOR_INACTIVE = getIcon("editor/inactive/game_editor.png"); DEFINE_EDITOR_ACTIVE = getIcon("editor/active/define_editor.png"); DEFINE_EDITOR_INACTIVE = getIcon("editor/inactive/define_editor.png"); TEXT_EDITOR_ACTIVE = getIcon("editor/active/text_editor.png"); TEXT_EDITOR_INACTIVE = getIcon("editor/inactive/text_editor.png"); SELECT_ACTIVE = getIcon("editor/active/select.png"); SELECT_INACTIVE = getIcon("editor/inactive/select.png"); UNDO_ACTIVE = getIcon("editor/active/undo.png"); UNDO_INACTIVE = getIcon("editor/inactive/undo.png"); REDO_ACTIVE = getIcon("editor/active/redo.png"); REDO_INACTIVE = getIcon("editor/inactive/redo.png"); break; } } @SuppressWarnings("static-method") public String name() { return name; } private static final int DEFAULT_INPUTAREA_PADDING_BOTTOM = 12; public static int INPUTAREA_PADDING_BOTTOM = (int) (DEFAULT_INPUTAREA_PADDING_BOTTOM * SCALAR); private static final int DEFAULT_HEADER_PADDING_BOTTOM = 3; public static int HEADER_PADDING_BOTTOM = (int) (DEFAULT_HEADER_PADDING_BOTTOM * SCALAR); private static final int DEFAULT_HEADER_PADDING_TOP = 10; public static int HEADER_PADDING_TOP = (int) (DEFAULT_HEADER_PADDING_TOP * SCALAR); private static final int DEFAULT_INPUTFIELD_PADDING_LEFT_TERMINAL = 10; public static int INPUTFIELD_PADDING_LEFT_TERMINAL = (int) (DEFAULT_INPUTFIELD_PADDING_LEFT_TERMINAL * SCALAR); private static final int DEFAULT_INPUTFIELD_PADDING_RIGHT_NONTERMINAL = 5; public static int INPUTFIELD_PADDING_RIGHT_NONTERMINAL = (int) (DEFAULT_INPUTFIELD_PADDING_RIGHT_NONTERMINAL * SCALAR); private static final int DEFAULT_HEADER_TITLE_CONNECTION_SPACE = 5; public static int HEADER_TITLE_CONNECTION_SPACE = (int) (DEFAULT_HEADER_TITLE_CONNECTION_SPACE * SCALAR); private static final float DEFAULT_CONNECTION_STROKE_WIDTH = 2f; public static float CONNECTION_STROKE_WIDTH = DEFAULT_CONNECTION_STROKE_WIDTH * SCALAR; private static final int DEFAULT_NODE_BORDER_WIDTH = 2; public static int NODE_BORDER_WIDTH = (int) (DEFAULT_NODE_BORDER_WIDTH * SCALAR); private static final int DEFAULT_BACKGROUND_DOT_DIAMETER = 4; private static final int DEFAULT_BACKGROUND_LINE_WIDTH = 1; public static int BACKGROUND_DOT_DIAMETER = (int) (DEFAULT_BACKGROUND_DOT_DIAMETER * SCALAR); public static final int BACKGROUND_LINE_WIDTH = DEFAULT_BACKGROUND_LINE_WIDTH; private static final int DEFAULT_BACKGROUND_DOT_PADDING = 25; private static final int DEFAULT_BACKGROUND_LINE_PADDING = 25; public static int BACKGROUND_DOT_PADDING = (int) (DEFAULT_BACKGROUND_DOT_PADDING * SCALAR); public static int BACKGROUND_LINE_PADDING = (int) (DEFAULT_BACKGROUND_LINE_PADDING * SCALAR); public static void scale(final float scalar) { SCALAR *= scalar; SCALAR = (float) Math.min(2.0, Math.max(0.85, SCALAR)); NODE_WIDTH = (int) (DEFAULT_NODE_WIDTH * (1.0/SCALAR)); TERMINAL_INPUT_HEIGHT = (int) (DEFAULT_TERMINAL_INPUT_HEIGHT * (1.0/SCALAR)); LUDEME_INPUT_FONT_SIZE = (int) (DEFAULT_LUDEME_INPUT_FONT_SIZE * (1.0/SCALAR)); LUDEME_TITLE_FONT_SIZE = (int) (DEFAULT_LUDEME_TITLE_FONT_SIZE * (1.0/SCALAR)); INPUTAREA_PADDING_BOTTOM = (int) (DEFAULT_INPUTAREA_PADDING_BOTTOM * (1.0/SCALAR)); HEADER_PADDING_BOTTOM = (int) (DEFAULT_HEADER_PADDING_BOTTOM * (1.0/SCALAR)); HEADER_PADDING_TOP = (int) (DEFAULT_HEADER_PADDING_TOP * (1.0/SCALAR)); INPUTFIELD_PADDING_LEFT_TERMINAL = (int) (DEFAULT_INPUTFIELD_PADDING_LEFT_TERMINAL * (1.0/SCALAR)); INPUTFIELD_PADDING_RIGHT_NONTERMINAL = (int) (DEFAULT_INPUTFIELD_PADDING_RIGHT_NONTERMINAL * (1.0/SCALAR)); HEADER_TITLE_CONNECTION_SPACE = (int) (DEFAULT_HEADER_TITLE_CONNECTION_SPACE * (1.0/SCALAR)); CONNECTION_STROKE_WIDTH = (float) (DEFAULT_CONNECTION_STROKE_WIDTH * (1.0/SCALAR)); NODE_BORDER_WIDTH = (int) (DEFAULT_NODE_BORDER_WIDTH * (1.0/SCALAR)); BACKGROUND_DOT_DIAMETER = (int) (DEFAULT_BACKGROUND_DOT_DIAMETER * (1.0/SCALAR)); BACKGROUND_DOT_PADDING = (int) (DEFAULT_BACKGROUND_DOT_PADDING * (1.0/SCALAR)); BACKGROUND_LINE_PADDING = (int) (DEFAULT_BACKGROUND_LINE_PADDING * (1.0/SCALAR)); LUDEME_TITLE_FONT = new Font("Arial", Font.BOLD, LUDEME_TITLE_FONT_SIZE); LUDEME_INPUT_FONT = new Font("Arial", Font.PLAIN, LUDEME_INPUT_FONT_SIZE); LUDEME_INPUT_FONT_ITALIC = new Font("Arial", Font.ITALIC, LUDEME_INPUT_FONT_SIZE); LUDEME_EDGE_STROKE = new BasicStroke(CONNECTION_STROKE_WIDTH, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND); LUDEME_NODE_BORDER = BorderFactory.createLineBorder(DesignPalette.LUDEME_BORDER_COLOR(), NODE_BORDER_WIDTH); LUDEME_NODE_BORDER_SELECTED = BorderFactory.createLineBorder(DesignPalette.LUDEME_SELECTION_COLOR(), NODE_BORDER_WIDTH); LUDEME_NODE_BORDER_UNCOMPILABLE = BorderFactory.createLineBorder(DesignPalette.LUDEME_UNCOMPILABLE_COLOR(), NODE_BORDER_WIDTH); INPUT_AREA_PADDING_BORDER = new EmptyBorder(0,0,DesignPalette.INPUTAREA_PADDING_BOTTOM,0); HEADER_PADDING_BORDER = new EmptyBorder(DesignPalette.HEADER_PADDING_TOP,0,DesignPalette.HEADER_PADDING_BOTTOM,0); } public static Color BACKGROUND_EDITOR() { return BACKGROUND_EDITOR; } public static Color BACKGROUND_VISUAL_HELPER() { return BACKGROUND_VISUAL_HELPER; } public static Color BACKGROUND_HEADER_PANEL() { return BACKGROUND_HEADER_PANEL; } public static Color FONT_LUDEME_INPUTS_COLOR() { return FONT_LUDEME_INPUTS_COLOR; } public static Color FONT_LUDEME_TITLE_COLOR() { return FONT_LUDEME_TITLE_COLOR; } public static Color BACKGROUND_LUDEME_BODY() { return BACKGROUND_LUDEME_BODY; } public static Color BACKGROUND_LUDEME_BODY_EQUIPMENT() { return BACKGROUND_LUDEME_BODY_EQUIPMENT; } public static Color BACKGROUND_LUDEME_BODY_FUNCTIONS() { return BACKGROUND_LUDEME_BODY_FUNCTIONS; } public static Color BACKGROUND_LUDEME_BODY_RULES() { return BACKGROUND_LUDEME_BODY_RULES; } public static Color BACKGROUND_LUDEME_BODY_DEFINE() { return BACKGROUND_LUDEME_BODY_DEFINE; } public static Color LUDEME_BORDER_COLOR() { return LUDEME_BORDER_COLOR; } public static Color LUDEME_SELECTION_COLOR() { return LUDEME_SELECTION_COLOR; } public static Color LUDEME_UNCOMPILABLE_COLOR() { return LUDEME_UNCOMPILABLE_COLOR; } public static Color LUDEME_CONNECTION_POINT() { return LUDEME_CONNECTION_POINT; } public static Color LUDEME_CONNECTION_POINT_INACTIVE() { return LUDEME_CONNECTION_POINT_INACTIVE; } public static Color LUDEME_CONNECTION_EDGE() { return LUDEME_CONNECTION_EDGE; } public static Color COMPILABLE_COLOR() { return COMPILABLE_COLOR; } public static Color NOT_COMPILABLE_COLOR() { return NOT_COMPILABLE_COLOR; } public static Color PLAY_BUTTON_FOREGROUND() { return PLAY_BUTTON_FOREGROUND; } public static Color INPUT_FIELD_BACKGROUND() { return INPUT_FIELD_BACKGROUND; } public static Color INPUT_FIELD_BORDER_COLOUR() { return INPUT_FIELD_BORDER_COLOUR; } public static Color INPUT_FIELD_FOREGROUND() { return INPUT_FIELD_FOREGROUND; } // LUDEME BLOCK // public static Font LUDEME_TITLE_FONT = new Font("Arial", Font.BOLD, LUDEME_TITLE_FONT_SIZE); public static Font LUDEME_INPUT_FONT = new Font("Arial", Font.PLAIN, LUDEME_INPUT_FONT_SIZE); public static Font LUDEME_INPUT_FONT_ITALIC = new Font("Arial", Font.ITALIC, LUDEME_INPUT_FONT_SIZE); // ~~ ICONS ~~ // // FRAME // public static final ImageIcon LUDII_ICON = new ImageIcon(Objects.requireNonNull(DesignPalette.class.getResource("/ludii-logo-64x64.png"))); // HEADER EDITORS // public static final ImageIcon COMPILABLE_ICON = getIcon("editor/play.png"); public static final ImageIcon NOT_COMPILABLE_ICON = getIcon("editor/not_compilable.png"); private static ImageIcon GAME_EDITOR_ACTIVE = getIcon("editor/active/game_editor.png"); private static ImageIcon GAME_EDITOR_INACTIVE = getIcon("editor/inactive/game_editor.png"); private static final ImageIcon GAME_EDITOR_HOVER = getIcon("editor/hover/game_editor.png"); private static ImageIcon DEFINE_EDITOR_ACTIVE = getIcon("editor/active/define_editor.png"); private static ImageIcon DEFINE_EDITOR_INACTIVE = getIcon("editor/inactive/define_editor.png"); private static final ImageIcon DEFINE_EDITOR_HOVER = getIcon("editor/hover/define_editor.png"); private static ImageIcon TEXT_EDITOR_ACTIVE = getIcon("editor/active/text_editor.png"); private static ImageIcon TEXT_EDITOR_INACTIVE = getIcon("editor/inactive/text_editor.png"); private static final ImageIcon TEXT_EDITOR_HOVER = getIcon("editor/hover/text_editor.png"); // HEADER TOOLS // private static ImageIcon SELECT_ACTIVE = getIcon("editor/active/select.png"); private static ImageIcon SELECT_INACTIVE = getIcon("editor/inactive/select.png"); private static final ImageIcon SELECT_HOVER = getIcon("editor/hover/select.png"); private static ImageIcon UNDO_ACTIVE = getIcon("editor/active/undo.png"); private static ImageIcon UNDO_INACTIVE = getIcon("editor/inactive/undo.png"); private static final ImageIcon UNDO_HOVER = getIcon("editor/hover/undo.png"); private static ImageIcon REDO_ACTIVE = getIcon("editor/active/redo.png"); private static ImageIcon REDO_INACTIVE = getIcon("editor/inactive/redo.png"); private static final ImageIcon REDO_HOVER = getIcon("editor/hover/redo.png"); public static ImageIcon GAME_EDITOR_ACTIVE() { return GAME_EDITOR_ACTIVE; } public static ImageIcon GAME_EDITOR_INACTIVE() { return GAME_EDITOR_INACTIVE; } public static ImageIcon GAME_EDITOR_HOVER() { return GAME_EDITOR_HOVER; } public static ImageIcon DEFINE_EDITOR_ACTIVE() { return DEFINE_EDITOR_ACTIVE; } public static ImageIcon DEFINE_EDITOR_INACTIVE() { return DEFINE_EDITOR_INACTIVE; } public static ImageIcon DEFINE_EDITOR_HOVER() { return DEFINE_EDITOR_HOVER; } public static ImageIcon TEXT_EDITOR_ACTIVE() { return TEXT_EDITOR_ACTIVE; } public static ImageIcon TEXT_EDITOR_INACTIVE() { return TEXT_EDITOR_INACTIVE; } public static ImageIcon TEXT_EDITOR_HOVER() { return TEXT_EDITOR_HOVER; } public static ImageIcon SELECT_ACTIVE() { return SELECT_ACTIVE; } public static ImageIcon SELECT_INACTIVE() { return SELECT_INACTIVE; } public static ImageIcon SELECT_HOVER() { return SELECT_HOVER; } public static ImageIcon UNDO_ACTIVE() { return UNDO_ACTIVE; } public static ImageIcon UNDO_INACTIVE() { return UNDO_INACTIVE; } public static ImageIcon UNDO_HOVER() { return UNDO_HOVER; } public static ImageIcon REDO_ACTIVE() { return REDO_ACTIVE; } public static ImageIcon REDO_INACTIVE() { return REDO_INACTIVE; } public static ImageIcon REDO_HOVER() { return REDO_HOVER; } public static Color HEADER_BUTTON_ACTIVE_COLOR() { return HEADER_BUTTON_ACTIVE_COLOR; } public static Color HEADER_BUTTON_INACTIVE_COLOR() { return HEADER_BUTTON_INACTIVE_COLOR; } public static Color HEADER_BUTTON_HOVER_COLOR() { return HEADER_BUTTON_HOVER_COLOR; } // LUDEME BLOCK // private static ImageIcon CHOICE_ICON_ACTIVE = getIcon("node/active/choice.png"); private static final ImageIcon CHOICE_ICON_HOVER = getIcon("node/hover/choice.png"); private static ImageIcon COLLECTION_ICON_ACTIVE = getIcon("node/active/collection_add.png"); private static final ImageIcon COLLECTION_ICON_HOVER = getIcon("node/hover/collection_add.png"); private static final ImageIcon COLLECTION_REMOVE_ICON_HOVER = getIcon("node/hover/collection_remove.png"); private static ImageIcon COLLECTION_REMOVE_ICON_ACTIVE = getIcon("node/active/collection_remove.png"); private static ImageIcon DOWN_ICON = getIcon("node/active/down.png"); private static ImageIcon UNCOLLAPSE_ICON = getIcon("node/active/uncollapse.png"); public static ImageIcon UNCOLLAPSE_ICON_HOVER = getIcon("node/hover/uncollapse.png"); private static ImageIcon COLLAPSE_ICON = getIcon("popup/collapse.png"); public static ImageIcon CHOICE_ICON_ACTIVE() { return CHOICE_ICON_ACTIVE; } public static ImageIcon CHOICE_ICON_HOVER() { return CHOICE_ICON_HOVER; } public static ImageIcon COLLECTION_ICON_ACTIVE() { return COLLECTION_ICON_ACTIVE; } public static ImageIcon COLLECTION_ICON_HOVER() { return COLLECTION_ICON_HOVER; } public static ImageIcon COLLECTION_REMOVE_ICON_ACTIVE() { return COLLECTION_REMOVE_ICON_ACTIVE; } public static ImageIcon COLLECTION_REMOVE_ICON_HOVER() { return COLLECTION_REMOVE_ICON_HOVER; } public static ImageIcon DOWN_ICON() { return DOWN_ICON; } public static ImageIcon COLLAPSE_ICON() { return COLLAPSE_ICON; } public static ImageIcon UNCOLLAPSE_ICON() { return UNCOLLAPSE_ICON; } public static ImageIcon UNCOLLAPSE_ICON_HOVER() { return UNCOLLAPSE_ICON_HOVER; } public static final ImageIcon DELETE_ICON = getIcon("popup/delete.png"); public static final ImageIcon COPY_ICON = getIcon("popup/copy.png"); public static final ImageIcon PASTE_ICON = getIcon("popup/paste.png"); public static final ImageIcon DUPLICATE_ICON = getIcon("popup/duplicate.png"); public static final ImageIcon ADD_ICON = getIcon("popup/add.png"); // ~~ STROKES AND BORDERS ~~ // private static Border LUDEME_NODE_BORDER = BorderFactory.createLineBorder(LUDEME_BORDER_COLOR(), NODE_BORDER_WIDTH); private static Border LUDEME_NODE_BORDER_SELECTED = BorderFactory.createLineBorder(LUDEME_SELECTION_COLOR(), NODE_BORDER_WIDTH); private static Border LUDEME_NODE_BORDER_UNCOMPILABLE = BorderFactory.createLineBorder(LUDEME_UNCOMPILABLE_COLOR(), NODE_BORDER_WIDTH); public static Border LUDEME_NODE_BORDER() { return LUDEME_NODE_BORDER; } public static Border LUDEME_NODE_BORDER_SELECTED() { return LUDEME_NODE_BORDER_SELECTED; } public static Border LUDEME_NODE_BORDER_UNCOMPILABLE() { return LUDEME_NODE_BORDER_UNCOMPILABLE; } public static BasicStroke LUDEME_EDGE_STROKE = new BasicStroke(CONNECTION_STROKE_WIDTH, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND); public static EmptyBorder INPUT_AREA_PADDING_BORDER = new EmptyBorder(0,0,DesignPalette.INPUTAREA_PADDING_BOTTOM,0); public static EmptyBorder HEADER_PADDING_BORDER = new EmptyBorder(DesignPalette.HEADER_PADDING_TOP,0,DesignPalette.HEADER_PADDING_BOTTOM,0); private static URL getIconURL(final String path) { return DesignPalette.class.getResource("/visual_editor/"+path); } private static ImageIcon getIcon(final String path) { return new ImageIcon(getIconURL(path)); } }
28,237
33.818742
163
java
Ludii
Ludii-master/PlayerDesktop/src/app/display/dialogs/visual_editor/view/panels/IGraphPanel.java
package app.display.dialogs.visual_editor.view.panels; import app.display.dialogs.visual_editor.LayoutManagement.LayoutHandler; import app.display.dialogs.visual_editor.model.DescriptionGraph; import app.display.dialogs.visual_editor.model.LudemeNode; import app.display.dialogs.visual_editor.model.NodeArgument; import app.display.dialogs.visual_editor.model.interfaces.iGNode; import app.display.dialogs.visual_editor.view.components.ludemenodecomponent.LudemeNodeComponent; import app.display.dialogs.visual_editor.view.panels.editor.ConnectionHandler; import javax.swing.*; import java.awt.*; import java.util.List; public interface IGraphPanel { // When Handler changes the graph /** Whether this panel is of a define graph. */ boolean isDefineGraph(); /** Notifies the panel that a node was added to the graph. */ void notifyNodeAdded(LudemeNode node, boolean connect); /** Notifies the panel that a node was removed from the graph. */ void notifyNodeRemoved(LudemeNodeComponent lnc); /** Notifies the panel that an edge between two nodes was established, outgoing from a given input field index */ void notifyEdgeAdded(LudemeNodeComponent from, LudemeNodeComponent to, int inputFieldIndex); /** Notifies the panel that an edge between two nodes was established, outgoing from an input field with a given NodeArgument */ void notifyEdgeAdded(LudemeNodeComponent from, LudemeNodeComponent to, NodeArgument inputFieldArgument); /** Notifies the panel that a collection edge between two nodes was removed, outgoing from an input field with a given NodeArgument */ void notifyEdgeAdded(LudemeNodeComponent from, LudemeNodeComponent to, NodeArgument inputFieldArgument, int elementIndex); /** Notifies the panel that an edge between two nodes was removed */ void notifyEdgeRemoved(LudemeNodeComponent from, LudemeNodeComponent to); /** Notifies the panel that an edge between two nodes was removed , of a collection */ void notifyEdgeRemoved(LudemeNodeComponent from, LudemeNodeComponent to, int elementIndex); /** Notifies the panel that a node was collapsed/expanded */ void notifyCollapsed(LudemeNodeComponent lnc, boolean collapsed); /** Notifies the panel that a node's inputs were updated */ void notifyInputsUpdated(LudemeNodeComponent lnc); /** Notifies the panel that a collection element was added to a node */ void notifyCollectionAdded(LudemeNodeComponent lnc, NodeArgument inputFieldArgument, int elementIndex); /*+ Notifies the panel that a node's collection element was removed */ void notifyCollectionRemoved(LudemeNodeComponent lnc, NodeArgument inputFieldArgument, int elementIndex); /** Notifies the panel that the node's selected clause was changed */ void notifySelectedClauseChanged(LudemeNodeComponent lnc); /** Notifies the panel that a node's optional terminal input was activated/deactivated */ void notifyTerminalActivated(LudemeNodeComponent lnc, NodeArgument inputFieldArgument, boolean activated); /** Notifies the panel about an updated collapsed-status of a list of nodes */ void updateCollapsed(List<LudemeNodeComponent> lncs); /** Returns the ScrollPane this panel is in */ JScrollPane parentScrollPane(); JPanel panel(); /** Whether the graph is currently busy (e.g. a node is being added) */ boolean isBusy(); /** Updates the busy-status */ void setBusy(boolean b); /** Returns the DescriptionGraph this Panel represents */ DescriptionGraph graph(); /** Returns the ConnectionHandler for this panel */ ConnectionHandler connectionHandler(); /** Finds the LudemeNodeComponent for a given LudemeNode */ LudemeNodeComponent nodeComponent(LudemeNode node); /** */ void enterSelectionMode(); /** */ boolean isSelectionMode(); /** */ Rectangle exitSelectionMode(); /** Adds a node to the list of selected nodes */ void addNodeToSelections(LudemeNodeComponent lnc); /** List of selected nodes */ List<iGNode> selectedNodes(); /** List of selected nodes */ List<LudemeNodeComponent> selectedLnc(); /** Selects all nodes */ void selectAllNodes(); /** Unselects all nodes */ void deselectEverything(); /** Displays all available ludemes that may be created */ void showAllAvailableLudemes(); /** Notifies the panel that the user clicked on a node */ void clickedOnNode(LudemeNodeComponent lnc); /** The LayoutHandler */ LayoutHandler getLayoutHandler(); /** Updates the Graph (position of nodes, etc.) */ void updateGraph(); /** */ void syncNodePositions(); /** Repaints the graph */ void repaint(); }
4,727
48.25
138
java
Ludii
Ludii-master/PlayerDesktop/src/app/display/dialogs/visual_editor/view/panels/NodeHelp.java
package app.display.dialogs.visual_editor.view.panels; import app.display.dialogs.visual_editor.model.LudemeNode; import main.grammar.Clause; import main.grammar.ClauseArg; import javax.swing.*; import java.awt.event.ItemEvent; import java.util.HashMap; /** * Displays the help information for a node. */ public class NodeHelp extends JDialog { private static final long serialVersionUID = 1L; private final LudemeNode node; private final JLabel parameterDescriptions = new JLabel(); public NodeHelp(LudemeNode node) { this.node = node; setTitle("Help: " + node.symbol().name()); setSize(300, 300); setLocationRelativeTo(null); setModal(true); setResizable(false); setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); setLayout(new BoxLayout(getContentPane(), BoxLayout.Y_AXIS)); // add symbol title JLabel symbolTitle = new JLabel(node.symbol().name()); // add description JLabel description = new JLabel(node.description()); // add dropdown of clauses JLabel clauses = new JLabel("Clauses:"); JList<String> clauseList = new JList<>(); String[] clauseStrings = new String[node.clauses().size()]; HashMap<String, Clause> clauseMap = new HashMap<>(); for (int i = 0; i < node.clauses().size(); i++) { clauseStrings[i] = node.clauses().get(i).toString(); clauseMap.put(clauseStrings[i], node.clauses().get(i)); } clauseList.setListData(clauseStrings); JComboBox<String> clauseDropdown = new JComboBox<>(clauseStrings); clauseDropdown.addItemListener(e -> { if (e.getStateChange() == ItemEvent.SELECTED) { Clause selectedClause = clauseMap.get(clauseDropdown.getSelectedItem()); updateParameterPanel(selectedClause); } }); updateParameterPanel(node.clauses().get(0)); add(symbolTitle); add(description); add(clauses); add(clauseDropdown); add(parameterDescriptions); setVisible(true); } private void updateParameterPanel(Clause c) { StringBuilder newDescription = new StringBuilder(); if(c.args() == null) { parameterDescriptions.setText(""); repaint(); return; } for (ClauseArg arg : c.args()) newDescription.append(arg.toString()).append(": ").append(node.helpInformation().parameter(arg)).append("\n"); newDescription = new StringBuilder(newDescription.toString().replaceAll("<", "&lt;")); newDescription = new StringBuilder(newDescription.toString().replaceAll(">", "&gt;")); newDescription = new StringBuilder(newDescription.toString().replaceAll("\n", "<br>")); newDescription = new StringBuilder("<html>" + newDescription + "</html>"); parameterDescriptions.setText(newDescription.toString()); repaint(); } }
3,045
32.844444
122
java
Ludii
Ludii-master/PlayerDesktop/src/app/display/dialogs/visual_editor/view/panels/editor/ConnectionHandler.java
package app.display.dialogs.visual_editor.view.panels.editor; import app.display.dialogs.visual_editor.handler.Handler; import app.display.dialogs.visual_editor.model.LudemeNode; import app.display.dialogs.visual_editor.view.components.ludemenodecomponent.ImmutablePoint; import app.display.dialogs.visual_editor.view.components.ludemenodecomponent.LudemeConnection; import app.display.dialogs.visual_editor.view.components.ludemenodecomponent.LudemeNodeComponent; import app.display.dialogs.visual_editor.view.components.ludemenodecomponent.inputs.LConnectionComponent; import app.display.dialogs.visual_editor.view.components.ludemenodecomponent.inputs.LIngoingConnectionComponent; import app.display.dialogs.visual_editor.view.components.ludemenodecomponent.inputs.LInputField; import app.display.dialogs.visual_editor.view.designPalettes.DesignPalette; import app.display.dialogs.visual_editor.view.panels.IGraphPanel; import main.grammar.ClauseArg; import main.grammar.Symbol; import java.awt.*; import java.awt.geom.Path2D; import java.util.ArrayList; import java.util.List; /** * Handles connections between LudemeNodeComponents on a iGraphPanel */ public class ConnectionHandler { /** The graph panel */ private final IGraphPanel graphPanel; /** Stores the Edges */ private final List<LudemeConnection> edges; /** The currently selected LudemeNodeComponent's Connection Component */ private LConnectionComponent selectedConnectionComponent; public ConnectionHandler(IGraphPanel graphPanel) { this.graphPanel = graphPanel; this.edges = new ArrayList<>(); } /** * Starts a new connection * @param source the LudemeNodeComponent to connect from */ public void startNewConnection(LConnectionComponent source) { // if a previous connection component was selected, deselect it cancelNewConnection(); // set the selected connection component selectedConnectionComponent = source; if(Handler.autoplacement) ((GraphPanel)graphPanel).showCurrentlyAvailableLudemes(); } /** * Cancels the currently created connection */ public void cancelNewConnection() { if(selectedConnectionComponent != null) { selectedConnectionComponent.fill(false); selectedConnectionComponent = null; } } /** * Finalises the currently created connection * @param target the LudemeNodeComponent to connect to */ public void finishNewConnection(LudemeNodeComponent target) { Handler.addEdge(graphPanel.graph(), selectedConnectionComponent.inputField().inputArea().LNC().node(), target.node(), selectedConnectionComponent.inputField().inputArea().inputFieldIndex(selectedConnectionComponent.inputField())); selectedConnectionComponent = null; } /** * Creates a connection between two Connection Components * @param source the LudemeNodeComponent's Connection Component to connect from * @param target the LudemeNodeComponent's Connection Component to connect to */ public void addConnection(LConnectionComponent source, LIngoingConnectionComponent target) { // update the positions of the connection components LConnectionComponent source2 = source; source2.updatePosition(); target.updatePosition(); // If the InputField was merged, notify the InputArea to remove the NodeArgument from the merged list if(source2.inputField().isMerged()) { source2.fill(false); LInputField singledOutField = source2.lnc().inputArea().addedConnection(target.getHeader().ludemeNodeComponent(), source2.inputField()); if(singledOutField.connectionComponent() == null) { for(ClauseArg arg : singledOutField.nodeArgument(0).args()) { if(!arg.symbol().ludemeType().equals(Symbol.LudemeType.Predefined)) { singledOutField.nodeArgument(0).setActiveChoiceArg(arg); singledOutField.reconstruct(); break; } } } source2 = singledOutField.connectionComponent(); } // Otherwise notify the InputArea about the added connection else { source2.lnc().inputArea().addedConnection(target.getHeader().ludemeNodeComponent(), source2.inputField()); } // update creator argument of the target node // find correct NodeArgument target.getHeader().ludemeNodeComponent().node().setCreatorArgument(source2.inputField().nodeArgument(0)); // update the positions of the source connection component again (for the case that the InputField was merged) source2.updatePosition(); // fill the connection components source2.fill(true); target.setFill(true); // update the connection in the source source2.setConnectedTo(target.getHeader().ludemeNodeComponent()); target.setInputField(source2.inputField()); // Add an edge LudemeConnection connection = new LudemeConnection(source2, target); edges.add(connection); // Update the provided input via the Handler // differentiate between an input provided to a collection and otherwise if(source2.inputField().nodeArgument(0).collection()) Handler.updateCollectionInput(graphPanel.graph(), source2.lnc().node(), source2.inputField().nodeArgument(0), target.getHeader().ludemeNodeComponent().node(), source2.inputField().elementIndex()); else Handler.updateInput(graphPanel.graph(), source2.lnc().node(), source2.inputField().nodeArgument(0), target.getHeader().ludemeNodeComponent().node()); if(Handler.autoplacement) graphPanel.getLayoutHandler().executeLayout(); //TODO: check if menu is opened; if yes - close graphPanel.repaint(); } /** * Removes all connections of a node * @param node */ public void removeAllConnections(LudemeNode node) { removeAllConnections(node, true); } /** * Removes all connections of a node * @param node * @param onlyOutgoingConnections Whether only outgoing connections of the given node should be removed */ public void removeAllConnections(LudemeNode node, boolean onlyOutgoingConnections) { for(LudemeConnection e : new ArrayList<>(edges)) { if(e.outgoingNode() != node && !(!onlyOutgoingConnections && e.ingoingNode() == node)) { continue; } edges.remove(e); LudemeNodeComponent source = e.getConnectionComponent().inputField().inputArea().LNC(); source.inputArea().removedConnection(e.getConnectionComponent().inputField()); e.getIngoingConnectionComponent().setFill(false); // the node source was connected to is not connected anymore e.getConnectionComponent().fill(false); // the node source is not connected anymore // notify handler (different for collection and non-collection inputs) if(e.getConnectionComponent().inputField().nodeArgument(0).collection()) Handler.updateCollectionInput(graphPanel.graph(), source.node(), e.getConnectionComponent().inputField().nodeArgument(0), null, e.getConnectionComponent().inputField().elementIndex()); else Handler.updateInput(graphPanel.graph(), source.node(), e.getConnectionComponent().inputField().nodeArgument(0), null); } graphPanel.repaint(); } /** * removes all outgoing connections of a given node's connection component * @param node * @param connection */ public void removeConnection(LudemeNode node, LConnectionComponent connection) { for(LudemeConnection e : new ArrayList<>(edges)) { if(e.getConnectionComponent().equals(connection)) { edges.remove(e); if(e.ingoingNode().creatorArgument() != null && e.ingoingNode().creatorArgument().collection()) { // find index in collection int elementIndex = -1; for(Object input : e.outgoingNode().providedInputsMap().values()) { if(!(input instanceof Object[])) continue; Object[] currentCollection = (Object[]) input; for(int i = 0; i < currentCollection.length; i++) { if(currentCollection[i] == e.ingoingNode()) { elementIndex = i; break; } } } Handler.removeEdge(graphPanel.graph(), node, e.ingoingNode(), elementIndex, false); } else Handler.removeEdge(graphPanel.graph(), node, e.ingoingNode(), false); e.getIngoingConnectionComponent().setFill(false); // header e.getConnectionComponent().fill(false); // input e.getConnectionComponent().setConnectedTo(null); e.getConnectionComponent().inputField().inputArea().removedConnection(e.getConnectionComponent().inputField()); if(connection.inputField().nodeArgument(0).collection()) { LudemeNode sourceNode = connection.lnc().node(); int collectionElementIndex = 0; if(connection.inputField().parent() != null) collectionElementIndex = connection.inputField().parent().children().indexOf(connection.inputField())+1; Handler.updateCollectionInput(graphPanel.graph(), sourceNode, connection.inputField().nodeArgument(0), null, collectionElementIndex); connection.inputField().updateUserInputs(); } else { Handler.updateInput(graphPanel.graph(), e.getConnectionComponent().lnc().node(), e.getConnectionComponent().inputField().nodeArgument(0), null); } } } graphPanel.repaint(); } /** * Draws an edge between an argument field and the mouse pointer (while establishing a connection) * @param g2 * @param mousePosition */ public void drawNewConnection(Graphics2D g2, Point mousePosition) { if(selectedConnectionComponent != null && mousePosition != null) { ImmutablePoint connection_point = selectedConnectionComponent.connectionPointPosition(); Path2D p2d = new Path2D.Double(); int cp_x = connection_point.x + Math.abs((connection_point.x-mousePosition.x)/2); p2d.moveTo(connection_point.x, connection_point.y); p2d.curveTo(cp_x, connection_point.y, cp_x, mousePosition.y, mousePosition.x, mousePosition.y); g2.draw(p2d); } } /** * * @return The currently selected LConnectionComponent */ public LConnectionComponent selectedComponent() { return selectedConnectionComponent; } /** * Paints the edges * @param g2 */ public void paintConnections(Graphics2D g2) { // set color for edges g2.setColor(DesignPalette.LUDEME_CONNECTION_EDGE()); // set stroke for edges g2.setStroke(DesignPalette.LUDEME_EDGE_STROKE); for(LudemeConnection e : edges) { if(!(e.outgoingNode().visible() && e.ingoingNode().visible())) { continue; } ImmutablePoint inputPoint = e.getInputPosition(); ImmutablePoint targetPoint = e.getTargetPosition(); int cp_x = inputPoint.x + Math.abs((inputPoint.x-targetPoint.x)/2); int cp1_y = inputPoint.y; int cp2_y = targetPoint.y; Path2D p2d = new Path2D.Double(); p2d.moveTo(inputPoint.x, inputPoint.y); p2d.curveTo(cp_x, cp1_y, cp_x, cp2_y, targetPoint.x, targetPoint.y); g2.draw(p2d); } } }
12,463
39.865574
238
java
Ludii
Ludii-master/PlayerDesktop/src/app/display/dialogs/visual_editor/view/panels/editor/EditorPopupMenu.java
package app.display.dialogs.visual_editor.view.panels.editor; import app.display.dialogs.visual_editor.handler.Handler; import app.display.dialogs.visual_editor.view.designPalettes.DesignPalette; import app.display.dialogs.visual_editor.view.panels.IGraphPanel; import app.display.dialogs.visual_editor.view.panels.editor.gameEditor.GameGraphPanel; import javax.swing.*; import java.awt.*; public class EditorPopupMenu extends JPopupMenu { /** * */ private static final long serialVersionUID = 5378508370225281683L; public EditorPopupMenu(IGraphPanel graphPanel, int x, int y) { JMenuItem newLudeme = new JMenuItem("New Ludeme"); JMenuItem paste = new JMenuItem("Paste"); paste.addActionListener(e -> { Handler.paste(graphPanel.graph(), x, y); // deselect all previously selected nodes graphPanel.deselectEverything(); }); JMenuItem compact = new JMenuItem("Arrange graph"); compact.addActionListener(e -> graphPanel.getLayoutHandler().executeLayout()); newLudeme.addActionListener(e -> graphPanel.showAllAvailableLudemes()); JMenuItem collapse = new JMenuItem("Collapse"); collapse.addActionListener(e -> Handler.collapse(graphPanel.graph())); int iconHeight = (int)(newLudeme.getPreferredSize().getHeight()*0.75); ImageIcon newLudemeIcon = new ImageIcon(DesignPalette.ADD_ICON.getImage().getScaledInstance(iconHeight, iconHeight, Image.SCALE_SMOOTH)); newLudeme.setIcon(newLudemeIcon); ImageIcon pasteIcon = new ImageIcon(DesignPalette.PASTE_ICON.getImage().getScaledInstance(iconHeight, iconHeight, Image.SCALE_SMOOTH)); paste.setIcon(pasteIcon); ImageIcon collapseIcon = new ImageIcon(DesignPalette.COLLAPSE_ICON().getImage().getScaledInstance(iconHeight, iconHeight, Image.SCALE_SMOOTH)); collapse.setIcon(collapseIcon); paste.setEnabled(!Handler.clipboard().isEmpty()); collapse.setEnabled(!Handler.selectedNodes(graphPanel.graph()).isEmpty()); add(newLudeme); if(graphPanel instanceof GameGraphPanel) { JMenuItem addDefine = new JMenuItem("Add Define"); GameGraphPanel ggp = (GameGraphPanel) graphPanel; addDefine.addActionListener(e -> ggp.showAddDefinePanel()); add(addDefine); } add(paste); add(compact); add(collapse); JMenuItem fix = new JMenuItem("Fix group"); fix.addActionListener(e -> graphPanel.graph().getNode(graphPanel.graph().selectedRoot()).setFixed(true)); JMenuItem unfix = new JMenuItem("Unfix group"); unfix.addActionListener(e -> graphPanel.graph().getNode(graphPanel.graph().selectedRoot()).setFixed(false)); if (graphPanel.graph().selectedRoot() != -1 && graphPanel.graph().getNode(graphPanel.graph().selectedRoot()).fixed()) { add(unfix); graphPanel.repaint(); } else if (graphPanel.graph().selectedRoot() != -1) { add(fix); graphPanel.repaint(); } JMenuItem undo = new JMenuItem("Undo"); undo.addActionListener(e -> Handler.undo()); add(undo); JMenuItem redo = new JMenuItem("Redo"); redo.addActionListener(e -> Handler.redo()); add(redo); } }
3,393
35.106383
151
java
Ludii
Ludii-master/PlayerDesktop/src/app/display/dialogs/visual_editor/view/panels/editor/EditorSidebar.java
package app.display.dialogs.visual_editor.view.panels.editor; import app.display.dialogs.visual_editor.handler.Handler; import app.display.dialogs.visual_editor.view.panels.editor.tabPanels.LayoutSettingsPanel; import javax.swing.*; /** * Sidebar panel of visual editor * @author nic0gin */ public class EditorSidebar extends JTabbedPane { /** * */ private static final long serialVersionUID = 7035094102486105836L; private static EditorSidebar editorSidebar; /** * Constructor */ private EditorSidebar() { setVisible(Handler.sidebarVisible); // adding layout settings tab LayoutSettingsPanel layoutPanel = LayoutSettingsPanel.getLayoutSettingsPanel(); Handler.lsPanel = layoutPanel; addTab("Layout settings", layoutPanel); setSelectedComponent(layoutPanel); // add other tabs here... // invisible by default setVisible(false); } /** * Get a single instance of the editor sidebar */ public static EditorSidebar getEditorSidebar() { if (editorSidebar == null) editorSidebar = new EditorSidebar(); return editorSidebar; } @SuppressWarnings("static-method") public void setSidebarVisible(boolean visible) { editorSidebar.setVisible(visible); editorSidebar.repaint(); } @SuppressWarnings("static-method") public void setLayoutTabSelected() { int LAYOUT_TAB_INDEX = 0; editorSidebar.setSelectedIndex(LAYOUT_TAB_INDEX);} }
1,532
24.131148
90
java
Ludii
Ludii-master/PlayerDesktop/src/app/display/dialogs/visual_editor/view/panels/editor/GraphPanel.java
package app.display.dialogs.visual_editor.view.panels.editor; import app.display.dialogs.visual_editor.LayoutManagement.GraphRoutines; import app.display.dialogs.visual_editor.LayoutManagement.LayoutHandler; import app.display.dialogs.visual_editor.LayoutManagement.Vector2D; import app.display.dialogs.visual_editor.handler.Handler; import app.display.dialogs.visual_editor.model.DescriptionGraph; import app.display.dialogs.visual_editor.model.LudemeNode; import app.display.dialogs.visual_editor.model.NodeArgument; import app.display.dialogs.visual_editor.model.interfaces.iGNode; import app.display.dialogs.visual_editor.view.components.AddArgumentPanel; import app.display.dialogs.visual_editor.view.components.ludemenodecomponent.LudemeNodeComponent; import app.display.dialogs.visual_editor.view.components.ludemenodecomponent.inputs.LConnectionComponent; import app.display.dialogs.visual_editor.view.components.ludemenodecomponent.inputs.LIngoingConnectionComponent; import app.display.dialogs.visual_editor.view.components.ludemenodecomponent.inputs.LInputArea; import app.display.dialogs.visual_editor.view.components.ludemenodecomponent.inputs.LInputField; import app.display.dialogs.visual_editor.view.designPalettes.DesignPalette; import app.display.dialogs.visual_editor.view.panels.IGraphPanel; import app.display.dialogs.visual_editor.view.panels.editor.selections.FixedGroupSelection; import app.display.dialogs.visual_editor.view.panels.editor.selections.SelectionBox; import app.display.dialogs.visual_editor.view.panels.editor.tabPanels.LayoutSettingsPanel; import grammar.Grammar; import main.grammar.Symbol; import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class GraphPanel extends JPanel implements IGraphPanel { /** * */ private static final long serialVersionUID = -7514241007809349985L; // The graph this panel is displaying private final DescriptionGraph GRAPH = new DescriptionGraph(); // The parent JScrollPane private JScrollPane parentScrollPane; // The node components in this panel private final List<LudemeNodeComponent> NODE_COMPONENTS = new ArrayList<>(); private final Map<Integer, LudemeNodeComponent> NODE_COMPONENTS_BY_ID = new HashMap<>(); // The last position of the mouse Point mousePosition; // The LayoutHandler private final LayoutHandler lm; // The ConnectionHandler private final ConnectionHandler CONNECTION_HANDLER; // window to add a new ludeme out of all possible ones private final AddArgumentPanel addLudemePanel; // window to add a new ludeme as an input final AddArgumentPanel connectArgumentPanel; // List of nodes that are not satisfied/complete private List<LudemeNodeComponent> uncompilableNodes = new ArrayList<>(); // Whether this panel is currently busy private boolean busy = false; // list of symbols that can be created without connection public static List<Symbol> symbolsWithoutConnection; // flag to check if select button is active boolean SELECTION_MODE = false; // flag to check if user performs selection boolean SELECTING = false; // flag to check if selection was performed boolean SELECTED = false; // list of selected nodes private List<LudemeNodeComponent> selectedLnc = new ArrayList<>(); // latencies for user testing code completion (Filip) // private final List<Long> latencies = new ArrayList<>(); private final List<Integer> selectedCompletion = new ArrayList<>(); public GraphPanel(int width, int height) { setLayout(null); setPreferredSize(new Dimension(width, height)); Handler.addGraphPanel(graph(), this); GraphPanel.symbolsWithoutConnection = symbolsWithoutConnection(); this.addLudemePanel = new AddArgumentPanel(symbolsWithoutConnection, this, false); // window to add a new ludeme as an input this.connectArgumentPanel = new AddArgumentPanel(symbolsWithoutConnection, this, true); this.lm = new LayoutHandler(graph()); this.CONNECTION_HANDLER = new ConnectionHandler(this); } /** * Initializes the graph panel. */ public void initialize(JScrollPane parentScrollPane1) { this.parentScrollPane = parentScrollPane1; addMouseListener(clickListener); addMouseMotionListener(motionListener); addMouseWheelListener(wheelListener); addMouseListener(panelDragListener); addMouseMotionListener(panelDragListener); addKeyListener(CTRL_listener); add(addLudemePanel); add(connectArgumentPanel); } /** * Whether this panel is of a define graph. */ @Override public boolean isDefineGraph() { return false; } private final MouseAdapter panelDragListener = new MouseAdapter() { private Point origin; @Override public void mousePressed(MouseEvent e) { origin = new Point(e.getPoint()); } @Override public void mouseDragged(MouseEvent e) { if (origin != null && !isSelectionMode()) { JViewport viewPort = (JViewport) SwingUtilities.getAncestorOfClass(JViewport.class, GraphPanel.this); if (viewPort != null) { int deltaX = origin.x - e.getX(); int deltaY = origin.y - e.getY(); Rectangle view = viewPort.getViewRect(); view.x += deltaX; view.y += deltaY; scrollRectToVisible(view); } } } }; /** * Notifies the panel that a node was added to the graph. * * @param node * @param connect */ @Override public void notifyNodeAdded(LudemeNode node, boolean connect) { addLudemeNodeComponent(node, connect); } /** * Notifies the panel that a node was removed from the graph. * * @param lnc */ @Override public void notifyNodeRemoved(LudemeNodeComponent lnc) { NODE_COMPONENTS.remove(lnc); NODE_COMPONENTS_BY_ID.remove(Integer.valueOf(lnc.node().id())); remove(lnc); connectionHandler().removeAllConnections(lnc.node(), false); repaint(); } /** * Notifies the panel that an edge between two nodes was established, outgoing from a given input field index * * @param from * @param to * @param inputFieldIndex */ @Override public void notifyEdgeAdded(LudemeNodeComponent from, LudemeNodeComponent to, int inputFieldIndex) { LConnectionComponent source = from.inputArea().currentInputFields.get(inputFieldIndex).connectionComponent(); LIngoingConnectionComponent target = to.header().ingoingConnectionComponent(); connectionHandler().addConnection(source, target); } private static LInputField findInputField(LudemeNodeComponent lnc, NodeArgument inputFieldArgument) { for(LInputField ii : lnc.inputArea().currentInputFields) if(ii.nodeArguments().contains(inputFieldArgument)) return ii; return null; } /** * Notifies the panel that an edge between two nodes was established, outgoing from an input field with a given NodeArgument * * @param from * @param to * @param inputFieldArgument */ @Override public void notifyEdgeAdded(LudemeNodeComponent from, LudemeNodeComponent to, NodeArgument inputFieldArgument) { LInputField inputField = findInputField(from, inputFieldArgument); assert inputField != null; LConnectionComponent source = inputField.connectionComponent(); LIngoingConnectionComponent target = to.header().ingoingConnectionComponent(); connectionHandler().addConnection(source, target); } /** * Notifies the panel that a collection edge between two nodes was removed, outgoing from an input field with a given NodeArgument * * @param from * @param to * @param inputFieldArgument * @param elementIndex */ @Override public void notifyEdgeAdded(LudemeNodeComponent from, LudemeNodeComponent to, NodeArgument inputFieldArgument, int elementIndex) { LInputField inputField = findInputField(from, inputFieldArgument); if(elementIndex > 0) { assert inputField != null; int index = inputField.inputArea().inputFieldIndex(inputField) + elementIndex; while(index >= from.inputArea().currentInputFields.size()) { from.inputArea(); LInputArea.addCollectionItem(inputField); } inputField = from.inputArea().currentInputFields.get(index); } assert inputField != null; LConnectionComponent source = inputField.connectionComponent(); LIngoingConnectionComponent target = to.header().ingoingConnectionComponent(); connectionHandler().addConnection(source, target); } /** * Notifies the panel that an edge between two nodes was removed * * @param from * @param to */ @Override public void notifyEdgeRemoved(LudemeNodeComponent from, LudemeNodeComponent to) { // find inputfield of from node LInputField inputField = findInputField(from, to.node().creatorArgument()); assert inputField != null; connectionHandler().removeConnection(from.node(), inputField.connectionComponent()); } /** * Notifies the panel that an edge between two nodes was removed , of a collection * * @param from * @param to * @param elementIndex */ @Override public void notifyEdgeRemoved(LudemeNodeComponent from, LudemeNodeComponent to, int elementIndex) { // find inputfield of from node LInputField inputField = findInputField(from, to.node().creatorArgument()); inputField = from.inputArea().currentInputFields.get(from.inputArea().inputFieldIndex(inputField) + elementIndex); assert inputField != null; connectionHandler().removeConnection(from.node(), inputField.connectionComponent()); } /** * Notifies the panel that a node was collapsed/expanded * * @param lnc * @param collapsed */ @Override public void notifyCollapsed(LudemeNodeComponent lnc, boolean collapsed) { lnc.header().inputField().notifyCollapsed(); if(!collapsed) lnc.setVisible(true); repaint(); } /** * Notifies the panel that a node's inputs were updated * * @param lnc */ @Override public void notifyInputsUpdated(LudemeNodeComponent lnc) { lnc.updateProvidedInputs(); } /** * Notifies the panel that a collection element was added to a node * * @param lnc * @param inputFieldArgument * @param elementIndex */ @Override public void notifyCollectionAdded(LudemeNodeComponent lnc, NodeArgument inputFieldArgument, int elementIndex) { // find parent inputfield LInputField inputField = findInputField(lnc, inputFieldArgument); assert inputField != null; inputField.notifyCollectionAdded(); } @Override public void notifyCollectionRemoved(LudemeNodeComponent lnc, NodeArgument inputFieldArgument, int elementIndex) { // find removed inputfield LInputField inputField = findInputField(lnc, inputFieldArgument); inputField = lnc.inputArea().currentInputFields.get(lnc.inputArea().inputFieldIndex(inputField) + elementIndex); inputField.notifyCollectionRemoved(); } /** * Notifies the panel that the node's selected clause was changed * * @param lnc */ @Override public void notifySelectedClauseChanged(LudemeNodeComponent lnc) { lnc.inputArea().changedSelectedClause(); } /** * Notifies the panel that a node's optional terminal input was activated/deactivated * * @param lnc * @param inputFieldArgument * @param activated */ @Override public void notifyTerminalActivated(LudemeNodeComponent lnc, NodeArgument inputFieldArgument, boolean activated) { LInputField inputField = findInputField(lnc, inputFieldArgument); assert inputField != null; if(!inputField.isMerged()) { if (activated) inputField.notifyActivated(); else inputField.notifyDeactivated(); } else lnc.addTerminal(inputFieldArgument, inputField); } /** * Notifies the panel about an updated collapsed-status of a list of nodes * * @param lncs */ @Override public void updateCollapsed(List<LudemeNodeComponent> lncs) { for(LudemeNodeComponent lnc : lncs) if(lnc.node().collapsed()) if(lnc.header().inputField() != null) lnc.header().inputField().notifyCollapsed(); } /** * Notifies the panel which nodes are not compilable * * @param lncs */ public void notifyUncompilable(List<LudemeNodeComponent> lncs) { unmarkUncompilableNodes(); uncompilableNodes = lncs; for(LudemeNodeComponent lnc : lncs) lnc.markUncompilable(true); } private void unmarkUncompilableNodes() { for(LudemeNodeComponent lnc : uncompilableNodes) lnc.markUncompilable(false); uncompilableNodes.clear(); } /** * Returns the ScrollPane this panel is in */ @Override public JScrollPane parentScrollPane() { return parentScrollPane; } @Override public JPanel panel() { return this; } /** * Creates a LudemeNodeComponent for a given node * * @param node * @param connect */ private void addLudemeNodeComponent(LudemeNode node, boolean connect) { LudemeNodeComponent lc = new LudemeNodeComponent(node, this); hideAllAddArgumentPanels(); NODE_COMPONENTS.add(lc); NODE_COMPONENTS_BY_ID.put(Integer.valueOf(node.id()), lc); add(lc); lc.updatePositions(); if(connect) connectionHandler().finishNewConnection(lc); } /** * Whether the graph is currently busy (e.g. a node is being added) */ @Override public boolean isBusy() { return busy; } /** * Updates the busy-status * * @param b */ @Override public void setBusy(boolean b) { this.busy = b; } /** * Returns the DescriptionGraph this Panel represents */ @Override public DescriptionGraph graph() { return GRAPH; } /** * Returns the ConnectionHandler for this panel */ @Override public ConnectionHandler connectionHandler() { return CONNECTION_HANDLER; } /** * Finds the LudemeNodeComponent for a given LudemeNode * * @param node */ @Override public LudemeNodeComponent nodeComponent(LudemeNode node) { LudemeNodeComponent lnc = NODE_COMPONENTS_BY_ID.get(Integer.valueOf(node.id())); if(lnc != null) return lnc; for(LudemeNodeComponent ln : NODE_COMPONENTS) if(ln.node() == node) return ln; return null; } /** * */ @Override public void enterSelectionMode() { this.SELECTION_MODE = true; } /** * */ @Override public boolean isSelectionMode() { return SELECTION_MODE; } /** * */ @Override public Rectangle exitSelectionMode() { SELECTING = false; SELECTION_MODE = false; Handler.turnOffSelectionBtn(); repaint(); revalidate(); return SelectionBox.endSelection(); } /** * Adds a node to the list of selected nodes * * @param lnc */ @Override public void addNodeToSelections(LudemeNodeComponent lnc) { if (!selectedLnc.contains(lnc)) { SELECTED = true; lnc.setSelected(true); selectedLnc.add(lnc); // add collapsed subtrees too for(LudemeNode child : lnc.node().childrenNodes()) { LudemeNodeComponent childLnc = nodeComponent(child); if(childLnc.node().collapsed()) for(LudemeNodeComponent lncc : subtree(childLnc)) { if(selectedLnc.contains(lncc)) continue; lncc.setSelected(true); selectedLnc.add(lncc); } } } } /** * Returns the subtree of a given node * @param lnc * @return */ private List<LudemeNodeComponent> subtree(LudemeNodeComponent lnc) { List<LudemeNodeComponent> subtree = new ArrayList<>(); subtree.add(lnc); for(LudemeNode child : lnc.node().childrenNodes()) { LudemeNodeComponent childLnc = nodeComponent(child); subtree.add(childLnc); subtree.addAll(subtree(childLnc)); } return subtree; } /** * List of selected nodes */ @Override public List<iGNode> selectedNodes() { List<iGNode> nodeList = new ArrayList<>(); for (LudemeNodeComponent lnc: selectedLnc) nodeList.add(lnc.node()); return nodeList; } /** * List of selected nodes */ @Override public List<LudemeNodeComponent> selectedLnc() { return selectedLnc; } /** * Selects all nodes */ @Override public void selectAllNodes() { for (LudemeNodeComponent lnc: NODE_COMPONENTS) addNodeToSelections(lnc); repaint(); revalidate(); } public void showCurrentlyAvailableLudemes() { // get game description up to current point int upUntilIndex = connectionHandler().selectedComponent().inputField().nodeArguments().get(0).index(); for(NodeArgument ii : connectionHandler().selectedComponent().inputField().nodeArguments()) if(ii.index() < upUntilIndex) upUntilIndex = ii.index(); //long start = System.nanoTime(); List<Symbol> possibleSymbols = connectionHandler().selectedComponent().possibleSymbolInputs(); //[UNCOMMENT FILIP] String gameDescription = connectionHandler().selectedComponent().inputField().inputArea().LNC().node().toLudCodeCompletion(connectionHandler().selectedComponent().inputField().nodeArguments()); List<Symbol> typeMatched = possibleSymbols; //[UNCOMMENT FILIP] List<Symbol> typeMatched = TypeMatch.getInstance().typematch(gameDescription, StartVisualEditor.controller(),possibleSymbols); connectArgumentPanel.updateList(connectionHandler().selectedComponent().inputField(), typeMatched); connectArgumentPanel.setVisible(true); connectArgumentPanel.setLocation(mousePosition); connectArgumentPanel.searchField.requestFocus(); revalidate(); repaint(); } /** * Displays all available ludemes that may be created */ @Override public void showAllAvailableLudemes() { addLudemePanel.setVisible(true); addLudemePanel.setLocation(mousePosition); addLudemePanel.searchField.requestFocus(); revalidate(); repaint(); } public Point mousePosition() { return mousePosition; } /** * Notifies the panel that the user clicked on a node */ @Override public void clickedOnNode(LudemeNodeComponent lnc) { LudemeNode node = lnc.node(); LConnectionComponent selectedConnectionComponent = connectionHandler().selectedComponent(); if(selectedConnectionComponent != null) { if (selectedConnectionComponent.inputField().nodeArgument(0).collection2D() && !lnc.ingoingConnectionComponent().isFilled()) { if (lnc.node().creatorArgument().arg().equals(selectedConnectionComponent.inputField().nodeArgument(0).arg())) connectionHandler().finishNewConnection(lnc); } else if(selectedConnectionComponent.possibleSymbolInputs().contains(node.symbol()) && !lnc.ingoingConnectionComponent().isFilled()) connectionHandler().finishNewConnection(lnc); else if(node.isDefineNode() && selectedConnectionComponent.possibleSymbolInputs().contains(node.macroNode().symbol())) connectionHandler().finishNewConnection(lnc); } } /** * The LayoutHandler */ @Override public LayoutHandler getLayoutHandler() { return lm; } /** * Updates the Graph (position of nodes, etc.) */ @Override public void updateGraph() { for (LudemeNodeComponent lc : NODE_COMPONENTS) { lc.revalidate(); lc.updateProvidedInputs(); lc.updatePositions(); } revalidate(); repaint(); } /** * */ @Override public void syncNodePositions() { for (LudemeNodeComponent lc : NODE_COMPONENTS) lc.syncPositionsWithLN(); revalidate(); repaint(); } /** * Unselects all nodes */ @Override public void deselectEverything() { graph().getNodes().forEach(n -> { LudemeNodeComponent lnc = nodeComponent(n); lnc.setSelected(false); lnc.setDoubleSelected(false); }); graph().setSelectedRoot(-1); LayoutSettingsPanel.getLayoutSettingsPanel().disableFixButton(); LayoutSettingsPanel.getLayoutSettingsPanel().disableUnfixButton(); selectedLnc = new ArrayList<>(); SELECTED = false; repaint(); revalidate(); } /** * @return A list of symbols which can be created without an ingoing connection */ private static List<Symbol> symbolsWithoutConnection() { List<Symbol> allSymbols = Grammar.grammar().symbols(); List<Symbol> symbolsWithoutConnection1 = new ArrayList<>(); for (Symbol symbol : allSymbols) { if(symbol.ludemeType().equals(Symbol.LudemeType.Constant) || symbol.ludemeType().equals(Symbol.LudemeType.Predefined) || symbol.ludemeType().equals(Symbol.LudemeType.Structural) || symbol.ludemeType().equals(Symbol.LudemeType.Primitive) || symbol.ludemeType().equals(Symbol.LudemeType.SubLudeme)) continue; symbolsWithoutConnection1.add(symbol); } return symbolsWithoutConnection1; } @Override public void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2 = (Graphics2D) g.create(); g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); if(getBackground() != DesignPalette.BACKGROUND_EDITOR()) setBackground(DesignPalette.BACKGROUND_EDITOR()); // draw background if(parentScrollPane!=null) Handler.currentBackground().paint(parentScrollPane().getViewport().getViewRect(), getWidth(), getHeight(), g2); // set color for edges g2.setColor(DesignPalette.LUDEME_CONNECTION_EDGE()); // set stroke for edges g2.setStroke(DesignPalette.LUDEME_EDGE_STROKE); // draw new connection connectionHandler().drawNewConnection(g2, mousePosition); // draw existing connections connectionHandler().paintConnections(g2); // Draw selection area if (SELECTION_MODE && !SELECTING) SelectionBox.drawSelectionModeIdle(mousePosition, g2); if (SELECTION_MODE && SELECTING) SelectionBox.drawSelectionArea(mousePosition, mousePosition, g2); // Draw fixed groups area for(LudemeNodeComponent lc : NODE_COMPONENTS) if (lc.node().fixed()) { Rectangle subtreeArea = GraphRoutines.getSubtreeArea(graph(), lc.node().id()); FixedGroupSelection.drawGroupBox(subtreeArea, (Graphics2D) g); } } public void hideAllAddArgumentPanels() { connectArgumentPanel.setVisible(false); addLudemePanel.setVisible(false); } // LISTENERS final MouseListener clickListener = new MouseAdapter() { private void openPopupMenu(MouseEvent e) { JPopupMenu popupMenu = new EditorPopupMenu(GraphPanel.this, e.getX(), e.getY()); popupMenu.show(e.getComponent(), e.getX(), e.getY()); } @Override public void mouseClicked(MouseEvent e) { super.mouseClicked(e); if(connectArgumentPanel.isVisible()) connectionHandler().cancelNewConnection(); hideAllAddArgumentPanels(); if(e.getButton() == MouseEvent.BUTTON1) { // user is drawing a new connection if(connectionHandler().selectedComponent() != null) { // if it's a 2D collection, connect to a 1D collection equivalent if(connectionHandler().selectedComponent().inputField().nodeArgument(0).collection2D()) Handler.addNode(graph(), connectionHandler().selectedComponent().inputField().nodeArgument(0), e.getX(), e.getY()); // if user has no choice for next ludeme -> automatically add required ludeme else if(connectionHandler().selectedComponent().possibleSymbolInputs().size() == 1) Handler.addNode(graph(), connectionHandler().selectedComponent().possibleSymbolInputs().get(0), connectionHandler().selectedComponent().inputField().nodeArgument(0), e.getX(), e.getY(), true); else if(!connectArgumentPanel.isVisible() && connectionHandler().selectedComponent().possibleSymbolInputs().size() > 1) showCurrentlyAvailableLudemes(); } // When selection was performed user can clear it out by clicking on blank area if (SELECTED) { LayoutSettingsPanel.getLayoutSettingsPanel().setSelectedComponent("Empty", false); deselectEverything(); } } else { // user is selecting a connection -> cancel new connection if(connectionHandler().selectedComponent() != null) connectionHandler().cancelNewConnection(); } repaint(); revalidate(); } @Override public void mouseDragged(MouseEvent e) { super.mouseDragged(e); } @Override public void mousePressed(MouseEvent e) { if(e.getButton() == MouseEvent.BUTTON3) { connectionHandler().cancelNewConnection(); openPopupMenu(e); } if (SELECTION_MODE && e.getButton() == MouseEvent.BUTTON1) { SELECTING = true; repaint(); revalidate(); } } /** * - Open pop up menu right click on empty space * - Select nodes that fall within selection area * @param e mouse event */ @Override public void mouseReleased(MouseEvent e) { if(e.getButton() == MouseEvent.BUTTON3) openPopupMenu(e); if (SELECTING && e.getButton() == MouseEvent.BUTTON1) { Rectangle region = exitSelectionMode(); if (region != null) { graph().getNodes().forEach(n -> { LudemeNodeComponent lnc = nodeComponent(n); if (region.intersects(lnc.getBounds())) { addNodeToSelections(lnc); SELECTED = true; } }); } } } }; final MouseMotionListener motionListener = new MouseAdapter() { @Override public void mouseMoved(MouseEvent e) { super.mouseMoved(e); mousePosition = e.getPoint(); if (SELECTION_MODE || connectionHandler().selectedComponent() != null) repaint(); } @Override public void mouseDragged(MouseEvent e) { super.mouseDragged(e); mousePosition = e.getPoint(); if (SELECTING) repaint(); } }; // key listener check if ctrl is pressed/released final KeyAdapter CTRL_listener = new KeyAdapter() { @Override public void keyTyped(KeyEvent e) { super.keyTyped(e); if (e.getKeyCode() == 17) LudemeNodeComponent.cltrPressed = true; } @Override public void keyPressed(KeyEvent e) { super.keyPressed(e); if (e.getKeyCode() == 17) LudemeNodeComponent.cltrPressed = true; } @Override public void keyReleased(KeyEvent e) { super.keyReleased(e); if (e.getKeyCode() == 17) LudemeNodeComponent.cltrPressed = false; } }; // # Mouse wheel listeners # /* Notes on proper scaling: - node is a box with 4 coords: (x1,y1);(x2,y2);(x3,y3);(x4,y4); - s is a scaling factor 1. translate (x1,y1): (x1-w/2, -1*(y1-h/2)) = (x', y') 2. scale (x',y') by s: (x'*s, y'*s) = (xs, ys) 3. scale h, w by s: hs = h*s, ws = w*s 4. translate (xs, ys) back: (xs+w/2, -1*ys+h/2) */ final MouseWheelListener wheelListener = new MouseAdapter() { @Override public void mouseWheelMoved(MouseWheelEvent e) { if(e.getWheelRotation() > 0) { DesignPalette.scale(1.02f); if (DesignPalette.SCALAR < 1.9f) scaleNodesPositions(0.98); } else { DesignPalette.scale(1.0f/1.02f); if (DesignPalette.SCALAR > 0.86f) scaleNodesPositions(1.0/0.98); } syncNodePositions(); repaint(); } }; /** * Iterate through nodes on a panel and scale their positions for zooming in/out */ void scaleNodesPositions(double scalar) { graph().getNodes().forEach(ludemeNode -> { Vector2D scaledPos = getScaledCoords(ludemeNode.pos(), scalar, Handler.getViewPortSize().width, Handler.getViewPortSize().height); ludemeNode.setPos(scaledPos); }); } /** * Scale coordinates of single node. * Usage of integer coordinates by java swing graphical components introduces rounding errors that may degrade scaling. * @param pos position to be scaled * @param scalar scalar * @param W screen width * @param H screen height * @return scaled position */ private Vector2D getScaledCoords(Vector2D pos, double scalar, double W, double H) { // account for changed viewport int viewportX = parentScrollPane.getViewport().getViewRect().x; int viewportY = parentScrollPane.getViewport().getViewRect().y; // translate into cartesian coordinates double xp = pos.x()-viewportX-W/2; double yp = (pos.y()-viewportY-H/2)*-1; // scale xp*=scalar; yp*=scalar; // return translated back to java swing scaled coordinates return new Vector2D(xp+viewportX+W/2, -1*yp+H/2+viewportY); } public List<Integer> selectedCompletion() { return selectedCompletion; } }
32,465
31.049358
221
java
Ludii
Ludii-master/PlayerDesktop/src/app/display/dialogs/visual_editor/view/panels/editor/backgrounds/CartesianGridBackground.java
package app.display.dialogs.visual_editor.view.panels.editor.backgrounds; import app.display.dialogs.visual_editor.view.designPalettes.DesignPalette; import java.awt.*; import java.awt.geom.Line2D; public class CartesianGridBackground implements IBackground { @Override public void paint(Rectangle viewRectangle, int width, int height, Graphics2D g2) { int lineWidth = DesignPalette.BACKGROUND_LINE_WIDTH; int frequency = DesignPalette.BACKGROUND_LINE_PADDING; g2.setColor(DesignPalette.BACKGROUND_VISUAL_HELPER()); g2.setStroke(new BasicStroke(lineWidth)); // draw vertical lines for (int x = 0; x < width; x += frequency) { Line2D line = new Line2D.Double(x, viewRectangle.y, x, viewRectangle.y+height); g2.draw(line); } // draw horizontal lines for (int y = 0; y < height; y += frequency) { Line2D line = new Line2D.Double(viewRectangle.x, y, viewRectangle.x+width, y); g2.draw(line); } } }
1,057
30.117647
91
java
Ludii
Ludii-master/PlayerDesktop/src/app/display/dialogs/visual_editor/view/panels/editor/backgrounds/DotGridBackground.java
package app.display.dialogs.visual_editor.view.panels.editor.backgrounds; import app.display.dialogs.visual_editor.view.designPalettes.DesignPalette; import java.awt.*; public class DotGridBackground implements IBackground { @Override public void paint(Rectangle viewRectangle, int width, int height, Graphics2D g2) { // draw background points // every 50 pixel a circle int paddingHorizontal = 35; int paddingvertical = 15; int frequency = DesignPalette.BACKGROUND_DOT_PADDING; int diameter = DesignPalette.BACKGROUND_DOT_DIAMETER; // to improve performance, only draw points that are in the visible area for (int i = paddingHorizontal; i < width - paddingHorizontal; i += frequency) { for (int j = paddingvertical; j < height - paddingvertical; j += frequency) { if(i < viewRectangle.x || i > viewRectangle.x + viewRectangle.width || j < viewRectangle.y || j > viewRectangle.y + viewRectangle.height) continue; g2.setColor(DesignPalette.BACKGROUND_VISUAL_HELPER()); g2.fillOval(i, j, diameter, diameter); } } } }
1,216
37.03125
153
java
Ludii
Ludii-master/PlayerDesktop/src/app/display/dialogs/visual_editor/view/panels/editor/backgrounds/EmptyBackground.java
package app.display.dialogs.visual_editor.view.panels.editor.backgrounds; import java.awt.*; public class EmptyBackground implements IBackground { @Override public void paint(Rectangle viewRectangle, int width, int height, Graphics2D g2) { // Nothing to do } }
285
21
85
java
Ludii
Ludii-master/PlayerDesktop/src/app/display/dialogs/visual_editor/view/panels/editor/backgrounds/IBackground.java
package app.display.dialogs.visual_editor.view.panels.editor.backgrounds; import java.awt.*; public interface IBackground { void paint(Rectangle viewRectangle, int width, int height, Graphics2D g2); }
207
22.111111
78
java
Ludii
Ludii-master/PlayerDesktop/src/app/display/dialogs/visual_editor/view/panels/editor/defineEditor/DefineEditor.java
package app.display.dialogs.visual_editor.view.panels.editor.defineEditor; import app.display.dialogs.visual_editor.handler.Handler; import app.display.dialogs.visual_editor.view.panels.IGraphPanel; import javax.swing.*; import java.awt.*; import java.util.HashMap; import java.util.Map; public class DefineEditor extends JPanel { /** * */ private static final long serialVersionUID = -5720022256564467244L; private final JTabbedPane tabbedPane = new JTabbedPane(SwingConstants.TOP, JTabbedPane.SCROLL_TAB_LAYOUT); private final Map<JScrollPane, DefineGraphPanel> defineGraphPanels = new HashMap<>(); private final Map<DefineGraphPanel, JScrollPane> defineScrollPanes = new HashMap<>(); public DefineEditor() { Handler.defineEditor = this; setLayout(new BorderLayout()); add(tabbedPane, BorderLayout.CENTER); tabbedPane.addTab(" + ", null, new JPanel(), "Add a new Define"); addNewPanel("New Define 1"); final JPopupMenu popupMenu = new JPopupMenu(); final JMenuItem addNewPanelMenuItem = new JMenuItem("Add New Define"); final JMenuItem removePanelMenuItem = new JMenuItem("Remove Selected Define"); addNewPanelMenuItem.addActionListener(e -> { addNewPanel("New Define " + (defineGraphPanels.size()+1)); tabbedPane.setSelectedIndex(tabbedPane.getTabCount() - 1); }); removePanelMenuItem.addActionListener(e -> removePanel((JScrollPane) tabbedPane.getSelectedComponent())); popupMenu.add(addNewPanelMenuItem); popupMenu.add(removePanelMenuItem); tabbedPane.setComponentPopupMenu(popupMenu); tabbedPane.addChangeListener(e -> { // if clicked on + button: if(tabbedPane.getSelectedIndex() == tabbedPane.indexOfTab(" + ")) { addNewPanel("New Define " + (defineGraphPanels.size()+1)); tabbedPane.setSelectedIndex(tabbedPane.getTabCount() - 1); } // update current graph panel IGraphPanel graphPanel = defineGraphPanels.get(tabbedPane.getSelectedComponent()); Handler.updateCurrentGraphPanel(graphPanel); }); setVisible(true); } public void addNewPanel(String name) { DefineGraphPanel graphPanel = new DefineGraphPanel(name, 10000, 10000); JScrollPane scrollPane = new JScrollPane(graphPanel); centerScrollPane(scrollPane); graphPanel.initialize(scrollPane); defineGraphPanels.put(scrollPane, graphPanel); defineScrollPanes.put(graphPanel, scrollPane); tabbedPane.addTab(name, scrollPane); tabbedPane.setSelectedComponent(scrollPane); } private void removePanel(JScrollPane scrollPane) { tabbedPane.remove(scrollPane); Handler.removeGraphPanel(defineGraphPanels.get(scrollPane)); defineScrollPanes.remove(defineGraphPanels.get(scrollPane)); defineGraphPanels.remove(scrollPane); } public void removalGraph(IGraphPanel graphPanel) { removePanel(defineScrollPanes.get(graphPanel)); } public void updateName(String name) { tabbedPane.setTitleAt(tabbedPane.getSelectedIndex(), name); } public JScrollPane currentScrollPane() { return (JScrollPane) tabbedPane.getSelectedComponent(); } public IGraphPanel currentGraphPanel() { return defineGraphPanels.get(currentScrollPane()); } private static void centerScrollPane(JScrollPane scrollPane) { Rectangle rect = scrollPane.getViewport().getViewRect(); int centerX = (scrollPane.getViewport().getViewSize().width - rect.width) / 2; int centerY = (scrollPane.getViewport().getViewSize().height - rect.height) / 2; scrollPane.getViewport().setViewPosition(new Point(centerX, centerY)); } }
3,932
32.615385
107
java
Ludii
Ludii-master/PlayerDesktop/src/app/display/dialogs/visual_editor/view/panels/editor/defineEditor/DefineGraphPanel.java
package app.display.dialogs.visual_editor.view.panels.editor.defineEditor; import app.display.dialogs.visual_editor.handler.Handler; import app.display.dialogs.visual_editor.model.DescriptionGraph; import app.display.dialogs.visual_editor.model.LudemeNode; import app.display.dialogs.visual_editor.view.panels.editor.GraphPanel; import javax.swing.*; public class DefineGraphPanel extends GraphPanel { /** * */ private static final long serialVersionUID = 493013782396870985L; private final DescriptionGraph GRAPH; public DefineGraphPanel(String name, int width, int height) { super(width, height); this.GRAPH = new DescriptionGraph(name, true); Handler.addGraphPanel(graph(), this); } @Override public DescriptionGraph graph() { return GRAPH; } @Override public void initialize(JScrollPane scrollPane) { super.initialize(scrollPane); // Create a "define" root node LudemeNode defineRoot = new LudemeNode(scrollPane.getViewport().getViewRect().x + (int)(scrollPane.getViewport().getViewRect().getWidth()/2), scrollPane.getViewport().getViewRect().y + (int)(scrollPane.getViewport().getViewRect().getHeight()/2), GraphPanel.symbolsWithoutConnection, true); defineRoot.setProvidedInput(defineRoot.currentNodeArguments().get(0),graph().title()); Handler.recordUserActions = false; Handler.addNode(graph(), defineRoot); Handler.updateInput(graph(), defineRoot, defineRoot.currentNodeArguments().get(0), graph().title()); Handler.recordUserActions = true; } @Override public boolean isDefineGraph() { return true; } }
1,712
30.145455
163
java
Ludii
Ludii-master/PlayerDesktop/src/app/display/dialogs/visual_editor/view/panels/editor/gameEditor/GameEditor.java
package app.display.dialogs.visual_editor.view.panels.editor.gameEditor; import app.display.dialogs.visual_editor.view.designPalettes.DesignPalette; import app.display.dialogs.visual_editor.view.panels.IGraphPanel; import javax.swing.*; import java.awt.*; /** * Panel for the game graph panel */ public class GameEditor extends JPanel { /** * */ private static final long serialVersionUID = -7742630637240183L; private final JScrollPane SCROLL_PANE; private final GameGraphPanel GRAPH_PANEL; public GameEditor() { setLayout(new BorderLayout()); GRAPH_PANEL = new GameGraphPanel(DesignPalette.DEFAULT_GRAPHPANEL_SIZE.width, DesignPalette.DEFAULT_GRAPHPANEL_SIZE.height); SCROLL_PANE = new JScrollPane(GRAPH_PANEL); centerScrollPane(); // center scroll pane position add(SCROLL_PANE, BorderLayout.CENTER); GRAPH_PANEL.initialize(SCROLL_PANE); setVisible(true); } private void centerScrollPane() { Rectangle rect = SCROLL_PANE.getViewport().getViewRect(); int centerX = (SCROLL_PANE.getViewport().getViewSize().width - rect.width) / 2; int centerY = (SCROLL_PANE.getViewport().getViewSize().height - rect.height) / 2; SCROLL_PANE.getViewport().setViewPosition(new Point(centerX, centerY)); } public IGraphPanel graphPanel() { return GRAPH_PANEL; } }
1,406
28.3125
133
java
Ludii
Ludii-master/PlayerDesktop/src/app/display/dialogs/visual_editor/view/panels/editor/gameEditor/GameGraphPanel.java
package app.display.dialogs.visual_editor.view.panels.editor.gameEditor; import app.display.dialogs.visual_editor.handler.Handler; import app.display.dialogs.visual_editor.model.LudemeNode; import app.display.dialogs.visual_editor.view.components.AddArgumentPanel; import app.display.dialogs.visual_editor.view.panels.editor.GraphPanel; import grammar.Grammar; import main.grammar.Clause; import main.grammar.Symbol; import javax.swing.*; import java.util.ArrayList; import java.util.List; public class GameGraphPanel extends GraphPanel { /** * */ private static final long serialVersionUID = 8032967124439631423L; private final AddArgumentPanel addDefinePanel = new AddArgumentPanel(new ArrayList<>(), this, false, true); public GameGraphPanel(int width, int height) { super(width, height); Handler.gameGraphPanel = this; Handler.addGraphPanel(graph(), this); Handler.updateCurrentGraphPanel(this); add(addDefinePanel); } @Override public void initialize(JScrollPane scrollPane) { super.initialize(scrollPane); // Create a "game" root node Handler.recordUserActions = false; LudemeNode gameLudemeNode = Handler.addNode(graph(), Grammar.grammar().symbolsByName("Game").get(0), null, scrollPane.getViewport().getViewRect().x + (int)(scrollPane.getViewport().getViewRect().getWidth()/2), scrollPane.getViewport().getViewRect().y + (int)(scrollPane.getViewport().getViewRect().getHeight()/2), false); // find default game clause Clause defaultGameClause; if(gameLudemeNode.symbolClauseMap().get(gameLudemeNode.symbol()).get(0).args().size() > 2) defaultGameClause = gameLudemeNode.symbolClauseMap().get(gameLudemeNode.symbol()).get(0); else defaultGameClause = gameLudemeNode.symbolClauseMap().get(gameLudemeNode.symbol()).get(1); Handler.updateCurrentClause(graph(), gameLudemeNode, defaultGameClause); Handler.recordUserActions = true; } public void showAddDefinePanel() { // Define Nodes List<LudemeNode> defines = Handler.defineNodes(); // Their Symbols List<Symbol> defineSymbols = new ArrayList<>(); for(LudemeNode n : defines) if(n!=null) defineSymbols.add(n.symbol()); // Update list of defines addDefinePanel.updateList(defineSymbols, defines); addDefinePanel.setVisible(true); addDefinePanel.setLocation(mousePosition()); addDefinePanel.searchField.requestFocus(); revalidate(); repaint(); } @Override public void hideAllAddArgumentPanels() { super.hideAllAddArgumentPanels(); addDefinePanel.setVisible(false); } }
2,831
33.120482
119
java
Ludii
Ludii-master/PlayerDesktop/src/app/display/dialogs/visual_editor/view/panels/editor/selections/FixedGroupSelection.java
package app.display.dialogs.visual_editor.view.panels.editor.selections; import java.awt.*; /** * Functionality for drawing selection box around grouped nodes * @author nic0gin */ public class FixedGroupSelection { /** * Padding for the fixed node group selection */ private static final int PADDING = 10; public static void drawGroupBox(Rectangle rect, Graphics2D g2d) { float[] dashingPattern = {10f, 4f}; Stroke stroke = new BasicStroke(2f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER, 1.0f, dashingPattern, 0.0f); g2d.setColor(new Color(51, 51, 51)); g2d.setStroke(stroke); g2d.drawRect(rect.x-PADDING, rect.y-PADDING, rect.width+PADDING*2, rect.height+PADDING*2); g2d.setColor(new Color(236, 221, 144, 50)); g2d.fillRect(rect.x-PADDING, rect.y-PADDING, rect.width+PADDING*2, rect.height+PADDING*2); } }
922
26.969697
98
java
Ludii
Ludii-master/PlayerDesktop/src/app/display/dialogs/visual_editor/view/panels/editor/selections/SelectionBox.java
package app.display.dialogs.visual_editor.view.panels.editor.selections; import java.awt.*; /** * Creates selection area for editor panel * @author nic0gin */ public class SelectionBox { private static Point A; private static Rectangle rect; private static SelectionBox sb; public SelectionBox(Point A) { SelectionBox.A = A; } public static void drawSelectionArea(Point A1, Point B, Graphics2D g2d) { if (sb == null) sb = new SelectionBox(A1); float[] dashingPattern = {10f, 4f}; Stroke stroke = new BasicStroke(2f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER, 1.0f, dashingPattern, 0.0f); g2d.setColor(new Color(92, 150, 242)); g2d.setStroke(stroke); int x = SelectionBox.A.x; int y = SelectionBox.A.y; int width = B.x - x; int height = B.y - y; if (B.getX() < x) { x = B.x; width = SelectionBox.A.x - x; } if (B.getY() < y) { y = B.y; height = SelectionBox.A.y - y; } g2d.drawRect(x, y, width, height); g2d.setColor(new Color(157, 210, 235, 50)); g2d.fillRect(x, y, width, height); SelectionBox.rect = new Rectangle(x, y, width, height); } public static void drawSelectionModeIdle(Point m, Graphics2D g2d) { float[] dashingPattern = {10f, 4f}; Stroke stroke = new BasicStroke(2f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER, 1.0f, dashingPattern, 0.0f); g2d.setColor(new Color(92, 150, 242)); g2d.setStroke(stroke); g2d.drawLine(m.x-10000,m.y,m.x+10000,m.y); g2d.drawLine(m.x,m.y+10000,m.x,m.y-10000); } public static Rectangle endSelection() { sb = null; return rect; } }
1,859
24.135135
75
java
Ludii
Ludii-master/PlayerDesktop/src/app/display/dialogs/visual_editor/view/panels/editor/tabPanels/LayoutSettingsPanel.java
package app.display.dialogs.visual_editor.view.panels.editor.tabPanels; import app.display.dialogs.visual_editor.LayoutManagement.DFBoxDrawing; import app.display.dialogs.visual_editor.LayoutManagement.GraphRoutines; import app.display.dialogs.visual_editor.LayoutManagement.LayoutHandler; import app.display.dialogs.visual_editor.LayoutManagement.NodePlacementRoutines; import app.display.dialogs.visual_editor.handler.Handler; import app.display.dialogs.visual_editor.view.panels.IGraphPanel; import app.display.dialogs.visual_editor.view.panels.editor.EditorSidebar; import javax.swing.*; import javax.swing.event.ChangeListener; import java.awt.*; /** * Class for the single instance of the Layout Settings Panel * @author nic0gin */ public class LayoutSettingsPanel extends JPanel { private static final long serialVersionUID = 1L; private final JSlider dSl; private final JSlider oSl; private final JSlider sSl; private final JSlider cSl; private final LayoutHandler lh; private final JLabel selectedComponent; private static LayoutSettingsPanel lsPanel; private boolean changeListen = true; private final JCheckBox autoPlacement = new JCheckBox("Automatic placement"); private final JCheckBox animatePlacement = new JCheckBox("Animate layout"); private final JButton fixNodes; private final JButton unfixNodes; private LayoutSettingsPanel() { setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS)); selectedComponent = new JLabel("Selection: Empty"); lh = Handler.currentGraphPanel.getLayoutHandler(); oSl = new JSlider(0, (int) (100 * GraphRoutines.odsTuning()[0])); dSl = new JSlider(0, (int) (100 * GraphRoutines.odsTuning()[1])); sSl = new JSlider(0, (int) (100 * GraphRoutines.odsTuning()[2])); cSl = new JSlider(0, 100); updateSliderValues(DFBoxDrawing.defaultO(), DFBoxDrawing.defaultD(), DFBoxDrawing.defaultS()); cSl.setValue(100); JLabel offsetText = new JLabel("Offset: " + getSliderValue(oSl)); JLabel distanceText = new JLabel("Distance: " + Math.round(getSliderValue(dSl)/GraphRoutines.odsTuning()[1]*100)/100.0); JLabel spreadText = new JLabel("Spread: " + Math.round(getSliderValue(sSl)/GraphRoutines.odsTuning()[2]*100)/100.0); JLabel compactnessText = new JLabel("Compactness: " + getSliderValue(cSl)); Dimension buttonDim = new Dimension(175, 20); JButton redraw = createButton("Arrange graph", buttonDim); JButton alignX = createButton("Align vertically", buttonDim); JButton alignY = createButton("Align horizontally", buttonDim); fixNodes = createButton("Group subtree", buttonDim); fixNodes.setEnabled(false); unfixNodes = createButton("Ungroup subtree", buttonDim); unfixNodes.setEnabled(false); redraw.addActionListener(lh.getEvaluateAndArrange()); alignX.addActionListener(e -> NodePlacementRoutines.alignNodes(Handler.currentGraphPanel.selectedNodes(), NodePlacementRoutines.X_AXIS, Handler.currentGraphPanel)); alignY.addActionListener(e -> NodePlacementRoutines.alignNodes(Handler.currentGraphPanel.selectedNodes(), NodePlacementRoutines.Y_AXIS, Handler.currentGraphPanel)); ChangeListener sliderUpdateListener = e -> { offsetText.setText("Offset: " + getSliderValue(oSl)); distanceText.setText("Distance: " + getSliderValue(dSl)); spreadText.setText("Spread: " + getSliderValue(sSl)); compactnessText.setText("Compactness: " + getSliderValue(cSl)); if (changeListen) { updateWeights(); executeDFSLayout(Handler.currentGraphPanel); } }; dSl.addChangeListener(sliderUpdateListener); oSl.addChangeListener(sliderUpdateListener); sSl.addChangeListener(sliderUpdateListener); cSl.addChangeListener(sliderUpdateListener); add(selectedComponent); // # Adding sliders # Box sliderBox = Box.createVerticalBox(); sliderBox.add(offsetText); sliderBox.add(oSl); sliderBox.add(distanceText); sliderBox.add(dSl); sliderBox.add(spreadText); sliderBox.add(sSl); sliderBox.add(compactnessText); sliderBox.add(cSl); add(sliderBox); // # Adding buttons # Box buttonBox = Box.createVerticalBox(); addAButton(redraw, buttonBox); addAButton(alignX, buttonBox); addAButton(alignY, buttonBox); add(buttonBox); // # Adding check boxes # autoPlacement.addChangeListener(e -> Handler.autoplacement = ((JCheckBox) e.getSource()).isSelected()); autoPlacement.setSelected(Handler.autoplacement); //add(autoPlacement); animatePlacement.addChangeListener(e -> Handler.animation = ((JCheckBox) e.getSource()).isSelected()); animatePlacement.setSelected(Handler.animation); //add(animatePlacement); // # Adding fix buttons fixNodes.addActionListener(e -> { Handler.currentGraphPanel.graph().getNode(Handler.currentGraphPanel.graph().selectedRoot()).setFixed(true); fixNodes.setEnabled(false); unfixNodes.setEnabled(true); Handler.currentGraphPanel.repaint(); }); unfixNodes.addActionListener(e -> { Handler.currentGraphPanel.graph().getNode(Handler.currentGraphPanel.graph().selectedRoot()).setFixed(false); fixNodes.setEnabled(true); unfixNodes.setEnabled(false); Handler.currentGraphPanel.repaint(); }); Box buttonFixBox = Box.createVerticalBox(); addAButton(fixNodes, buttonFixBox); addAButton(unfixNodes, buttonFixBox); add(buttonFixBox); JButton closeLayoutTab = createButton("Close Layout Settings", buttonDim); closeLayoutTab.addActionListener(e -> EditorSidebar.getEditorSidebar().setSidebarVisible(false)); Box closeBox = Box.createVerticalBox(); addAButton(closeLayoutTab, closeBox); add(closeBox); } /** * Adds a JButton of specified size to container */ private static void addAButton(JButton button, Container container) { button.setAlignmentX(Component.LEFT_ALIGNMENT); button.setPreferredSize(new Dimension(200, 20)); button.setMinimumSize(new Dimension(200, 20)); container.add(button); } /** * Creates a JButton with specified text and size */ private static JButton createButton(String text, Dimension size) { JButton button = new JButton(text); button.setPreferredSize(size); button.setMinimumSize(size); button.setMaximumSize(size); return button; } /** * Singleton getter method for layout settings panel */ public static LayoutSettingsPanel getLayoutSettingsPanel() { if (lsPanel == null) lsPanel = new LayoutSettingsPanel(); return lsPanel; } /** * Updates layout metrics values in LayoutHander according to slider values */ private void updateWeights() { lh.updateCompactness(getSliderValue(cSl)); lh.updateDFSWeights(getSliderValue(oSl), getSliderValue(dSl), getSliderValue(sSl)); } /** * Update slider values for layout metrics */ public void updateSliderValues(double o, double d, double s) { changeListen = false; oSl.setValue((int)(o * 100)); dSl.setValue((int)(d * 100)); sSl.setValue((int)(s * 100)); changeListen = true; } /** * Get slider value for arrangement */ private static double getSliderValue(JSlider slider) {return slider.getValue() / 100.0;} /** * Executes arrangement procedure of graph in a specified panel */ private static void executeDFSLayout(IGraphPanel graphPanel) { graphPanel.getLayoutHandler().arrangeTreeComponents(); } /** * Display name of selected ludeme node */ public void setSelectedComponent(String node, boolean subtree) { if (subtree) selectedComponent.setText("Selected subtree of: "+node); else selectedComponent.setText("Selected: "+node); } public void enableFixButton() { fixNodes.setEnabled(true); } public void disableFixButton() { fixNodes.setEnabled(false); } public void enableUnfixButton() { unfixNodes.setEnabled(true); } public void disableUnfixButton() { unfixNodes.setEnabled(false); } public JCheckBox animatePlacement() {return animatePlacement;} public JCheckBox autoPlacement() {return autoPlacement;} }
8,788
34.873469
172
java
Ludii
Ludii-master/PlayerDesktop/src/app/display/dialogs/visual_editor/view/panels/editor/textEditor/TextEditor.java
package app.display.dialogs.visual_editor.view.panels.editor.textEditor; import app.display.dialogs.visual_editor.handler.Handler; import javax.swing.*; import java.awt.*; import java.awt.event.FocusEvent; import java.awt.event.FocusListener; public class TextEditor extends JPanel { /** * */ private static final long serialVersionUID = -6330942893371205110L; JTextArea textArea = new JTextArea(""); public TextEditor() { super(); setLayout(new BorderLayout()); textArea.setText(""); textArea.addFocusListener(new FocusListener() { @Override public void focusLost(FocusEvent e) { textArea.setEditable(true); } @Override public void focusGained(FocusEvent e) { textArea.setEditable(false); } }); updateLud(); add(textArea, BorderLayout.CENTER); } public void updateLud() { textArea.setText(Handler.toLud()); } }
1,155
23.083333
72
java
Ludii
Ludii-master/PlayerDesktop/src/app/display/dialogs/visual_editor/view/panels/header/EditorPickerPanel.java
package app.display.dialogs.visual_editor.view.panels.header; import app.display.dialogs.visual_editor.view.VisualEditorPanel; import app.display.dialogs.visual_editor.view.designPalettes.DesignPalette; import javax.swing.*; public class EditorPickerPanel extends JPanel { /** * */ private static final long serialVersionUID = -6411018044454485107L; private final HeaderButton gameEditorBtn; private final HeaderButton defineEditorBtn; private final HeaderButton textEditorBtn; public EditorPickerPanel(VisualEditorPanel visualEditorPanel) { super(); setLayout(new BoxLayout(this, BoxLayout.X_AXIS)); gameEditorBtn = new HeaderButton(DesignPalette.GAME_EDITOR_ACTIVE(), DesignPalette.GAME_EDITOR_INACTIVE(), DesignPalette.GAME_EDITOR_HOVER(), "Game Editor", true, true); defineEditorBtn = new HeaderButton(DesignPalette.DEFINE_EDITOR_ACTIVE(), DesignPalette.DEFINE_EDITOR_INACTIVE(), DesignPalette.DEFINE_EDITOR_HOVER(), "Define Editor", false, true); textEditorBtn = new HeaderButton(DesignPalette.TEXT_EDITOR_ACTIVE(), DesignPalette.TEXT_EDITOR_INACTIVE(), DesignPalette.TEXT_EDITOR_HOVER(), ".lud", false, true); gameEditorBtn.setClickListenerOn(false); defineEditorBtn.setClickListenerOn(false); textEditorBtn.setClickListenerOn(false); gameEditorBtn.addActionListener(e -> { if(gameEditorBtn.isActive()) return; visualEditorPanel.openGameEditor(); gameEditorBtn.setActive(); defineEditorBtn.setInactive(); textEditorBtn.setInactive(); }); defineEditorBtn.addActionListener(e -> { if(defineEditorBtn.isActive()) return; visualEditorPanel.openDefineEditor(); defineEditorBtn.setActive(); gameEditorBtn.setInactive(); textEditorBtn.setInactive(); }); textEditorBtn.addActionListener(e -> { if(textEditorBtn.isActive()) return; visualEditorPanel.openTextEditor(); textEditorBtn.setActive(); gameEditorBtn.setInactive(); defineEditorBtn.setInactive(); }); setOpaque(false); add(Box.createHorizontalStrut(20)); add(gameEditorBtn); add(Box.createHorizontalStrut(10)); add(defineEditorBtn); add(Box.createHorizontalStrut(10)); add(textEditorBtn); } @Override public void repaint() { super.repaint(); if(gameEditorBtn == null) return; if(gameEditorBtn.ACTIVE_ICON != DesignPalette.GAME_EDITOR_ACTIVE()) { gameEditorBtn.ACTIVE_ICON = DesignPalette.GAME_EDITOR_ACTIVE(); gameEditorBtn.INACTIVE_ICON = DesignPalette.GAME_EDITOR_INACTIVE(); gameEditorBtn.HOVER_ICON = DesignPalette.GAME_EDITOR_HOVER(); gameEditorBtn.ACTIVE_COLOR = DesignPalette.HEADER_BUTTON_ACTIVE_COLOR(); gameEditorBtn.INACTIVE_COLOR = DesignPalette.HEADER_BUTTON_INACTIVE_COLOR(); gameEditorBtn.HOVER_COLOR = DesignPalette.HEADER_BUTTON_HOVER_COLOR(); gameEditorBtn.updateDP(); defineEditorBtn.ACTIVE_ICON = DesignPalette.DEFINE_EDITOR_ACTIVE(); defineEditorBtn.INACTIVE_ICON = DesignPalette.DEFINE_EDITOR_INACTIVE(); defineEditorBtn.HOVER_ICON = DesignPalette.DEFINE_EDITOR_HOVER(); defineEditorBtn.ACTIVE_COLOR = DesignPalette.HEADER_BUTTON_ACTIVE_COLOR(); defineEditorBtn.INACTIVE_COLOR = DesignPalette.HEADER_BUTTON_INACTIVE_COLOR(); defineEditorBtn.HOVER_COLOR = DesignPalette.HEADER_BUTTON_HOVER_COLOR(); defineEditorBtn.updateDP(); textEditorBtn.ACTIVE_ICON = DesignPalette.TEXT_EDITOR_ACTIVE(); textEditorBtn.INACTIVE_ICON = DesignPalette.TEXT_EDITOR_INACTIVE(); textEditorBtn.HOVER_ICON = DesignPalette.TEXT_EDITOR_HOVER(); textEditorBtn.ACTIVE_COLOR = DesignPalette.HEADER_BUTTON_ACTIVE_COLOR(); textEditorBtn.INACTIVE_COLOR = DesignPalette.HEADER_BUTTON_INACTIVE_COLOR(); textEditorBtn.HOVER_COLOR = DesignPalette.HEADER_BUTTON_HOVER_COLOR(); textEditorBtn.updateDP(); } } }
4,339
38.816514
188
java
Ludii
Ludii-master/PlayerDesktop/src/app/display/dialogs/visual_editor/view/panels/header/HeaderButton.java
package app.display.dialogs.visual_editor.view.panels.header; import app.display.dialogs.visual_editor.handler.Handler; import app.display.dialogs.visual_editor.view.designPalettes.DesignPalette; import javax.swing.*; import java.awt.*; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; public class HeaderButton extends JButton { /** * */ private static final long serialVersionUID = 1030696490446456185L; public Color ACTIVE_COLOR; public Color INACTIVE_COLOR; public Color HOVER_COLOR; public ImageIcon ACTIVE_ICON; public ImageIcon INACTIVE_ICON; public ImageIcon HOVER_ICON; final boolean selectable; boolean active; boolean clickListenerOn = true; public HeaderButton(ImageIcon activeIcon, ImageIcon inactiveIcon, ImageIcon hoverIcon, String text, boolean active, boolean selectable) { super(text); this.active = active; this.selectable = selectable; this.ACTIVE_ICON = activeIcon; this.INACTIVE_ICON = inactiveIcon; this.HOVER_ICON = hoverIcon; this.ACTIVE_COLOR = DesignPalette.HEADER_BUTTON_ACTIVE_COLOR(); this.INACTIVE_COLOR = DesignPalette.HEADER_BUTTON_INACTIVE_COLOR(); this.HOVER_COLOR = DesignPalette.HEADER_BUTTON_HOVER_COLOR(); if(active) setActive(); else setInactive(); setFont(new Font("Roboto Bold", Font.PLAIN, 12)); // make transparent setBorder(BorderFactory.createEmptyBorder()); setFocusPainted(false); setOpaque(false); setContentAreaFilled(false); setBorderPainted(false); addMouseListener(hoverMouseListener); } public void setClickListenerOn(boolean on) { clickListenerOn = on; } public void updateDP() { if(active) setActive(); else setInactive(); } @Override public void setEnabled(boolean enabled) { super.setEnabled(enabled); if(enabled) setActive(); else setInactive(); } public void setActive() { active = true; setForeground(ACTIVE_COLOR); setIcon(ACTIVE_ICON); repaint(); } public void setInactive() { active = false; setForeground(INACTIVE_COLOR); setIcon(INACTIVE_ICON); repaint(); } public void setHover() { setForeground(HOVER_COLOR); setIcon(HOVER_ICON); repaint(); } final MouseListener hoverMouseListener = new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { super.mouseClicked(e); if(!clickListenerOn) return; if (!active) { if (selectable) setActive(); } else if (selectable) { setInactive(); Handler.deactivateSelectionMode(); } } @Override public void mouseEntered(MouseEvent e) { if((selectable && !active) || (!selectable && active)) setHover(); } @Override public void mouseExited(MouseEvent e) { if(!active) setInactive(); else setActive(); } }; public boolean isActive() { return active; } }
3,538
22.751678
139
java
Ludii
Ludii-master/PlayerDesktop/src/app/display/dialogs/visual_editor/view/panels/header/HeaderPanel.java
package app.display.dialogs.visual_editor.view.panels.header; import app.display.dialogs.visual_editor.handler.Handler; import app.display.dialogs.visual_editor.view.VisualEditorPanel; import app.display.dialogs.visual_editor.view.designPalettes.DesignPalette; import javax.swing.*; import java.awt.*; public class HeaderPanel extends JPanel { /** * */ private static final long serialVersionUID = 3999066959490436008L; private final EditorPickerPanel editorPickerPanel; private final ToolsPanel toolsPanel; public HeaderPanel(VisualEditorPanel visualEditorPanel) { setLayout(new BorderLayout()); editorPickerPanel = new EditorPickerPanel(visualEditorPanel); add(editorPickerPanel, BorderLayout.LINE_START); toolsPanel = new ToolsPanel(); Handler.toolsPanel = toolsPanel; add(toolsPanel, BorderLayout.LINE_END); setOpaque(true); setBackground(DesignPalette.BACKGROUND_HEADER_PANEL()); int preferredHeight = getPreferredSize().height; setPreferredSize(new Dimension(getPreferredSize().width, preferredHeight+20)); } @Override public void paintComponent(Graphics g) { super.paintComponent(g); if(getBackground() != DesignPalette.BACKGROUND_HEADER_PANEL()) { setBackground(DesignPalette.BACKGROUND_HEADER_PANEL()); editorPickerPanel.repaint(); toolsPanel.repaint(); } } }
1,465
29.541667
86
java
Ludii
Ludii-master/PlayerDesktop/src/app/display/dialogs/visual_editor/view/panels/header/PlayButton.java
package app.display.dialogs.visual_editor.view.panels.header; import app.display.dialogs.visual_editor.handler.Handler; import app.display.dialogs.visual_editor.view.designPalettes.DesignPalette; import game.Game; import javax.swing.*; import java.awt.*; public class PlayButton extends JButton { /** * */ private static final long serialVersionUID = 2525022058118158573L; private boolean compilable = true; public PlayButton() { super("Play"); setIcon(DesignPalette.COMPILABLE_ICON); setFont(new Font("Roboto Bold", Font.PLAIN, 12)); setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); setFocusPainted(false); setOpaque(true); //setContentAreaFilled(false); setBorderPainted(false); setBackground(DesignPalette.COMPILABLE_COLOR()); setForeground(DesignPalette.PLAY_BUTTON_FOREGROUND()); // try to compile addActionListener(e -> { if (!compilable) { Handler.markUncompilable(); @SuppressWarnings("unchecked") java.util.List<String> errors = (java.util.List<String>) Handler.lastCompile[1]; String errorMessage = ""; if (errors.isEmpty()) { errorMessage = "Could not create \"game\" ludeme from description."; } else { errorMessage = errors.toString(); errorMessage = errorMessage.substring(1, errorMessage.length() - 1); } JOptionPane.showMessageDialog(null, errorMessage, "Couldn't compile", JOptionPane.ERROR_MESSAGE); } else { // try to compile Object[] output = Handler.compile(); if (output[0] != null) { setCompilable(); setToolTipText(null); Handler.play((Game) output[0]); } else { @SuppressWarnings("unchecked") java.util.List<String> errors = (java.util.List<String>) output[1]; String errorMessage = ""; if (errors.isEmpty()) { errorMessage = "Could not create \"game\" ludeme from description."; } else { errorMessage = errors.toString(); errorMessage = errorMessage.substring(1, errorMessage.length() - 1); } JOptionPane.showMessageDialog(this, errorMessage, "Couldn't compile", JOptionPane.ERROR_MESSAGE); } } }); } @Override public void paintComponent(Graphics g) { super.paintComponent(g); if(compilable) { if (getBackground() != DesignPalette.COMPILABLE_COLOR()) { setBackground(DesignPalette.COMPILABLE_COLOR()); setForeground(DesignPalette.PLAY_BUTTON_FOREGROUND()); } } else { if (getBackground() != DesignPalette.NOT_COMPILABLE_COLOR()) { setBackground(DesignPalette.NOT_COMPILABLE_COLOR()); setForeground(DesignPalette.PLAY_BUTTON_FOREGROUND()); } } } public void setNotCompilable() { compilable = false; setIcon(DesignPalette.NOT_COMPILABLE_ICON); setBackground(DesignPalette.NOT_COMPILABLE_COLOR()); } public void setCompilable() { compilable = true; setIcon(DesignPalette.COMPILABLE_ICON); setBackground(DesignPalette.COMPILABLE_COLOR()); } public void updateCompilable(Object[] output) { if (output[0] != null) { setCompilable(); setToolTipText(null); } else { @SuppressWarnings("unchecked") java.util.List<String> errors = (java.util.List<String>) output[1]; String errorMessage = ""; if (errors.isEmpty()) errorMessage = "Could not create \"game\" ludeme from description."; else { errorMessage = errors.toString(); errorMessage = errorMessage.substring(1, errorMessage.length() - 1); } setNotCompilable(); setToolTipText(errorMessage); } } }
4,585
31.295775
117
java
Ludii
Ludii-master/PlayerDesktop/src/app/display/dialogs/visual_editor/view/panels/header/ToolsPanel.java
package app.display.dialogs.visual_editor.view.panels.header; import app.display.dialogs.visual_editor.handler.Handler; import app.display.dialogs.visual_editor.model.UserActions.IUserAction; import app.display.dialogs.visual_editor.view.designPalettes.DesignPalette; import javax.swing.*; import java.util.Stack; public class ToolsPanel extends JPanel { /** * */ private static final long serialVersionUID = -8204545001319914476L; private final HeaderButton selectBtn = new HeaderButton(DesignPalette.SELECT_ACTIVE(), DesignPalette.SELECT_INACTIVE(), DesignPalette.SELECT_HOVER(), "Select", false, true); private final HeaderButton undoBtn = new HeaderButton(DesignPalette.UNDO_ACTIVE(), DesignPalette.UNDO_INACTIVE(), DesignPalette.UNDO_HOVER(), "Undo", false, false); private final HeaderButton redoBtn = new HeaderButton(DesignPalette.REDO_ACTIVE(), DesignPalette.REDO_INACTIVE(), DesignPalette.REDO_HOVER(), "Redo", false, false); public final PlayButton play = new PlayButton(); public ToolsPanel() { super(); setLayout(new BoxLayout(this, BoxLayout.X_AXIS)); setOpaque(false); undoBtn.addActionListener(e -> Handler.undo()); redoBtn.addActionListener(e -> Handler.redo()); selectBtn.addActionListener(e -> { if (!selectBtn.isActive()) Handler.activateSelectionMode(); // else Handler.deactivateSelectionMode(); }); add(selectBtn); add(Box.createHorizontalStrut(30)); add(undoBtn); add(Box.createHorizontalStrut(8)); add(redoBtn); add(Box.createHorizontalStrut(30)); add(play); add(Box.createHorizontalStrut(20)); } public void updateUndoRedoBtns(Stack<IUserAction> performedActions, Stack<IUserAction> undoneActions) { undoBtn.setEnabled(!performedActions.isEmpty()); redoBtn.setEnabled(!undoneActions.isEmpty()); if(!performedActions.isEmpty()) undoBtn.setToolTipText(performedActions.peek().actionType().toString()); else undoBtn.setToolTipText(null); if(!undoneActions.isEmpty()) redoBtn.setToolTipText(undoneActions.peek().actionType().toString()); else redoBtn.setToolTipText(null); } public void deactivateSelection() { selectBtn.setInactive(); selectBtn.repaint(); selectBtn.revalidate(); } @Override public void repaint() { super.repaint(); if(selectBtn == null) return; if(selectBtn.ACTIVE_COLOR != DesignPalette.HEADER_BUTTON_ACTIVE_COLOR()) { selectBtn.ACTIVE_ICON = DesignPalette.SELECT_ACTIVE(); selectBtn.INACTIVE_ICON = DesignPalette.SELECT_INACTIVE(); selectBtn.HOVER_ICON = DesignPalette.SELECT_HOVER(); selectBtn.ACTIVE_COLOR = DesignPalette.HEADER_BUTTON_ACTIVE_COLOR(); selectBtn.INACTIVE_COLOR = DesignPalette.HEADER_BUTTON_INACTIVE_COLOR(); selectBtn.HOVER_COLOR = DesignPalette.HEADER_BUTTON_HOVER_COLOR(); selectBtn.updateDP(); undoBtn.ACTIVE_ICON = DesignPalette.UNDO_ACTIVE(); undoBtn.INACTIVE_ICON = DesignPalette.UNDO_INACTIVE(); undoBtn.HOVER_ICON = DesignPalette.UNDO_HOVER(); undoBtn.ACTIVE_COLOR = DesignPalette.HEADER_BUTTON_ACTIVE_COLOR(); undoBtn.INACTIVE_COLOR = DesignPalette.HEADER_BUTTON_INACTIVE_COLOR(); undoBtn.HOVER_COLOR = DesignPalette.HEADER_BUTTON_HOVER_COLOR(); undoBtn.updateDP(); redoBtn.ACTIVE_ICON = DesignPalette.REDO_ACTIVE(); redoBtn.INACTIVE_ICON = DesignPalette.REDO_INACTIVE(); redoBtn.HOVER_ICON = DesignPalette.REDO_HOVER(); redoBtn.ACTIVE_COLOR = DesignPalette.HEADER_BUTTON_ACTIVE_COLOR(); redoBtn.INACTIVE_COLOR = DesignPalette.HEADER_BUTTON_INACTIVE_COLOR(); redoBtn.HOVER_COLOR = DesignPalette.HEADER_BUTTON_HOVER_COLOR(); redoBtn.updateDP(); } } }
4,079
37.857143
174
java
Ludii
Ludii-master/PlayerDesktop/src/app/display/dialogs/visual_editor/view/panels/menus/EditMenu.java
package app.display.dialogs.visual_editor.view.panels.menus; import app.display.dialogs.visual_editor.handler.Handler; import javax.swing.*; import java.awt.event.ActionListener; public class EditMenu extends JMenu { /** * */ private static final long serialVersionUID = 3590839696737937583L; public EditMenu(EditorMenuBar menuBar) { super("Edit"); EditorMenuBar.addJMenuItem(this, "Undo", undo, KeyStroke.getKeyStroke("control Z")); EditorMenuBar.addJMenuItem(this, "Redo", redo, KeyStroke.getKeyStroke("control Y")); add(new JSeparator()); EditorMenuBar.addJMenuItem(this, "Copy", copy, KeyStroke.getKeyStroke("control C")); EditorMenuBar.addJMenuItem(this, "Paste", paste, KeyStroke.getKeyStroke("control V")); EditorMenuBar.addJMenuItem(this, "Duplicate", duplicate, KeyStroke.getKeyStroke("control shift D")); EditorMenuBar.addJMenuItem(this, "Delete", delete, KeyStroke.getKeyStroke("control D")); add(new JSeparator()); EditorMenuBar.addJMenuItem(this, "Select All", selectAll, KeyStroke.getKeyStroke("control A")); EditorMenuBar.addJMenuItem(this, "Unselect All", unselectAll); EditorMenuBar.addJMenuItem(this, "Collapse", collapse, KeyStroke.getKeyStroke("control W")); EditorMenuBar.addJMenuItem(this, "Expand", expand, KeyStroke.getKeyStroke("control E")); EditorMenuBar.addJMenuItem(this, "Expand All", expandAll); add(new JSeparator()); EditorMenuBar.addJCheckBoxMenuItem(this, "Confirm Sensitive Actions", Handler.sensitivityToChanges, e -> Handler.sensitivityToChanges = !Handler.sensitivityToChanges); } final ActionListener undo = e -> Handler.undo(); final ActionListener redo = e -> Handler.redo(); final ActionListener copy = e -> Handler.copy(); final ActionListener paste = e -> Handler.paste(-1, -1); final ActionListener duplicate = e -> Handler.duplicate(); final ActionListener delete = e -> Handler.remove(); final ActionListener selectAll = e -> Handler.selectAll(); final ActionListener unselectAll = e -> Handler.unselectAll(); final ActionListener collapse = e -> Handler.collapse(); final ActionListener expand = e -> Handler.expand(); final ActionListener expandAll = e -> { Handler.selectAll(); Handler.expand(); }; }
2,378
38.65
175
java
Ludii
Ludii-master/PlayerDesktop/src/app/display/dialogs/visual_editor/view/panels/menus/EditorMenuBar.java
package app.display.dialogs.visual_editor.view.panels.menus; import app.display.dialogs.visual_editor.view.panels.menus.viewMenu.ViewMenu; import app.display.dialogs.visual_editor.view.panels.userGuide.UserGuideFrame; import javax.swing.*; import java.awt.event.ActionListener; /** * Menu bar of visual editor * @author nic0gin */ public class EditorMenuBar extends JMenuBar { /** * */ private static final long serialVersionUID = 1223558045694729428L; public EditorMenuBar() { JMenu settings = new JMenu("Settings"); // adjust editor settings e.g. font size, colors ect. // adding settings menu items addJMenuItem(settings, "Open settings...", null); JMenu about = new JMenu("Help"); // read about the editor: documentation, research report, DLP // adding about menu items addJMenuItem(about, "User Guide", e-> new UserGuideFrame()); addJMenuItem(about, "Documentation", null); addJMenuItem(about, "About Visual Editor...", null); // opens research paper addJMenuItem(about, "About DLP...", null); add(new FileMenu(this)); add(new EditMenu(this)); add(new ViewMenu(this)); add(new TreeLayoutMenu(this)); //add(settings); add(new RunMenu(this)); add(about); } public static void addJMenuItem(JMenu menu, String itemName, ActionListener actionListener) { JMenuItem jMenuItem = new JMenuItem(itemName); jMenuItem.addActionListener(actionListener); menu.add(jMenuItem); } public static void addJMenuItem(JMenu menu, String itemName, ActionListener actionListener, KeyStroke keyStroke) { JMenuItem jMenuItem = new JMenuItem(itemName); jMenuItem.addActionListener(actionListener); jMenuItem.setAccelerator(keyStroke); menu.add(jMenuItem); } public static void addJCheckBoxMenuItem(JMenu menu, String itemName, boolean selected, ActionListener actionListener) { JCheckBoxMenuItem jMenuItem = new JCheckBoxMenuItem(itemName); jMenuItem.addActionListener(actionListener); jMenuItem.setSelected(selected); menu.add(jMenuItem); } }
2,205
31.925373
121
java
Ludii
Ludii-master/PlayerDesktop/src/app/display/dialogs/visual_editor/view/panels/menus/FileMenu.java
package app.display.dialogs.visual_editor.view.panels.menus; import java.io.File; import javax.swing.JFileChooser; import javax.swing.JMenu; import javax.swing.filechooser.FileNameExtensionFilter; import app.display.dialogs.visual_editor.handler.Handler; import main.FileHandling; /** * File menu for visual editor * @author nic0gin */ public class FileMenu extends JMenu { /** * */ private static final long serialVersionUID = -6694747737057742537L; /** * Constructor */ public FileMenu(EditorMenuBar menuBar) { super("File"); // TODO: unfortunately we did not managed to complete all functionalities for this menu in time; // adding file menu items // menuBar.addJMenuItem(this, "New", null); // menuBar.addJMenuItem(this, "Open...", e -> openDescriptionFile()); // menuBar.addJMenuItem(this, "Open recent", null); // menuBar.addJMenuItem(this, "Close file", null); // add(new JSeparator()); // menuBar.addJMenuItem(this, "Save", null); // menuBar.addJMenuItem(this, "Save as...", null); EditorMenuBar.addJMenuItem(this, "Export as .lud", e -> exportAsLud()); // add(new JSeparator()); // menuBar.addJMenuItem(this, "Exit", null); } // /** // * Opens selection menu of .lud game description to be imported into graph panel // * TODO: utilized due to parsing issues // */ // private static void openDescriptionFile() // { // // reused code from class GameLoading method loadGameFromMemory // final String[] choices = FileHandling.listGames(); // String initialChoice = choices[0]; // final String choice = GameLoaderDialog.showDialog(DesktopApp.frame(), choices, initialChoice); // // if (choice != null) // { // String path = choice.replaceAll(Pattern.quote("\\"), "/"); // path = path.substring(path.indexOf("/lud/")); // // path = Objects.requireNonNull(GameLoader.class.getResource(path)).getPath(); // path = path.replaceAll(Pattern.quote("%20"), " "); // // File file = new File(path); // ProgressBar progressBar = new ProgressBar("Loading game from file", // null, 8); // StartGraphParsingThread(file, Handler.gameGraphPanel, progressBar); // } // } /** * Export game graph to .lud */ private static void exportAsLud() { String lud = Handler.toLud(); JFileChooser fileChooser = new JFileChooser(); fileChooser.setDialogTitle("Export as .lud"); fileChooser.addChoosableFileFilter(new FileNameExtensionFilter("Ludii Game", "lud")); int userSelection = fileChooser.showSaveDialog(Handler.visualEditorFrame); if(userSelection == JFileChooser.APPROVE_OPTION) { File file = fileChooser.getSelectedFile(); String path = file.getAbsolutePath(); if(!file.getName().endsWith(".lud")) path += ".lud"; FileHandling.saveStringToFile(lud, path, ""); } System.out.println("\n\n## GAME DESCRIPTION .lud ###"); System.out.println(lud); System.out.println("############################\n\n"); } // /** // * Initiates parsing of ludeme description to graph // */ // private static void StartGraphParsingThread(File file, IGraphPanel panel, ProgressBar progressBar) // { // // SwingWorker<?, ?> swingWorker = new SwingWorker<Object, Object>() // { // @Override // protected Object doInBackground() // { // GameParser.ParseFileToGraph(file, Handler.gameGraphPanel, progressBar); // return null; // } // // @Override // protected void done() // { // super.done(); // progressBar.close(); // panel.getLayoutHandler().executeLayout(); // } // }; // // swingWorker.execute(); // } }
4,082
30.651163
104
java
Ludii
Ludii-master/PlayerDesktop/src/app/display/dialogs/visual_editor/view/panels/menus/RunMenu.java
package app.display.dialogs.visual_editor.view.panels.menus; import app.display.dialogs.visual_editor.handler.Handler; import javax.swing.*; import java.awt.event.ActionListener; public class RunMenu extends JMenu { /** * */ private static final long serialVersionUID = -7766009187364586583L; public RunMenu(EditorMenuBar menuBar) { super("Run"); EditorMenuBar.addJMenuItem(this, "Compile", compile, KeyStroke.getKeyStroke("control shift R")); EditorMenuBar.addJMenuItem(this, "Play Game", play, KeyStroke.getKeyStroke("control P")); add(new JSeparator()); EditorMenuBar.addJCheckBoxMenuItem(this, "Auto Compile", Handler.liveCompile, autocompile); } final ActionListener autocompile = e -> Handler.liveCompile = ((JCheckBoxMenuItem) e.getSource()).isSelected(); final ActionListener compile = e -> Handler.compile(true); final ActionListener play = e -> Handler.play(); }
949
32.928571
115
java
Ludii
Ludii-master/PlayerDesktop/src/app/display/dialogs/visual_editor/view/panels/menus/TreeLayoutMenu.java
package app.display.dialogs.visual_editor.view.panels.menus; import app.display.dialogs.visual_editor.LayoutManagement.GraphAnimator; import app.display.dialogs.visual_editor.handler.Handler; import app.display.dialogs.visual_editor.view.panels.editor.EditorSidebar; import app.display.dialogs.visual_editor.view.panels.editor.tabPanels.LayoutSettingsPanel; import app.display.dialogs.visual_editor.view.panels.userGuide.LayoutUserGuideFrame; import javax.swing.*; public class TreeLayoutMenu extends JMenu { /** * */ private static final long serialVersionUID = -9127390803169376994L; public static final JMenuItem undoP = new JMenuItem("Undo Placement"); public static final JMenuItem redoP = new JMenuItem("Redo Placement"); /** * Constructor */ public TreeLayoutMenu(EditorMenuBar menuBar) { super("Layout"); undoP.setEnabled(false); redoP.setEnabled(false); undoP.addActionListener(e -> { GraphAnimator.getGraphAnimator().updateToInitPositions(); undoP.setEnabled(false); redoP.setEnabled(true); Handler.gameGraphPanel.repaint(); }); redoP.addActionListener(e -> { GraphAnimator.getGraphAnimator().updateToFinalPositions(); undoP.setEnabled(true); redoP.setEnabled(false); Handler.gameGraphPanel.repaint(); }); EditorMenuBar.addJMenuItem(this, "Arrange Graph", Handler.currentGraphPanel.getLayoutHandler().getEvaluateAndArrange()); add(new JSeparator()); add(undoP); add(redoP); add(new JSeparator()); EditorMenuBar.addJCheckBoxMenuItem(this, "Animation", Handler.animation, e -> { LayoutSettingsPanel.getLayoutSettingsPanel().animatePlacement().setSelected(((JCheckBoxMenuItem) e.getSource()).isSelected()); Handler.animation = ((JCheckBoxMenuItem) e.getSource()).isSelected(); }); EditorMenuBar.addJCheckBoxMenuItem(this, "Auto Placement", Handler.autoplacement, e -> { LayoutSettingsPanel.getLayoutSettingsPanel().autoPlacement().setSelected(((JCheckBoxMenuItem) e.getSource()).isSelected()); Handler.autoplacement = ((JCheckBoxMenuItem) e.getSource()).isSelected(); }); EditorMenuBar.addJCheckBoxMenuItem(this, "Preserve Configurations", Handler.autoplacement, e -> Handler.evaluateLayoutMetrics = ((JCheckBoxMenuItem) e.getSource()).isSelected()); add(new JSeparator()); EditorMenuBar.addJMenuItem(this, "Open Layout Settings", e -> { EditorSidebar.getEditorSidebar().setVisible(true); EditorSidebar.getEditorSidebar().setLayoutTabSelected(); }); EditorMenuBar.addJMenuItem(this, "Help", e -> new LayoutUserGuideFrame()); } }
2,847
35.987013
186
java
Ludii
Ludii-master/PlayerDesktop/src/app/display/dialogs/visual_editor/view/panels/menus/viewMenu/ViewMenu.java
package app.display.dialogs.visual_editor.view.panels.menus.viewMenu; import app.display.dialogs.visual_editor.handler.Handler; import app.display.dialogs.visual_editor.view.panels.menus.EditorMenuBar; import javax.swing.*; import java.awt.event.ActionListener; import java.util.List; public class ViewMenu extends JMenu { /** * */ private static final long serialVersionUID = -5378448276139884202L; public ViewMenu(EditorMenuBar menuBar) { super("View"); JMenu appearance = new JMenu("Colour Scheme"); JMenu background = new JMenu("Background"); JMenu fontSize = new JMenu("Font Size"); add(appearance); add(background); add(fontSize); List<String> paletteNames = Handler.palettes(); for (String paletteName : paletteNames) EditorMenuBar.addJMenuItem(appearance, paletteName, e -> Handler.setPalette(paletteName)); EditorMenuBar.addJMenuItem(background, "Dot Grid", dotGrid); EditorMenuBar.addJMenuItem(background, "Cartesian Grid", cartesianGrid); EditorMenuBar.addJMenuItem(background, "No Grid", noGrid); EditorMenuBar.addJMenuItem(fontSize, "Small", e->Handler.setFont("Small")); EditorMenuBar.addJMenuItem(fontSize, "Medium", e->Handler.setFont("Medium")); EditorMenuBar.addJMenuItem(fontSize, "Large", e->Handler.setFont("Large")); } final ActionListener dotGrid = e -> Handler.setBackground(Handler.DotGridBackground); final ActionListener cartesianGrid = e -> Handler.setBackground(Handler.CartesianGridBackground); final ActionListener noGrid = e -> Handler.setBackground(Handler.EmptyBackground); }
1,683
35.608696
102
java
Ludii
Ludii-master/PlayerDesktop/src/app/display/dialogs/visual_editor/view/panels/userGuide/LayoutUserGuideFrame.java
package app.display.dialogs.visual_editor.view.panels.userGuide; import app.display.dialogs.visual_editor.handler.Handler; import app.display.dialogs.visual_editor.view.designPalettes.DesignPalette; import javax.swing.*; import java.awt.*; import java.awt.event.WindowEvent; import java.util.ArrayList; import java.util.List; /** * Pop-up frame with helper information about layout management system * Heavily based on UserGuideFrame * @author nic0gin */ public class LayoutUserGuideFrame extends JFrame { /** * */ private static final long serialVersionUID = 8439659036667946213L; final List<UserGuideContentPanel> panels = new ArrayList<>(); UserGuideContentPanel currentPanel; JScrollPane scrollPane; int currentIndex; /** * Constructor */ public LayoutUserGuideFrame() { // set frame properties setTitle("Layout User Guide"); setSize(new Dimension(750, 440)); setLocationRelativeTo(Handler.visualEditorFrame); setDefaultCloseOperation(DISPOSE_ON_CLOSE); setLayout(new BorderLayout()); setBackground(DesignPalette.BACKGROUND_EDITOR()); initialiseContents(); currentIndex = 0; currentPanel = panels.get(currentIndex); scrollPane = new JScrollPane(currentPanel); // three buttons: previous, next, close JPanel buttonPanel = new JPanel(); buttonPanel.setLayout(new FlowLayout(FlowLayout.RIGHT)); buttonPanel.setBackground(DesignPalette.BACKGROUND_EDITOR()); JButton previousButton = new JButton("Previous"); previousButton.addActionListener(e -> previousPanel()); JButton nextButton = new JButton("Next"); nextButton.addActionListener(e -> nextPanel()); JButton closeButton = new JButton("Close"); closeButton.addActionListener(e -> dispatchEvent(new WindowEvent(this, WindowEvent.WINDOW_CLOSING))); buttonPanel.add(previousButton); buttonPanel.add(nextButton); buttonPanel.add(closeButton); add(buttonPanel, BorderLayout.SOUTH); add(scrollPane, BorderLayout.CENTER); setResizable(false); setVisible(true); // add user guide panel //add(new UserGuidePanel()); } private void initialiseContents() { String image; String paragraph; UserGuideContent content; List<UserGuideContent> contents; UserGuideContentPanel panel; // Layout menu image = "layout_menu.png"; paragraph = "<html> " + "<i>Arrange Graph</i>: Arranges layout of graph on the current panel. <br>" + " <br>" + "<i>Undo Placement</i>: Moves nodes on their previous position - before layout arranged by user. <br>" + " <br>" + "<i>Redo Placement</i>: Cancels actions of <i>Undo Placement</i>. <br>" + " <br>" + "<i>Animation</i>: Animate transition of nodes' positions when arranging the graph. <br>" + " <br>" + "<i>Auto Placement</i>: Nodes are placed automatically according to arrangement procedure <br>" + " with pre-specified layout configurations. <br>" + " <br>" + "<i>Preserve Configurations</i>: Update of layout configurations to match user-placement. <br>" + " <br>" + "<i>Open Layout Settings</i>: Opens sidebar with extended layout settings." + "</html>"; content = new UserGuideContent(paragraph, image); panel = new UserGuideContentPanel("Layout menu", content); panels.add(panel); // Advanced layout settings image = "sliders.png"; paragraph = "<html>" + "In the sidebar layout settings it possible to manually adjust metrics. <br>" + "By moving the sliders layout will be automatically updated. <br>" + " <br>" + "<i>Offset</i>: Relative position of subtree nodes regarding its root. <br>" + "0.0 - nodes are lower than root, 1.0 - nodes are higher than root. <br>" + " <br>" + "<i>Distance</i>: Distance between subtree nodes from its root. <br>" + "0.0 - minimum distance, 1.0 - maximum distance. <br>" + " <br>" + "<i>Spread</i>: inner spread of subtree nodes. <br>" + "0.0 - minimum spread, 1.0 - maximum spread. <br>" + " <br>" + "<i>Compactness</i>: with increase of value empty space is minimised. <br>" + "</html>"; content = new UserGuideContent(paragraph, image); contents = new ArrayList<>(); contents.add(content); image = "layout_btns.png"; paragraph = "<html>" + "The sidebar also provides extra functionalities for graph arrangement. <br>" + "The next page discusses each button in detail." + "</html>"; content = new UserGuideContent(paragraph, image); contents.add(content); panel = new UserGuideContentPanel("Sidebar: Advanced Layout Settings", contents); panels.add(panel); // Functionalities of sidebar buttons image = "layout_btns.png"; paragraph = "<html>" + "<i>Arrange Graph</i>: Executes arrangement procedure; tries to preserve induced layout metrics. <br>" + "</html>"; content = new UserGuideContent(paragraph, image); contents = new ArrayList<>(); contents.add(content); image = "align_vertically.png"; paragraph = "<html>"+ "<i>Align Vertically</i>: Aligns selected nodes to Y-coordinate of left-most selected node. <br>" + "</html>"; content = new UserGuideContent(paragraph, image); contents.add(content); image = "align_horizontally.png"; paragraph = "<html>"+ "<i>Align Horizontally</i>: Aligns selected nodes to X-coordinate of left-most selected node. <br>" + "</html>"; content = new UserGuideContent(paragraph, image); contents.add(content); image = "group_subtree.png"; paragraph = "<html>"+ "<i>Group subtree</i>: When subtree is selected (by double-click on a sub-root) it can be grouped into hyper-node, <br>" + "i.e. when arranging layout it is treated as a new single node. <br>" + "</html>"; content = new UserGuideContent(paragraph, image); contents.add(content); panel = new UserGuideContentPanel("Sidebar buttons", contents); panels.add(panel); } private void nextPanel() { if(currentIndex < panels.size() - 1) { currentIndex++; remove(scrollPane); currentPanel = panels.get(currentIndex); scrollPane = new JScrollPane(currentPanel); add(scrollPane, BorderLayout.CENTER); revalidate(); repaint(); } } private void previousPanel() { if(currentIndex > 0) { currentIndex--; remove(scrollPane); currentPanel = panels.get(currentIndex); scrollPane = new JScrollPane(currentPanel); add(scrollPane, BorderLayout.CENTER); revalidate(); repaint(); } } }
7,551
35.133971
138
java
Ludii
Ludii-master/PlayerDesktop/src/app/display/dialogs/visual_editor/view/panels/userGuide/UserGuideContent.java
package app.display.dialogs.visual_editor.view.panels.userGuide; import javax.imageio.ImageIO; import java.awt.*; import java.io.IOException; import java.util.ArrayList; import java.util.List; /** * Contains a paragraph + image (if any). * Displays image */ public class UserGuideContent { private final String paragraph; private final List<Image> images; /** * Constructor. * @param paragraph * @param imageNames Names of images in the folder Common/res/img/visual_editor/user_guide/ */ public UserGuideContent(String paragraph, List<String> imageNames) { this.paragraph = paragraph; images = new ArrayList<>(); for(String imageName : imageNames) { String path = "/visual_editor/user_guide/" + imageName; try { images.add(ImageIO.read(getClass().getResource(path))); } catch (IOException e) { throw new RuntimeException(e); } } } public UserGuideContent(String paragraph, String image) { this.paragraph = paragraph; List<String> imageNames = new ArrayList<>(); imageNames.add(image); images = new ArrayList<>(); for(String imageName : imageNames) { String path = "/visual_editor/user_guide/" + imageName; try { images.add(ImageIO.read(getClass().getResource(path))); } catch (IOException e) { throw new RuntimeException(e); } } } public List<Image> images() { return images; } public String paragraph() { return paragraph; } }
1,762
22.506667
95
java
Ludii
Ludii-master/PlayerDesktop/src/app/display/dialogs/visual_editor/view/panels/userGuide/UserGuideContentPanel.java
package app.display.dialogs.visual_editor.view.panels.userGuide; import javax.swing.*; import java.awt.*; import java.util.List; public class UserGuideContentPanel extends JPanel { /** * */ private static final long serialVersionUID = -3924543171342069471L; private JLabel titleLabel = new JLabel(); public UserGuideContentPanel(String title, List<UserGuideContent> contents) { setLayout(new BoxLayout(this, BoxLayout.Y_AXIS)); setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); titleLabel.setText(title); titleLabel.setFont(new Font("Arial", Font.BOLD, 20)); add(titleLabel); add(Box.createVerticalStrut(15)); for(UserGuideContent content : contents) { for(Image image : content.images()) { JLabel imageLabel = new JLabel(new ImageIcon(image)); add(imageLabel); } add (Box.createVerticalStrut(4)); JLabel paragraphLabel = new JLabel(content.paragraph()); paragraphLabel.setFont(new Font("Arial", Font.PLAIN, 16)); add(paragraphLabel); add (Box.createVerticalStrut(18)); } setVisible(true); } public UserGuideContentPanel(String title, UserGuideContent content) { setLayout(new BoxLayout(this, BoxLayout.Y_AXIS)); setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); titleLabel.setText(title); titleLabel.setFont(new Font("Arial", Font.BOLD, 20)); add(titleLabel); add(Box.createVerticalStrut(15)); for(Image image : content.images()) { JLabel imageLabel = new JLabel(new ImageIcon(image)); add(imageLabel); } add (Box.createVerticalStrut(4)); JLabel paragraphLabel = new JLabel(content.paragraph()); paragraphLabel.setFont(new Font("Arial", Font.PLAIN, 16)); add(paragraphLabel); add (Box.createVerticalStrut(18)); setVisible(true); } }
2,051
30.090909
79
java
Ludii
Ludii-master/PlayerDesktop/src/app/display/dialogs/visual_editor/view/panels/userGuide/UserGuideFrame.java
package app.display.dialogs.visual_editor.view.panels.userGuide; import app.display.dialogs.visual_editor.handler.Handler; import app.display.dialogs.visual_editor.view.designPalettes.DesignPalette; import javax.swing.*; import java.awt.*; import java.awt.event.WindowEvent; import java.util.ArrayList; import java.util.List; /** * Displays the user guide for the visual editor */ public class UserGuideFrame extends JFrame { /** * */ private static final long serialVersionUID = -6195079005810201411L; List<UserGuideContentPanel> panels = new ArrayList<>(); UserGuideContentPanel currentPanel; JScrollPane scrollPane; int currentIndex; /** * Constructor */ public UserGuideFrame() { // set frame properties setTitle("User Guide"); setSize(new Dimension(750, 440)); setLocationRelativeTo(Handler.visualEditorFrame); setDefaultCloseOperation(DISPOSE_ON_CLOSE); setLayout(new BorderLayout()); setBackground(DesignPalette.BACKGROUND_EDITOR()); initialiseContents(); currentIndex = 0; currentPanel = panels.get(currentIndex); scrollPane = new JScrollPane(currentPanel); // three buttons: previous, next, close JPanel buttonPanel = new JPanel(); buttonPanel.setLayout(new FlowLayout(FlowLayout.RIGHT)); buttonPanel.setBackground(DesignPalette.BACKGROUND_EDITOR()); JButton previousButton = new JButton("Previous"); previousButton.addActionListener(e -> previousPanel()); JButton nextButton = new JButton("Next"); nextButton.addActionListener(e -> nextPanel()); JButton closeButton = new JButton("Close"); closeButton.addActionListener(e -> dispatchEvent(new WindowEvent(this, WindowEvent.WINDOW_CLOSING))); buttonPanel.add(previousButton); buttonPanel.add(nextButton); buttonPanel.add(closeButton); add(buttonPanel, BorderLayout.SOUTH); add(scrollPane, BorderLayout.CENTER); setResizable(false); setVisible(true); // add user guide panel //add(new UserGuidePanel()); } private void initialiseContents() { String image; String paragraph = ""; UserGuideContent content; List<UserGuideContent> contents; UserGuideContentPanel panel; // What are nodes? image = "game_tooltip.png"; paragraph = "<html> " + "A node is a graphical element representing a Ludeme. <br>" + "Ludemes describe concepts related to rules and equipment. <br>" + "By hovering above the node's title, a description of the concept is displayed. <br>" + "<br>" + "Most Ludemes need to be provided with arguments.<br>" + "<br>" + "By creating and supplying nodes, a game can be described." + "</html>"; content = new UserGuideContent(paragraph, image); panel = new UserGuideContentPanel("What are nodes?", content); panels.add(panel); // Constructors image = "game_node_constructors.png"; paragraph = "<html>" + "A node can have different constructors. To access the list of constructors,<br>" + "click on the top right button of the node." + "</html>"; content = new UserGuideContent(paragraph, image); contents = new ArrayList<>(); contents.add(content); image = "piece_argument_tooltip.png"; paragraph = "<html>" + "You can hover over an argument field to display a short description of it." + "</html>"; content = new UserGuideContent(paragraph, image); contents.add(content); panel = new UserGuideContentPanel("Constructors", contents); panels.add(panel); // Non-Terminal Arguments image = "established_connection.png"; paragraph = "<html>" + "Non-terminal arguments are arguments that can be connected to another node.<br>" + "To connect a non-terminal argument to a node, click on the node and click onto the <br>" + "node to connect to." + "</html>"; content = new UserGuideContent(paragraph, image); contents = new ArrayList<>(); contents.add(content); image = "equipment_establish_connection_with_tip.png"; paragraph = "<html>"+ "Alternatively, you can click on an empty area to connect to a new node." + "</html>"; content = new UserGuideContent(paragraph, image); contents.add(content); panel = new UserGuideContentPanel("Non-Terminal Arguments", contents); panels.add(panel); // Optional Arguments image = "game_node.png"; paragraph = "<html>" + "Optional arguments are arguments that can be connected to a node, but are not required.<br>" + "Optional Non-Terminal Arguments are indicated by a blue connection component, whereas <br>" + "mandatory Non-Terminal Arguments are indicated by a red connection component." + "</html>"; content = new UserGuideContent(paragraph, image); contents = new ArrayList<>(); contents.add(content); image = "terminal_optional.png"; paragraph = "<html>" + "Terminal Optional Arguments (such as strings or numbers) have a \"x\" or \"+\" symbol <br>to disable/enable the argument." + "</html>"; content = new UserGuideContent(paragraph, image); contents.add(content); panel = new UserGuideContentPanel("Optional Arguments", contents); panels.add(panel); // Choice Arguments image = "choice.png"; paragraph = "<html>" + "Choice Arguments indicate that the current argument may be replaced by another. Upon clicking <br>" + "on the choice icon, you can select among all possible alternatives." + "</html>"; content = new UserGuideContent(paragraph, image); panel = new UserGuideContentPanel("Choice Arguments", content); panels.add(panel); // Collection Arguments image = "equipment_collection.png"; paragraph = "<html>" + "Collection Arguments mean that you can supply a list of the given argument. To add an additional <br>" + "element to the list, click on the <b>\"+\"</b> icon. To remove an element, click on the <b>\"-\"</b> icon." + "</html>"; content = new UserGuideContent(paragraph, image); panel = new UserGuideContentPanel("Collection Arguments", content); panels.add(panel); // Collapsing image = "game_eq_collapsed.png"; paragraph = "<html>" + "Nodes can be collapsed into their parent by <i>CTRL+W</i> or via the right-click menu.<br>" + "To expand use <i>CTRL+E</i> or the expand icon." + "</html>"; content = new UserGuideContent(paragraph, image); panel = new UserGuideContentPanel("Collapsing", content); panels.add(panel); // Select Subtree image = "double_click.png"; paragraph = "<html>" + "You can select a subtree by double-clicking on the node. <br>" + "Actions, such as copying, can be performed on all selected nodes at once." + "</html>"; content = new UserGuideContent(paragraph, image); panel = new UserGuideContentPanel("Select Subtree", content); panels.add(panel); // Compile & Play image = "toolbar.png"; paragraph = "<html>" + "To compile and play the game, click on the <b>Play</b> button on the toolbar <br>" + "situated at the top-right of the editor." + "</html>"; contents = new ArrayList<>(); content = new UserGuideContent(paragraph, image); contents.add(content); image = "auto_compile.png"; paragraph = "<html>" + "When the auto-compile feature is turned on, the game is compiled at every change to the <br>" + "description. <b>Warning!: This can be computationally expensive!</b> <br>" + "When the game is not compilable, the Play button appears red and offers disclosure." + "</html>"; content = new UserGuideContent(paragraph, image); contents.add(content); panel = new UserGuideContentPanel("Compile & Play", contents); panels.add(panel); } private void nextPanel() { if(currentIndex < panels.size() - 1) { currentIndex++; remove(scrollPane); currentPanel = panels.get(currentIndex); scrollPane = new JScrollPane(currentPanel); add(scrollPane, BorderLayout.CENTER); revalidate(); repaint(); } } private void previousPanel() { if(currentIndex > 0) { currentIndex--; remove(scrollPane); currentPanel = panels.get(currentIndex); scrollPane = new JScrollPane(currentPanel); add(scrollPane, BorderLayout.CENTER); revalidate(); repaint(); } } }
9,547
35.166667
141
java
Ludii
Ludii-master/PlayerDesktop/src/app/display/screenCapture/GifSequenceWriter.java
package app.display.screenCapture; import java.awt.image.RenderedImage; import java.io.IOException; import java.util.Iterator; import javax.imageio.IIOException; import javax.imageio.IIOImage; import javax.imageio.ImageIO; import javax.imageio.ImageTypeSpecifier; import javax.imageio.ImageWriteParam; import javax.imageio.ImageWriter; import javax.imageio.metadata.IIOMetadata; import javax.imageio.metadata.IIOMetadataNode; import javax.imageio.stream.ImageOutputStream; public class GifSequenceWriter { protected ImageWriter gifWriter; protected ImageWriteParam imageWriteParam; protected IIOMetadata imageMetaData; /** * Creates a new GifSequenceWriter * * @param outputStream the ImageOutputStream to be written to * @param imageType one of the imageTypes specified in BufferedImage * @param timeBetweenFramesMS the time between frames in milliseconds * @param loopContinuously whether the gif should loop repeatedly * @throws IIOException if no gif ImageWriters are found * * @author Elliot Kroo (elliot[at]kroo[dot]net) */ public GifSequenceWriter( final ImageOutputStream outputStream, final int imageType, final int timeBetweenFramesMS, final boolean loopContinuously) throws IIOException, IOException { // my method to create a writer gifWriter = getWriter(); imageWriteParam = gifWriter.getDefaultWriteParam(); final ImageTypeSpecifier imageTypeSpecifier = ImageTypeSpecifier.createFromBufferedImageType(imageType); imageMetaData = gifWriter.getDefaultImageMetadata(imageTypeSpecifier, imageWriteParam); final String metaFormatName = imageMetaData.getNativeMetadataFormatName(); final IIOMetadataNode root = (IIOMetadataNode) imageMetaData.getAsTree(metaFormatName); final IIOMetadataNode graphicsControlExtensionNode = getNode( root, "GraphicControlExtension"); graphicsControlExtensionNode.setAttribute("disposalMethod", "none"); graphicsControlExtensionNode.setAttribute("userInputFlag", "FALSE"); graphicsControlExtensionNode.setAttribute( "transparentColorFlag", "FALSE"); graphicsControlExtensionNode.setAttribute( "delayTime", Integer.toString(timeBetweenFramesMS / 10)); graphicsControlExtensionNode.setAttribute( "transparentColorIndex", "0"); final IIOMetadataNode commentsNode = getNode(root, "CommentExtensions"); commentsNode.setAttribute("CommentExtension", "Created by MAH"); final IIOMetadataNode appEntensionsNode = getNode( root, "ApplicationExtensions"); final IIOMetadataNode child = new IIOMetadataNode("ApplicationExtension"); child.setAttribute("applicationID", "NETSCAPE"); child.setAttribute("authenticationCode", "2.0"); final int loop = loopContinuously ? 0 : 1; child.setUserObject(new byte[]{ 0x1, (byte) (loop & 0xFF), (byte) ((loop >> 8) & 0xFF)}); appEntensionsNode.appendChild(child); imageMetaData.setFromTree(metaFormatName, root); gifWriter.setOutput(outputStream); gifWriter.prepareWriteSequence(null); } public void writeToSequence(final RenderedImage img) throws IOException { gifWriter.writeToSequence( new IIOImage( img, null, imageMetaData), imageWriteParam); } /** * Close this GifSequenceWriter object. This does not close the underlying * stream, just finishes off the GIF. */ public void close() throws IOException { gifWriter.endWriteSequence(); } /** * Returns the first available GIF ImageWriter using * ImageIO.getImageWritersBySuffix("gif"). * * @return a GIF ImageWriter object * @throws IIOException if no GIF image writers are returned */ private static ImageWriter getWriter() throws IIOException { final Iterator<ImageWriter> iter = ImageIO.getImageWritersBySuffix("gif"); if(!iter.hasNext()) { throw new IIOException("No GIF Image Writers Exist"); } else { return iter.next(); } } /** * Returns an existing child node, or creates and returns a new child node (if * the requested node does not exist). * * @param rootNode the <tt>IIOMetadataNode</tt> to search for the child node. * @param nodeName the name of the child node. * * @return the child node, if found or a new node created with the given name. */ private static IIOMetadataNode getNode( final IIOMetadataNode rootNode, final String nodeName) { final int nNodes = rootNode.getLength(); for (int i = 0; i < nNodes; i++) { if (rootNode.item(i).getNodeName().compareToIgnoreCase(nodeName) == 0) { return((IIOMetadataNode) rootNode.item(i)); } } final IIOMetadataNode node = new IIOMetadataNode(nodeName); rootNode.appendChild(node); return(node); } }
4,486
28.715232
78
java
Ludii
Ludii-master/PlayerDesktop/src/app/display/screenCapture/ScreenCapture.java
package app.display.screenCapture; import java.awt.AWTException; import java.awt.EventQueue; import java.awt.Point; import java.awt.Rectangle; import java.awt.Robot; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Timer; import java.util.TimerTask; import javax.imageio.ImageIO; import javax.imageio.stream.FileImageOutputStream; import javax.imageio.stream.ImageOutputStream; import app.DesktopApp; public class ScreenCapture { //------------------------------------------------------------------------- // Variables for coordinating gif animation generation. static boolean gifScreenshotTimerComplete = true; static boolean gifSaveImageTimerComplete = true; static boolean gifCombineImageTimerComplete = true; static boolean screenshotComplete = true; //------------------------------------------------------------------------- /** * Save a screenshot of the current game board state. */ public static void gameScreenshot(final String savedName) { screenshotComplete = false; EventQueue.invokeLater(() -> { Robot robot = null; try { robot = new Robot(); } catch (final AWTException e) { e.printStackTrace(); } final java.awt.Container panel = DesktopApp.frame().getContentPane(); final Point pos = panel.getLocationOnScreen(); final Rectangle bounds = panel.getBounds(); bounds.x = pos.x; bounds.y = pos.y; bounds.x -= 1; bounds.y -= 1; bounds.width += 2; bounds.height += 2; final BufferedImage snapShot = robot.createScreenCapture(bounds); try { final File outputFile = new File(savedName + ".png"); outputFile.getParentFile().mkdirs(); ImageIO.write(snapShot, "png", outputFile); screenshotComplete = true; } catch (final Exception e) { try { final File outputFile = new File(savedName + ".png"); ImageIO.write(snapShot, "png", outputFile); screenshotComplete = true; } catch (final IOException e2) { e.printStackTrace(); } } }); } //------------------------------------------------------------------------- /** * Save a gif animation of the current game board state. */ public static void gameGif(final String savedName, final int numberPictures) { gifCombineImageTimerComplete = false; gifSaveImageTimerComplete = false; gifScreenshotTimerComplete = false; EventQueue.invokeLater(() -> { final int delay = 100; // First, set up our robot to take several pictures, based on the above parameters. Robot robotTemp = null; try { robotTemp = new Robot(); } catch (final AWTException e) { e.printStackTrace(); } final Robot robot = robotTemp; final java.awt.Container panel = DesktopApp.frame().getContentPane(); final Point pos = panel.getLocationOnScreen(); final Rectangle bounds = panel.getBounds(); bounds.x = pos.x; bounds.y = pos.y; bounds.x -= 1; bounds.y -= 1; bounds.width += 2; bounds.height += 2; final List<BufferedImage> snapshots = new ArrayList<>(); final List<String> imgLst = new ArrayList<>(); final Timer screenshotTimer = new Timer(); screenshotTimer.scheduleAtFixedRate(new TimerTask() { int index = 0; @Override public void run() { if (index >= numberPictures) { System.out.println("Gif images taken."); gifScreenshotTimerComplete = true; screenshotTimer.cancel(); screenshotTimer.purge(); } else { final BufferedImage snapshot = robot.createScreenCapture(bounds); snapshots.add(snapshot); index++; } } }, 0, delay); // Second, save these pictures as jpeg files. final Timer saveImageTimer = new Timer(); saveImageTimer.scheduleAtFixedRate(new TimerTask() { @Override public void run() { if (gifScreenshotTimerComplete) { for (int i = 0; i < snapshots.size(); i++) { final BufferedImage snapshot = snapshots.get(i); try { final String imageName = savedName + i + ".jpeg"; final File outputFile = new File(imageName); try { outputFile.getParentFile().mkdirs(); } catch (final Exception e) { // didn't need to mkdirs } ImageIO.write(snapshot, "jpeg", new File(imageName)); imgLst.add(imageName); } catch (final IOException e) { e.printStackTrace(); } } System.out.println("Gif images saved."); gifSaveImageTimerComplete = true; saveImageTimer.cancel(); saveImageTimer.purge(); } } }, 0, delay); // Third, Combine these jpeg files into a single .gif animation final Timer combineImageTimer = new Timer(); combineImageTimer.scheduleAtFixedRate(new TimerTask() { @Override public void run() { if (gifSaveImageTimerComplete) { final String videoLocation = savedName + ".gif"; try { // grab the output image type from the first image in the sequence final BufferedImage firstImage = ImageIO.read(new File(imgLst.get(0))); // create a new BufferedOutputStream with the last argument try(final ImageOutputStream output = new FileImageOutputStream(new File(videoLocation))) { // create a gif sequence with the type of the first image, 10 milliseconds between frames, which loops continuously. final GifSequenceWriter writer = new GifSequenceWriter(output, firstImage.getType(), 1, true); // write out all images in our sequence. for(int i=0; i<imgLst.size(); i++) { final File imageFile = new File(imgLst.get(i)); final BufferedImage nextImage = ImageIO.read(imageFile); writer.writeToSequence(nextImage); imageFile.delete(); } writer.close(); } System.out.println("Gif animation completed. (" + videoLocation + ")"); gifCombineImageTimerComplete = true; combineImageTimer.cancel(); combineImageTimer.purge(); } catch (final IOException e) { e.printStackTrace(); } } } }, 0, delay); }); } //------------------------------------------------------------------------- public static boolean gifAnimationComplete() { return gifCombineImageTimerComplete; } public static boolean screenshotComplete() { return screenshotComplete; } public static void resetGifAnimationVariables() { gifCombineImageTimerComplete = false; gifSaveImageTimerComplete = false; gifScreenshotTimerComplete = false; } public static void resetScreenshotVariables() { screenshotComplete = false; } //------------------------------------------------------------------------- }
7,101
25.5
124
java
Ludii
Ludii-master/PlayerDesktop/src/app/display/util/DesktopGUIUtil.java
package app.display.util; import java.awt.Point; import java.awt.Rectangle; import java.util.ArrayList; import app.DesktopApp; import app.PlayerApp; import app.views.players.PlayerViewUser; import main.Constants; import manager.ai.AIRegistry; import metadata.graphics.util.PieceStackType; import metadata.graphics.util.StackPropertyType; import other.context.Context; import other.location.Location; import other.state.container.ContainerState; import util.ContainerUtil; /** * Utility functions for the GUI. * * @author Matthew Stephenson */ public class DesktopGUIUtil { //------------------------------------------------------------------------- /** * If the current system is a Mac computer. */ public static boolean isMac() { final String osName = System.getProperty("os.name"); final boolean isMac = osName.toLowerCase().startsWith("mac os x"); return isMac; } //------------------------------------------------------------------------- /** * Get a list of all AI display names. */ public static ArrayList<String> getAIDropdownStrings(final PlayerApp app, final boolean includeHuman) { final ArrayList<String> allStrings = new ArrayList<>(); if (includeHuman) allStrings.add("Human"); allStrings.addAll(AIRegistry.generateValidAgentNames(app.contextSnapshot().getContext(app).game())); allStrings.add("From JAR"); allStrings.add("From JSON"); allStrings.add("From AI.DEF"); return allStrings; } //----------------------------------------------------------------------------- /** * Repaints the necessary area for a component moving between two points. */ public static void repaintComponentBetweenPoints(final PlayerApp app, final Context context, final Location componentLocation, final Point oldPoint, final Point newPoint) { try { if (app.contextSnapshot().getContext(app).game().hasLargePiece()) { DesktopApp.view().repaint(); return; } // If any of the player panels have been moved due to metadata, repaint the whole board. for (final PlayerViewUser panel : DesktopApp.view().getPlayerPanel().playerSections) { if (context.game().metadata().graphics().handPlacement(context, panel.playerId()) != null) { DesktopApp.view().repaint(); return; } } // Determine the size of the component image being dragged. final int cellSize = app.bridge().getContainerStyle(context.board().index()).cellRadiusPixels() * 2; final int containerId = ContainerUtil.getContainerId(context, componentLocation.site(), componentLocation.siteType()); final ContainerState cs = context.state().containerStates()[containerId]; final int localState = cs.state(componentLocation.site(), componentLocation.level(), componentLocation.siteType()); final int who = cs.who(componentLocation.site(), componentLocation.level(), componentLocation.siteType()); final int value = cs.value(componentLocation.site(), componentLocation.level(), componentLocation.siteType()); final int rotation = cs.rotation(componentLocation.site(), componentLocation.level(), componentLocation.siteType()); final PieceStackType componentStackType = PieceStackType.getTypeFromValue((int) context.metadata().graphics().stackMetadata(context, context.equipment().containers()[containerId], componentLocation.site(), componentLocation.siteType(), localState, value, StackPropertyType.Type)); // Find the largest component image in the stack. int maxComponentSize = cellSize; for (int level = componentLocation.level(); level < Constants.MAX_STACK_HEIGHT; level++) { final int what = cs.what(componentLocation.site(), componentLocation.level(), componentLocation.siteType()); if (what == 0) break; final int componentSize = app.graphicsCache().getComponentImageSize(containerId, what, who, localState, value, 0, rotation); if (componentSize > maxComponentSize) maxComponentSize = componentSize; } int midX = (newPoint.x + oldPoint.x) / 2; int midY = (newPoint.y + oldPoint.y) / 2; int width = ((Math.abs(newPoint.x - oldPoint.x) + maxComponentSize + cellSize)); int height = ((Math.abs(newPoint.y - oldPoint.y) + maxComponentSize + cellSize)); // If the component is stacked in a vertical manner, need to repaint the whole column. if (componentStackType.verticalStack()) { height = DesktopApp.frame().getHeight(); midY = height/2; } // If the component is stacked in a horizontal manner, need to repaint the whole row. if (componentStackType.horizontalStack()) { width = DesktopApp.frame().getWidth(); midX = width/2; } final Rectangle repaintArea = new Rectangle(midX - width/2, midY - height/2, width, height); DesktopApp.view().repaint(repaintArea); } catch (final Exception e) { // mouse off screen } } //----------------------------------------------------------------------------- }
4,948
34.099291
283
java
Ludii
Ludii-master/PlayerDesktop/src/app/display/util/DevTooltip.java
package app.display.util; import java.awt.Point; import java.awt.image.BufferedImage; import java.io.File; import java.util.regex.Pattern; import javax.imageio.ImageIO; import javax.swing.ToolTipManager; import org.jfree.graphics2d.svg.SVGGraphics2D; import app.DesktopApp; import app.PlayerApp; import app.utils.SVGUtil; import app.views.tools.ToolButton; import game.Game; import game.equipment.component.Card; import game.equipment.component.Component; import game.types.board.SiteType; import game.types.component.CardType; import main.Constants; import other.context.Context; import other.location.Location; import other.state.container.ContainerState; import util.ContainerUtil; import util.LocationUtil; import view.component.ComponentStyle; /** * Tooltip used for displaying developer information. * * @author Matthew.Stephenson */ public class DevTooltip { //------------------------------------------------------------------------- /** * Display a tool tip message for the current point * Shows the following values: * - cellIndex * - componentName * - componentIndex * - cellOwner * - localState * - rotationState * - countState * - hidden value for each player * - component image */ public static void displayToolTipMessage(final PlayerApp app, final Point pt) { ToolTipManager.sharedInstance().setDismissDelay(Integer.MAX_VALUE); ToolTipManager.sharedInstance().setReshowDelay(500); boolean toolTipShown = false; // If cursor is over any tool buttons then print message. for (final ToolButton toolButton : DesktopApp.view().toolPanel().buttons) { if (toolButton != null && toolButton.mouseOver()) { String toolTipMessage = "<html>"; toolTipMessage += toolButton.tooltipMessage(); toolTipMessage += "</html>"; DesktopApp.view().setToolTipText(toolTipMessage); toolTipShown = true; break; } } // If dev tooltips are on, show full information. if ( !toolTipShown && app.settingsPlayer().cursorTooltipDev() && app.manager().settingsNetwork().getActiveGameId() == 0 ) { try { final Context context = app.manager().ref().context(); final Game game = context.game(); ToolTipManager.sharedInstance().setEnabled(true); final Point ptOff = new Point(pt.x, pt.y); final Location location = LocationUtil.calculateNearestLocation(context, app.bridge(), ptOff, LocationUtil.getAllLocations(context, app.bridge())); final int index = location.site(); final int level = location.level(); final SiteType type = location.siteType(); final int containerId = ContainerUtil.getContainerId(context, index, type); final ContainerState cs = context.state().containerStates()[containerId]; final int componentIndex = cs.what(index, level, type); String componentName = ""; Component component = null; if (componentIndex != 0) { component = context.equipment().components()[componentIndex]; componentName = component.name(); } final int owner = cs.who(index, level, type); final int localState = cs.state(index, level, type); final int rotationState = cs.rotation(index, level, type); final int countState = cs.count(index, type); final int cardSuit = component.isCard() ? ((Card)component).suit() : Constants.UNDEFINED; final int cardRank = component.rank(); final int trumpRank = component.trumpRank(); final int trumpValue = component.trumpValue(); final CardType cardType = component.cardType(); final int value1 = cs.value(index, level, type); final int value2 = component.getValue2(); final int stackSize = cs.sizeStack(index, type); final String[] hiddenArray = new String[game.players().count()+1]; if (game.hiddenInformation() || game.hasCard()) { for (int i = 1; i <= game.players().count(); i++) { final boolean hidden = cs.isHidden(i, index, level, type); final boolean hiddenWhat = cs.isHiddenWhat(i, index, level, type); final boolean hiddenWho = cs.isHiddenWho(i, index, level, type); final boolean hiddenCount = cs.isHiddenState(i, index, level, type); final boolean hiddenValue = cs.isHiddenValue(i, index, level, type); final boolean hiddenState = cs.isHiddenCount(i, index, level, type); final boolean hiddenRotation = cs.isHiddenRotation(i, index, level, type); hiddenArray[i] = "hidden: " + hidden + ", hiddenWhat: " + hiddenWhat + ", hiddenWho: " + hiddenWho + ", hiddenCount: " + hiddenCount + ", hiddenValue: " + hiddenValue + ", hiddenState: " + hiddenState + ", hiddenRotation: " + hiddenRotation; } } String toolTipMessage = "<html>"; try { final int imageSize = 100; // this size of the image when displayed on the tooltip final File outputfile = File.createTempFile("tooltipImage", ".png"); outputfile.deleteOnExit(); String fullPath = outputfile.getAbsolutePath(); fullPath = "file:" + fullPath.replaceAll(Pattern.quote("\\"), "/"); final ComponentStyle componentStyle = app.bridge().getComponentStyle(component.index()); componentStyle.renderImageSVG(context, containerId, imageSize, localState, value1, true, 0, rotationState); final SVGGraphics2D svg = app.bridge().getComponentStyle(component.index()).getImageSVG(localState); final BufferedImage toolTipImage = SVGUtil.createSVGImage(svg.getSVGDocument(), imageSize, imageSize); ImageIO.write(toolTipImage, "png", outputfile); toolTipMessage += "<img src=\"" + fullPath + "\">" +"<br>"; } catch (final Exception e) { // something went wrong when displaying the image, carry on. } toolTipMessage += "Index: " + index +"<br>"; if (type != null) toolTipMessage += "Type: " + type +"<br>"; if (componentIndex != 0) toolTipMessage += "componentName: " + componentName +"<br>"; if (componentIndex != 0) toolTipMessage += "componentIndex: " + componentIndex +"<br>"; if (owner != 0) toolTipMessage += "Owner: " + owner +"<br>"; if (localState != 0) toolTipMessage += "localState: " + localState +"<br>"; //if (rotationState != 0) toolTipMessage += "rotationState: " + rotationState +"<br>"; if (countState != 0) toolTipMessage += "countState: " + countState +"<br>"; if (value1 != -1) toolTipMessage += "value1: " + value1 +"<br>"; if (value2 != -1) toolTipMessage += "value2: " + value2 +"<br>"; if (game.isStacking()) { toolTipMessage += "stackSize: " + stackSize +"<br>"; toolTipMessage += "level: " + level +"<br>"; } if (game.hasCard()) { toolTipMessage += "cardSuit: " + cardSuit +"<br>"; toolTipMessage += "cardRank: " + cardRank +"<br>"; toolTipMessage += "trumpRank: " + trumpRank +"<br>"; toolTipMessage += "trumpValue: " + trumpValue +"<br>"; toolTipMessage += "cardType: " + cardType +"<br>"; } for (int i = 1; i < hiddenArray.length; i++) { if (hiddenArray[i] != null) { toolTipMessage += "Player " + (i) + ": " + hiddenArray[i] +"<br>"; } } toolTipMessage += "</html>"; DesktopApp.view().setToolTipText(toolTipMessage); toolTipShown = true; } catch (final Exception e) { //e.printStackTrace(); DesktopApp.view().setToolTipText(null); return; } } if (!toolTipShown) DesktopApp.view().setToolTipText(null); } //------------------------------------------------------------------------- }
7,665
33.223214
247
java
Ludii
Ludii-master/PlayerDesktop/src/app/display/util/Thumbnails.java
package app.display.util; import java.awt.Graphics2D; import java.awt.RenderingHints; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.util.concurrent.ThreadLocalRandom; import javax.imageio.ImageIO; import app.DesktopApp; import app.PlayerApp; import app.utils.BufferedImageUtil; import app.utils.GameUtil; import app.utils.SVGUtil; import game.equipment.container.board.Board; import main.DatabaseInformation; import other.context.Context; import other.trial.Trial; import util.PlaneType; import view.container.ContainerStyle; import view.container.styles.board.BoardlessStyle; /** * Functions for generating thumbnail images. * * @author Matthew Stephenson */ public class Thumbnails { //------------------------------------------------------------------------- /** * Take snapshots of the current game's starting position and end position. */ public static void generateThumbnails(final PlayerApp app, final boolean includeRulesetName) { final int imageSize = DesktopApp.view().getBoardPanel().boardSize(); final Board board = app.manager().ref().context().board(); final Context context = app.manager().ref().context(); boolean boardEmptyAtStart = true; for (int i = 0; i < app.manager().ref().context().board().topology().cells().size(); i++) if (context.containerState(0).whatCell(i) != 0) boardEmptyAtStart = false; for (int i = 0; i < app.manager().ref().context().board().topology().vertices().size(); i++) if (context.containerState(0).whatVertex(i) != 0) boardEmptyAtStart = false; for (int i = 0; i < app.manager().ref().context().board().topology().edges().size(); i++) if (context.containerState(0).whatEdge(i) != 0) boardEmptyAtStart = false; final ContainerStyle boardStyle = app.bridge().getContainerStyle(board.index()); final BufferedImage image = new BufferedImage(imageSize, imageSize, BufferedImage.TYPE_INT_ARGB); final Graphics2D g2d = image.createGraphics(); g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC); g2d.setRenderingHint(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY); g2d.setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION, RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY); g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); if (!app.manager().ref().context().game().metadata().graphics().boardHidden()) { boardStyle.render(PlaneType.BOARD, context); final String svg = boardStyle.containerSVGImage(); final BufferedImage img = SVGUtil.createSVGImage(svg, imageSize, imageSize); if (!(boardStyle instanceof BoardlessStyle)) g2d.drawImage(img, 0, 0, imageSize, imageSize, 0, 0, img.getWidth(), img.getHeight(), null); } app.bridge().getContainerStyle(context.board().index()).draw(g2d, PlaneType.COMPONENTS, context); app.bridge().getContainerStyle(context.board().index()).draw(g2d, PlaneType.HINTS, context); app.bridge().getContainerStyle(context.board().index()).draw(g2d, PlaneType.COSTS, context); String outputName = app.manager().ref().context().game().name(); if (includeRulesetName && app.manager().settingsManager().userSelections().ruleset() != -1) { final String rulesetNameString = DatabaseInformation.getRulesetDBName(app.manager().ref().context().game().description().rulesets().get(app.manager().settingsManager().userSelections().ruleset()).heading()); outputName += "-" + rulesetNameString; } outputName = outputName.trim(); try { final File outputfile = new File("./thumb-" + outputName + "-a.png"); ImageIO.write(image, "png", outputfile); final File outputfileSmallEmpty = new File("./thumb-" + outputName + "-f.png"); ImageIO.write(BufferedImageUtil.resize(image, 100, 100), "png", outputfileSmallEmpty); } catch (final IOException e) { e.printStackTrace(); } // 2. Save end position final BufferedImage image2; if (boardEmptyAtStart) image2 = generateEndPosition(app, imageSize, true, outputName); else image2 = generateEndPosition(app, imageSize, false, outputName); // If the initial screenshot of the game is empty, then use the end state for thumbnail. if (boardEmptyAtStart) { try { final File outputfileBig = new File("./thumb-" + outputName + "-d.png"); ImageIO.write(image2, "png", outputfileBig); final File outputfile = new File("./thumb-" + outputName + "-c.png"); ImageIO.write(BufferedImageUtil.resize(image2, 100, 100), "png", outputfile); final File outputfileSmall = new File("./thumb-" + outputName + "-e.png"); ImageIO.write(BufferedImageUtil.resize(image2, 30, 30), "png", outputfileSmall); } catch (final IOException e) { e.printStackTrace(); } } else { try { final File outputfileBig = new File("./thumb-" + outputName + "-d.png"); ImageIO.write(image, "png", outputfileBig); final File outputfile = new File("./thumb-" + outputName + "-c.png"); ImageIO.write(BufferedImageUtil.resize(image, 100, 100), "png", outputfile); final File outputfileSmall = new File("./thumb-" + outputName + "-e.png"); ImageIO.write(BufferedImageUtil.resize(image, 30, 30), "png", outputfileSmall); } catch (final IOException e) { e.printStackTrace(); } } app.graphicsCache().clearAllCachedImages(); app.repaint(); } //------------------------------------------------------------------------- /** * Generate the ending position of the game using a random playout. */ private static BufferedImage generateEndPosition(final PlayerApp app, final int imageSize, final boolean notEmpty, final String outputName) { final Board board2 = app.manager().ref().context().board(); final int moveLimit = 300; boolean boardEmptyAtEnd = true; // Create a context for drawing in the background Trial trial2 = new Trial(app.manager().ref().context().game()); Context context2 = new Context(app.manager().ref().context().game(), trial2); app.manager().ref().context().game().start(context2); app.manager().ref().context().game().playout(context2, null, 1.0, null, 0, moveLimit, ThreadLocalRandom.current()); for (int i = 0; i < app.manager().ref().context().board().topology().cells().size(); i++) { if (context2.containerState(0).whatCell(i) != 0) { boardEmptyAtEnd = false; } } for (int i = 0; i < app.manager().ref().context().board().topology().vertices().size(); i++) { if (context2.containerState(0).whatVertex(i) != 0) { boardEmptyAtEnd = false; } } for (int i = 0; i < app.manager().ref().context().board().topology().edges().size(); i++) { if (context2.containerState(0).whatEdge(i) != 0) { boardEmptyAtEnd = false; } } if (notEmpty) { int counter = 0; while (boardEmptyAtEnd && counter < 50) { // Create a context for drawing in the background trial2 = new Trial(app.manager().ref().context().game()); context2 = new Context(app.manager().ref().context().game(), trial2); app.manager().ref().context().game().start(context2); app.manager().ref().context().game().playout(context2, null, 1.0, null, 0, moveLimit, ThreadLocalRandom.current()); for (int i = 0; i < app.manager().ref().context().board().topology().cells().size(); i++) { if (context2.containerState(0).whatCell(i) != 0) { boardEmptyAtEnd = false; } } for (int i = 0; i < app.manager().ref().context().board().topology().vertices().size(); i++) { if (context2.containerState(0).whatVertex(i) != 0) { boardEmptyAtEnd = false; } } for (int i = 0; i < app.manager().ref().context().board().topology().edges().size(); i++) { if (context2.containerState(0).whatEdge(i) != 0) { boardEmptyAtEnd = false; } } counter++; } } final ContainerStyle boardStyle = app.bridge().getContainerStyle(board2.index()); final BufferedImage image2 = new BufferedImage(imageSize, imageSize, BufferedImage.TYPE_INT_ARGB); final Graphics2D g2d2 = image2.createGraphics(); g2d2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g2d2.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); g2d2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC); g2d2.setRenderingHint(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY); g2d2.setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION, RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY); g2d2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); if (!app.manager().ref().context().game().metadata().graphics().boardHidden()) { boardStyle.render(PlaneType.BOARD, context2); final String svg = boardStyle.containerSVGImage(); final BufferedImage img = SVGUtil.createSVGImage(svg, imageSize, imageSize); if (!(boardStyle instanceof BoardlessStyle)) g2d2.drawImage(img, 0, 0, imageSize, imageSize, 0, 0, img.getWidth(), img.getHeight(), null); } app.bridge().getContainerStyle(context2.board().index()).draw(g2d2, PlaneType.COMPONENTS, context2); app.bridge().getContainerStyle(context2.board().index()).draw(g2d2, PlaneType.HINTS, context2); app.bridge().getContainerStyle(context2.board().index()).draw(g2d2, PlaneType.COSTS, context2); try { final File outputfile = new File("./thumb-" + outputName + "-b.png"); ImageIO.write(image2, "png", outputfile); } catch (final IOException e) { e.printStackTrace(); } return image2; } //------------------------------------------------------------------------- /** * Take snapshot of the current game's board. */ public static void generateBoardThumbnail(final PlayerApp app) { final int imageSize = DesktopApp.view().getBoardPanel().boardSize(); final Board board = app.manager().ref().context().board(); // Create a context for drawing in the background final Trial trial = new Trial(app.manager().ref().context().game()); final Context context = new Context(app.manager().ref().context().game(), trial); GameUtil.startGame(app); final ContainerStyle boardStyle = app.bridge().getContainerStyle(board.index()); //BoardView.drawBoardState(g2d, context); final BufferedImage image = new BufferedImage(imageSize, imageSize, BufferedImage.TYPE_INT_ARGB); final Graphics2D g2d = image.createGraphics(); g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC); g2d.setRenderingHint(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY); g2d.setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION, RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY); g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); if (!app.manager().ref().context().game().metadata().graphics().boardHidden()) { boardStyle.render(PlaneType.BOARD, context); final String svg = boardStyle.containerSVGImage(); final BufferedImage img = SVGUtil.createSVGImage(svg, imageSize, imageSize); if (!(boardStyle instanceof BoardlessStyle)) g2d.drawImage(img, 0, 0, imageSize, imageSize, 0, 0, img.getWidth(), img.getHeight(), null); } try { final File outputfile = new File("./thumb-Board_" + app.manager().ref().context().game().name() + ".png"); ImageIO.write(image, "png", outputfile); } catch (final IOException e) { e.printStackTrace(); } app.graphicsCache().clearAllCachedImages(); app.repaint(); } //------------------------------------------------------------------------- }
12,188
37.330189
210
java
Ludii
Ludii-master/PlayerDesktop/src/app/display/util/ZoomBox.java
package app.display.util; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Point; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.geom.AffineTransform; import java.awt.image.BufferedImage; import javax.swing.JComponent; import javax.swing.JPanel; import javax.swing.JWindow; import app.DesktopApp; import app.PlayerApp; import app.display.MainWindowDesktop; /** * Magnifying glass like zoom view. * Only useful for screens with a very high pixel density. * https://stackoverflow.com/questions/18158550/zoom-box-for-area-around-mouse-location-on-screen * * @author Matthew.Stephenson */ public class ZoomBox extends JPanel { private static final long serialVersionUID = 1L; //------------------------------------------------------------------------- final JWindow popup; private final JComponent parent; private BufferedImage buffer; private static final int ZOOM_AREA = 200; private static final float zoomLevel = 2.0f; //------------------------------------------------------------------------- /** * Create ZoomBox window. */ public ZoomBox(final PlayerApp app, final MainWindowDesktop parent) { this.parent = parent; popup = new JWindow(); popup.setLayout(new BorderLayout()); popup.add(this); popup.pack(); final MouseAdapter ma = new MouseAdapter() { @Override public void mouseMoved(final MouseEvent e) { if ( app.settingsPlayer().showZoomBox() && DesktopApp.view().getBoardPanel().placement().contains(e.getPoint()) ) { popup.setVisible(true); final Point p = e.getPoint(); final Point pos = e.getLocationOnScreen(); updateBuffer(p); popup.setLocation(pos.x + 16, pos.y + 16); repaint(); } else { popup.setVisible(false); } } @Override public void mouseExited(final MouseEvent e) { popup.setVisible(false); } }; parent.addMouseListener(ma); parent.addMouseMotionListener(ma); } //------------------------------------------------------------------------- /** * Update displayed visuals. */ protected void updateBuffer(final Point p) { final int width = Math.round(ZOOM_AREA); final int height = Math.round(ZOOM_AREA); buffer = new BufferedImage(width-2, height-2, BufferedImage.TYPE_INT_ARGB); final Graphics2D g2d = buffer.createGraphics(); final AffineTransform at = new AffineTransform(); int xPos = (ZOOM_AREA / 2) - p.x; int yPos = (ZOOM_AREA / 2) - p.y; if (xPos > 0) { xPos = 0; } if (yPos > 0) { yPos = 0; } if ((xPos * -1) + ZOOM_AREA > parent.getWidth()) { xPos = (parent.getWidth() - ZOOM_AREA) * -1; } if ((yPos * -1) + ZOOM_AREA > parent.getHeight()) { yPos = (parent.getHeight()- ZOOM_AREA) * -1; } at.translate(xPos, yPos); g2d.setTransform(at); parent.paint(g2d); g2d.dispose(); } //------------------------------------------------------------------------- @Override public Dimension getPreferredSize() { return new Dimension(Math.round(ZOOM_AREA * zoomLevel), Math.round(ZOOM_AREA * zoomLevel)); } //------------------------------------------------------------------------- @Override protected void paintComponent(final Graphics g) { super.paintComponent(g); final Graphics2D g2d = (Graphics2D) g.create(); g2d.setColor(Color.BLACK); g2d.fillRect(0, 0, getWidth(), getHeight()); g2d.setColor(Color.WHITE); g2d.fillRect(1, 1, getWidth()-2, getHeight()-2); if (buffer != null) { final AffineTransform at = g2d.getTransform(); g2d.setTransform(AffineTransform.getScaleInstance(zoomLevel, zoomLevel)); g2d.drawImage(buffer, 1, 1, this); g2d.setTransform(at); } g2d.dispose(); } //------------------------------------------------------------------------- }
4,339
25.956522
97
java
Ludii
Ludii-master/PlayerDesktop/src/app/display/views/OverlayView.java
package app.display.views; import java.awt.Color; import java.awt.Font; import java.awt.Graphics2D; import java.awt.Rectangle; import java.awt.RenderingHints; import java.awt.geom.Rectangle2D; import java.awt.image.BufferedImage; import java.io.IOException; import java.io.InputStream; import java.net.URL; import javax.imageio.ImageIO; import javax.swing.JTextArea; import app.DesktopApp; import app.PlayerApp; import app.display.MainWindowDesktop; import app.move.MoveVisuals; import app.move.animation.MoveAnimation; import app.utils.BufferedImageUtil; import app.utils.DrawnImageInfo; import app.utils.EnglishSwedishTranslations; import app.utils.SettingsExhibition; import app.views.View; import app.views.tools.ToolView; import game.equipment.container.Container; import graphics.ImageProcessing; import main.Constants; import other.context.Context; import other.location.FullLocation; import other.location.Location; //----------------------------------------------------------------------------- /** * Panel that covers the entire DesktopApp.view(). Used to draw aspects that cover several other Views * * @author Matthew.Stephenson and cambolbro */ public final class OverlayView extends View { /** Font for displaying values. */ protected Font fontForDisplay; final JTextArea englishDescriptionField = new JTextArea(); //------------------------------------------------------------------------ /** * Constructor. */ public OverlayView(final PlayerApp app) { super(app); DesktopApp.frame().add(englishDescriptionField); } //------------------------------------------------------------------------- @Override public void paint(final Graphics2D g2d) { g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); final ToolView toolview = DesktopApp.view().toolPanel(); final Rectangle passRect = toolview.buttons.get(ToolView.PASS_BUTTON_INDEX).rect(); Rectangle otherRect = new Rectangle(0,0); if (toolview.buttons.get(ToolView.OTHER_BUTTON_INDEX) != null) otherRect = toolview.buttons.get(ToolView.OTHER_BUTTON_INDEX).rect(); final Context context = app.contextSnapshot().getContext(app); if (!app.settingsPlayer().isPerformingTutorialVisualisation() && !app.settingsPlayer().usingMYOGApp() && !SettingsExhibition.exhibitionVersion) drawLoginDisc(app, g2d); // Draw unique section text for exhibition app. if (app.settingsPlayer().usingMYOGApp()) { // //final Font exhbitionTitleFont = new Font("Cantarell", Font.BOLD, 52); // //g2d.setFont(exhbitionTitleFont); // // try(InputStream in = getClass().getResourceAsStream("/National-Bold.ttf")) // { // g2d.setFont(Font.createFont(Font.TRUETYPE_FONT, in).deriveFont(52f)); // } // catch (final Exception e) // { // e.printStackTrace(); // } // // g2d.setColor(new Color(29,136,188)); // g2d.drawString(EnglishSwedishTranslations.MYOGTITLE.toString(), 45, 80); if (app.manager().ref().context().game().hasSharedPlayer()) { // g2d.setColor(new Color(227,62,41)); // //final Font exhbitionLabelFont = new Font("Cantarell", Font.PLAIN, 24); // //g2d.setFont(exhbitionLabelFont); // // try(InputStream in = getClass().getResourceAsStream("/National-Regular.ttf")) // { // g2d.setFont(Font.createFont(Font.TRUETYPE_FONT, in).deriveFont(24f)); // } // catch (final Exception e) // { // e.printStackTrace(); // } // // g2d.drawString("1. " + EnglishSwedishTranslations.CHOOSEBOARD.toString(), 50, 150); // // if (app.manager().ref().context().board().numSites() > 1) // g2d.drawString("2. " + EnglishSwedishTranslations.DRAGPIECES.toString(), 50, 375); } else { // If playing a game, show toEnglish of that game's description Font exhbitionDescriptionFont = null; //new Font("Cantarell", Font.PLAIN, 22); try(InputStream in = getClass().getResourceAsStream("/National-Regular.ttf")) { exhbitionDescriptionFont = Font.createFont(Font.TRUETYPE_FONT, in).deriveFont(28f); } catch (final Exception e) { e.printStackTrace(); } englishDescriptionField.setFont(exhbitionDescriptionFont); englishDescriptionField.setForeground(new Color(242, 238, 209)); // exhibition beige //Color.white); englishDescriptionField.setBounds(50, 100, 580, 450); englishDescriptionField.setCaretColor(new Color(0,0,0,0)); englishDescriptionField.setOpaque(false); englishDescriptionField.setLineWrap(true); englishDescriptionField.setWrapStyleWord(true); englishDescriptionField.setText("\n" + app.settingsPlayer().lastGeneratedGameEnglishRules()); englishDescriptionField.setVisible(true); } } if (app.bridge().settingsVC().thisFrameIsAnimated()) { MoveAnimation.moveAnimation(app, g2d); } else { calculateFont(); if (app.manager().liveAIs() != null && !app.manager().liveAIs().isEmpty() && app.settingsPlayer().showAIDistribution()) MoveVisuals.drawAIDistribution(app, g2d, context, passRect, otherRect); if (app.settingsPlayer().showLastMove() && context.currentInstanceContext().trial().numMoves() > context.currentInstanceContext().trial().numInitialPlacementMoves()) MoveVisuals.drawLastMove(app, g2d, context, passRect, otherRect); if (app.settingsPlayer().isPerformingTutorialVisualisation()) MoveVisuals.drawTutorialVisualisatonArrows(app, g2d, context, passRect, otherRect); if (app.manager().settingsManager().showRepetitions()) MoveVisuals.drawRepeatedStateMove(app, g2d, context, passRect, otherRect); if ( !app.bridge().settingsVC().selectedFromLocation().equals(new FullLocation(Constants.UNDEFINED)) && app.bridge().settingsVC().pieceBeingDragged() && DesktopApp.view().getMousePosition() != null ) drawDraggedPiece(g2d, app.bridge().settingsVC().selectedFromLocation(), DesktopApp.view().getMousePosition().x, DesktopApp.view().getMousePosition().y); } drawSandBoxIcon(g2d); drawExtraGameInformation(g2d, context); paintDebug(g2d, Color.BLACK); } //------------------------------------------------------------------------- /** * Draw the Sandbox icon on the top left of the DesktopApp.view(). */ private void drawSandBoxIcon(final Graphics2D g2d) { if (app.settingsPlayer().sandboxMode()) { final URL resource = this.getClass().getResource("/sandbox.png"); try { BufferedImage sandboxImage = ImageIO.read(resource); sandboxImage = BufferedImageUtil.resize(sandboxImage, placement.height/15, placement.height/15); g2d.drawImage(sandboxImage, sandboxImage.getWidth()/10, sandboxImage.getHeight()/10, null); } catch (final IOException e) { e.printStackTrace(); } } } //------------------------------------------------------------------------- /** * Show ball in top right to indicate whether app is connected to the network (green) or not (red). */ protected static void drawLoginDisc(final PlayerApp app, final Graphics2D g2d) { final int r = 7; final Color markerColour = (app.manager().settingsNetwork().getLoginId() == 0) ? Color.RED : Color.GREEN; ImageProcessing.ballImage(g2d, DesktopApp.view().getWidth()-r*2-r, r, r, markerColour); } //------------------------------------------------------------------------- /** * Calculate the font size to display values at. */ private void calculateFont() { int maxVertices = 0; int maxEdges = 0; int maxFaces = 0; final Context context = app.contextSnapshot().getContext(app); for (int i = 0; i < context.numContainers(); i++) { final Container container = context.equipment().containers()[i]; maxVertices += container.topology().cells().size(); maxEdges += container.topology().edges().size(); maxFaces += container.topology().vertices().size(); } final int maxDisplayNumber = Math.max(maxVertices, Math.max(maxEdges, maxFaces)); final int fontMultiplier = (int) (app.bridge().getContainerStyle(context.board().index()).cellRadius() * 2 * DesktopApp.view().getBoardPanel().boardSize()); int fontSize = (fontMultiplier); if (maxDisplayNumber > 9) fontSize = fontMultiplier/2; if (maxDisplayNumber > 99) fontSize = fontMultiplier/3; if (maxDisplayNumber > 999) fontSize = fontMultiplier/4; fontForDisplay = new Font("Arial", Font.BOLD, fontSize); } //------------------------------------------------------------------------- /** * Draw extra important information about the current game context (e.g. pot). */ private void drawExtraGameInformation(final Graphics2D g2d, final Context context) { //System.out.println("At OverlayView.drawExtraGameInformation()..."); // Skip extra game information in certain circumstances. if (app.settingsPlayer().isPerformingTutorialVisualisation()) return; // temporary message if (MainWindowDesktop.volatileMessage().length() > 0) { drawStringBelowBoard(g2d, MainWindowDesktop.volatileMessage(), 0.98); } else if (DesktopApp.view().temporaryMessage().length() > 0) { drawStringBelowBoard(g2d, DesktopApp.view().temporaryMessage(), 0.98); } // shared pot if (context.game().requiresBet()) { final String str = "Pot: $" + context.state().pot(); drawStringBelowBoard(g2d, str, 0.95); } // // Game over message for exhibition // if (app.settingsPlayer().usingMYOGApp() && context.trial().over()) // { // final Font font = new Font("Arial", Font.BOLD, 40); // g2d.setFont(font); // g2d.setColor(Color.RED); // // //System.out.println("Is MYOG, context.winners() is: " + context.winners()); // //System.out.println("boardPanel is at: " + DesktopApp.view().getBoardPanel().placement()); // // if (EnglishSwedishTranslations.inEnglish()) // { // if (context.winners().size() > 0) // { // final String message = "Player " + context.winners().get(0) + " has won"; // final Rectangle2D bounds = g2d.getFontMetrics().getStringBounds(message, g2d); // final int pixels = DesktopApp.view().getBoardPanel().placement().width; // g2d.drawString(message, pixels + 42, (int)(0.5 * pixels + placement.y * 2 + bounds.getHeight()/1.1)); // } // else // { // final String message = "Draw"; // final Rectangle2D bounds = g2d.getFontMetrics().getStringBounds(message, g2d); // final int pixels = DesktopApp.view().getBoardPanel().placement().width; // g2d.drawString(message, pixels + 170, (int)(0.5 * pixels + placement.y * 2 + bounds.getHeight()/1.1)); // } // } // else // { // if (context.winners().size() > 0) // { // final String message = "Spelare " + context.winners().get(0) + " har vunnit"; // final Rectangle2D bounds = g2d.getFontMetrics().getStringBounds(message, g2d); // final int pixels = DesktopApp.view().getBoardPanel().placement().width; // g2d.drawString(message, pixels, (int)(0.5 * pixels + placement.y * 2 + bounds.getHeight()/1.1)); // } // else // { // final String message = "Dra"; // final Rectangle2D bounds = g2d.getFontMetrics().getStringBounds(message, g2d); // final int pixels = DesktopApp.view().getBoardPanel().placement().width; // g2d.drawString(message, pixels + 190, (int)(0.5 * pixels + placement.y * 2 + bounds.getHeight()/1.1)); // } // } // } } //------------------------------------------------------------------------- /** * Draw a specified string message below the board. */ private void drawStringBelowBoard(final Graphics2D g2d, final String message, final double percentageBelow) { final int pixels = DesktopApp.view().getBoardPanel().placement().width; final Font font = new Font("Arial", Font.PLAIN, 16); g2d.setFont(font); g2d.setColor(Color.BLACK); final Rectangle2D bounds = g2d.getFontMetrics().getStringBounds(message, g2d); g2d.drawString(message, (int)(0.5 * pixels - bounds.getWidth()/2.0), (int)(percentageBelow * pixels + placement.y * 2)); } //------------------------------------------------------------------------- /** * Draw the piece being dragged or animated. */ public void drawDraggedPiece(final Graphics2D g2d, final Location selectedLocation, final int x, final int y) { for (final DrawnImageInfo image : MoveAnimation.getMovingPieceImages(app, null, selectedLocation, x, y, false)) g2d.drawImage(image.pieceImage(), (int)image.imageInfo().drawPosn().getX(), (int)image.imageInfo().drawPosn().getY(), null); } //------------------------------------------------------------------------- }
12,678
34.219444
168
java
Ludii
Ludii-master/PlayerDesktop/src/app/display/views/tabs/TabPage.java
package app.display.views.tabs; import java.awt.Color; import java.awt.Desktop; import java.awt.Font; import java.awt.Graphics2D; import java.awt.Point; import java.awt.Rectangle; import java.awt.geom.Rectangle2D; import java.io.IOException; import java.io.InputStream; import java.io.StringWriter; import java.net.URI; import java.net.URISyntaxException; import javax.swing.JEditorPane; import javax.swing.JScrollPane; import javax.swing.JTextPane; import javax.swing.ScrollPaneConstants; import javax.swing.event.HyperlinkEvent; import javax.swing.event.HyperlinkListener; import javax.swing.text.BadLocationException; import javax.swing.text.DefaultCaret; import javax.swing.text.Style; import javax.swing.text.StyleConstants; import javax.swing.text.html.HTMLDocument; import javax.swing.text.html.HTMLEditorKit; import app.DesktopApp; import app.PlayerApp; import app.display.views.tabs.pages.InfoPage; import app.display.views.tabs.pages.RulesPage; import app.utils.SettingsExhibition; import app.views.View; import other.context.Context; //----------------------------------------------------------------------------- /** * View showing a single tab page. * * @author Matthew.Stephenson and cambolbro */ public abstract class TabPage extends View { /** Tab title. */ protected String title = "Tab"; /** Text area. */ protected JTextPane textArea = new JTextPane(); { textArea.setContentType("text/html"); } protected HTMLDocument doc = (HTMLDocument)textArea.getDocument(); protected Style textstyle = textArea.addStyle("text style", null); /** Font colour. */ protected Color fontColour; /** Faded font colour. */ protected Color fadedFontColour; /** Scroll pane for the text area. */ protected JScrollPane scrollPane = new JScrollPane(textArea); /** Solid text to show on the text area. */ public String solidText = ""; /** Faded text to show on the text area. */ public String fadedText = ""; /** Rectangle bounding box for title. */ public Rectangle titleRect = null; //new Rectangle(); /** Whether or not a mouse is over the title. */ protected boolean mouseOverTitle = false; /** Tab page index. */ public final int pageIndex; /** Tab view that holds all tab pages. */ private final TabView parent; //------------------------------------------------------------------------- /** * Constructor. * * @param rect * @param title * @param text */ public TabPage ( final PlayerApp app, final Rectangle rect, final String title, final String text, final int pageIndex, final TabView parent ) { super(app); this.parent = parent; placement = rect; this.title = new String(title); this.pageIndex = pageIndex; final int charWidth = 9; // approximate char width for spacing tab page headers final int wd = charWidth * this.title.length(); final int ht = TabView.fontSize; titleRect = new Rectangle(rect.x, rect.y, wd, ht); scrollPane.setBounds(placement); scrollPane.setBorder(null); scrollPane.setVisible(false); scrollPane.setFocusable(false); textArea.setFocusable(true); textArea.setEditable(false); textArea.setBackground(new Color(255, 255, 255)); final DefaultCaret caret = (DefaultCaret) textArea.getCaret(); caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE); textArea.setFont(new Font("Arial", Font.PLAIN, app.settingsPlayer().tabFontSize())); textArea.setContentType("text/html"); textArea.putClientProperty(JEditorPane.HONOR_DISPLAY_PROPERTIES, Boolean.valueOf(true)); fontColour = new Color(50, 50, 50); textArea.setBackground(Color.white); if (SettingsExhibition.exhibitionVersion) { try(InputStream in = getClass().getResourceAsStream("/National-Regular.ttf")) { textArea.setFont(Font.createFont(Font.TRUETYPE_FONT, in).deriveFont(32f)); } catch (final Exception e) { e.printStackTrace(); } textArea.setBackground(Color.black); fontColour = Color.white; textArea.setForeground(fontColour); scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_NEVER); scrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); } fadedFontColour = new Color(fontColour.getRed() + (int) ((255 - fontColour.getRed()) * 0.75), fontColour.getGreen() + (int) ((255 - fontColour.getGreen()) * 0.75), fontColour.getBlue() + (int) ((255 - fontColour.getBlue()) * 0.75)); StyleConstants.setForeground(textstyle, fontColour); textArea.setVisible(false); textArea.setText(text); DesktopApp.view().setLayout(null); DesktopApp.view().add(scrollPane()); textArea.addHyperlinkListener(new HyperlinkListener() { @Override public void hyperlinkUpdate(final HyperlinkEvent e) { if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) { if (Desktop.isDesktopSupported() && Desktop.getDesktop().isSupported(Desktop.Action.BROWSE)) { try { Desktop.getDesktop().browse(new URI(e.getURL().toString())); } catch (IOException | URISyntaxException e1) { e1.printStackTrace(); } } } } }); } //------------------------------------------------------------------------- public abstract void updatePage(final Context context); public abstract void reset(); //------------------------------------------------------------------------- public String title() { return title; } public Rectangle titleRect() { return titleRect; } public void setTitleRect(final int x, final int y, final int wd, final int ht) { titleRect = new Rectangle(x, y, wd, ht); } public JScrollPane scrollPane() { return scrollPane; } //------------------------------------------------------------------------- /** * Show/hide tab page. * * @param show */ public void show(final boolean show) { textArea.setVisible(show); scrollPane.setVisible(show); } //------------------------------------------------------------------------- /** * Clear the console text. */ public void clear() { textArea.setText(""); } //------------------------------------------------------------------------- /** * Add text to tab page. */ public void addText(final String str) { if (SettingsExhibition.exhibitionVersion) textArea.setText(textArea.getText() + str); StyleConstants.setForeground(textstyle, fontColour); try { if (this instanceof InfoPage || this instanceof RulesPage) { final String htmlString = str.replaceAll("\n", "<br>"); final HTMLEditorKit editorKit = (HTMLEditorKit)textArea.getEditorKit(); doc = (HTMLDocument)textArea.getDocument(); try { // NOTE. This line can sometimes cause freezes when running tutorial generation. Not sure why... if (!app.settingsPlayer().isPerformingTutorialVisualisation()) editorKit.insertHTML(doc, doc.getLength(), htmlString, 0, 0, null); } catch (final IOException e1) { e1.printStackTrace(); } final StringWriter writer = new StringWriter(); try { editorKit.write(writer, doc, 0, doc.getLength()); } catch (final IOException e) { e.printStackTrace(); } solidText = textArea.getText().replaceAll("\n", ""); } else { doc.insertString(doc.getLength(), str, textstyle); solidText = doc.getText(0, doc.getLength()); } } catch (final BadLocationException ex) { ex.printStackTrace(); } } //------------------------------------------------------------------------- /** * Add faded text to tab page. */ protected void addFadedText(final String str) { StyleConstants.setForeground(textstyle, fadedFontColour); try { doc.insertString(doc.getLength(), str, textstyle); fadedText = doc.getText(solidText.length(), doc.getLength()-solidText.length()); Rectangle r = null; textArea.setCaretPosition(solidText.length()); r = textArea.modelToView(textArea.getCaretPosition()); textArea.scrollRectToVisible(r); } catch (final Exception e) { // carry on } } //------------------------------------------------------------------------- /** * @return Current text. */ public String text() { try { return doc.getText(0, doc.getLength()); } catch (final BadLocationException e) { e.printStackTrace(); return textArea.getText(); } } //------------------------------------------------------------------------- /** * Draw player details. * * @param g2d */ @Override public void paint(final Graphics2D g2d) { if (!parent.titlesSet()) parent.setTitleRects(); drawTabPageTitle(g2d); paintDebug(g2d, Color.YELLOW); } //------------------------------------------------------------------------- /** * Draw title of the tab page. */ private void drawTabPageTitle(final Graphics2D g2d) { if (SettingsExhibition.exhibitionVersion) return; final Font oldFont = g2d.getFont(); final Font font = new Font("Arial", Font.BOLD, TabView.fontSize); g2d.setFont(font); final Color dark = new Color(50, 50, 50); final Color light = new Color(255, 255, 255); final Color mouseOver = new Color(150,150,150); if (pageIndex == app.settingsPlayer().tabSelected()) g2d.setColor(dark); else if (mouseOverTitle) g2d.setColor(mouseOver); else g2d.setColor(light); final String str = title(); final Rectangle2D bounds = g2d.getFontMetrics().getStringBounds(str, g2d); final int tx = titleRect.x + (int)((titleRect.width / 2 - bounds.getWidth()/2)); final int ty = titleRect.y + titleRect.height / 2 + 5; g2d.drawString(str, tx, ty); g2d.setFont(oldFont); } //------------------------------------------------------------------------- @Override public void mouseOverAt(final Point pixel) { // See if mouse is over any of the tabs titles if (titleRect.contains(pixel.x, pixel.y)) { if (!mouseOverTitle) { mouseOverTitle = true; DesktopApp.view().repaint(titleRect); } } else { if (mouseOverTitle) { mouseOverTitle = false; DesktopApp.view().repaint(titleRect); } } } //------------------------------------------------------------------------- }
10,407
24.385366
125
java
Ludii
Ludii-master/PlayerDesktop/src/app/display/views/tabs/TabView.java
package app.display.views.tabs; import java.awt.Color; import java.awt.Graphics2D; import java.awt.Point; import java.awt.Rectangle; import java.util.ArrayList; import java.util.List; import app.DesktopApp; import app.PlayerApp; import app.display.views.tabs.pages.AnalysisPage; import app.display.views.tabs.pages.InfoPage; import app.display.views.tabs.pages.LudemePage; import app.display.views.tabs.pages.MovesPage; import app.display.views.tabs.pages.RulesPage; import app.display.views.tabs.pages.StatusPage; import app.display.views.tabs.pages.TurnsPage; import app.utils.SettingsExhibition; import app.views.View; import other.context.Context; //----------------------------------------------------------------------------- /** * View area containing all TabViews * * @author Matthew.Stephenson and cambolbro */ public class TabView extends View { /** Background colour. */ public final static Color bgColour = new Color(255, 255, 230); /** Size of tab headings. */ public final static int fontSize = 16; /** Tab Page values. */ public static final int PanelStatus = 0; public static final int PanelMoves = 1; public static final int PanelTurns = 2; public static final int PanelAnalysis = 3; public static final int PanelLudeme = 4; public static final int PanelRules = 5; public static final int PanelInfo = 6; //------------------------------------------------------------------------- /** If the titles of the tabs has been already set. */ private boolean titlesSet = false; /** Tab panels. */ private final List<TabPage> pages = new ArrayList<>(); //------------------------------------------------------------------------- /** * Constructor. */ public TabView(final PlayerApp app, final boolean portraitMode) { super(app); pages.clear(); final int toolHeight = DesktopApp.view().toolPanel().placement().height; int boardSize = DesktopApp.view().getBoardPanel().placement().width; int startX = boardSize; int startY = DesktopApp.view().getPlayerPanel().placement().height; int width = DesktopApp.view().getWidth() - boardSize; int height = DesktopApp.view().getHeight() - DesktopApp.view().getPlayerPanel().placement().height - toolHeight; if (SettingsExhibition.exhibitionVersion) { height -= 100; width -= 50; startY += 120; } if (portraitMode) { boardSize = app.width(); startX = 8; startY = boardSize + DesktopApp.view().getPlayerPanel().placement().height + 40; // +40 for the height of the toolView width = boardSize - 16; height = app.height() - boardSize - DesktopApp.view().getPlayerPanel().placement().height - 40; } placement.setBounds(startX, startY, width, height); // Add tab pages final Rectangle tabPagePlacement = new Rectangle(placement.x + 10, placement.y + TabView.fontSize + 6, placement.width - 16, placement.height - TabView.fontSize - 20); final TabPage statusPage = new StatusPage(app, tabPagePlacement, " Status ", "", PanelStatus, this); final TabPage movesPage = new MovesPage(app, tabPagePlacement, " Moves ", "", PanelMoves, this); final TabPage turnsPage = new TurnsPage(app, tabPagePlacement, " Turns", "", PanelTurns, this); final TabPage analysisPage = new AnalysisPage(app, tabPagePlacement, " Analysis ", "", PanelAnalysis, this); final TabPage ludemePage = new LudemePage(app, tabPagePlacement, " Ludeme ", "", PanelLudeme, this); final TabPage rulesPage = new RulesPage(app, tabPagePlacement, " Rules ", "", PanelRules, this); final TabPage infoPage = new InfoPage(app, tabPagePlacement, " Info ", "", PanelInfo, this); pages.add(statusPage); pages.add(movesPage); pages.add(turnsPage); pages.add(analysisPage); pages.add(ludemePage); pages.add(rulesPage); pages.add(infoPage); resetTabs(); select(app.settingsPlayer().tabSelected()); if (SettingsExhibition.exhibitionVersion) select(5); for (final View view : pages) DesktopApp.view().getPanels().add(view); } //------------------------------------------------------------------------- public boolean titlesSet() { return titlesSet; } //------------------------------------------------------------------------- @Override public void paint(final Graphics2D g2d) { if (SettingsExhibition.exhibitionVersion) return; final int x0 = placement.x; final int y0 = placement.y; final int sx = placement.width; final int sy = placement.height; if (!titlesSet) { setTitleRects(); titlesSet = true; } g2d.setColor(Color.white); g2d.fillRect(x0, y0, sx, sy); // Title bar final int tx0 = placement.x; final int ty0 = placement.y; final int tsx = placement.width; final int tsy = fontSize + 6; g2d.setColor(new Color(200, 200, 200)); g2d.fillRect(tx0, ty0, tsx, tsy); for (final TabPage page : pages) page.paint(g2d); paintDebug(g2d, Color.GREEN); } //------------------------------------------------------------------------- /** * Sets rectangle bounds for all tab page titles. Used to select specific tab pages. */ public void setTitleRects() { int x = placement.x; final int y = placement.y; for (final TabPage page : pages) { final int wd = (int)page.titleRect().getWidth(); final int ht = fontSize + 6; page.setTitleRect(x, y, wd, ht); x += wd; } } //------------------------------------------------------------------------- /** * Select the specified tab index * @param pid */ public void select(final int pid) { for (final TabPage p : pages) p.show(false); pages.get(pid).show(true); app.settingsPlayer().setTabSelected(pid); app.repaint(); } //------------------------------------------------------------------------- /** * Handle click on tab title. * @param pixel */ public void clickAt(final Point pixel) { for (final TabPage p : pages) if (p.titleRect.contains(pixel.x, pixel.y)) { select(p.pageIndex); return; } } //------------------------------------------------------------------------- public void updateTabs(final Context context) { for(int i = 0; i < pages.size(); i++) pages.get(i).updatePage(context); } //------------------------------------------------------------------------- public void resetTabs() { for(int i = 0; i < pages.size(); i++) pages.get(i).reset(); } //------------------------------------------------------------------------- public TabPage page(final int i) { return pages.get(i); } public List<TabPage> pages() { return pages; } //------------------------------------------------------------------------- }
6,684
26.064777
169
java
Ludii
Ludii-master/PlayerDesktop/src/app/display/views/tabs/pages/AnalysisPage.java
package app.display.views.tabs.pages; import java.awt.Rectangle; import app.PlayerApp; import app.display.views.tabs.TabPage; import app.display.views.tabs.TabView; import other.context.Context; /** * Tab for displaying the results of analytical experiments. * * @author Matthew.Stephenson */ public class AnalysisPage extends TabPage { //------------------------------------------------------------------------- public AnalysisPage(final PlayerApp app, final Rectangle rect, final String title, final String text, final int pageIndex, final TabView parent) { super(app, rect, title, text, pageIndex, parent); } //------------------------------------------------------------------------- @Override public void updatePage(final Context context) { //reset(); } //------------------------------------------------------------------------- @Override public void reset() { clear(); } //------------------------------------------------------------------------- }
997
21.681818
145
java
Ludii
Ludii-master/PlayerDesktop/src/app/display/views/tabs/pages/InfoPage.java
package app.display.views.tabs.pages; import java.awt.Rectangle; import java.util.Arrays; import app.PlayerApp; import app.display.views.tabs.TabPage; import app.display.views.tabs.TabView; import game.Game; import metadata.Metadata; import other.context.Context; /** * Tab for displaying information about the current game. * * @author Matthew.Stephenson */ public class InfoPage extends TabPage { //------------------------------------------------------------------------- public InfoPage(final PlayerApp app, final Rectangle rect, final String title, final String text, final int pageIndex, final TabView parent) { super(app, rect, title, text, pageIndex, parent); } //------------------------------------------------------------------------- @Override public void updatePage(final Context context) { //reset(); } //------------------------------------------------------------------------- @Override public void reset() { clear(); final Game game = app.contextSnapshot().getContext(app).game(); try { final Metadata metadata = game.metadata(); if (metadata != null) { // info tab if (metadata.info().getDescription().size() > 0) { addText("Description:\n"); addText(metadata.info().getDescription().get(metadata.info().getDescription().size()-1)); addText("\n\n"); } if (metadata.info().getAuthor().size() > 0) { addText("Author:\n"); addText(metadata.info().getAuthor().get(metadata.info().getAuthor().size()-1)); addText("\n\n"); } if (metadata.info().getPublisher().size() > 0) { addText("Publisher:\n"); addText(metadata.info().getPublisher().get(metadata.info().getPublisher().size()-1)); addText("\n\n"); } if (metadata.info().getDate().size() > 0) { addText("Date:\n"); addText(metadata.info().getDate().get(metadata.info().getDate().size()-1)); addText("\n\n"); } if (metadata.info().getAliases().length > 0) { addText("Aliases:\n"); addText(Arrays.toString(metadata.info().getAliases())); addText("\n\n"); } if (metadata.info().getOrigin().size() > 0) { addText("Origin:\n"); addText(metadata.info().getOrigin().get(metadata.info().getOrigin().size()-1)); addText("\n\n"); } if (metadata.info().getClassification().size() > 0) { addText("Classification:\n"); addText(metadata.info().getClassification().get(metadata.info().getClassification().size()-1)); addText("\n\n"); } if (metadata.info().getCredit().size() > 0) { addText("Credit:\n"); addText(metadata.info().getCredit().get(metadata.info().getCredit().size()-1)); addText("\n\n"); } if (metadata.info().getVersion().size() > 0) { addText("Version:\n"); addText(metadata.info().getVersion().get(metadata.info().getVersion().size()-1)); addText("\n\n"); } clear(); addText(solidText); } } catch (final Exception e) { // One of the above was not defined properly. e.printStackTrace(); } } //------------------------------------------------------------------------- }
3,170
25.647059
141
java
Ludii
Ludii-master/PlayerDesktop/src/app/display/views/tabs/pages/LudemePage.java
package app.display.views.tabs.pages; import java.awt.Rectangle; import app.PlayerApp; import app.display.views.tabs.TabPage; import app.display.views.tabs.TabView; import game.Game; import other.context.Context; /** * Tab for displaying ludeme description of the current game. * * @author Matthew.Stephenson */ public class LudemePage extends TabPage { //------------------------------------------------------------------------- public LudemePage(final PlayerApp app, final Rectangle rect, final String title, final String text, final int pageIndex, final TabView parent) { super(app, rect, title, text, pageIndex, parent); } //------------------------------------------------------------------------- @Override public void updatePage(final Context context) { //reset(); } //------------------------------------------------------------------------- @Override public void reset() { clear(); final Game game = app.contextSnapshot().getContext(app).game(); addText(game.description().raw()); } //------------------------------------------------------------------------- }
1,115
22.744681
143
java
Ludii
Ludii-master/PlayerDesktop/src/app/display/views/tabs/pages/MovesPage.java
package app.display.views.tabs.pages; import java.awt.Rectangle; import app.PlayerApp; import app.display.views.tabs.TabPage; import app.display.views.tabs.TabView; import app.move.MoveUtil; import app.utils.TrialUtil; import other.context.Context; import other.location.Location; import other.move.Move; import other.state.container.ContainerState; import util.ContainerUtil; import util.HiddenUtil; /** * Tab for displaying all moves that have been made. * * @author Matthew.Stephenson */ public class MovesPage extends TabPage { //------------------------------------------------------------------------- public MovesPage(final PlayerApp app, final Rectangle rect, final String title, final String text, final int pageIndex, final TabView parent) { super(app, rect, title, text, pageIndex, parent); } @Override public void updatePage(final Context context) { // Don't display moves if playing an online game with hidden information. if (app.manager().settingsNetwork().getActiveGameId() != 0 && app.contextSnapshot().getContext(app).game().hiddenInformation()) return; String newSolidText = ""; String newFadedText = ""; for (int i = TrialUtil.getInstanceStartIndex(context); i < context.trial().numMoves(); i++) newSolidText += getMoveStringToDisplay(context, context.trial().getMove(i), i); if (app.manager().undoneMoves().size() > 0) for (int i = 0; i < app.manager().undoneMoves().size(); i++) newFadedText += getMoveStringToDisplay(context, app.manager().undoneMoves().get(i), context.trial().numMoves() + i); if (!newSolidText.equals(solidText) || !newFadedText.equals(fadedText)) { clear(); addText(newSolidText); addFadedText(newFadedText); } } //------------------------------------------------------------------------- /** * Gets the move string for a specified move number in the current trial. */ private String getMoveStringToDisplay(final Context context, final Move move, final int moveNumber) { // If the move's from or to is hidden then don't show the move. final int moverToPrint = move.mover(); final int playerMoverId = app.contextSnapshot().getContext(app).pointofView(); final Location locationFrom = move.getFromLocation(); final int containerIdFrom = ContainerUtil.getContainerId(context, locationFrom.site(), locationFrom.siteType()); final Location locationTo = move.getToLocation(); final int containerIdTo = ContainerUtil.getContainerId(context, locationTo.site(), locationTo.siteType()); if (containerIdFrom != -1 && containerIdTo != -1) { final ContainerState csFrom = context.state().containerStates()[containerIdFrom]; final ContainerState csTo = context.state().containerStates()[containerIdTo]; if (HiddenUtil.siteHiddenBitsetInteger(context, csFrom, locationFrom.site(), locationFrom.level(), playerMoverId, locationFrom.siteType()) > 0 || HiddenUtil.siteHiddenBitsetInteger(context, csTo, locationTo.site(), locationTo.level(), playerMoverId, locationTo.siteType()) > 0) { final int moveNumberToPrint = moveNumber - TrialUtil.getInstanceStartIndex(context) + 1; if (moverToPrint > 0) return (moveNumberToPrint) + ". (" + moverToPrint + ") \n"; else return (moveNumberToPrint) + ". \n"; } } final int moveNumberToPrint = moveNumber - TrialUtil.getInstanceStartIndex(context) + 1; final String moveString = MoveUtil.getMoveFormat(app, move, context); return (moveNumberToPrint) + ". " + moveString + "\n"; } //------------------------------------------------------------------------- @Override public void reset() { clear(); updatePage(app.contextSnapshot().getContext(app)); } //------------------------------------------------------------------------- }
3,771
35.269231
145
java
Ludii
Ludii-master/PlayerDesktop/src/app/display/views/tabs/pages/RulesPage.java
package app.display.views.tabs.pages; import java.awt.Rectangle; import java.util.List; import app.PlayerApp; import app.display.views.tabs.TabPage; import app.display.views.tabs.TabView; import app.utils.SettingsExhibition; import game.Game; import main.Constants; import main.options.Option; import metadata.Metadata; import other.context.Context; /** * Tab for displaying the rules of the current game. * * @author Matthew.Stephenson */ public class RulesPage extends TabPage { //------------------------------------------------------------------------- public RulesPage(final PlayerApp app, final Rectangle rect, final String title, final String text, final int pageIndex, final TabView parent) { super(app, rect, title, text, pageIndex, parent); } //------------------------------------------------------------------------- @Override public void updatePage(final Context context) { //reset(); } //------------------------------------------------------------------------- @Override public void reset() { clear(); final Game game = app.contextSnapshot().getContext(app).game(); try { final Metadata metadata = game.metadata(); if (metadata != null) { // rules tab if (metadata.info().getRules().size() > 0) { if (!SettingsExhibition.exhibitionVersion) addText("Rules:\n"); for (final String s : metadata.info().getRules()) { if (SettingsExhibition.exhibitionVersion) { for (final String line : s.split(">")) { if (line.trim().length() > 1) addText(line.trim() + "\n\n"); } } else { addText(s.trim()); addText("\n\n"); } } } if (metadata.info().getSource().size() > 0) { addText("Source:\n"); for (final String s : metadata.info().getSource()) { addText(s); addText("\n"); } addText("\n"); } if (app.manager().settingsManager().userSelections().ruleset() == Constants.UNDEFINED && !SettingsExhibition.exhibitionVersion) { final List<Option> activeOptions = game.description().gameOptions().activeOptionObjects ( app.manager().settingsManager().userSelections().selectedOptionStrings() ); if (activeOptions.size() > 0) { addText("Options:\n"); for (final Option option : activeOptions) { addText(option.description() + "\n"); } } } clear(); addText(solidText); } } catch (final Exception e) { // one of the above was not defined properly e.printStackTrace(); } } //------------------------------------------------------------------------- }
2,707
22.754386
142
java
Ludii
Ludii-master/PlayerDesktop/src/app/display/views/tabs/pages/StatusPage.java
package app.display.views.tabs.pages; import java.awt.Rectangle; import app.PlayerApp; import app.display.views.tabs.TabPage; import app.display.views.tabs.TabView; import other.context.Context; /** * Tab for displaying all status messages (persistent between games). * * @author Matthew.Stephenson */ public class StatusPage extends TabPage { //------------------------------------------------------------------------- public StatusPage(final PlayerApp app, final Rectangle rect, final String title, final String text, final int pageIndex, final TabView parent) { super(app, rect, title, text, pageIndex, parent); } //------------------------------------------------------------------------- @Override public void updatePage(final Context context) { app.settingsPlayer().setSavedStatusTabString(text()); } //------------------------------------------------------------------------- @Override public void reset() { clear(); addText(app.settingsPlayer().savedStatusTabString()); } //------------------------------------------------------------------------- }
1,104
23.555556
143
java
Ludii
Ludii-master/PlayerDesktop/src/app/display/views/tabs/pages/TurnsPage.java
package app.display.views.tabs.pages; import java.awt.Rectangle; import app.PlayerApp; import app.display.views.tabs.TabPage; import app.display.views.tabs.TabView; import app.utils.TrialUtil; import game.types.play.ModeType; import other.action.Action; import other.context.Context; import other.location.Location; import other.move.Move; import other.state.container.ContainerState; import util.ContainerUtil; import util.HiddenUtil; /** * Tab for displaying all turns that have been made. * * @author Matthew.Stephenson */ public class TurnsPage extends TabPage { //------------------------------------------------------------------------- public static int turnNumber = 0; public static int lastMover = -100; //------------------------------------------------------------------------- public TurnsPage(final PlayerApp app, final Rectangle rect, final String title, final String text, final int pageIndex, final TabView parent) { super(app, rect, title, text, pageIndex, parent); } //------------------------------------------------------------------------- @Override public void updatePage(final Context context) { // Don't display turns if playing an online game with hidden information. if (app.manager().settingsNetwork().getActiveGameId() != 0 && app.contextSnapshot().getContext(app).game().hiddenInformation()) return; lastMover = -100; turnNumber = 0; String newSolidText = ""; String newFadedText = ""; for (int i = TrialUtil.getInstanceStartIndex(context); i < context.trial().numMoves(); i++) newSolidText += getTurnStringToDisplay(context, context.trial().getMove(i)); if (app.manager().undoneMoves() != null) for (int i = 0; i < app.manager().undoneMoves().size(); i++) newFadedText += getTurnStringToDisplay(context, app.manager().undoneMoves().get(i)); if (!newSolidText.equals(solidText) || !newFadedText.equals(fadedText)) { clear(); addText(newSolidText); addFadedText(newFadedText); } } //------------------------------------------------------------------------- /** * Gets the turn string for a specified move number in the current trial. */ private String getTurnStringToDisplay(final Context context, final Move move) { // If the move's from or to is hidden then don't show the move. boolean keepSecret = false; final int playerMoverId = app.contextSnapshot().getContext(app).pointofView(); final Location locationFrom = move.getFromLocation(); final int containerIdFrom = ContainerUtil.getContainerId(context, locationFrom.site(), locationFrom.siteType()); final Location locationTo = move.getToLocation(); final int containerIdTo = ContainerUtil.getContainerId(context, locationTo.site(), locationTo.siteType()); if (containerIdFrom != -1 && containerIdTo != -1) { final ContainerState csFrom = context.state().containerStates()[containerIdFrom]; final ContainerState csTo = context.state().containerStates()[containerIdTo]; if (HiddenUtil.siteHiddenBitsetInteger(context, csFrom, locationFrom.site(), locationFrom.level(), playerMoverId, locationFrom.siteType()) > 0 || HiddenUtil.siteHiddenBitsetInteger(context, csTo, locationTo.site(), locationTo.level(), playerMoverId, locationTo.siteType()) > 0) { keepSecret = true; } } String stringMove = ". "; final boolean useCoords = app.settingsPlayer().isMoveCoord(); if (context.game().mode().mode() == ModeType.Simultaneous) { for (final Action action : move.actions()) if (action.isDecision()) stringMove += action.toTurnFormat(context.currentInstanceContext(), useCoords) + ", "; if (stringMove.length() > 0) stringMove = stringMove.substring(0, stringMove.length() - 2); } else if (context.game().mode().mode() == ModeType.Simulation) { for (final Action action : move.actions()) stringMove += action.toTurnFormat(context.currentInstanceContext(), useCoords) + ", "; if (stringMove.length() > 0) stringMove = stringMove.substring(0, stringMove.length() - 2); } else { for (final Action action : move.actions()) if (action.isDecision()) { stringMove = action.toTurnFormat(context.currentInstanceContext(), useCoords); break; } } String textToAdd = ""; if (move.mover() != lastMover) { turnNumber++; if (turnNumber != 1) textToAdd += "\n"; if (keepSecret) textToAdd += "Turn " + turnNumber + ". -"; else textToAdd += "Turn " + turnNumber + ". " + stringMove; } else { textToAdd += ", " + stringMove; } lastMover = move.mover(); return textToAdd; } //------------------------------------------------------------------------- @Override public void reset() { clear(); updatePage(app.contextSnapshot().getContext(app)); } //------------------------------------------------------------------------- }
4,883
29.716981
145
java
Ludii
Ludii-master/PlayerDesktop/src/app/loading/FileLoading.java
package app.loading; import java.awt.Dimension; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; import javax.swing.Action; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.filechooser.FileFilter; import javax.swing.filechooser.FileNameExtensionFilter; import app.DesktopApp; import app.display.MainWindowDesktop; import app.util.SettingsDesktop; /** * Functions for loading external resources. * * @author Matthew Stephenson */ public class FileLoading { //------------------------------------------------------------------------- /** * Select a file to load (used when loading .lud and .svg) * @return Filepath of selected file. */ public static final String selectFile(final JFrame parent, final boolean isOpen, final String relativePath, final String description, final MainWindowDesktop view, final String... extensions) { final String baseFolder = System.getProperty("user.dir"); String folder = baseFolder + relativePath; final File testFile = new File(folder); if (!testFile.exists()) folder = baseFolder; // no suitable subfolder - let user find them final JFileChooser dlg = new JFileChooser(folder); dlg.setPreferredSize(new Dimension(500, 500)); // Set the file filter to show mgl files only final FileFilter filter = new FileNameExtensionFilter(description, extensions); dlg.setFileFilter(filter); int response; if (isOpen) response = dlg.showOpenDialog(parent); else response = dlg.showSaveDialog(parent); if (response == JFileChooser.APPROVE_OPTION) return dlg.getSelectedFile().getAbsolutePath(); return null; } //------------------------------------------------------------------------- /** * Instantiates a few File Chooser objects */ public static void createFileChoosers() { DesktopApp.setJsonFileChooser(createFileChooser(DesktopApp.lastSelectedJsonPath(), ".json", "JSON files (.json)")); DesktopApp.setJarFileChooser(createFileChooser(DesktopApp.lastSelectedJarPath(), ".jar", "JAR files (.jar)")); DesktopApp.setGameFileChooser(createFileChooser(DesktopApp.lastSelectedGamePath(), ".lud", "LUD files (.lud)")); DesktopApp.setAiDefFileChooser(createFileChooser(DesktopApp.lastSelectedAiDefPath(), "ai.def", "AI.DEF files (ai.def)")); // Also create file chooser for saving played games DesktopApp.setSaveGameFileChooser(new JFileChooser(DesktopApp.lastSelectedSaveGamePath())); DesktopApp.saveGameFileChooser().setPreferredSize(new Dimension(SettingsDesktop.defaultWidth, SettingsDesktop.defaultHeight)); DesktopApp.setLoadTrialFileChooser(new JFileChooser(DesktopApp.lastSelectedLoadTrialPath())); DesktopApp.loadTrialFileChooser().setPreferredSize(new Dimension(SettingsDesktop.defaultWidth, SettingsDesktop.defaultHeight)); DesktopApp.setLoadTournamentFileChooser(new JFileChooser(DesktopApp.lastSelectedLoadTournamentPath())); DesktopApp.loadTournamentFileChooser().setPreferredSize(new Dimension(SettingsDesktop.defaultWidth, SettingsDesktop.defaultHeight)); } //------------------------------------------------------------------------- /** * Creates a File Chooser at a specified directory looking for a specific file extension. */ public static JFileChooser createFileChooser(final String defaultDir, final String extension, final String description) { final JFileChooser fileChooser; // Try to set a useful default directory if (defaultDir != null && defaultDir.length() > 0 && new File(defaultDir).exists()) { fileChooser = new JFileChooser(defaultDir); } else { fileChooser = new JFileChooser(""); } final FileFilter filter = new FileFilter() { @Override public boolean accept(final File f) { return f.isDirectory() || f.getName().endsWith(extension); } @Override public String getDescription() { return description; } }; fileChooser.setFileFilter(filter); fileChooser.setPreferredSize(new Dimension(SettingsDesktop.defaultWidth, SettingsDesktop.defaultHeight)); // Automatically try to switch to details view in file chooser final Action details = fileChooser.getActionMap().get("viewTypeDetails"); if (details != null) details.actionPerformed(null); return fileChooser; } //------------------------------------------------------------------------- /** * Writes specified text to a specified file, at the root directory. */ public static void writeTextToFile(final String fileName, final String text) { final File file = new File("." + File.separator + fileName); if (!file.exists()) { try { file.createNewFile(); } catch (final IOException e2) { e2.printStackTrace(); } } try (FileWriter writer = new FileWriter(file);) { writer.write(text + "\n"); writer.close(); DesktopApp.view().setTemporaryMessage("Log file created."); } catch (final Exception e1) { e1.printStackTrace(); } } //------------------------------------------------------------------------- /** * Writes specified exception message to a specified file, at the root directory. */ public static void writeErrorFile(final String fileName, final Exception e) { final File file = new File("." + File.separator + fileName); if (!file.exists()) { try { file.createNewFile(); } catch (final IOException e2) { e2.printStackTrace(); } } try (final PrintWriter writer = new PrintWriter(file)) { final StringWriter errors = new StringWriter(); e.printStackTrace(new PrintWriter(errors)); writer.println(errors.toString() + "\n"); writer.close(); DesktopApp.view().setTemporaryMessage("Error report file created."); } catch (final Exception e1) { e1.printStackTrace(); } } //------------------------------------------------------------------------- }
5,922
28.467662
134
java
Ludii
Ludii-master/PlayerDesktop/src/app/loading/GameLoading.java
package app.loading; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.EnumSet; import java.util.List; import java.util.Random; import java.util.regex.Pattern; import javax.swing.JFileChooser; import app.DesktopApp; import app.PlayerApp; import app.display.dialogs.GameLoaderDialog; import app.utils.GameSetup; import main.Constants; import main.FileHandling; import main.GameNames; import other.GameLoader; public class GameLoading { //------------------------------------------------------------------------- /** * Load a game from an external .lud file. */ public static void loadGameFromFile(final PlayerApp app) { final int fcReturnVal = DesktopApp.gameFileChooser().showOpenDialog(DesktopApp.frame()); if (fcReturnVal == JFileChooser.APPROVE_OPTION) { File file = DesktopApp.gameFileChooser().getSelectedFile(); String filePath = file.getAbsolutePath(); if (!filePath.endsWith(".lud")) { filePath += ".lud"; file = new File(filePath); } if (file.exists()) { final String fileName = file.getAbsolutePath(); // TODO if we want to preserve per-game last-selected-options in preferences, load them here app.manager().settingsManager().userSelections().setRuleset(Constants.UNDEFINED); app.manager().settingsManager().userSelections().setSelectOptionStrings(new ArrayList<String>()); loadGameFromFilePath(app, fileName); } } } //------------------------------------------------------------------------- /** * Load a specified external .lud file. */ public static void loadGameFromFilePath(final PlayerApp app, final String filePath) { if (filePath != null) { app.manager().setSavedLudName(filePath); String desc = ""; try { app.settingsPlayer().setLoadedFromMemory(false); desc = FileHandling.loadTextContentsFromFile(filePath); GameSetup.compileAndShowGame(app, desc, false); } catch (final FileNotFoundException ex) { System.out.println("Unable to open file '" + filePath + "'"); } catch (final IOException ex) { System.out.println("Error reading file '" + filePath + "'"); } } } //------------------------------------------------------------------------- /** * Load an internal .lud game description from memory */ public static void loadGameFromMemory(final PlayerApp app, final boolean debug) { final String[] choices = FileHandling.listGames(); String initialChoice = choices[0]; for (final String choice : choices) { if (app.manager().savedLudName() != null && app.manager().savedLudName().endsWith(choice.replaceAll(Pattern.quote("\\"), "/"))) { initialChoice = choice; break; } } final String choice = GameLoaderDialog.showDialog(DesktopApp.frame(), choices, initialChoice); if (choice != null) { // TODO if we want to preserve per-game last-selected-options in preferences, load them here app.manager().settingsManager().userSelections().setRuleset(Constants.UNDEFINED); app.manager().settingsManager().userSelections().setSelectOptionStrings(new ArrayList<String>()); loadGameFromMemory(app, choice, debug); } } //------------------------------------------------------------------------- /** * Load a selected internal .lud game description. */ public static void loadGameFromMemory(final PlayerApp app, final String gamePath, final boolean debug) { // Get game description from resource final StringBuilder sb = new StringBuilder(); if (gamePath != null) { InputStream in = null; String path = gamePath.replaceAll(Pattern.quote("\\"), "/"); path = path.substring(path.indexOf("/lud/")); app.manager().setSavedLudName(path); in = GameLoader.class.getResourceAsStream(path); try (final BufferedReader rdr = new BufferedReader(new InputStreamReader(in, "UTF-8"))) { String line; while ((line = rdr.readLine()) != null) sb.append(line + "\n"); } catch (final IOException e) { e.printStackTrace(); } app.settingsPlayer().setLoadedFromMemory(true); GameSetup.compileAndShowGame(app, sb.toString(), debug); } } //------------------------------------------------------------------------- /** * Load game from name. * * @param name Filename + .lud extension. * @param options List of options to select */ public static void loadGameFromName(final PlayerApp app, final String name, final List<String> options, final boolean debug) { try { final String gameDescriptionString = getGameDescriptionRawFromName(app, name); if (gameDescriptionString == null) { loadGameFromFilePath(app, name.substring(0, name.length())); } else { app.settingsPlayer().setLoadedFromMemory(true); app.manager().settingsManager().userSelections().setRuleset(Constants.UNDEFINED); app.manager().settingsManager().userSelections().setSelectOptionStrings(options); GameSetup.compileAndShowGame(app, gameDescriptionString, false); } } catch (final Exception e) { // used if a recent game was selected from an external file. } } //------------------------------------------------------------------------- /** * Returns the raw game description for a game, based on the name. */ public static String getGameDescriptionRawFromName(final PlayerApp app, final String name) { final String filePath = GameLoader.getFilePath(name); // Probably loading from an external .lud file. if (filePath == null) return null; final StringBuilder sb = new StringBuilder(); app.manager().setSavedLudName(filePath); try (InputStream in = GameLoader.class.getResourceAsStream(filePath)) { try (final BufferedReader rdr = new BufferedReader(new InputStreamReader(in, "UTF-8"))) { String line; while ((line = rdr.readLine()) != null) sb.append(line + "\n"); } catch (final IOException e) { e.printStackTrace(); } } catch (final Exception e) { System.out.println("Did you change the name??"); } return sb.toString(); } //------------------------------------------------------------------------- /** * Load a random game from the list of possible options in GameNames.java */ public static void loadRandomGame(final PlayerApp app) { final List<String> allGameNames = new ArrayList<>(); EnumSet.allOf(GameNames.class).forEach(game -> allGameNames.add(game.ludName())); final Random random = new Random(); final String chosenGameName = allGameNames.get(random.nextInt(allGameNames.size())); // TODO if we want to preserve per-game last-selected-options in preferences, load them here app.manager().settingsManager().userSelections().setRuleset(Constants.UNDEFINED); app.manager().settingsManager().userSelections().setSelectOptionStrings(new ArrayList<String>()); loadGameFromName(app, chosenGameName + ".lud", new ArrayList<String>(), false); } //------------------------------------------------------------------------- }
7,163
28.004049
130
java
Ludii
Ludii-master/PlayerDesktop/src/app/loading/MiscLoading.java
package app.loading; import java.awt.Color; import java.awt.Rectangle; import java.awt.RenderingHints; import java.awt.image.BufferedImage; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; import java.util.regex.Pattern; import javax.swing.JFileChooser; import javax.swing.JFrame; import org.jfree.graphics2d.svg.SVGGraphics2D; import org.json.JSONArray; import org.json.JSONObject; import org.json.JSONTokener; import app.DesktopApp; import app.PlayerApp; import app.display.MainWindowDesktop; import app.display.SVGWindow; import app.menu.MainMenu; import app.utils.GameUtil; import app.utils.SVGUtil; import game.Game; import graphics.svg.SVGtoImage; import manager.Referee; import manager.ai.AIUtil; import manager.utils.game_logs.MatchRecord; import other.context.Context; import tournament.Tournament; public class MiscLoading { //------------------------------------------------------------------------- /** * Load and view an external .svg file. */ public static void loadSVG(final PlayerApp app, final MainWindowDesktop view) { JFrame svgFrame = null; SVGWindow svgView = null; final String fileName = FileLoading.selectFile(DesktopApp.frame(), true, "/../Common/img/svg/", "SVG files (*.svg)", view, "svg"); if (fileName == null) return; svgView = new SVGWindow(); svgFrame = new JFrame("SVG Viewer"); svgFrame.add(svgView); final int sz = (Math.min(DesktopApp.frame().getWidth()/2, DesktopApp.frame().getHeight()-40)) - 20; svgFrame.setSize((sz + 20) * 2, sz + 60); svgFrame.setLocationRelativeTo(DesktopApp.frame()); final Context context = app.contextSnapshot().getContext(app); final SVGGraphics2D image1 = renderImageSVG(sz, fileName, app.bridge().settingsColour().playerColour(context, 1)); final SVGGraphics2D image2 = renderImageSVG(sz, fileName, app.bridge().settingsColour().playerColour(context, 2)); final BufferedImage img1 = SVGUtil.createSVGImage(image1.getSVGDocument(), sz, sz); final BufferedImage img2 = SVGUtil.createSVGImage(image2.getSVGDocument(), sz, sz); svgView.setImages(img1, img2); svgFrame.setVisible(true); svgView.repaint(); } //---------------------------------------------------------------------------- /** * Create SVG piece image of internal file, only used for the SVG viewer. */ public static SVGGraphics2D renderImageSVG(final int pixels, final String filePath1, final Color fillColour) { final SVGGraphics2D g2d = new SVGGraphics2D(pixels, pixels); g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); SVGtoImage.loadFromFilePath ( g2d, filePath1, new Rectangle(0,0,pixels,pixels), Color.BLACK, fillColour, 0 ); return g2d; } //------------------------------------------------------------------------- /** * Loads a demo as described by a JSON object. */ public static void loadDemo(final PlayerApp app, final JSONObject jsonDemo) { app.manager().settingsManager().setAgentsPaused(app.manager(), true); final Referee ref = app.manager().ref(); final Context context = ref.context(); final Game game = context.game(); final String gameName = jsonDemo.getString("Game"); final List<String> gameOptions = new ArrayList<>(); final JSONArray optionsArray = jsonDemo.optJSONArray("Options"); if (optionsArray != null) for (final Object object : optionsArray) gameOptions.add((String) object); GameLoading.loadGameFromName(app, gameName, gameOptions, false); for (int p = 1; p <= game.players().count(); ++p) { final JSONObject jsonPlayer = jsonDemo.optJSONObject("Player " + p); if (jsonPlayer != null) { if (jsonPlayer.has("AI")) AIUtil.updateSelectedAI(app.manager(), jsonPlayer, p, jsonPlayer.getJSONObject("AI").getString("algorithm")); if (jsonPlayer.has("Time Limit")) app.manager().aiSelected()[p].setThinkTime(jsonPlayer.getDouble("Time Limit")); } } final JSONObject jsonSettings = jsonDemo.optJSONObject("Settings"); if (jsonSettings != null) { if (jsonSettings.has("Show AI Distribution")) app.settingsPlayer().setShowAIDistribution(jsonSettings.getBoolean("Show AI Distribution")); } app.resetMenuGUI(); if (jsonDemo.has("Trial")) { final String trialFile = jsonDemo.getString("Trial").replaceAll(Pattern.quote("\\"), "/"); try ( final InputStreamReader reader = new InputStreamReader(MainMenu.class.getResourceAsStream(trialFile), "UTF-8"); ) { final MatchRecord loadedRecord = MatchRecord.loadMatchRecordFromInputStream(reader, game); app.manager().setCurrGameStartRngState(loadedRecord.rngState()); app.manager().ref().makeSavedMoves(app.manager(), loadedRecord.trial().generateCompleteMovesList()); } catch (final IOException e) { e.printStackTrace(); } } } //------------------------------------------------------------------------- /** * Select and load an external tournament file. * NOTE. Tournament should only include 2 player games. */ public static void loadTournamentFile(final PlayerApp app) { GameUtil.resetGame(app, false); final int fcReturnVal = DesktopApp.loadTournamentFileChooser().showOpenDialog(DesktopApp.frame()); if (fcReturnVal == JFileChooser.APPROVE_OPTION) { final File file = DesktopApp.loadTournamentFileChooser().getSelectedFile(); try (final InputStream inputStream = new FileInputStream(file)) { final JSONObject json = new JSONObject(new JSONTokener(inputStream)); app.setTournament(new Tournament(json)); app.tournament().setupTournament(); app.tournament().startNextTournamentGame(app.manager()); } catch (final Exception e1) { System.out.println("Tournament file is not formatted correctly"); } } } //------------------------------------------------------------------------- }
6,080
30.671875
132
java
Ludii
Ludii-master/PlayerDesktop/src/app/loading/TrialLoading.java
package app.loading; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.List; import javax.swing.JFileChooser; import app.DesktopApp; import app.PlayerApp; import app.display.MainWindowDesktop; import app.utils.GameUtil; import app.utils.SettingsExhibition; import main.Constants; import manager.ai.AIUtil; import manager.utils.game_logs.MatchRecord; import other.context.Context; import other.move.Move; public class TrialLoading { //------------------------------------------------------------------------- /** * Select and Save the current trial of the current game to an external file. */ public static void saveTrial(final PlayerApp app) { final int fcReturnVal = DesktopApp.saveGameFileChooser().showSaveDialog(DesktopApp.frame()); if (fcReturnVal == JFileChooser.APPROVE_OPTION) { File file = DesktopApp.saveGameFileChooser().getSelectedFile(); String filePath = file.getAbsolutePath(); if (!filePath.endsWith(".trl")) { filePath += ".trl"; file = new File(filePath); } saveTrial(app, file); if (app.settingsPlayer().saveHeuristics()) { // AIUtils.saveHeuristicScores // ( // app.manager().ref().context().trial(), // app.manager().ref().context(), // app.manager().currGameStartRngState(), // new File(filePath.replaceAll(Pattern.quote(".trl"), "_heuristics.csv")) // ); } } } //------------------------------------------------------------------------- /** * Save the current trial of the current game, to the specified file. */ public static void saveTrial(final PlayerApp app, final File file) { try { final Context context = app.manager().ref().context(); List<String> gameOptionStrings = new ArrayList<>(); if (context.game().description().gameOptions() != null) gameOptionStrings = context.game().description().gameOptions().allOptionStrings ( app.manager().settingsManager().userSelections().selectedOptionStrings() ); context.trial().saveTrialToTextFile ( file, app.manager().savedLudName(), gameOptionStrings, app.manager().currGameStartRngState(), false ); } catch (final IOException e) { e.printStackTrace(); } } //------------------------------------------------------------------------- /** * Select and load an external trial file. */ public static void loadTrial(final PlayerApp app, final boolean debug) { final int fcReturnVal = DesktopApp.loadTrialFileChooser().showOpenDialog(DesktopApp.frame()); if (fcReturnVal == JFileChooser.APPROVE_OPTION) { app.manager().ref().interruptAI(app.manager()); final File file = DesktopApp.loadTrialFileChooser().getSelectedFile(); loadTrial(app, file, debug); } } //------------------------------------------------------------------------- /** * Load a specified trial file. */ public static void loadTrial(final PlayerApp app, final File file, final boolean debug) { try { // load game path and options from file first try (final BufferedReader reader = new BufferedReader(new FileReader(file))) { final String gamePathLine = reader.readLine(); final String loadedGamePath = gamePathLine.substring("game=".length()); final List<String> gameOptions = new ArrayList<>(); String nextLine = reader.readLine(); boolean endOptionsFound = false; while (true) { if (nextLine == null) break; if (nextLine.startsWith("END GAME OPTIONS")) endOptionsFound = true; if (!nextLine.startsWith("START GAME OPTIONS") && !endOptionsFound) gameOptions.add(nextLine); if (nextLine.startsWith("END GAME OPTIONS")) endOptionsFound = true; if (nextLine.startsWith("LUDII_VERSION") && !nextLine.substring(14).equals(Constants.LUDEME_VERSION)) { System.out.println("Warning! Trial is of version " + nextLine.substring(14)); MainWindowDesktop.setVolatileMessage(app, "Warning! Trial is of version " + nextLine.substring(14)); } nextLine = reader.readLine(); } app.manager().settingsManager().userSelections().setRuleset(Constants.UNDEFINED); app.manager().settingsManager().userSelections().setSelectOptionStrings(gameOptions); GameLoading.loadGameFromName(app, loadedGamePath, gameOptions, debug); } final MatchRecord loadedRecord = MatchRecord.loadMatchRecordFromTextFile(file, app.manager().ref().context().game()); app.addTextToStatusPanel("Trial Loaded.\n"); final List<Move> trialMoves = loadedRecord.trial().generateCompleteMovesList(); app.manager().setCurrGameStartRngState(loadedRecord.rngState()); GameUtil.resetGame(app, true); app.manager().ref().makeSavedMoves(app.manager(), trialMoves); } catch (final IOException exception) { exception.printStackTrace(); } AIUtil.pauseAgentsIfNeeded(app.manager()); } //------------------------------------------------------------------------- /** * Only called when the app is opened. Loads the saved trial. */ public static void loadStartTrial(final PlayerApp app) { if (SettingsExhibition.exhibitionVersion) return; try { final File file = new File("." + File.separator + "ludii.trl"); if (!file.exists()) { try { file.createNewFile(); } catch (final IOException e) { e.printStackTrace(); } } else if (DesktopApp.shouldLoadTrial()) { TrialLoading.loadTrial(app, file, false); } } catch (final Exception e) { // try to delete trial final File brokenPreferences = new File("." + File.separator + "ludii.trl"); brokenPreferences.delete(); } } //------------------------------------------------------------------------- }
5,837
26.8
120
java
Ludii
Ludii-master/PlayerDesktop/src/app/manualGeneration/HtmlFileOutput.java
package app.manualGeneration; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeSet; import game.Game; import manager.Referee; import metadata.ai.heuristics.HeuristicUtil; import metadata.ai.heuristics.Heuristics; import metadata.ai.heuristics.terms.HeuristicTerm; import other.context.Context; import other.translation.LanguageUtils; public class HtmlFileOutput { //------------------------------------------------------------------------- final public static String htmlHeader = "<!DOCTYPE html>\n" + "<html lang=\"en\">\n" + "\n" + "<head>\n" + " <meta name=\"description\" content=\"Ludii Auto-Generated Instructions\" />\n" + " <meta charset=\"utf-8\">\n" + " <title>Ludii Auto-Generated Instructions</title>\n" + " <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n" + " <meta name=\"author\" content=\"\">\n" + " <link rel=\"stylesheet\" href=\"../css/style.css\">\n" + "</head>\n" + "\n" + "<body>"; final public static String htmlFooter = "</body>\n" + "</html>"; //------------------------------------------------------------------------- /** * Output toEnglish of the game description. */ public static String htmlEnglishRules(final Game game) { String outputString = "<h1>Game Rules:</h1>"; outputString += "<p><pre>" + formatString(game.toEnglish(game)) + "\n</pre></p>"; return outputString; } //------------------------------------------------------------------------- /** * Output board setup. */ public static String htmlBoardSetup() { String outputString = "<h1>Board Setup:</h1>"; outputString += "<img src=\"screenshot/Game_Setup.png\" />\n<br><br>"; return outputString; } //------------------------------------------------------------------------- /** * Output strategy/heuristics for this game based on metadata (if present). */ public static String htmlEnglishHeuristics(final Context context) { String outputString = ""; final Game game = context.game(); final metadata.ai.Ai aiMetadata = game.metadata().ai(); if (aiMetadata != null && aiMetadata.heuristics() != null) { // Record the heuristic strings that are applicable to each player. Index 0 applies to all players. final List<Map<String, Set<String>>> allHeuristicStringsPerPlayer = new ArrayList<>(); final Heuristics heuristicValueFunction = HeuristicUtil.normaliseHeuristic(Heuristics.copy(aiMetadata.heuristics())); outputString += "<h1>Game Heuristics:</h1>"; // Record heuristic strings/values for each player. for (int i = 0; i <= game.players().count(); i++) { allHeuristicStringsPerPlayer.add(new HashMap<>()); for (final HeuristicTerm heuristic : heuristicValueFunction.heuristicTerms()) { heuristic.init(game); heuristic.simplify(); String heuristicTitle = "<b>" + LanguageUtils.splitCamelCase(heuristic.getClass().getSimpleName()) + "</b>\n" + "<i>" + heuristic.description() + "</i>"; final String[] heuristicValuesStrings = heuristic.toEnglishString(context, i).split("\n"); // Get existing list of values for this heuristic. Set<String> existingValues = allHeuristicStringsPerPlayer.get(i).get(heuristicTitle); if (existingValues == null) existingValues = new HashSet<>(); for (String heuristicValueString : heuristicValuesStrings) if (heuristicValueString.length() > 0) existingValues.add(heuristicValueString); if (existingValues.size() > 0) allHeuristicStringsPerPlayer.get(i).put(heuristicTitle, existingValues); } } // Merge heuristic strings that apply to all players. Go through all the heuristics for player 1 and see if all other players have them. final Map<String, Set<String>> player1Heuristics = allHeuristicStringsPerPlayer.get(1); for (final Map.Entry<String, Set<String>> entry : player1Heuristics.entrySet()) { String heuristicTitle = entry.getKey(); Set<String> existingValues = allHeuristicStringsPerPlayer.get(0).get(heuristicTitle); if (existingValues == null) existingValues = new HashSet<>(); for (String heurisitcValue : entry.getValue()) { // Check if this heuristic already exists for all other players heuristics. boolean heuristicAcrossAllPlayers = true; for (int i = 2; i <= game.players().count(); i++) { if (!allHeuristicStringsPerPlayer.get(i).containsKey(heuristicTitle)) { heuristicAcrossAllPlayers = false; break; } if (!allHeuristicStringsPerPlayer.get(i).get(heuristicTitle).contains(heurisitcValue)) { heuristicAcrossAllPlayers = false; break; } } // Add this heuristic value to the merged heuristics. if (heuristicAcrossAllPlayers) { existingValues.add(heurisitcValue); allHeuristicStringsPerPlayer.get(0).put(heuristicTitle, existingValues); } } } // Remove any heuristic values that apply to all players from the individual player heuristics final Map<String, Set<String>> player0Heuristics = allHeuristicStringsPerPlayer.get(0); for (final Map.Entry<String, Set<String>> entry : player0Heuristics.entrySet()) { String heuristicTitle = entry.getKey(); for (String heuristicValue : entry.getValue()) { for (int i = 1; i <= game.players().count(); i++) { if (allHeuristicStringsPerPlayer.get(i).containsKey(heuristicTitle)) { allHeuristicStringsPerPlayer.get(i).get(heuristicTitle).remove(heuristicValue); if (allHeuristicStringsPerPlayer.get(i).get(heuristicTitle).size() == 0) allHeuristicStringsPerPlayer.get(i).remove(heuristicTitle); } } } } // Write the merged heuristic strings for (int i = 0; i < allHeuristicStringsPerPlayer.size(); i++) { if (allHeuristicStringsPerPlayer.get(i).size() > 0) { if (i == 0) outputString += "<h2>All Players:</h2>"; else outputString += "<h2>Player: " + i + "</h2>"; outputString += "<p><pre>"; for (final Map.Entry<String, Set<String>> entry : allHeuristicStringsPerPlayer.get(i).entrySet()) { String heuristicStringCombined = entry.getKey() + "\n"; for (String heuristicValue : entry.getValue()) heuristicStringCombined += heuristicValue + "\n"; outputString += heuristicStringCombined + "\n"; } outputString += "</pre></p>"; } } } return outputString + "<br>"; } //------------------------------------------------------------------------- /** * Output endings. */ public static String htmlEndings(final List<String> rankingStrings, final List<MoveCompleteInformation> endingMoveList) { String outputString = "<br><h1>Game Endings:</h1>"; for (int i = 0; i < rankingStrings.size(); i++) { final MoveCompleteInformation moveInformation = endingMoveList.get(i); outputString += "<p><pre>" + rankingStrings.get(i) + "</pre></p>"; outputString += formatString(moveInformation.endingDescription()) + "\n<br>"; outputString += "<img src=\"" + moveInformation.screenshotA() + "\" />\n"; outputString += "<img src=\"" + moveInformation.gifLocation() + "\" />\n"; outputString += "<img src=\"" + moveInformation.screenshotB() + "\" />\n"; outputString += "<br><br>\n"; } return outputString; } //------------------------------------------------------------------------- /** * Output all Move images/animations. */ public static String htmlMoves(final Referee ref, final List<MoveCompleteInformation> condensedMoveList) { String outputString = "<br><h1>Moves:</h1>"; final Set<String> allMovers = new TreeSet<>(); final Set<String> allComponents = new TreeSet<>(); final Set<String> allMoveEnglishDescriptions = new TreeSet<>(); final Set<String> allMoveActionDescriptions = new TreeSet<>(); for (final MoveCompleteInformation moveInformation : condensedMoveList) { allMovers.add(String.valueOf(moveInformation.move().mover())); allComponents.add(moveInformation.pieceName()); allMoveEnglishDescriptions.add(moveInformation.englishDescription()); allMoveActionDescriptions.add(moveInformation.move().actionDescriptionStringShort()); } final boolean splitMovers = MoveComparison.isCompareMover(); final boolean splitPieces = MoveComparison.isComparePieceName(); final boolean splitEnglishDescription = MoveComparison.isCompareEnglishDescription(); final boolean splitActionDescriptions = MoveComparison.isCompareActions(); if (!splitMovers) { allMovers.clear(); allMovers.add(""); } if (!splitPieces) { allComponents.clear(); allComponents.add(""); } if (!splitEnglishDescription) { allMoveEnglishDescriptions.clear(); allMoveEnglishDescriptions.add(""); } if (!splitActionDescriptions) { allMoveActionDescriptions.clear(); allMoveActionDescriptions.add(""); } final String[] storedTitles = {"", "", "", ""}; for (final String moverString : allMovers) { storedTitles[0] = splitMovers ? "<h2>Player: " + moverString + "</h2>\n" : ""; for (final String componentString : allComponents) { storedTitles[1] = splitPieces ? "<h3>Piece: " + componentString + "</h3>\n" : ""; for (final String moveEnglishString : allMoveEnglishDescriptions) { storedTitles[2] = splitEnglishDescription ? "<h4>Move: " + formatString(moveEnglishString) + "</h4>\n" : ""; for (final String actionDescriptionString : allMoveActionDescriptions) { //storedTitles[3] = splitActionDescriptions ? "<h5>Actions: " + actionDescriptionString + "</h5>\n" : ""; for (final MoveCompleteInformation moveInformation : condensedMoveList) { if ( (String.valueOf(moveInformation.move().mover()).equals(moverString) || !splitMovers) && (moveInformation.pieceName().equals(componentString) || !splitPieces) && (moveInformation.englishDescription().equals(moveEnglishString) || !splitEnglishDescription) && (moveInformation.move().actionDescriptionStringShort().equals(actionDescriptionString) || !splitActionDescriptions) ) { outputString += String.join("", storedTitles); Arrays.fill(storedTitles, ""); //outputString += moveInformation.move().actionDescriptionStringLong(ref.context(), true) + "\n<br>"; //outputString += moveInformation.move().actions().toString() + "\n<br>"; //outputString += moveInformation.move().actionDescriptionStringShort() + "\n<br>"; outputString += "<img src=\"" + moveInformation.screenshotA() + "\" />\n"; outputString += "<img src=\"" + moveInformation.gifLocation() + "\" />\n"; outputString += "<img src=\"" + moveInformation.screenshotB() + "\" />\n"; outputString += "<br><br>\n"; } } } } } } return outputString; } //------------------------------------------------------------------------- private static String formatString(String s) { String newString = s; if (s.length() <= 1) return s.toUpperCase(); // Make sure string starts with Capital newString = newString.substring(0, 1).toUpperCase() + newString.substring(1); // Remove any double spaces // newString = s.trim().replaceAll(" +", " "); // Remove any problematic html Characters newString = newString.replaceAll("<", "&lt;").replaceAll(">", "&gt;"); return newString; } }
11,802
34.551205
158
java
Ludii
Ludii-master/PlayerDesktop/src/app/manualGeneration/ManualGeneration.java
package app.manualGeneration; import java.io.File; import java.io.FileWriter; import java.util.ArrayList; import java.util.List; import java.util.Timer; import java.util.TimerTask; import org.apache.commons.rng.core.RandomProviderDefaultState; import app.DesktopApp; import app.display.screenCapture.ScreenCapture; import app.utils.AnimationVisualsType; import app.utils.GameUtil; import manager.Referee; import other.action.Action; import other.move.Move; import other.trial.Trial; public class ManualGeneration { //------------------------------------------------------------------------- // Adjustable Settings /** How many trials to run to provide all the moves for analysis. */ private final static int numberTrials = 10; /** Whether or not to include moves that are from the player's hands. */ private final static boolean includeHandMoves = true; /** Whether or not to include moves that have no corresponding piece. */ private final static boolean includeNoWhatMoves = false; //------------------------------------------------------------------------- // Variables for coordinating various functions. static boolean setupImageTimerComplete; static boolean generateMoveImagesTimerComplete; static boolean generateEndImagesTimerComplete; static boolean generateWebsiteTimerComplete; //------------------------------------------------------------------------- /** Root file path for storing game specific files. */ static String rootPath; //------------------------------------------------------------------------- /** * Main entry point for running the manual generation. */ public static void manualGeneration(final DesktopApp app) { setupImageTimerComplete = false; generateMoveImagesTimerComplete = false; generateEndImagesTimerComplete = false; generateWebsiteTimerComplete = false; // Check if this game is supported by manual generation. if (!ManualGenerationUtils.checkGameValid(app.manager().ref().context().game())) { System.out.println("Sorry. This game type is not supported yet."); ManualGeneration.generateWebsiteTimerComplete = true; return; } final Referee ref = app.manager().ref(); rootPath = "game_manuals/" + ref.context().game().name() + "/"; // Set some desired visual settings (recommend resetting preferences beforehand). app.settingsPlayer().setPerformingTutorialVisualisation(true); app.settingsPlayer().setShowEndingMove(false); app.settingsPlayer().setShowLastMove(false); app.settingsPlayer().setAnimationType(AnimationVisualsType.Single); app.bridge().settingsVC().setShowPossibleMoves(false); app.bridge().settingsVC().setFlatBoard(true); // Determine how wide to make the frame, based on what needs to be displayed. if (includeHandMoves && app.manager().ref().context().game().requiresHand()) DesktopApp.frame().setSize(800, 465); else DesktopApp.frame().setSize(410, 465); // Generate all trials that will be used. final List<Trial> generatedTrials = new ArrayList<>(); final List<RandomProviderDefaultState> generatedTrialsRNG = new ArrayList<>(); MoveGeneration.generateTrials(app, generatedTrials, generatedTrialsRNG, numberTrials); // Merge all similar moves from our generated trials into a condensed moves list. final List<MoveCompleteInformation> condensedMoveList = new ArrayList<>(); final List<String> rankingStrings = new ArrayList<>(); final List<MoveCompleteInformation> endingMoveList = new ArrayList<>(); MoveGeneration.recordTrialMoves(app, generatedTrials, generatedTrialsRNG, condensedMoveList, rankingStrings, endingMoveList, includeHandMoves, includeNoWhatMoves); System.out.println("\nTotal of " + condensedMoveList.size() + " condensed moves found."); System.out.println("Total of " + endingMoveList.size() + " ending moves found."); // Run the required processes generateSetupImage(app); generateMoveImages(app, condensedMoveList); generateEndImages(app, endingMoveList); generateWebsite(app, rankingStrings, condensedMoveList, endingMoveList); } //------------------------------------------------------------------------- /** * Take a screenshot of the game before it begins. */ private final static void generateSetupImage(final DesktopApp app) { GameUtil.resetGame(app, true); app.repaint(); final Timer setupScreenshotTimer = new Timer(); setupScreenshotTimer.scheduleAtFixedRate(new TimerTask() { @Override public void run() { if (ScreenCapture.screenshotComplete() && ScreenCapture.gifAnimationComplete() && !DesktopApp.view().isPainting) { ScreenCapture.resetScreenshotVariables(); final String filePath = "screenshot/Game_Setup"; ScreenCapture.gameScreenshot(rootPath + filePath); setupImageTimerComplete = true; setupScreenshotTimer.cancel(); setupScreenshotTimer.purge(); } } }, 0, 100); } //------------------------------------------------------------------------- /** * Take a screenshot/video of every move in the condensed list. */ private final static void generateMoveImages(final DesktopApp app, final List<MoveCompleteInformation> condensedMoveList) { final Timer moveScreenshotTimer = new Timer(); moveScreenshotTimer.scheduleAtFixedRate(new TimerTask() { int condensedMoveIndex = -1; @Override public void run() { if (setupImageTimerComplete && ScreenCapture.screenshotComplete() && ScreenCapture.gifAnimationComplete() && !DesktopApp.view().isPainting) { condensedMoveIndex++; if (condensedMoveIndex >= condensedMoveList.size()) { System.out.println("------------------------"); System.out.println("Move image generation complete."); generateMoveImagesTimerComplete = true; moveScreenshotTimer.cancel(); moveScreenshotTimer.purge(); } else { System.out.println("------------------------"); System.out.println("Move " + (condensedMoveIndex+1) + "/" + condensedMoveList.size()); final MoveCompleteInformation moveInformation = condensedMoveList.get(condensedMoveIndex); takeMoveImage(app, moveInformation, false); } } } }, 0, 100); } //------------------------------------------------------------------------- /** * Take a screenshot/video of every move in the ending move list. */ private final static void generateEndImages(final DesktopApp app, final List<MoveCompleteInformation> endingMoveList) { final Timer endScreenshotTimer = new Timer(); endScreenshotTimer.scheduleAtFixedRate(new TimerTask() { int endingMoveIndex = -1; @Override public void run() { if (generateMoveImagesTimerComplete && ScreenCapture.screenshotComplete() && ScreenCapture.gifAnimationComplete() && !DesktopApp.view().isPainting) { app.settingsPlayer().setShowEndingMove(true); endingMoveIndex++; if (endingMoveIndex >= endingMoveList.size()) { System.out.println("------------------------"); System.out.println("Ending image generation complete."); app.settingsPlayer().setShowEndingMove(false); generateEndImagesTimerComplete = true; endScreenshotTimer.cancel(); endScreenshotTimer.purge(); } else { System.out.println("------------------------"); System.out.println("End " + (endingMoveIndex+1) + "/" + endingMoveList.size()); final MoveCompleteInformation moveInformation = endingMoveList.get(endingMoveIndex); takeMoveImage(app, moveInformation, true); } } } }, 0, 100); } //------------------------------------------------------------------------- /** * Once the process is complete, combine all the stored images into a complete document. */ private final static void generateWebsite(final DesktopApp app, final List<String> rankingStrings, final List<MoveCompleteInformation> condensedMoveList, final List<MoveCompleteInformation> endingMoveList) { final Referee ref = app.manager().ref(); final Timer generateWebsiteTimer = new Timer(); generateWebsiteTimer.scheduleAtFixedRate(new TimerTask() { @Override public void run() { if (generateEndImagesTimerComplete && !DesktopApp.view().isPainting && ScreenCapture.screenshotComplete() && ScreenCapture.gifAnimationComplete()) { System.out.println("------------------------"); System.out.println("Generating html file."); try { final String filePath = rootPath + "output.html"; final File outputFile = new File(filePath); outputFile.getParentFile().mkdirs(); outputFile.createNewFile(); try(final FileWriter myWriter = new FileWriter(filePath)) { myWriter.write(HtmlFileOutput.htmlHeader); // Output toEnglish of the game description myWriter.write(HtmlFileOutput.htmlEnglishRules(ref.context().game())); // Output strategy/heuristics for this game based on metadata (if present). myWriter.write(HtmlFileOutput.htmlEnglishHeuristics(ref.context())); // Output board setup myWriter.write(HtmlFileOutput.htmlBoardSetup()); // Output endings myWriter.write(HtmlFileOutput.htmlEndings(rankingStrings, endingMoveList)); // Output all Move images/animations myWriter.write(HtmlFileOutput.htmlMoves(ref, condensedMoveList)); myWriter.write(HtmlFileOutput.htmlFooter); myWriter.close(); System.out.println("Process complete."); generateWebsiteTimerComplete = true; generateWebsiteTimer.cancel(); generateWebsiteTimer.purge(); } } catch (final Exception e) { e.printStackTrace(); } } } }, 0, 100); } //------------------------------------------------------------------------- /** * Takes a pair of screenshots and gif animation of the provided move. */ protected final static void takeMoveImage(final DesktopApp app, final MoveCompleteInformation moveInformation, final boolean endingMove) { ScreenCapture.resetGifAnimationVariables(); ScreenCapture.resetScreenshotVariables(); final Referee ref = app.manager().ref(); // Reset the game for the new trial. final Trial trial = moveInformation.trial(); final RandomProviderDefaultState trialRNG = moveInformation.rng(); app.manager().setCurrGameStartRngState(trialRNG); GameUtil.resetGame(app, true); // Apply all moves up until the one we want to capture. for (int i = trial.numInitialPlacementMoves(); i < moveInformation.moveIndex(); i++) { final Move move = trial.getMove(i); ref.context().game().apply(ref.context(), move); } // Update the GUI app.contextSnapshot().setContext(ref.context()); if (endingMove) { final List<Move> endingMoveList = new ArrayList<>(); endingMoveList.add(moveInformation.move()); app.settingsPlayer().setTutorialVisualisationMoves(endingMoveList); } else { app.settingsPlayer().setTutorialVisualisationMoves(moveInformation.similarMoves()); } // Repaint after apply all the saved moves. app.repaint(); // Determine the label for the gif/image. (mover-componentName-moveDescription-actionDescriptions) final String mover = String.valueOf(moveInformation.move().mover()); final String moveDescription = moveInformation.move().getDescription() + "_"; String allActionDescriptions = ""; for (final Action a : moveInformation.move().actions()) allActionDescriptions += a.getDescription() + "-"; final String imageLabel = (endingMove ? "END_" : "") + mover + "_" + moveDescription.toString().hashCode() + "_" + moveInformation.pieceName() + "_" + allActionDescriptions.toString().hashCode(); // Take the before screenshot final Timer beforeScreenshotTimer = new Timer(); beforeScreenshotTimer.scheduleAtFixedRate(new TimerTask() { @Override public void run() { if (!DesktopApp.view().isPainting) { ScreenCapture.resetScreenshotVariables(); System.out.println("Taking Before Screenshot"); final String filePath = "screenshot/" + imageLabel + "A_" + moveInformation.toString().hashCode(); ScreenCapture.gameScreenshot(rootPath + filePath); moveInformation.setScreenshotA(filePath + ".png"); app.settingsPlayer().setTutorialVisualisationMoves(new ArrayList<>()); app.repaint(); beforeScreenshotTimer.cancel(); beforeScreenshotTimer.purge(); } } }, 0, 100); // Start the gif animation recording process, and apply the move. final Timer gifAnimationTimer = new Timer(); gifAnimationTimer.scheduleAtFixedRate(new TimerTask() { @Override public void run() { if (!DesktopApp.view().isPainting && ScreenCapture.screenshotComplete()) { ScreenCapture.resetGifAnimationVariables(); ScreenCapture.resetScreenshotVariables(); System.out.println("Taking Gif Animation"); final String filePath = "gif/" + imageLabel + moveInformation.toString().hashCode(); ScreenCapture.gameGif(rootPath + filePath, 10); moveInformation.setGifLocation(filePath + ".gif"); ref.applyHumanMoveToGame(app.manager(), moveInformation.move()); gifAnimationTimer.cancel(); gifAnimationTimer.purge(); } } }, 0, 100); // Take the after screenshot final Timer afterScreenShotTimer = new Timer(); afterScreenShotTimer.scheduleAtFixedRate(new TimerTask() { @Override public void run() { if (!DesktopApp.view().isPainting && ScreenCapture.gifAnimationComplete()) { ScreenCapture.resetScreenshotVariables(); System.out.println("Taking After Screenshot"); final String filePath = "screenshot/" + imageLabel + "B_" + moveInformation.toString().hashCode(); ScreenCapture.gameScreenshot(rootPath + filePath); moveInformation.setScreenshotB(filePath + ".png"); afterScreenShotTimer.cancel(); afterScreenShotTimer.purge(); } } }, 0, 100); } //------------------------------------------------------------------------- public static boolean isProcessComplete() { return generateWebsiteTimerComplete; } //------------------------------------------------------------------------- }
15,042
36.235149
206
java
Ludii
Ludii-master/PlayerDesktop/src/app/manualGeneration/ManualGenerationUtils.java
package app.manualGeneration; import game.Game; import other.action.Action; import other.context.Context; import other.location.FullLocation; import other.location.Location; import other.move.Move; import other.state.State; import other.state.container.ContainerState; import util.ContainerUtil; public class ManualGenerationUtils { //------------------------------------------------------------------------- /** * Returns the what value of a given move at the current point in the context. */ public final static int getWhatOfMove(final Context context, final Move move) { final Location moveFrom = move.getFromLocation(); final int containerIdFrom = ContainerUtil.getContainerId(context, moveFrom.site(), moveFrom.siteType()); int what = -1; if (containerIdFrom != -1) { final State state = context.state(); final ContainerState cs = state.containerStates()[containerIdFrom]; // Get the what of the component at the move's from location what = cs.what(moveFrom.site(), moveFrom.level(), moveFrom.siteType()); // If adding a piece at the site, get the what of the first action that matches the move's from location instead. if (what == 0) { for (final Action a : move.actions()) { final Location actionLocationA = new FullLocation(a.from(), a.levelFrom(), a.fromType()); final Location actionLocationB = new FullLocation(a.to(), a.levelTo(), a.toType()); final Location testingLocation = new FullLocation(moveFrom.site(), moveFrom.level(), moveFrom.siteType()); if (actionLocationA.equals(testingLocation) && actionLocationB.equals(testingLocation)) { what = a.what(); break; } } } } return what; } //------------------------------------------------------------------------- public final static String getComponentNameFromIndex(final Context context, final int componentIndex) { String moveComponentName = "No Component"; if (context.game().isDeductionPuzzle()) moveComponentName = "Puzzle Value " + String.valueOf(componentIndex); else if (!context.game().isDeductionPuzzle() && componentIndex > 0) moveComponentName = context.equipment().components()[componentIndex].getNameWithoutNumber(); return moveComponentName; } //------------------------------------------------------------------------- public final static boolean checkGameValid(Game game) { if (game.isSimultaneousMoveGame()) return false; if (game.hasSubgames()) return false; return true; } //------------------------------------------------------------------------- }
2,627
28.863636
116
java
Ludii
Ludii-master/PlayerDesktop/src/app/manualGeneration/MoveComparison.java
package app.manualGeneration; import java.util.ArrayList; import java.util.List; import game.Game; import other.context.Context; import other.move.Move; public class MoveComparison { // Change these parameters to influence what is important when comparing moves. private static boolean compareMover = false; // The mover private final static boolean comparePieceName = true; // Piece being moved private final static boolean compareEnglishDescription = true; // movesLudemes.toEnglish() private final static boolean compareActions = true; // The actions in the move //------------------------------------------------------------------------- /** * Determines if two moves can be merged due to them containing the same key information. */ public final static boolean movesCanBeMerged(final Game game, final MoveCompleteInformation m1, final MoveCompleteInformation m2) { // compareMover can be set dynamically based on the properties of the game. compareMover = !game.noPieceOwnedBySpecificPlayer(); if (isCompareMover()) if (m1.move().mover() != m2.move().mover()) return false; if (isComparePieceName()) if (!m1.pieceName().equals(m2.pieceName())) return false; if (isCompareEnglishDescription()) if (!m1.englishDescription().equals(m2.englishDescription())) return false; if (isCompareActions()) { if (m1.move().actions().size() != m2.move().actions().size()) return false; for (int i = 0; i < m1.move().actions().size(); i++) { final String m1ActionDescription = m1.move().actions().get(i).getDescription(); final String m2ActionDescription = m2.move().actions().get(i).getDescription(); if (!m1ActionDescription.equals(m2ActionDescription)) return false; } } return true; } //------------------------------------------------------------------------- /** * Returns a list off all similar legal moves at the point in the context where the trueMove was applied. * Similar moves are those that can be merged, and are from the same location. */ public final static List<Move> similarMoves(final Context context, final Move trueMove) { final int trueMoveWhat = ManualGenerationUtils.getWhatOfMove(context, trueMove); final MoveCompleteInformation trueMoveCompleteInfo = new MoveCompleteInformation(context.game(), null, null, trueMove, -1, ManualGenerationUtils.getComponentNameFromIndex(context, trueMoveWhat), null); final List<Move> similarMoves = new ArrayList<>(); for (final Move move : context.moves(context).moves()) { final Move moveWithConsequences = new Move(move.getMoveWithConsequences(context)); moveWithConsequences.setMovesLudeme(move.movesLudeme()); final int moveWhat = ManualGenerationUtils.getWhatOfMove(context, moveWithConsequences); final MoveCompleteInformation moveCompleteInfo = new MoveCompleteInformation(context.game(), null, null, moveWithConsequences, -1, ManualGenerationUtils.getComponentNameFromIndex(context, moveWhat), null); if (movesCanBeMerged(context.game(), trueMoveCompleteInfo, moveCompleteInfo) && moveWithConsequences.getFromLocation().equals(trueMove.getFromLocation())) similarMoves.add(new Move(moveWithConsequences)); } if (similarMoves.isEmpty()) System.out.println("ERROR! similarMoves was empty"); return similarMoves; } //------------------------------------------------------------------------- public static boolean isCompareMover() { return compareMover; } public static boolean isComparePieceName() { return comparePieceName; } public static boolean isCompareEnglishDescription() { return compareEnglishDescription; } public static boolean isCompareActions() { return compareActions; } //------------------------------------------------------------------------- }
3,846
33.044248
208
java
Ludii
Ludii-master/PlayerDesktop/src/app/manualGeneration/MoveCompleteInformation.java
package app.manualGeneration; import java.util.List; import org.apache.commons.rng.core.RandomProviderDefaultState; import game.Game; import other.move.Move; import other.trial.Trial; /** * Object containing all necessary information to recreate (and compare) a specific move from a specific trial. * * @author Matthew.Stephenson */ public class MoveCompleteInformation { //------------------------------------------------------------------------- private final Trial trial; private final RandomProviderDefaultState rng; private final Move move; private final int moveIndex; private final String pieceName; private final List<Move> similarMoves; private final String englishDescription; private String endingDescription = "Not Found"; // Locations of generated gif/images private String gifLocation = ""; private String screenshotA = ""; private String screenshotB = ""; //------------------------------------------------------------------------- MoveCompleteInformation(final Game game, final Trial trial, final RandomProviderDefaultState rng, final Move move, final int moveIndex, final String pieceName, final List<Move> similarMoves) { this.trial = trial == null ? null : new Trial(trial); this.rng = rng == null ? null : new RandomProviderDefaultState(rng.getState()); this.move = move == null ? null : new Move(move); this.moveIndex = moveIndex; this.pieceName = pieceName; this.similarMoves = similarMoves; englishDescription = move.movesLudeme() == null ? "Not Found" : move.movesLudeme().toEnglish(game); } //------------------------------------------------------------------------- @Override public String toString() { return move().toString().replaceAll("[^a-zA-Z0-9]", "") + "_piece_" + pieceName() + "_mover_" + move().mover(); } Trial trial() { return trial; } RandomProviderDefaultState rng() { return rng; } Move move() { return move; } int moveIndex() { return moveIndex; } String pieceName() { return pieceName; } List<Move> similarMoves() { return similarMoves; } String englishDescription() { return englishDescription; } String endingDescription() { return endingDescription; } void setEndingDescription(String endingDescription) { this.endingDescription = endingDescription; } String gifLocation() { return gifLocation; } void setGifLocation(String gifLocation) { this.gifLocation = gifLocation; } String screenshotA() { return screenshotA; } void setScreenshotA(String screenshotA) { this.screenshotA = screenshotA; } String screenshotB() { return screenshotB; } void setScreenshotB(String screenshotB) { this.screenshotB = screenshotB; } //------------------------------------------------------------------------- }
2,804
19.777778
137
java
Ludii
Ludii-master/PlayerDesktop/src/app/manualGeneration/MoveGeneration.java
package app.manualGeneration; import java.util.List; import org.apache.commons.rng.core.RandomProviderDefaultState; import app.PlayerApp; import app.utils.GameUtil; import app.utils.UpdateTabMessages; import game.Game; import game.rules.end.End; import game.rules.end.EndRule; import game.rules.end.If; import other.context.Context; import other.move.Move; import other.trial.Trial; import util.ContainerUtil; public class MoveGeneration { //------------------------------------------------------------------------- public final static void generateTrials(final PlayerApp app, final List<Trial> generatedTrials, final List<RandomProviderDefaultState> generatedTrialsRNG, final int numberTrials) { while (generatedTrials.size() < numberTrials) { System.out.print("."); app.restartGame(); app.manager().ref().randomPlayout(app.manager()); generatedTrials.add(new Trial(app.manager().ref().context().trial())); generatedTrialsRNG.add(new RandomProviderDefaultState(app.manager().currGameStartRngState().getState())); } System.out.println("\nTrials Generated."); } //------------------------------------------------------------------------- public final static void recordTrialMoves(final PlayerApp app, final List<Trial> generatedTrials, final List<RandomProviderDefaultState> generatedTrialsRNG, final List<MoveCompleteInformation> condensedMoveList, final List<String> rankingStrings, final List<MoveCompleteInformation> endingMoveList, final boolean includeHandMoves, final boolean includeNoWhatMoves) { final Context context = app.manager().ref().context(); for (int trialIndex = 0; trialIndex < generatedTrials.size(); trialIndex++) { System.out.print("."); // Reset the game for the new trial. final Trial trial = generatedTrials.get(trialIndex); final RandomProviderDefaultState trialRNG = generatedTrialsRNG.get(trialIndex); app.manager().setCurrGameStartRngState(trialRNG); GameUtil.resetGame(app, true); for (int i = trial.numInitialPlacementMoves(); i < trial.numMoves(); i++) { // Find the corresponding move in the legal moves, to include movesLudeme. Move matchingLegalMove = null; Move move = trial.getMove(i); int matchesFound = 0; // Context used to copy the state reaching the terminal state before the game is over. Context prevContext = null; for (final Move m : context.game().moves(context).moves()) { if (m.toTrialFormat(context).equals(move.toTrialFormat(context))) { final Move newMove = new Move(m.getMoveWithConsequences(context)); newMove.setMovesLudeme(m.movesLudeme()); move = newMove; matchingLegalMove = m; matchesFound++; break; } } if (matchesFound != 1) { System.out.println("ERROR! exactly one match should be found, we found " + matchesFound); System.exit(0); } // Get complete information about the selected move. final int what = ManualGenerationUtils.getWhatOfMove(context, move); final List<Move> similarMoves = MoveComparison.similarMoves(context, move); final MoveCompleteInformation newMove = new MoveCompleteInformation(context.game(), trial, trialRNG, move, i, ManualGenerationUtils.getComponentNameFromIndex(context, what), similarMoves); // Record if the move involved hands at all. final boolean moveFromBoard = ContainerUtil.getContainerId(context, move.from(), move.fromType()) == 0; final boolean moveToBoard = ContainerUtil.getContainerId(context, move.to(), move.toType()) == 0; final boolean moveInvolvesHands = !moveFromBoard || !moveToBoard; // Skip moves without an associated component or which move from the hands (if desired). if ((what != -1 || includeNoWhatMoves) && (includeHandMoves || !moveInvolvesHands)) { // Determine if the move should be added to the condensed list. boolean addMove = true; for (int j = 0; j < condensedMoveList.size(); j++) { final MoveCompleteInformation priorMove = condensedMoveList.get(j); if (MoveComparison.movesCanBeMerged(context.game(), newMove, priorMove)) { // Check if the new move has a larger number of possible moves, if so replace the old move. if (newMove.similarMoves().size() > priorMove.similarMoves().size()) condensedMoveList.set(j, newMove); addMove = false; break; } } if (addMove) condensedMoveList.add(newMove); // We keep the context before the ending state for To English of the terminal condition. if(i == trial.numMoves()-1) prevContext = new Context(context); // Apply the move to update the context for the next move. context.game().apply(context, matchingLegalMove); // Get endingString for move. if (context.trial().over()) { // Check if the last move should be stored. final String rankingString = UpdateTabMessages.gameOverMessage(context, trial); //final String rankingString = "Game won by Player " + trial.status().winner() + ".\n"; // We update the context without to modify the data of prevContext. context.trial().lastMove().apply(prevContext, true); // Store the toEnglish of the end condition. for(final End end : getEnd(context.game())) { if(end != null && end.endRules() != null) { for (final EndRule endRule : end.endRules()) { if (endRule instanceof If) { final If ifEndRule = (If) endRule; ifEndRule.endCondition().preprocess(context.game()); if (ifEndRule.result() != null && ifEndRule.result().result() != null && ifEndRule.endCondition().eval(prevContext)) { newMove.setEndingDescription(((If) endRule).endCondition().toEnglish(context.game())); break; } } } } } // Check if any of our previous ending moves triggered the same condition. boolean endingStringFoundBefore = false; for (final MoveCompleteInformation endingMoveInformation : endingMoveList) if (endingMoveInformation.endingDescription().equals(newMove.endingDescription())) endingStringFoundBefore = true; // Only store the ending move/ranking if we haven't encountered this combination before. if (!rankingStrings.contains(rankingString) || !endingStringFoundBefore) { rankingStrings.add(rankingString); endingMoveList.add(newMove); } } } else { // Apply the move to update the context for the next move. context.game().apply(context, matchingLegalMove); } } } System.out.println("\nMoves Recorded."); } //------------------------------------------------------------------------- /** * @param game * @return A list of End rule objects for the given game. */ private static End[] getEnd(final Game game) { if (game.rules().phases().length == 1) { return new End[] {game.endRules()}; } else { final End[] phaseEnd = new End[game.rules().phases().length]; for (int i = 0; i < game.rules().phases().length; i++) phaseEnd[i] = game.rules().phases()[i].end(); return phaseEnd; } } //------------------------------------------------------------------------- }
7,370
35.855
365
java
Ludii
Ludii-master/PlayerDesktop/src/app/menu/MainMenu.java
package app.menu; import static java.awt.event.InputEvent.ALT_DOWN_MASK; import static java.awt.event.InputEvent.CTRL_DOWN_MASK; import java.awt.Font; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.InputEvent; import java.awt.event.ItemListener; import java.io.File; import java.io.FilenameFilter; import java.io.IOException; import java.io.InputStream; import java.net.URISyntaxException; import java.net.URL; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.regex.Pattern; import javax.swing.ButtonGroup; //import javax.swing.ButtonGroup; //import javax.swing.JCheckBoxMenuItem; import javax.swing.JCheckBoxMenuItem; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JRadioButtonMenuItem; import javax.swing.KeyStroke; import javax.swing.UIManager; import org.json.JSONException; import org.json.JSONObject; import org.json.JSONTokener; import app.DesktopApp; import app.PlayerApp; import app.loading.MiscLoading; import app.utils.PuzzleSelectionType; import app.utils.SettingsExhibition; import game.equipment.container.board.Track; import game.types.play.RepetitionType; import main.Constants; import main.FileHandling; import main.StringRoutines; import main.options.GameOptions; import main.options.Option; import main.options.Ruleset; import other.context.Context; //-------------------------------------------------------- /** * The app's main menu. * * @author cambolbro and Eric.Piette */ public class MainMenu extends JMenuBar { private static final long serialVersionUID = 1L; public static JMenu mainOptionsMenu; protected JMenu submenu; public JMenuItem showIndexOption; public JMenuItem showCoordinateOption; //------------------------------------------------------------------------- /** * Constructor. */ public MainMenu(final PlayerApp app) { // No menu for exhibition app. if (app.settingsPlayer().usingMYOGApp() || SettingsExhibition.exhibitionVersion) return; final ActionListener al = app; final ItemListener il = app; JMenuItem menuItem; JCheckBoxMenuItem cbMenuItem; UIManager.put("Menu.font", new Font("Arial", Font.PLAIN, 16)); UIManager.put("MenuItem.font", new Font("Arial", Font.PLAIN, 16)); UIManager.put("CheckBoxMenuItem.font", new Font("Arial", Font.PLAIN, 16)); UIManager.put("RadioButtonMenuItem.font", new Font("Arial", Font.PLAIN, 16)); //--------------------------------------------------------------------- // Ludii Menu JMenu menu = new JMenu("Ludii"); this.add(menu); menuItem = new JMenuItem("Preferences"); menuItem.setAccelerator(KeyStroke.getKeyStroke('S', InputEvent.SHIFT_DOWN_MASK)); menuItem.addActionListener(al); menu.add(menuItem); menuItem = new JMenuItem("Quit"); menuItem.setAccelerator(KeyStroke.getKeyStroke('Q', CTRL_DOWN_MASK)); menuItem.addActionListener(al); menu.add(menuItem); //--------------------------------------------------------------------- // File Menu if (app.manager().settingsNetwork().getActiveGameId() == 0) { menu = new JMenu("File"); this.add(menu); menuItem = new JMenuItem("Load Game"); menuItem.setAccelerator(KeyStroke.getKeyStroke('L', CTRL_DOWN_MASK)); menuItem.addActionListener(al); menu.add(menuItem); submenu = new JMenu("Load Recent"); for (int i = 0; i < app.settingsPlayer().recentGames().length; i++) { if (app.settingsPlayer().recentGames()[i] == null) { break; } menuItem = new JMenuItem(app.settingsPlayer().recentGames()[i]); switch(i) { case 0: menuItem.setAccelerator(KeyStroke.getKeyStroke('1', ALT_DOWN_MASK)); break; case 1: menuItem.setAccelerator(KeyStroke.getKeyStroke('2', ALT_DOWN_MASK)); break; case 2: menuItem.setAccelerator(KeyStroke.getKeyStroke('3', ALT_DOWN_MASK)); break; case 3: menuItem.setAccelerator(KeyStroke.getKeyStroke('4', ALT_DOWN_MASK)); break; case 4: menuItem.setAccelerator(KeyStroke.getKeyStroke('5', ALT_DOWN_MASK)); break; case 5: menuItem.setAccelerator(KeyStroke.getKeyStroke('6', ALT_DOWN_MASK)); break; case 6: menuItem.setAccelerator(KeyStroke.getKeyStroke('7', ALT_DOWN_MASK)); break; case 7: menuItem.setAccelerator(KeyStroke.getKeyStroke('8', ALT_DOWN_MASK)); break; case 8: menuItem.setAccelerator(KeyStroke.getKeyStroke('9', ALT_DOWN_MASK)); break; case 9: menuItem.setAccelerator(KeyStroke.getKeyStroke('0', ALT_DOWN_MASK)); break; } menuItem.addActionListener(al); submenu.add(menuItem); } menu.add(submenu); menuItem = new JMenuItem("Load Game from File"); menuItem.setAccelerator(KeyStroke.getKeyStroke('F', CTRL_DOWN_MASK)); menuItem.addActionListener(al); menuItem.setToolTipText("Load a game description from and external .lud file"); menu.add(menuItem); menuItem = new JMenuItem("Load Random Game"); menuItem.addActionListener(al); menu.add(menuItem); menu.addSeparator(); menuItem = new JMenuItem("Load Trial"); menuItem.addActionListener(al); menu.add(menuItem); menuItem.setAccelerator(KeyStroke.getKeyStroke('T', CTRL_DOWN_MASK)); menuItem = new JMenuItem("Save Trial"); menuItem.addActionListener(al); menu.add(menuItem); menuItem.setAccelerator(KeyStroke.getKeyStroke('S', CTRL_DOWN_MASK)); menu.addSeparator(); menuItem = new JMenuItem("Create Game"); menuItem.addActionListener(al); menu.add(menuItem); menuItem = new JMenuItem("Editor (Packed)"); menuItem.addActionListener(al); menu.add(menuItem); menuItem = new JMenuItem("Editor (Expanded)"); menuItem.addActionListener(al); menu.add(menuItem); menuItem = new JMenuItem("Visual Editor (Beta)"); menuItem.addActionListener(al); menu.add(menuItem); } //--------------------------------------------------------------------- // Game Menu menu = new JMenu("Game"); this.add(menu); if (app.manager().settingsNetwork().getActiveGameId() == 0) { menuItem = new JMenuItem("Restart"); menuItem.setAccelerator(KeyStroke.getKeyStroke('R', CTRL_DOWN_MASK)); menuItem.addActionListener(al); menu.add(menuItem); menuItem = new JMenuItem("Random Move"); menuItem.setAccelerator(KeyStroke.getKeyStroke('M', CTRL_DOWN_MASK)); menuItem.addActionListener(al); menu.add(menuItem); menuItem = new JMenuItem("Random Playout"); menuItem.setAccelerator(KeyStroke.getKeyStroke('P', CTRL_DOWN_MASK)); menuItem.addActionListener(al); menu.add(menuItem); } else if (app.manager().settingsNetwork().getActiveGameId() != 0) { menuItem = new JMenuItem("Propose/Accept a Draw"); menuItem.addActionListener(al); menu.add(menuItem); menuItem = new JMenuItem("Resign Game"); menuItem.addActionListener(al); menu.add(menuItem); menuItem = new JMenuItem("Leave Game"); menuItem.addActionListener(al); menu.add(menuItem); } menu.addSeparator(); // Don't allow legal moves to be listed if playing an online game with hidden information. if (app.manager().settingsNetwork().getActiveGameId() == 0 || !app.contextSnapshot().getContext(app).game().hiddenInformation()) { menuItem = new JMenuItem("List Legal Moves"); menuItem.setAccelerator(KeyStroke.getKeyStroke('L', InputEvent.SHIFT_DOWN_MASK)); menuItem.addActionListener(al); menu.add(menuItem); } menu.addSeparator(); menuItem = new JMenuItem("Game Screenshot"); menuItem.setAccelerator(KeyStroke.getKeyStroke('C', InputEvent.SHIFT_DOWN_MASK)); menuItem.addActionListener(al); menu.add(menuItem); menuItem = new JMenuItem("Game Gif"); menuItem.addActionListener(al); menu.add(menuItem); menuItem = new JMenuItem("Make QR Code"); menuItem.addActionListener(al); menu.add(menuItem); if (app.manager().settingsNetwork().getActiveGameId() == 0) { menu.addSeparator(); menuItem = new JMenuItem("Cycle Players"); menuItem.setAccelerator(KeyStroke.getKeyStroke('R', ALT_DOWN_MASK)); menuItem.addActionListener(al); menu.add(menuItem); menu.addSeparator(); menuItem = new JMenuItem("Test Ludeme"); menuItem.addActionListener(al); menu.add(menuItem); menu.addSeparator(); menuItem = new JMenuItem("Generate Grammar"); menuItem.setAccelerator(KeyStroke.getKeyStroke('G', CTRL_DOWN_MASK)); menuItem.addActionListener(al); menu.add(menuItem); menuItem = new JMenuItem("Count Ludemes"); menuItem.addActionListener(al); menu.add(menuItem); menuItem = new JMenuItem("Game Description Length"); menuItem.addActionListener(al); menu.add(menuItem); menuItem = new JMenuItem("Game Description Length (All Games)"); menuItem.addActionListener(al); menu.add(menuItem); } //--------------------------------------------------------------------- // Navigation Menu if (app.manager().settingsNetwork().getActiveGameId() == 0) { menu = new JMenu("Navigation"); this.add(menu); menuItem = new JMenuItem("Play/Pause"); menuItem.setAccelerator(KeyStroke.getKeyStroke("SPACE")); menuItem.addActionListener(al); menu.add(menuItem); menu.addSeparator(); menuItem = new JMenuItem("Previous Move"); menuItem.setAccelerator(KeyStroke.getKeyStroke("LEFT")); menuItem.addActionListener(al); menu.add(menuItem); menuItem = new JMenuItem("Next Move"); menuItem.setAccelerator(KeyStroke.getKeyStroke("RIGHT")); menuItem.addActionListener(al); menu.add(menuItem); menu.addSeparator(); menuItem = new JMenuItem("Go To Start"); menuItem.setAccelerator(KeyStroke.getKeyStroke("DOWN")); menuItem.addActionListener(al); menu.add(menuItem); menuItem = new JMenuItem("Go To End"); menuItem.setAccelerator(KeyStroke.getKeyStroke("UP")); menuItem.addActionListener(al); menu.add(menuItem); if (app.contextSnapshot().getContext(app).game().hasSubgames()) { menu.addSeparator(); menuItem = new JMenuItem("Random Playout Instance"); menuItem.addActionListener(al); menu.add(menuItem); } menu.addSeparator(); menuItem = new JMenuItem("Pass"); menuItem.setAccelerator(KeyStroke.getKeyStroke('P', ALT_DOWN_MASK)); menuItem.addActionListener(al); menu.add(menuItem); } //--------------------------------------------------------------------- // Puzzle Menu if (app.contextSnapshot().getContext(app).game().isDeductionPuzzle()) { menu = new JMenu("Puzzle"); this.add(menu); submenu = new JMenu("Value Selection"); JRadioButtonMenuItem rbMenuItem = new JRadioButtonMenuItem("Automatic"); rbMenuItem.setSelected(app.settingsPlayer().puzzleDialogOption() == PuzzleSelectionType.Automatic); rbMenuItem.addItemListener(il); submenu.add(rbMenuItem); rbMenuItem = new JRadioButtonMenuItem("Dialog"); rbMenuItem.setSelected(app.settingsPlayer().puzzleDialogOption() == PuzzleSelectionType.Dialog); rbMenuItem.addItemListener(il); submenu.add(rbMenuItem); rbMenuItem = new JRadioButtonMenuItem("Cycle"); rbMenuItem.setSelected(app.settingsPlayer().puzzleDialogOption() == PuzzleSelectionType.Cycle); rbMenuItem.addItemListener(il); submenu.add(rbMenuItem); menu.add(submenu); menu.addSeparator(); cbMenuItem = new JCheckBoxMenuItem("Illegal Moves Allowed"); cbMenuItem.setSelected(app.settingsPlayer().illegalMovesValid()); cbMenuItem.setAccelerator(KeyStroke.getKeyStroke('I', InputEvent.SHIFT_DOWN_MASK)); cbMenuItem.addItemListener(il); menu.add(cbMenuItem); menu.addSeparator(); cbMenuItem = new JCheckBoxMenuItem("Show Possible Values"); cbMenuItem.setSelected(app.bridge().settingsVC().showCandidateValues()); cbMenuItem.setAccelerator(KeyStroke.getKeyStroke('V', InputEvent.SHIFT_DOWN_MASK)); cbMenuItem.addItemListener(il); menu.add(cbMenuItem); } //--------------------------------------------------------------------- // Analysis Menu if (app.manager().settingsNetwork().getActiveGameId() == 0) { menu = new JMenu("Analysis"); this.add(menu); menuItem = new JMenuItem("Estimate Branching Factor"); menuItem.addActionListener(al); menu.add(menuItem); menuItem = new JMenuItem("Estimate Game Length"); menuItem.addActionListener(al); menu.add(menuItem); menuItem = new JMenuItem("Estimate Game Tree Complexity"); menuItem.addActionListener(al); menu.add(menuItem); menuItem = new JMenuItem("Estimate Game Tree Complexity (No State Repetition)"); menuItem.addActionListener(al); menu.add(menuItem); menu.addSeparator(); menuItem = new JMenuItem("Compare Agents"); menuItem.addActionListener(al); menu.add(menuItem); // menu.addSeparator(); // // menuItem = new JMenuItem("Prove Win"); // menuItem.addActionListener(al); // menu.add(menuItem); // // menuItem = new JMenuItem("Prove Loss"); // menuItem.addActionListener(al); // menu.add(menuItem); menu.addSeparator(); menuItem = new JMenuItem("Evaluation Dialog"); menuItem.setAccelerator(KeyStroke.getKeyStroke('E', InputEvent.CTRL_DOWN_MASK)); menuItem.addActionListener(al); menu.add(menuItem); menu.addSeparator(); menuItem = new JMenuItem("Show Compilation Concepts"); menuItem.addActionListener(al); menu.add(menuItem); menu.addSeparator(); if (app.manager().settingsNetwork().getActiveGameId() == 0) { menuItem = new JMenuItem("Time Random Playouts"); menuItem.setAccelerator(KeyStroke.getKeyStroke('O', CTRL_DOWN_MASK)); menuItem.addActionListener(al); menu.add(menuItem); menuItem = new JMenuItem("Time Random Playouts in Background"); menuItem.setAccelerator(KeyStroke.getKeyStroke('R', InputEvent.SHIFT_DOWN_MASK)); menuItem.addActionListener(al); menu.add(menuItem); } menu.addSeparator(); menuItem = new JMenuItem("Duplicates Moves Test"); menuItem.addActionListener(al); menu.add(menuItem); menu.addSeparator(); submenu = new JMenu("Predict Best Agent (internal)"); menuItem = new JMenuItem("Linear Regression (internal)"); menuItem.addActionListener(al); submenu.add(menuItem); menu.add(submenu); if (DesktopApp.devJar) { final File file = new File("../../LudiiPrivate/DataMiningScripts/Sklearn/res/trainedModels"); final String[] directories = file.list(new FilenameFilter() { @Override public boolean accept(final File current, final String name) { return new File(current, name).isDirectory(); } }); menu.addSeparator(); //--------------------------------------------------------------------- // Agent prediction submenu = new JMenu("Predict Best Agent (external)"); final JMenu submenuAgentReg = new JMenu("Regression"); final JMenu submenuAgentCla = new JMenu("Classification"); final JMenu submenuAgentRegComp = new JMenu("Compilation"); final JMenu submenuAgentClaComp = new JMenu("Compilation"); final JMenu submenuAgentRegAll = new JMenu("All"); final JMenu submenuAgentClaAll = new JMenu("All"); submenuAgentReg.add(submenuAgentRegComp); submenuAgentReg.add(submenuAgentRegAll); submenuAgentCla.add(submenuAgentClaComp); submenuAgentCla.add(submenuAgentClaAll); submenu.add(submenuAgentReg); submenu.add(submenuAgentCla); if (directories != null) { for (final String s : directories) { if (s.contains("Agents")) { if (s.contains("Classification")) { if (s.contains("True")) { menuItem = new JMenuItem(s.split("-")[0]); menuItem.addActionListener(al); submenuAgentClaComp.add(menuItem); } else if (s.contains("False")) { menuItem = new JMenuItem(s.split("-")[0]); menuItem.addActionListener(al); submenuAgentClaAll.add(menuItem); } } else { if (s.contains("True")) { menuItem = new JMenuItem(s.split("-")[0]); menuItem.addActionListener(al); submenuAgentRegComp.add(menuItem); } else if (s.contains("False")) { menuItem = new JMenuItem(s.split("-")[0]); menuItem.addActionListener(al); submenuAgentRegAll.add(menuItem); } } } } } menu.add(submenu); //--------------------------------------------------------------------- // Heuristic prediction submenu = new JMenu("Predict Best Heuristic (external)"); final JMenu submenuHeuristicReg = new JMenu("Regression"); final JMenu submenuHeuristicCla = new JMenu("Classification"); final JMenu submenuHeuristicRegComp = new JMenu("Compilation"); final JMenu submenuHeuristicClaComp = new JMenu("Compilation"); final JMenu submenuHeuristicRegAll = new JMenu("All"); final JMenu submenuHeuristicClaAll = new JMenu("All"); submenuHeuristicReg.add(submenuHeuristicRegComp); submenuHeuristicReg.add(submenuHeuristicRegAll); submenuHeuristicCla.add(submenuHeuristicClaComp); submenuHeuristicCla.add(submenuHeuristicClaAll); submenu.add(submenuHeuristicReg); submenu.add(submenuHeuristicCla); if (directories != null) { for (final String s : directories) { if (s.contains("Heuristics")) { if (s.contains("Classification")) { if (s.contains("True")) { menuItem = new JMenuItem(s.split("-")[0]); menuItem.addActionListener(al); submenuHeuristicClaComp.add(menuItem); } else if (s.contains("False")) { menuItem = new JMenuItem(s.split("-")[0]); menuItem.addActionListener(al); submenuHeuristicClaAll.add(menuItem); } } else { if (s.contains("True")) { menuItem = new JMenuItem(s.split("-")[0]); menuItem.addActionListener(al); submenuHeuristicRegComp.add(menuItem); } else if (s.contains("False")) { menuItem = new JMenuItem(s.split("-")[0]); menuItem.addActionListener(al); submenuHeuristicRegAll.add(menuItem); } } } } } menu.add(submenu); //--------------------------------------------------------------------- // Metric prediction submenu = new JMenu("Predict Metrics (external)"); final JMenu submenuComp = new JMenu("Compilation"); final JMenu submenuAll = new JMenu("All"); if (directories != null) { for (final String s : directories) { if (s.contains("Metrics")) { if (s.contains("True")) { menuItem = new JMenuItem(s.split("-")[0]); menuItem.addActionListener(al); submenuComp.add(menuItem); } else if (s.contains("False")) { menuItem = new JMenuItem(s.split("-")[0]); menuItem.addActionListener(al); submenuAll.add(menuItem); } } } } submenu.add(submenuComp); submenu.add(submenuAll); menu.add(submenu); //--------------------------------------------------------------------- // Portfolio parameter prediction menuItem = new JMenuItem("Portfolio Parameters (external)"); menuItem.addActionListener(al); menu.add(menuItem); } } // //--------------------------------------------------------------------- // // Generation menu // // if (app.manager().settingsNetwork().getActiveGameId() == 0) // { // menu = new JMenu("Generation"); // this.add(menu); // // menuItem = new JMenuItem("Generate Random Game"); // menuItem.addActionListener(al); // menu.add(menuItem); // // menuItem = new JMenuItem("Generate 1000 Random Games"); // menuItem.addActionListener(al); // menu.add(menuItem); // // if (DesktopApp.devJar) // { // menuItem = new JMenuItem("Generate 1 Game with Restrictions (dev)"); // menuItem.addActionListener(al); // menu.add(menuItem); // } // } //--------------------------------------------------------------------- // Options Menu boolean optionsFound = false; for (int o = 0; o < app.contextSnapshot().getContext(app).game().description().gameOptions().numCategories(); o++) { final List<Option> options = app.contextSnapshot().getContext(app).game().description().gameOptions().categories().get(o).options(); if (!options.isEmpty()) optionsFound = true; } if (optionsFound && app.manager().settingsNetwork().getActiveGameId()==0) { mainOptionsMenu = new JMenu("Options"); this.add(mainOptionsMenu); updateOptionsMenu(app, app.contextSnapshot().getContext(app), mainOptionsMenu); } //--------------------------------------------------------------------- // Network Menu menu = new JMenu("Remote"); this.add(menu); menuItem = new JMenuItem("Remote Play"); menuItem.addActionListener(al); menu.add(menuItem); menu.addSeparator(); menuItem = new JMenuItem("Initialise Server Socket"); menuItem.addActionListener(al); menu.add(menuItem); menuItem = new JMenuItem("Test Message Socket"); menuItem.addActionListener(al); menu.add(menuItem); menu.addSeparator(); menuItem = new JMenuItem("Select Move from String"); menuItem.setAccelerator(KeyStroke.getKeyStroke('S', ALT_DOWN_MASK)); menuItem.addActionListener(al); menu.add(menuItem); //--------------------------------------------------------------------- // Demos Menu if (app.manager().settingsNetwork().getActiveGameId() == 0) { menu = new JMenu("Demos"); final String[] demos = findDemos(); if (demos.length > 0) { this.add(menu); for (String demo : demos) { if (!demo.endsWith(".json")) continue; demo = demo.replaceAll(Pattern.quote("\\"), "/"); if (demo.contains("/demos/")) demo = demo.substring(demo.indexOf("/demos/")); if (!demo.startsWith("/")) demo = "/" + demo; if (!demo.startsWith("/demos")) demo = "/demos" + demo; try (final InputStream inputStream = MainMenu.class.getResourceAsStream(demo)) { final JSONObject json = new JSONObject(new JSONTokener(inputStream)); final JSONObject jsonDemo = json.getJSONObject("Demo"); final String demoName = jsonDemo.getString("Name"); menuItem = new JMenuItem(demoName); menuItem.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { MiscLoading.loadDemo(app, jsonDemo); } }); menu.add(menuItem); } catch (final JSONException e) { System.err.println("Warning: JSON parsing error for demo file: " + demo); } catch (final IOException e) { e.printStackTrace(); } } } } //--------------------------------------------------------------------- // Developer Menu if ( app.settingsPlayer().devMode() && app.manager().settingsNetwork().getActiveGameId() == 0 ) { menu = new JMenu("Developer"); this.add(menu); menuItem = new JMenuItem("Compile Game (Debug)"); menuItem.addActionListener(al); menu.add(menuItem); menuItem = new JMenuItem("Recompile Current Game"); menuItem.addActionListener(al); menu.add(menuItem); menuItem = new JMenuItem("Expanded Description"); menuItem.addActionListener(al); menu.add(menuItem); menuItem = new JMenuItem("Metadata Description"); menuItem.addActionListener(al); menu.add(menuItem); menuItem = new JMenuItem("Generate Symbols"); menuItem.setAccelerator(KeyStroke.getKeyStroke('G', ALT_DOWN_MASK)); menuItem.addActionListener(al); menu.add(menuItem); menuItem = new JMenuItem("Show Call Tree"); menuItem.addActionListener(al); menu.add(menuItem); menu.addSeparator(); menuItem = new JMenuItem("Rules in English"); menuItem.addActionListener(al); menu.add(menuItem); menuItem = new JMenuItem("Game Manual Generation (Beta)"); menuItem.addActionListener(al); menu.add(menuItem); // menu.addSeparator(); // // menuItem = new JMenuItem("Advanced Distance Dialog"); // menuItem.addActionListener(al); // menu.add(menuItem); menu.addSeparator(); menuItem = new JMenuItem("Print Board Graph"); menuItem.addActionListener(al); menu.add(menuItem); menuItem = new JMenuItem("Print Trajectories"); menuItem.addActionListener(al); menu.add(menuItem); menu.addSeparator(); menuItem = new JMenuItem("Jump to Move"); menuItem.addActionListener(al); menu.add(menuItem); menu.addSeparator(); menuItem = new JMenuItem("Serialise Game Object"); menuItem.addActionListener(al); menu.add(menuItem); menu.addSeparator(); cbMenuItem = new JCheckBoxMenuItem("Show dev tooltip"); cbMenuItem.setSelected(app.settingsPlayer().cursorTooltipDev()); cbMenuItem.addItemListener(il); menu.add(cbMenuItem); menu.addSeparator(); cbMenuItem = new JCheckBoxMenuItem("Sandbox"); cbMenuItem.setSelected(app.settingsPlayer().sandboxMode()); cbMenuItem.addItemListener(il); menu.add(cbMenuItem); menuItem = new JMenuItem("Clear Board"); menuItem.setEnabled(app.settingsPlayer().sandboxMode()); menuItem.addActionListener(al); menu.add(menuItem); menu.addSeparator(); if (DesktopApp.devJar) { menuItem = new JMenuItem("Export Thumbnails"); menuItem.addActionListener(al); menu.add(menuItem); menuItem = new JMenuItem("Export All Thumbnails"); menuItem.addActionListener(al); menu.add(menuItem); menuItem = new JMenuItem("Export Thumbnails (ruleset)"); menuItem.addActionListener(al); menu.add(menuItem); menuItem = new JMenuItem("Export Thumbnails (complete rulesets)"); menuItem.addActionListener(al); menu.add(menuItem); menuItem = new JMenuItem("Export All Thumbnails (rulesets)"); menuItem.addActionListener(al); menu.add(menuItem); menuItem = new JMenuItem("Export Board Thumbnail"); menuItem.addActionListener(al); menu.add(menuItem); menuItem = new JMenuItem("Export All Board Thumbnails"); menuItem.addActionListener(al); menu.add(menuItem); menu.addSeparator(); } app.settingsPlayer().setSwapRule(false); if (app.contextSnapshot().getContext(app).game().metaRules().usesSwapRule()) app.settingsPlayer().setSwapRule(true); app.settingsPlayer().setNoRepetition(false); if (app.contextSnapshot().getContext(app).game().metaRules().repetitionType() == RepetitionType.Positional) app.settingsPlayer().setNoRepetition(true); app.settingsPlayer().setNoRepetitionWithinTurn(false); if (app.contextSnapshot().getContext(app).game().metaRules().repetitionType() == RepetitionType.PositionalInTurn) app.settingsPlayer().setNoRepetitionWithinTurn(true); if (app.manager().settingsNetwork().getActiveGameId() == 0) { cbMenuItem = new JCheckBoxMenuItem("Swap Rule"); cbMenuItem.setAccelerator(KeyStroke.getKeyStroke('J', InputEvent.SHIFT_DOWN_MASK)); cbMenuItem.setSelected(app.settingsPlayer().swapRule()); cbMenuItem.addItemListener(il); menu.add(cbMenuItem); } if (app.manager().settingsNetwork().getActiveGameId() == 0) { cbMenuItem = new JCheckBoxMenuItem("No Repetition Of Game State"); cbMenuItem.setAccelerator(KeyStroke.getKeyStroke('N', InputEvent.SHIFT_DOWN_MASK)); cbMenuItem.setSelected(app.settingsPlayer().noRepetition()); cbMenuItem.addItemListener(il); menu.add(cbMenuItem); } if (app.manager().settingsNetwork().getActiveGameId() == 0) { cbMenuItem = new JCheckBoxMenuItem("No Repetition Within A Turn"); cbMenuItem.setAccelerator(KeyStroke.getKeyStroke('W', InputEvent.SHIFT_DOWN_MASK)); cbMenuItem.setSelected(app.settingsPlayer().noRepetitionWithinTurn()); cbMenuItem.addItemListener(il); menu.add(cbMenuItem); } menu.addSeparator(); cbMenuItem = new JCheckBoxMenuItem("Show Cell Indices"); cbMenuItem.setAccelerator(KeyStroke.getKeyStroke('I', ALT_DOWN_MASK)); cbMenuItem.setSelected(app.bridge().settingsVC().showCellIndices()); cbMenuItem.addItemListener(il); menu.add(cbMenuItem); cbMenuItem = new JCheckBoxMenuItem("Show Edge Indices"); cbMenuItem.setAccelerator(KeyStroke.getKeyStroke('E', ALT_DOWN_MASK)); cbMenuItem.setSelected(app.bridge().settingsVC().showEdgeIndices()); cbMenuItem.addItemListener(il); menu.add(cbMenuItem); cbMenuItem = new JCheckBoxMenuItem("Show Vertex Indices"); cbMenuItem.setAccelerator(KeyStroke.getKeyStroke('F', ALT_DOWN_MASK)); cbMenuItem.setSelected(app.bridge().settingsVC().showVertexIndices()); cbMenuItem.addItemListener(il); menu.add(cbMenuItem); cbMenuItem = new JCheckBoxMenuItem("Show Container Indices"); cbMenuItem.setSelected(app.bridge().settingsVC().showContainerIndices()); cbMenuItem.addItemListener(il); menu.add(cbMenuItem); menu.addSeparator(); cbMenuItem = new JCheckBoxMenuItem("Show Cell Coordinates"); cbMenuItem.setAccelerator(KeyStroke.getKeyStroke('C', ALT_DOWN_MASK)); cbMenuItem.setSelected(app.bridge().settingsVC().showCellCoordinates()); cbMenuItem.addItemListener(il); menu.add(cbMenuItem); cbMenuItem = new JCheckBoxMenuItem("Show Edge Coordinates"); cbMenuItem.setSelected(app.bridge().settingsVC().showEdgeCoordinates()); cbMenuItem.setAccelerator(KeyStroke.getKeyStroke('B', ALT_DOWN_MASK)); cbMenuItem.addItemListener(il); menu.add(cbMenuItem); cbMenuItem = new JCheckBoxMenuItem("Show Vertex Coordinates"); cbMenuItem.setAccelerator(KeyStroke.getKeyStroke('W', ALT_DOWN_MASK)); cbMenuItem.setSelected(app.bridge().settingsVC().showVertexCoordinates()); cbMenuItem.addItemListener(il); menu.add(cbMenuItem); menu.addSeparator(); menuItem = new JMenuItem("Print Working Directory"); menuItem.addActionListener(al); menu.add(menuItem); menu.addSeparator(); menuItem = new JMenuItem("Evaluate Heuristic"); menuItem.addActionListener(al); menu.add(menuItem); menuItem = new JMenuItem("Evaluate Features"); menuItem.addActionListener(al); menu.add(menuItem); cbMenuItem = new JCheckBoxMenuItem("Print Move Features"); cbMenuItem.setSelected(app.settingsPlayer().printMoveFeatures()); cbMenuItem.addItemListener(il); menu.add(cbMenuItem); cbMenuItem = new JCheckBoxMenuItem("Print Move Feature Instances"); cbMenuItem.setSelected(app.settingsPlayer().printMoveFeatureInstances()); cbMenuItem.addItemListener(il); menu.add(cbMenuItem); menu.addSeparator(); menuItem = new JMenuItem("Generate Random Game"); menuItem.addActionListener(al); menu.add(menuItem); menuItem = new JMenuItem("Generate 1000 Random Games"); menuItem.addActionListener(al); menu.add(menuItem); if (DesktopApp.devJar) { menuItem = new JMenuItem("Generate 1 Game with Restrictions (dev)"); menuItem.addActionListener(al); menu.add(menuItem); menuItem = new JMenuItem("Contextual Distance"); menuItem.addActionListener(al); menu.add(menuItem); } menu.addSeparator(); menuItem = new JMenuItem("Reconstruction Dialog"); menuItem.addActionListener(al); menu.add(menuItem); menu.addSeparator(); menuItem = new JMenuItem("More Developer Options"); menuItem.addActionListener(al); menu.add(menuItem); MenuScroller.setScrollerFor(menu, 30, 50, 0, 0); } //--------------------------------------------------------------------- // View Menu menu = new JMenu("View"); this.add(menu); menuItem = new JMenuItem("Clear Status Panel"); menuItem.addActionListener(al); menu.add(menuItem); menu.addSeparator(); cbMenuItem = new JCheckBoxMenuItem("Show Board"); cbMenuItem.setAccelerator(KeyStroke.getKeyStroke('B', InputEvent.SHIFT_DOWN_MASK)); cbMenuItem.setSelected(app.settingsPlayer().showBoard()); cbMenuItem.addItemListener(il); menu.add(cbMenuItem); cbMenuItem = new JCheckBoxMenuItem("Show Pieces"); cbMenuItem.setAccelerator(KeyStroke.getKeyStroke('P', InputEvent.SHIFT_DOWN_MASK)); cbMenuItem.setSelected(app.settingsPlayer().showPieces()); cbMenuItem.addItemListener(il); menu.add(cbMenuItem); cbMenuItem = new JCheckBoxMenuItem("Show Graph"); cbMenuItem.setAccelerator(KeyStroke.getKeyStroke('G', InputEvent.SHIFT_DOWN_MASK)); cbMenuItem.setSelected(app.settingsPlayer().showGraph()); cbMenuItem.addItemListener(il); menu.add(cbMenuItem); cbMenuItem = new JCheckBoxMenuItem("Show Cell Connections"); cbMenuItem.setAccelerator(KeyStroke.getKeyStroke('D', InputEvent.SHIFT_DOWN_MASK)); cbMenuItem.setSelected(app.settingsPlayer().showConnections()); cbMenuItem.addItemListener(il); menu.add(cbMenuItem); cbMenuItem = new JCheckBoxMenuItem("Show Axes"); cbMenuItem.setAccelerator(KeyStroke.getKeyStroke('A', InputEvent.SHIFT_DOWN_MASK)); cbMenuItem.setSelected(app.settingsPlayer().showAxes()); cbMenuItem.addItemListener(il); menu.add(cbMenuItem); menu.addSeparator(); cbMenuItem = new JCheckBoxMenuItem("Show Legal Moves"); cbMenuItem.setAccelerator(KeyStroke.getKeyStroke('M', ALT_DOWN_MASK)); cbMenuItem.setSelected(app.bridge().settingsVC().showPossibleMoves()); cbMenuItem.addItemListener(il); menu.add(cbMenuItem); cbMenuItem = new JCheckBoxMenuItem("Show Last Move"); cbMenuItem.setAccelerator(KeyStroke.getKeyStroke('L', ALT_DOWN_MASK)); cbMenuItem.setSelected(app.settingsPlayer().showLastMove()); cbMenuItem.addItemListener(il); menu.add(cbMenuItem); cbMenuItem = new JCheckBoxMenuItem("Show Ending Moves"); cbMenuItem.setSelected(app.settingsPlayer().showEndingMove()); cbMenuItem.addItemListener(il); menu.add(cbMenuItem); cbMenuItem = new JCheckBoxMenuItem("Show Repetitions"); cbMenuItem.setSelected(app.manager().settingsManager().showRepetitions()); cbMenuItem.addItemListener(il); menu.add(cbMenuItem); menu.addSeparator(); cbMenuItem = new JCheckBoxMenuItem("Show Indices"); cbMenuItem.setAccelerator(KeyStroke.getKeyStroke('I', CTRL_DOWN_MASK)); cbMenuItem.setSelected(app.bridge().settingsVC().showIndices()); cbMenuItem.addItemListener(il); menu.add(cbMenuItem); cbMenuItem = new JCheckBoxMenuItem("Show Coordinates"); cbMenuItem.setAccelerator(KeyStroke.getKeyStroke('C', CTRL_DOWN_MASK)); cbMenuItem.setSelected(app.bridge().settingsVC().showCoordinates()); cbMenuItem.addItemListener(il); menu.add(cbMenuItem); menu.addSeparator(); cbMenuItem = new JCheckBoxMenuItem("Show Magnifying Glass"); cbMenuItem.setSelected(app.settingsPlayer().showZoomBox()); cbMenuItem.addItemListener(il); menu.add(cbMenuItem); if (app.manager().settingsNetwork().getActiveGameId() == 0) { menu.addSeparator(); cbMenuItem = new JCheckBoxMenuItem("Show AI Distribution"); cbMenuItem.setAccelerator(KeyStroke.getKeyStroke('A', ALT_DOWN_MASK)); cbMenuItem.setSelected(app.settingsPlayer().showAIDistribution()); cbMenuItem.addItemListener(il); menu.add(cbMenuItem); } submenu = new JMenu("Pick Tracks to show"); if (app.contextSnapshot().getContext(app).board().tracks().size() > 0) { menu.addSeparator(); submenu = new JMenu("Show Tracks"); for (int trackNumber = 0; trackNumber < app.contextSnapshot().getContext(app).board().tracks().size(); trackNumber++) { final Track track = app.contextSnapshot().getContext(app).board().tracks().get(trackNumber); cbMenuItem = new JCheckBoxMenuItem("Show Track " + track.name()); boolean trackFound = false; for (int i = 0; i < app.bridge().settingsVC().trackNames().size(); i++) { if (cbMenuItem.getText().equals(app.bridge().settingsVC().trackNames().get(i))) { cbMenuItem.setSelected(app.bridge().settingsVC().trackShown().get(i).booleanValue()); trackFound = true; break; } } if (!trackFound) { app.bridge().settingsVC().trackNames().add(cbMenuItem.getText()); app.bridge().settingsVC().trackShown().add(Boolean.valueOf(false)); } // If our track number exceeds 9, we'd get weird keyboard shortcuts and maybe even duplicate ones if (trackNumber < 10) cbMenuItem.setAccelerator(KeyStroke.getKeyStroke((char)(trackNumber+'0'), InputEvent.SHIFT_DOWN_MASK)); cbMenuItem.addItemListener(il); submenu.add(cbMenuItem); } menu.add(submenu); } if (app.manager().settingsNetwork().getActiveGameId() == 0) { menu.addSeparator(); menuItem = new JMenuItem("View SVG"); menuItem.setAccelerator(KeyStroke.getKeyStroke('V', ALT_DOWN_MASK)); menuItem.addActionListener(al); menu.add(menuItem); menuItem = new JMenuItem("Load SVG"); menuItem.setAccelerator(KeyStroke.getKeyStroke('U', ALT_DOWN_MASK)); menuItem.addActionListener(al); menu.add(menuItem); } menu.addSeparator(); menuItem = new JMenuItem("Game Hashcode"); menuItem.addActionListener(al); menu.add(menuItem); //--------------------------------------------------------------------- // Help menu menu = new JMenu("Help"); this.add(menu); menuItem = new JMenuItem("About"); menuItem.setAccelerator(KeyStroke.getKeyStroke('H', CTRL_DOWN_MASK)); menuItem.addActionListener(al); menu.add(menuItem); } //------------------------------------------------------------------------- /** * Update the options menu listing with any options found for the current game. * @param context */ public static void updateOptionsMenu(final PlayerApp app, final Context context, final JMenu optionsMenu) { if (optionsMenu != null) { optionsMenu.removeAll(); final GameOptions gameOptions = context.game().description().gameOptions(); final List<String> currentOptions = gameOptions.allOptionStrings ( app.manager().settingsManager().userSelections().selectedOptionStrings() ); // List possible options for (int cat = 0; cat < gameOptions.numCategories(); cat++) { // Create a submenu for this option group final List<Option> options = gameOptions.categories().get(cat).options(); if (options.isEmpty()) continue; // no options for this group final List<String> headings = options.get(0).menuHeadings(); if (headings.size() < 2) { System.out.println("** Not enough headings for menu option group: " + headings); return; } final JMenu submenu = new JMenu(headings.get(0)); optionsMenu.add(submenu); // Group the choices for this option group together final ButtonGroup group = new ButtonGroup(); for (int i = 0; i < options.size(); i++) { final Option option = options.get(i); if (option.menuHeadings().size() < 2) { System.out.println("** Not enough headings for menu option: " + option.menuHeadings()); return; } if (!option.menuHeadings().contains("Incomplete")) // Eric wants to hide incomplete options { final JRadioButtonMenuItem rbMenuItem = new JRadioButtonMenuItem(option.menuHeadings().get(1)); rbMenuItem.setSelected(currentOptions.contains(StringRoutines.join("/", option.menuHeadings()))); rbMenuItem.addItemListener(app); group.add(rbMenuItem); submenu.add(rbMenuItem); } } MenuScroller.setScrollerFor(submenu, 20, 50, 0, 0); } // Auto-select ruleset if necessary if (app.manager().settingsManager().userSelections().ruleset() == Constants.UNDEFINED) app.manager().settingsManager().userSelections().setRuleset(context.game().description().autoSelectRuleset(currentOptions)); // List predefined rulesets final List<Ruleset> rulesets = context.game().description().rulesets(); if (rulesets != null && !rulesets.isEmpty()) { optionsMenu.addSeparator(); final ButtonGroup rulesetGroup = new ButtonGroup(); for (int rs = 0; rs < rulesets.size(); rs++) { final Ruleset ruleset = rulesets.get(rs); if (!ruleset.optionSettings().isEmpty() && !ruleset.heading().contains("Incomplete")) // Eric wants to hide unimplemented and incomplete rulesets { if (ruleset.variations().isEmpty()) { final JRadioButtonMenuItem rbMenuItem = new JRadioButtonMenuItem(ruleset.heading()); rbMenuItem.setSelected(app.manager().settingsManager().userSelections().ruleset() == rs); rbMenuItem.addItemListener(app); rulesetGroup.add(rbMenuItem); optionsMenu.add(rbMenuItem); } else { final JMenu submenuRuleset = new JMenu(ruleset.heading()); optionsMenu.add(submenuRuleset); final JRadioButtonMenuItem rbMenuDefaultItem = new JRadioButtonMenuItem("Default"); rbMenuDefaultItem.setSelected(app.manager().settingsManager().userSelections().ruleset() == rs); rbMenuDefaultItem.addItemListener(app); rulesetGroup.add(rbMenuDefaultItem); submenuRuleset.add(rbMenuDefaultItem); // Group the choices for this option group together for (final String rulesetOptionName : ruleset.variations().keySet()) { final JMenu rbMenuItem = new JMenu(rulesetOptionName); submenuRuleset.add(rbMenuItem); // Group the choices for this option group together final ButtonGroup rulesetOptionsGroup = new ButtonGroup(); for (int i = 0; i < ruleset.variations().get(rulesetOptionName).size(); i++) { final String rulesetOption = ruleset.variations().get(rulesetOptionName).get(i); final JRadioButtonMenuItem rulesetOptionMenuItem = new JRadioButtonMenuItem(rulesetOption); rulesetOptionMenuItem.setSelected(currentOptions.contains(rulesetOptionName + "/" + rulesetOption)); rulesetOptionMenuItem.addItemListener(app); rulesetOptionsGroup.add(rulesetOptionMenuItem); rbMenuItem.add(rulesetOptionMenuItem); } } MenuScroller.setScrollerFor(submenuRuleset, 20, 50, 0, 0); } } } } MenuScroller.setScrollerFor(optionsMenu, 20, 50, 0, 0); } } //------------------------------------------------------------------------- /** * Finds all demos in the Player module. * @return List of our demos */ private static String[] findDemos() { // Try loading from JAR file String[] choices = FileHandling.getResourceListing(MainMenu.class, "demos/", ".json"); if (choices == null) { try { // Try loading from memory in IDE // Start with known .json file final URL url = MainMenu.class.getResource("/demos/Hnefatafl - Common.json"); String path = new File(url.toURI()).getPath(); path = path.substring(0, path.length() - "Hnefatafl - Common.json".length()); // Get the list of .json files in this directory and subdirectories final List<String> names = new ArrayList<>(); visitFindDemos(path, names); Collections.sort(names); choices = names.toArray(new String[names.size()]); } catch (final URISyntaxException exception) { exception.printStackTrace(); } } return choices; } //------------------------------------------------------------------------- /** * Recursive helper method for finding all demos * @param path * @param names */ private static void visitFindDemos(final String path, final List<String> names) { final File root = new File( path ); final File[] list = root.listFiles(); if (list == null) return; for (final File file : list) { if (file.isDirectory()) { visitFindDemos(path + file.getName() + File.separator, names); } else { if (file.getName().contains(".json")) { // Add this demo name to the list of choices final String name = new String(file.getName()); names.add(path.substring(path.indexOf(File.separator + "demos" + File.separator)) + name); } } } } //------------------------------------------------------------------------- }
44,635
30.389592
150
java
Ludii
Ludii-master/PlayerDesktop/src/app/menu/MainMenuFunctions.java
package app.menu; import java.awt.Container; import java.awt.EventQueue; import java.awt.event.ActionEvent; import java.awt.event.ItemEvent; import java.awt.image.BufferedImage; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.URL; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.HashSet; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Map.Entry; import java.util.Timer; import java.util.TimerTask; import java.util.regex.Pattern; import javax.imageio.ImageIO; import javax.swing.ImageIcon; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.JPopupMenu; import agentPrediction.external.AgentPredictionExternal; import agentPrediction.external.MetricPredictionExternal; import agentPrediction.internal.AgentPredictionInternal; import agentPrediction.internal.models.LinearRegression; import app.DesktopApp; import app.PlayerApp; import app.display.dialogs.AboutDialog; import app.display.dialogs.DeveloperDialog; import app.display.dialogs.EvaluationDialog; import app.display.dialogs.GameLoaderDialog; import app.display.dialogs.ReconstructionDialog; import app.display.dialogs.SVGViewerDialog; import app.display.dialogs.TestLudemeDialog; import app.display.dialogs.MoveDialog.PossibleMovesDialog; import app.display.dialogs.editor.EditorDialog; import app.display.dialogs.visual_editor.StartVisualEditor; import app.display.screenCapture.ScreenCapture; import app.display.util.Thumbnails; import app.display.views.tabs.TabView; import app.loading.GameLoading; import app.loading.MiscLoading; import app.loading.TrialLoading; import app.manualGeneration.ManualGeneration; import app.utils.GameSetup; import app.utils.GameUtil; import app.utils.PuzzleSelectionType; import app.utils.QrCodeGeneration; import app.views.tools.ToolView; import approaches.random.Generator; import contextualiser.ContextualSimilarity; import features.feature_sets.BaseFeatureSet; import game.Game; import game.rules.phase.Phase; import game.rules.play.moves.BaseMoves; import game.rules.play.moves.Moves; import game.types.play.RepetitionType; import gnu.trove.list.array.TIntArrayList; import grammar.Grammar; import graphics.svg.SVGLoader; import main.Constants; import main.FileHandling; import main.StringRoutines; import main.collections.FastArrayList; import main.grammar.Call; import main.grammar.Description; import main.grammar.Report; import main.options.GameOptions; import main.options.Option; import main.options.Ruleset; import manager.ai.AIDetails; import manager.ai.AIUtil; import manager.network.local.LocalFunctions; import metadata.ai.features.Features; import metadata.ai.heuristics.Heuristics; import other.AI; import other.GameLoader; import other.action.Action; import other.action.move.remove.ActionRemove; import other.action.state.ActionSetNextPlayer; import other.concept.Concept; import other.concept.ConceptComputationType; import other.concept.ConceptDataType; import other.concept.ConceptType; import other.context.Context; import other.location.FullLocation; import other.model.Model; import other.move.Move; import other.trial.Trial; import parser.Parser; import policies.softmax.SoftmaxPolicyLinear; import search.pns.ProofNumberSearch.ProofGoals; import supplementary.EvalUtil; import supplementary.experiments.EvalAIsThread; import supplementary.experiments.EvalGamesSet; import supplementary.experiments.ludemes.CountLudemes; import util.StringUtil; //-------------------------------------------------------- /** * The app's main menu. * * @author cambolbro and Matthew.Stephenson and Eric.Piette */ public class MainMenuFunctions extends JMenuBar { private static final long serialVersionUID = 1L; /** Thread in which we're timing random playouts. */ private static Thread timeRandomPlayoutsThread = null; /** Thread in which we're comparing agents. */ private static Thread agentComparisonThread = null; /** The visual editor. */ private static StartVisualEditor startVisualEditor; //------------------------------------------------------------------------- public static void checkActionsPerformed(final DesktopApp app, final ActionEvent e) { app.bridge().settingsVC().setSelectedFromLocation(new FullLocation(Constants.UNDEFINED)); final JMenuItem source = (JMenuItem) (e.getSource()); final Context context = app.manager().ref().context(); final Game game = context.game(); if (source.getText().equals("About")) { AboutDialog.showAboutDialog(app); } else if (source.getText().equals("Count Ludemes")) { final CountLudemes ludemeCounter = new CountLudemes(); app.addTextToStatusPanel("\nChar count (including spaces): " + context.game().description().raw().length()); app.addTextToStatusPanel("\nChar count (excluding spaces): " + context.game().description().raw().replaceAll("\\s+","").length()); app.addTextToStatusPanel(ludemeCounter.result()); System.out.println(ludemeCounter.result()); } else if (source.getText().equals("Game Description Length")) { final String allOutputs = game.name() + ", Raw: " + game.description().raw().replaceAll("\\s+","").length() + ", Expanded: " + game.description().expanded().replaceAll("\\s+","").length() + ", Tokens: " + game.description().tokenForest().tokenTree().countKeywords() + ", ludemes: " + game.description().callTree().countClasses(); app.addTextToStatusPanel(allOutputs + "\n"); } else if (source.getText().equals("Game Description Length (All Games)")) { final String[] choices = FileHandling.listGames(); for (final String s : choices) { if (!FileHandling.shouldIgnoreLudRelease(s)) { final Game gameTemp = GameLoader.loadGameFromName(s.split("/")[s.split("/").length-1]); // Skip the Match game luds if (gameTemp.hasSubgames()) continue; final String allOutputs = gameTemp.name() + "," + gameTemp.description().raw().replaceAll("\\s+","").length() + "," + gameTemp.description().expanded().replaceAll("\\s+","").length() + "," + gameTemp.description().tokenForest().tokenTree().countKeywords() + "," + gameTemp.description().callTree().countClasses(); System.out.println(allOutputs); } } System.out.println("Done"); } else if (source.getText().equals("Load Game")) { if (!app.manager().settingsManager().agentsPaused()) { app.manager().settingsManager().setAgentsPaused(app.manager(), true); } GameLoading.loadGameFromMemory(app, false); } else if (source.getText().equals("Load Game from File")) { if (!app.manager().settingsManager().agentsPaused()) { app.manager().settingsManager().setAgentsPaused(app.manager(), true); } GameLoading.loadGameFromFile(app); } else if (source.getText().equals("Load Random Game")) { if (!app.manager().settingsManager().agentsPaused()) app.manager().settingsManager().setAgentsPaused(app.manager(), true); GameLoading.loadRandomGame(app); } else if (source.getText().equals("Save Trial")) { TrialLoading.saveTrial(app); } else if (source.getText().equals("Test Ludeme")) { TestLudemeDialog.showDialog(app); } else if (source.getText().equals("Create Game")) { final String savedPath = EditorDialog.saveGameDescription(app, Constants.BASIC_GAME_DESCRIPTION); GameLoading.loadGameFromFilePath(app, savedPath + ".lud"); EditorDialog.createAndShowGUI(app, true, true, true); } else if (source.getText().equals("Load Trial")) { if (!app.manager().settingsManager().agentsPaused()) { app.manager().settingsManager().setAgentsPaused(app.manager(), true); } TrialLoading.loadTrial(app, false); } else if (source.getText().equals("Load Tournament File")) { if (!app.manager().settingsManager().agentsPaused()) { app.manager().settingsManager().setAgentsPaused(app.manager(), true); } MiscLoading.loadTournamentFile(app); } else if (source.getText().equals("Editor (Packed)")) { EditorDialog.createAndShowGUI(app, false, true, true); } else if (source.getText().equals("Editor (Expanded)")) { EditorDialog.createAndShowGUI(app, true, true, true); } else if (source.getText().equals("Visual Editor (Beta)")) { // Create and lauch an instance of the visual editor setStartVisualEditor(new StartVisualEditor(app)); } // IMPORTANT These next four menu functions are just for us, not the user else if (source.getText().equals("Export Thumbnails")) { // DesktopApp.frame().setSize(462, 462); Eric Resolution DesktopApp.frame().setSize(464, 464); EventQueue.invokeLater(() -> { Thumbnails.generateThumbnails(app, false); QrCodeGeneration.makeQRCode(game, 5, 2, false); }); } else if (source.getText().equals("Export Thumbnails (ruleset)")) { DesktopApp.frame().setSize(464, 464); EventQueue.invokeLater(() -> { Thumbnails.generateThumbnails(app, true); }); } else if (source.getText().equals("Export Thumbnails (complete rulesets)")) { DesktopApp.frame().setSize(464, 464); final ArrayList<List<String>> gameOptions = new ArrayList<>(); System.out.println("Getting rulesets from game:"); final List<Ruleset> rulesets = game.description().rulesets(); if (rulesets != null && !rulesets.isEmpty()) for (int rs = 0; rs < rulesets.size(); rs++) if (!rulesets.get(rs).optionSettings().isEmpty() && !rulesets.get(rs).heading().contains("Incomplete")) gameOptions.add(rulesets.get(rs).optionSettings()); final Timer t = new Timer( ); t.scheduleAtFixedRate(new TimerTask() { int gameChoice = 0; @Override public void run() { if (gameChoice >= gameOptions.size()) { System.out.println("Thumbnails Done."); t.cancel(); t.purge(); return; } EventQueue.invokeLater(() -> { GameLoading.loadGameFromName(app, game.name(), gameOptions.get(gameChoice), false); gameChoice++; }); } }, 1000,50000); final Timer t2 = new Timer( ); t2.scheduleAtFixedRate(new TimerTask() { @Override public void run() { Thumbnails.generateThumbnails(app, true); } }, 24000,50000); } else if (source.getText().equals("Export All Thumbnails")) { DesktopApp.frame().setSize(464, 464); final String[] choices = FileHandling.listGames(); final ArrayList<String> validChoices = new ArrayList<>(); for (final String s : choices) { if (!FileHandling.shouldIgnoreLudThumbnails(s)) { validChoices.add(s); } } final Timer t = new Timer( ); t.scheduleAtFixedRate(new TimerTask() { int gameChoice = 0; @Override public void run() { if (gameChoice >= validChoices.size()) { t.cancel(); t.purge(); return; } EventQueue.invokeLater(() -> { GameLoading.loadGameFromName(app, validChoices.get(gameChoice), new ArrayList<String>(), false); gameChoice++; }); } }, 1000,50000); final Timer t2 = new Timer( ); t2.scheduleAtFixedRate(new TimerTask() { @Override public void run() { Thumbnails.generateThumbnails(app, false); } }, 24000,50000); } else if (source.getText().equals("Export All Thumbnails (rulesets)")) { DesktopApp.frame().setSize(464, 464); final String[] choices = FileHandling.listGames(); final ArrayList<String> validChoices = new ArrayList<>(); final ArrayList<List<String>> gameOptions = new ArrayList<>(); System.out.println("Getting rulesets from games:"); for (final String s : choices) { if (!FileHandling.shouldIgnoreLudThumbnails(s)) { System.out.println(s); final Game tempGame = GameLoader.loadGameFromName(s.split("\\/")[s.split("\\/").length-1]); final List<Ruleset> rulesets = tempGame.description().rulesets(); if (rulesets != null && !rulesets.isEmpty()) { for (int rs = 0; rs < rulesets.size(); rs++) { if (!rulesets.get(rs).optionSettings().isEmpty()) { validChoices.add(s); gameOptions.add(rulesets.get(rs).optionSettings()); } } } } } final Timer t = new Timer( ); t.scheduleAtFixedRate(new TimerTask() { int gameChoice = 0; @Override public void run() { if (gameChoice >= validChoices.size()) { t.cancel(); t.purge(); return; } EventQueue.invokeLater(() -> { GameLoading.loadGameFromName(app, validChoices.get(gameChoice), gameOptions.get(gameChoice), false); gameChoice++; }); } }, 1000,50000); final Timer t2 = new Timer( ); t2.scheduleAtFixedRate(new TimerTask() { @Override public void run() { Thumbnails.generateThumbnails(app, true); } }, 24000,50000); } else if (source.getText().equals("Export Board Thumbnail")) { Thumbnails.generateBoardThumbnail(app); } else if (source.getText().equals("Export All Board Thumbnails")) { //PlayerApp.frame.setSize(464, 464); final String[] choices = FileHandling.listGames(); final ArrayList<String> validChoices = new ArrayList<>(); for (final String s : choices) if (!FileHandling.shouldIgnoreLudThumbnails(s)) validChoices.add(s); final Timer t = new Timer( ); t.scheduleAtFixedRate(new TimerTask() { int gameChoice = 0; @Override public void run() { if (gameChoice >= validChoices.size()) { t.cancel(); t.purge(); return; } GameLoading.loadGameFromName(app, validChoices.get(gameChoice), new ArrayList<String>(), false); gameChoice++; } }, 1000,20000); final Timer t2 = new Timer( ); t2.scheduleAtFixedRate(new TimerTask() { @Override public void run() { Thumbnails.generateBoardThumbnail(app); } }, 11000,20000); } else if (source.getText().equals("Linear Regression (internal)")) { AgentPredictionInternal.predictAI(app.manager(), new LinearRegression()); } else if (source.getText().equals("Restart")) { app.addTextToStatusPanel("-------------------------------------------------\n"); app.addTextToStatusPanel("Game Restarted.\n"); GameUtil.resetGame(app, false); } else if (source.getText().equals("Random Move")) { app.manager().ref().randomMove(app.manager()); } else if (source.getText().equals("Random Playout")) { if (!game.isDeductionPuzzle()) app.manager().ref().randomPlayout(app.manager()); // System.out.println("Num Moves: " + app.manager().ref().context().trial().numMoves()); // System.out.println("Num Turns: " + app.manager().ref().context().trial().numTurns()); // System.out.println("Num Decisions: " + app.manager().ref().context().trial().numLogicalDecisions(game)); // System.out.println("Num Forced Passes: " + app.manager().ref().context().trial().numForcedPasses()); } else if (source.getText().equals("Time Random Playouts")) { if (!game.isDeductionPuzzle()) { app.setVolatileMessage("This will take about 40 seconds, during which time the UI will not respond.\n"); // Just use a series of EventQueues to ensure this gets run after the GUI has properly updated. EventQueue.invokeLater(() -> { EventQueue.invokeLater(() -> { EventQueue.invokeLater(() -> { EventQueue.invokeLater(() -> { app.manager().ref().interruptAI(app.manager()); DesktopApp.frame().setContentPane(DesktopApp.view()); final double rate = app.manager().ref().timeRandomPlayouts(); app.addTextToStatusPanel("" + String.format(Locale.US, "%.2f", Double.valueOf(rate)) + " random playouts/s.\n"); app.setTemporaryMessage(""); app.setTemporaryMessage("Analysis Complete.\n"); }); }); }); }); } else { app.setVolatileMessage("Time Random Playouts is disabled for deduction puzzles.\n"); } } else if (source.getText().equals("Time Random Playouts in Background")) { if (timeRandomPlayoutsThread != null) { app.addTextToStatusPanel("Time Random Playouts is already in progress!\n"); return; } if (!game.isDeductionPuzzle()) { timeRandomPlayoutsThread = new Thread(() -> { final double rate = app.manager().ref().timeRandomPlayouts(); EventQueue.invokeLater(() -> { app.addTextToStatusPanel("" + String.format(Locale.US, "%.2f", Double.valueOf(rate)) + " random playouts/s.\n"); app.setTemporaryMessage(""); app.setTemporaryMessage("Analysis Complete.\n"); timeRandomPlayoutsThread = null; }); }); app.setTemporaryMessage("Time Random Playouts is starting. This will take about 40 seconds.\n"); timeRandomPlayoutsThread.setDaemon(true); timeRandomPlayoutsThread.start(); } else { app.setVolatileMessage("Time Random Playouts is disabled for deduction puzzles.\n"); } } else if (source.getText().equals("Show Compilation Concepts")) { final List<List<String>> conceptsPerCategories = new ArrayList<List<String>>(); for (int i = 0; i < ConceptType.values().length; i++) conceptsPerCategories.add(new ArrayList<String>()); for (int i = 0; i < Concept.values().length; i++) { final Concept concept = Concept.values()[i]; final ConceptType type = concept.type(); if (game.booleanConcepts().get(concept.id())) conceptsPerCategories.get(type.ordinal()).add(concept.name()); } final StringBuffer properties = new StringBuffer("The boolean concepts of the game are: \n\n"); for (int i = 0; i < conceptsPerCategories.size(); i++) { if(!conceptsPerCategories.get(i).isEmpty()) { final ConceptType type = ConceptType.values()[i]; properties.append("******* " + type.name() + " concepts *******\n"); for(int j = 0; j < conceptsPerCategories.get(i).size();j++) { final String concept = conceptsPerCategories.get(i).get(j); properties.append(concept + "\n"); } properties.append("\n"); } } properties.append("\nThe non boolean concepts of the game are: \n\n"); for (int i = 0; i < Concept.values().length; i++) { final Concept concept = Concept.values()[i]; final String name = concept.name(); final Integer idConcept = Integer.valueOf(concept.id()); if (!concept.dataType().equals(ConceptDataType.BooleanData) && concept.computationType().equals(ConceptComputationType.Compilation)) properties.append(name + ": " + game.nonBooleanConcepts().get(idConcept) + "\n"); } app.manager().getPlayerInterface().addTextToAnalysisPanel(properties.toString()); app.selectAnalysisTab(); } else if (source.getText().equals("Duplicates Moves Test")) { final StringBuffer results = new StringBuffer(); final int numPlayouts = 100; boolean duplicateMove = false; for (int i = 0; i < numPlayouts; i++) { final List<AI> ais = new ArrayList<AI>(); ais.add(null); for (int p = 1; p <= game.players().count(); ++p) ais.add(new utils.RandomAI()); final Context tempContext = new Context(game, new Trial(game)); final Trial trial = tempContext.trial(); game.start(tempContext); for (int p = 1; p <= game.players().count(); ++p) ais.get(p).initAI(game, p); final Model model = tempContext.model(); while (!trial.over()) { final int mover = tempContext.state().mover(); final Phase currPhase = game.rules().phases()[tempContext.state().currentPhase(mover)]; final Moves legal = currPhase.play().moves().eval(tempContext); for (int j = 0; j < legal.moves().size(); j++) { final Move m1 = legal.moves().get(j); for (int k = j + 1; k < legal.moves().size(); k++) { final Move m2 = legal.moves().get(k); if (Model.movesEqual(m1, m2, context)) { duplicateMove = true; results.append("Move num " + trial.moveNumber() + " with Move = " + m1 + "\n"); break; } } if (duplicateMove) break; } if (duplicateMove) break; model.startNewStep(tempContext, ais, 1.0); } } if (!duplicateMove) results.append("No duplicate moves detected.\n"); else results.append("DUPLICATE MOVES DETECTED!\n"); app.addTextToAnalysisPanel(results.toString()); } else if (source.getText().equals("Resign Game")) { if (app.manager().settingsNetwork().getNetworkPlayerNumber() > Constants.MAX_PLAYERS) { app.addTextToStatusPanel("You are just a spectator, leave the game alone!\n"); } else if (!app.manager().settingsNetwork().activePlayers()[app.manager().settingsNetwork().getNetworkPlayerNumber()]) { app.addTextToStatusPanel("The game is already over for you."); } else if (app.manager().settingsNetwork().getActiveGameId() != 0) { final URL resource = app.getClass().getResource("/ludii-logo-64x64.png"); BufferedImage image = null; try { image = ImageIO.read(resource); } catch (final IOException e1) { //couldn't read logo } final int dialogResult = JOptionPane.showConfirmDialog (DesktopApp.frame(), "Do you really want to resign this game?\nIf the game has already started then this will be considered a loss.", "Last Chance!", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, new ImageIcon(image)); if(dialogResult == JOptionPane.YES_OPTION) { app.manager().databaseFunctionsPublic().sendForfeitToDatabase(app.manager()); } } } else if (source.getText().equals("Leave Game")) { app.remoteDialogFunctionsPublic().leaveGameUpdateGui(app.manager()); } else if (source.getText().equals("Propose/Accept a Draw")) { if (app.manager().settingsNetwork().getNetworkPlayerNumber() > Constants.MAX_PLAYERS) app.addTextToStatusPanel("You are just a spectator, leave the game alone!\n"); else if (!app.manager().settingsNetwork().activePlayers()[app.manager().settingsNetwork().getNetworkPlayerNumber()]) app.addTextToStatusPanel("The game is already over for you."); else if (app.manager().settingsNetwork().getActiveGameId() != 0) app.manager().databaseFunctionsPublic().sendProposeDraw(app.manager()); } else if (source.getText().equals("List Legal Moves")) { final Moves legal = game.moves(context); app.addTextToStatusPanel("Legal Moves: " + "\n"); for (int i = 0; i < legal.moves().size(); i++) app.addTextToStatusPanel(i + " - " + legal.moves().get(i).getActionsWithConsequences(context) + "\n"); } else if (source.getText().equals("Game Screenshot")) { ScreenCapture.gameScreenshot("Image " + new Date().getTime()); } else if (source.getText().equals("Game Gif")) { final String numFramesString = JOptionPane.showInputDialog("How many frames? (1 frame ≈ 100ms)"); int numFrames = 10; try { numFrames = Integer.parseInt(numFramesString); } catch (final Exception e2) { app.addTextToStatusPanel("Invalid entry, defaulting to 10 frames."); } final int finalNumFrames = numFrames; // Delay the gif animation a little bit to allow all dialogs to close. new java.util.Timer().schedule ( new java.util.TimerTask() { @Override public void run() { ScreenCapture.gameGif("Image " + new Date().getTime(), finalNumFrames); } }, 500 ); } else if (source.getText().equals("Make QR Code")) { QrCodeGeneration.makeQRCode(game); } else if (source.getText().equals("Play/Pause")) { DesktopApp.view().toolPanel().buttons.get(ToolView.PLAY_BUTTON_INDEX).press(); } else if (source.getText().equals("Previous Move")) { DesktopApp.view().toolPanel().buttons.get(ToolView.BACK_BUTTON_INDEX).press(); } else if (source.getText().equals("Next Move")) { DesktopApp.view().toolPanel().buttons.get(ToolView.FORWARD_BUTTON_INDEX).press(); } else if (source.getText().equals("Go To Start")) { DesktopApp.view().toolPanel().buttons.get(ToolView.START_BUTTON_INDEX).press(); } else if (source.getText().equals("Go To End")) { DesktopApp.view().toolPanel().buttons.get(ToolView.END_BUTTON_INDEX).press(); } else if (source.getText().equals("Pass")) { DesktopApp.view().toolPanel().buttons.get(ToolView.PASS_BUTTON_INDEX).press(); } else if (source.getText().equals("Random Playout Instance")) { app.manager().ref().randomPlayoutSingleInstance(app.manager()); } else if (source.getText().equals("Clear Board")) { final Moves csq = new BaseMoves(null); final Move nextMove = new Move(new ActionSetNextPlayer(context.state().mover())); csq.moves().add(nextMove); for (int i = 0; i < context.board().numSites(); i++) { for (int j = 0; j < Constants.MAX_STACK_HEIGHT; j++) { final Action actionRemove = ActionRemove.construct(context.board().defaultSite(), i, j, true); final Move moveToApply = new Move(actionRemove); moveToApply.then().add(csq); for (final Action a : moveToApply.actions()) a.apply(context, false); final int currentMover = context.state().mover(); final int nextMover = context.state().next(); final int previousMover = context.state().prev(); context.state().setMover(currentMover); context.state().setNext(nextMover); context.state().setPrev(previousMover); } } app.updateTabs(context); } else if (source.getText().equals("Next Player")) { final ActionSetNextPlayer actionSetNextPlayer = new ActionSetNextPlayer(context.state().next()); final Move moveToApply = new Move(actionSetNextPlayer); for (final Action a : moveToApply.actions()) a.apply(context, false); final int currentMover = context.state().mover(); final int nextMover = context.state().next(); final int previousMover = context.state().prev(); context.state().setMover(currentMover); context.state().setNext(nextMover); context.state().setPrev(previousMover); app.updateTabs(context); } else if (source.getText().equals("Cycle Players")) { AIUtil.cycleAgents(app.manager()); } else if (source.getText().equals("Generate Grammar")) { app.addTextToStatusPanel(Grammar.grammar().toString()); System.out.print(Grammar.grammar()); System.out.println("Aliases in grammar:\n" + Grammar.grammar().aliases()); try { Grammar.grammar().export("ludii-grammar-" + Constants.LUDEME_VERSION + ".txt"); } catch (final IOException e1) { e1.printStackTrace(); } } else if (source.getText().equals("Generate Symbols")) { app.addTextToStatusPanel(Grammar.grammar().getFormattedSymbols()); System.out.print(Grammar.grammar().getFormattedSymbols()); System.out.print(Grammar.grammar().symbolDetails()); } else if (source.getText().equals("Rules in English")) { final String rules = game.toEnglish(game); app.addTextToStatusPanel(rules); System.out.print(rules); } else if (source.getText().equals("Game Manual Generation (Beta)")) { ManualGeneration.manualGeneration(app); } else if (source.getText().equals("Estimate Branching Factor")) { EvalUtil.estimateBranchingFactor(app); } else if (source.getText().equals("Estimate Game Length")) { EvalUtil.estimateGameLength(app); } else if (source.getText().equals("Estimate Game Tree Complexity")) { EvalUtil.estimateGameTreeComplexity(app, false); } else if (source.getText().equals("Estimate Game Tree Complexity (No State Repetition)")) { EvalUtil.estimateGameTreeComplexity(app, true); } else if (source.getText().equals("Compare Agents")) { final List<AI> aiList = new ArrayList<>(); for (int i = 1; i <= game.players().count(); i++) { final AI agent = app.manager().aiSelected()[i].ai(); if (agent == null) app.addTextToStatusPanel("Player " + i + " should be set to an AI player."); else aiList.add(agent); } if (aiList.size() == game.players().count()) { final String playoutNumberString = JOptionPane.showInputDialog("How many playouts?"); try { final int playoutNumber = Integer.parseInt(playoutNumberString); agentComparisonThread = new Thread(() -> { final EvalGamesSet gamesSet = new EvalGamesSet() .setGameName(game.name() + ".lud") .setAgents(aiList) .setMaxSeconds(AIDetails.convertToThinkTimeArray(app.manager().aiSelected())) .setWarmingUpSecs(0) .setNumGames(playoutNumber) .setRoundToNextPermutationsDivisor(false) .setRotateAgents(true); gamesSet.startGames(game); app.addTextToAnalysisPanel(gamesSet.resultsSummary().generateIntermediateSummary()); app.selectAnalysisTab(); app.setTemporaryMessage(""); app.setTemporaryMessage("Comparisons have finished.\n"); }); app.setTemporaryMessage(""); app.setTemporaryMessage("Comparisons have started.\n"); agentComparisonThread.setDaemon(true); agentComparisonThread.start(); } catch (final NumberFormatException numberException) { app.addTextToStatusPanel("Invalid number of playouts"); } } } else if (source.getText().equals("Prove Win")) { EvalUtil.proveState(app, ProofGoals.PROVE_WIN); } else if (source.getText().equals("Prove Loss")) { EvalUtil.proveState(app, ProofGoals.PROVE_LOSS); } else if (source.getText().equals("Evaluate AI vs. AI")) { if (!app.manager().settingsManager().agentsPaused()) { DesktopApp.view().tabPanel().page(TabView.PanelAnalysis).addText("Cannot start evaluation of AIs when agents are not paused!"); return; } final EvalAIsThread evalThread = EvalAIsThread.construct(app.manager().ref(), AIDetails.convertToAIList(app.manager().aiSelected()), app.manager()); app.manager().settingsManager().setAgentsPaused(app.manager(), false); evalThread.start(); } else if (source.getText().startsWith("Evaluation Dialog")) { EvaluationDialog.showDialog(app); } else if (source.getText().equals("Clear Status Panel")) { DesktopApp.view().tabPanel().page(TabView.PanelStatus).clear(); } else if (source.getText().startsWith("Compile Game (Debug)")) { if (!app.manager().settingsManager().agentsPaused()) { app.manager().settingsManager().setAgentsPaused(app.manager(), true); } GameLoading.loadGameFromMemory(app, true); } else if (source.getText().startsWith("Recompile Current Game")) { GameSetup.compileAndShowGame(app, context.game().description().raw(), false); } else if (source.getText().startsWith("Show Call Tree")) { final Call callTree = game.description().callTree(); System.out.println(callTree); callTree.export("call-tree-" + game.name() + ".txt"); } else if (source.getText().startsWith("Expanded Description")) { // Get the user to choose a .lud final String[] choices = FileHandling.listGames(); String initialChoice = choices[0]; for (final String choice : choices) { if (app.manager().savedLudName() != null && app.manager().savedLudName().endsWith(choice.replaceAll(Pattern.quote("\\"), "/"))) { initialChoice = choice; break; } } final String choice = GameLoaderDialog.showDialog(DesktopApp.frame(), choices, initialChoice); if (choice == null) return; // Get game description from resource String path = choice.replaceAll(Pattern.quote("\\"), "/"); path = path.substring(path.indexOf("/lud/")); final InputStream in = GameLoader.class.getResourceAsStream(path); String desc = ""; try (final BufferedReader rdr = new BufferedReader(new InputStreamReader(in, "UTF-8"))) { String line; while ((line = rdr.readLine()) != null) desc += line + "\n"; } catch (final IOException e2) { e2.printStackTrace(); } final Description gameDescription = new Description(desc); final boolean didParse = Parser.expandAndParse ( gameDescription, app.manager().settingsManager().userSelections(), new Report(), false //true ); final String report = "Expanded game description:\n" + gameDescription.expanded() + "\nGame description " + (didParse ? "parsed." : "did not parse. "); System.out.println(report); app.addTextToStatusPanel(report); } else if (source.getText().startsWith("Metadata Description")) { // Get the user to choose a .lud final String[] choices = FileHandling.listGames(); String initialChoice = choices[0]; for (final String choice : choices) if (app.manager().savedLudName() != null && app.manager().savedLudName().endsWith(choice.replaceAll(Pattern.quote("\\"), "/"))) { initialChoice = choice; break; } final String choice = GameLoaderDialog.showDialog(DesktopApp.frame(), choices, initialChoice); if (choice == null) return; // Get game description from resource String path = choice.replaceAll(Pattern.quote("\\"), "/"); path = path.substring(path.indexOf("/lud/")); final InputStream in = GameLoader.class.getResourceAsStream(path); String desc = ""; try (final BufferedReader rdr = new BufferedReader(new InputStreamReader(in, "UTF-8"))) { String line; while ((line = rdr.readLine()) != null) desc += line + "\n"; } catch (final IOException e2) { e2.printStackTrace(); } final Description gameDescription = new Description(desc); Parser.expandAndParse ( gameDescription, app.manager().settingsManager().userSelections(), new Report(), false ); final String report = "Metadata:\n" + gameDescription.metadata(); System.out.println(report); app.addTextToStatusPanel(report); } else if (source.getText().startsWith("Jump to Move")) { try { final int moveToJumpTo = Integer.parseInt(JOptionPane.showInputDialog(DesktopApp.frame(), "Which move to jump to?")); if (app.manager().settingsNetwork().getActiveGameId() == 0) ToolView.jumpToMove(app, moveToJumpTo + app.contextSnapshot().getContext(app).trial().numInitialPlacementMoves()); } catch (final NumberFormatException exception) { // Probably just closed the dialog. } } else if (source.getText().startsWith("Serialise Game Object")) { System.out.println("Game object not serialisable yet."); app.addTextToStatusPanel("Game object not serialisable yet."); // // Choose a default file path // String tempFilePath = DesktopApp.lastSelectedJsonPath(); // if (tempFilePath == null) // tempFilePath = System.getProperty("user.dir"); // final String defaultFilePath = tempFilePath; // // // Get the destination folder // final JFileChooser fileChooser = FileLoading.createFileChooser(defaultFilePath, ".*", "All files"); //".txt", "TXT files (.txt)"); // fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); // fileChooser.setDialogTitle("Select output directory."); // // final int choice = fileChooser.showOpenDialog(DesktopApp.frame()); // final File directory = (choice == JFileChooser.APPROVE_OPTION) ? fileChooser.getSelectedFile() : null; // // if (directory != null && directory.exists()) // { // System.out.println("Storing to folder: " + directory); // // final String outFileName = "game.ser"; // try // ( // final FileOutputStream file = new FileOutputStream(outFileName); // final ObjectOutputStream out = new ObjectOutputStream(file) // ) // { // out.writeObject(game); // } // catch(final Exception e1) // { // e1.printStackTrace(); // } // System.out.println("Game has been serialised."); // } // else // { // System.out.println("Something went wrong."); // } } else if (source.getText().startsWith("Print Working Directory")) { final File file = new File("."); try { app.addTextToStatusPanel("Current working directory: " + file.getCanonicalPath()); } catch (final IOException e1) { e1.printStackTrace(); } } else if (source.getText().startsWith("Evaluate Heuristic")) { final String heuristicStr = JOptionPane.showInputDialog(DesktopApp.frame(), "Enter heuristic."); if (app.manager().settingsNetwork().getActiveGameId() == 0) { final Heuristics heuristics = (Heuristics)compiler.Compiler.compileObject ( "(heuristics " + heuristicStr + ")", "metadata.ai.heuristics.Heuristics", new Report() ); heuristics.init(game); for (int p = 1; p <= game.players().count(); ++p) { app.addTextToAnalysisPanel("Heuristic score for Player " + p + " = " + heuristics.computeValue(context, p, 0.f) + "\n"); } } } else if (source.getText().startsWith("Evaluate Features")) { final String featuresStr = JOptionPane.showInputDialog(DesktopApp.frame(), "Enter features."); if (app.manager().settingsNetwork().getActiveGameId() == 0) { final Features features = (Features)compiler.Compiler.compileObject ( featuresStr, "metadata.ai.features.Features", new Report() ); final SoftmaxPolicyLinear softmax = SoftmaxPolicyLinear.constructSelectionPolicy(features, 0.0); softmax.initAI(game, context.state().mover()); final BaseFeatureSet[] featureSets = softmax.featureSets(); final BaseFeatureSet featureSet; if (featureSets.length == 1) featureSet = featureSets[0]; else featureSet = featureSets[context.state().mover()]; final FastArrayList<Move> legalMoves = game.moves(context).moves(); final TIntArrayList[] sparseFeatureVectors = featureSet.computeSparseSpatialFeatureVectors ( context, legalMoves, false ); @SuppressWarnings("unchecked") final List<String>[] moveStrings = new List[featureSet.getNumSpatialFeatures()]; for (int moveIdx = 0; moveIdx < legalMoves.size(); ++moveIdx) { final TIntArrayList activeFeatures = sparseFeatureVectors[moveIdx]; for (int i = 0; i < activeFeatures.size(); ++i) { final int featureIdx = activeFeatures.getQuick(i); if (moveStrings[featureIdx] == null) moveStrings[featureIdx] = new ArrayList<String>(); moveStrings[featureIdx].add(legalMoves.get(moveIdx).toString()); } } System.out.println("------------------------------------------------"); System.out.println("Printing moves for which features are active..."); for (int featureIdx = 0; featureIdx < moveStrings.length; ++featureIdx) { final List<String> moves = moveStrings[featureIdx]; if (moves != null && moves.size() > 0) { System.out.println("Feature: " + featureSet.spatialFeatures()[featureIdx].toString()); for (final String moveStr : moves) { System.out.println("active for move: " + moveStr); } } } System.out.println("------------------------------------------------"); app.addTextToAnalysisPanel("Active features are only printed in the console.\n"); } } else if (source.getText().startsWith("Game Hashcode")) { System.out.println("File encoding: " + System.getProperty("file.encoding")); app.addTextToStatusPanel("Game Hashcode: " + StringUtil.hashCode(game.description().raw()) + "\n"); } else if (source.getText().startsWith("Print Board Graph")) { System.out.println(context.board().graph()); } // else if (source.getText().startsWith("Advanced Distance Dialog")) // { // AdvancedDistanceDialog.showDialog(); // } else if (source.getText().startsWith("Print Trajectories")) { context.board().graph().trajectories().report(context.board().graph()); } else if (source.getText().startsWith("Preferences")) { app.showSettingsDialog(); } else if (source.getText().equals("Load SVG")) { MiscLoading.loadSVG(app, DesktopApp.view()); } else if (source.getText().equals("View SVG")) { SVGViewerDialog.showDialog(app, DesktopApp.frame(), SVGLoader.listSVGs()); } else if (source.getText().equals("Remote Play")) { app.manager().settingsNetwork().setRemoteDialogPosition(null); app.remoteDialogFunctionsPublic().showRemoteDialog(app); } else if (source.getText().equals("Initialise Server Socket")) { final String port = JOptionPane.showInputDialog("Port Number (4 digits)"); int portNumber = 0; try { if (port.length() != 4) throw new Exception("Port number must be four digits long."); portNumber = Integer.parseInt(port); } catch (final Exception E) { app.addTextToStatusPanel("Please enter a valid four digit port number.\n"); return; } LocalFunctions.initialiseServerSocket(app.manager(), portNumber); } else if (source.getText().equals("Test Message Socket")) { final String port = JOptionPane.showInputDialog("Port Number (4 digits)"); int portNumber = 0; try { if (port.length() != 4) throw new Exception("Port number must be four digits long."); portNumber = Integer.parseInt(port); } catch (final Exception E) { app.addTextToStatusPanel("Please enter a valid four digit port number.\n"); return; } final String message = JOptionPane.showInputDialog("Message"); LocalFunctions.initialiseClientSocket(portNumber, message); } else if (source.getText().equals("Select Move from String")) { final FastArrayList<Move> substringMatchingMoves = new FastArrayList<>(); boolean exactMatchFound = false; final String moveString = JOptionPane.showInputDialog("Enter desired move in Trial, Turn or Move format."); for (final Move m : context.game().moves(context).moves()) { // Check for exact match first if ( m.toTrialFormat(context).equals(moveString) || m.toTurnFormat(context, true).equals(moveString) || m.toTurnFormat(context, false).equals(moveString) || m.toMoveFormat(context, true).equals(moveString) || m.toMoveFormat(context, false).equals(moveString) || m.toString().equals(moveString) ) { exactMatchFound = true; app.manager().ref().applyHumanMoveToGame(app.manager(), m); break; } else { // Check for substring match if (m.toTrialFormat(context).contains(moveString)) substringMatchingMoves.add(m); else if (m.toTurnFormat(context, true).contains(moveString)) substringMatchingMoves.add(m); else if (m.toTurnFormat(context, false).contains(moveString)) substringMatchingMoves.add(m); else if (m.toMoveFormat(context, true).contains(moveString)) substringMatchingMoves.add(m); else if (m.toMoveFormat(context, false).contains(moveString)) substringMatchingMoves.add(m); else if (m.toString().contains(moveString)) substringMatchingMoves.add(m); } } if (!exactMatchFound) { if (substringMatchingMoves.size() == 1) app.manager().ref().applyHumanMoveToGame(app.manager(), substringMatchingMoves.get(0)); else if (substringMatchingMoves.size() > 1) PossibleMovesDialog.createAndShowGUI(app, context, substringMatchingMoves, true); else System.out.println("No matching move found."); } } else if (source.getText().equals("Quit")) { System.exit(0); } else if (source.getText().equals("More Developer Options")) { DeveloperDialog.showDialog(app); } else if (source.getText().equals("Generate Random Game")) { boolean validGameFound = false; while (!validGameFound) { final String gameDescription = Generator.testGames(1, true, true, false, true); if (gameDescription != null) { GameSetup.compileAndShowGame(app, gameDescription, false); validGameFound = true; } } } else if (source.getText().equals("Generate 1000 Random Games")) { Generator.testGames ( 1000, // num games true, // random true, // valid false, // boardless true // save ); } else if (source.getText().equals("Generate 1 Game with Restrictions (dev)")) { Generator.testGamesEric(1, true, false); } else if (source.getText().equals("Contextual Distance")) { final Map<String, Double> rulesetSimilaritiesCultural = ContextualSimilarity.getRulesetSimilarities(game, false); final Map<String, Double> rulesetSimilaritiesConcept = ContextualSimilarity.getRulesetSimilarities(game, true); final Map<String, Double> rulesetSimilaritiesGeographical = ContextualSimilarity.getRulesetGeographicSimilarities(game); final Map<String, Double> rulesetSimilaritiesYears = ContextualSimilarity.getRulesetYearSimilarities(game); final int NUM_TO_PRINT = 10; System.out.println("------------------"); System.out.println("Closest cultural rulesets:"); if (new HashSet<Double>(rulesetSimilaritiesCultural.values()).size() > 1) { for(int i = 0; i < NUM_TO_PRINT; i++) { final double maxValueInMapCultural = (Collections.max(rulesetSimilaritiesCultural.values()).doubleValue()); if (maxValueInMapCultural > 0) for (final Entry<String, Double> entry : rulesetSimilaritiesCultural.entrySet()) if (entry.getValue().doubleValue() == maxValueInMapCultural) System.out.println(entry.getKey() + " (" + maxValueInMapCultural + ")"); // Print the rulesets with max cultural similarity rulesetSimilaritiesCultural.values().removeIf(value -> (value.doubleValue() == maxValueInMapCultural)); } } System.out.println(); System.out.println("Closest concept rulesets:"); if (new HashSet<Double>(rulesetSimilaritiesConcept.values()).size() > 1) { for(int i = 0; i < NUM_TO_PRINT; i++) { final double maxValueInMapConcept = (Collections.max(rulesetSimilaritiesConcept.values()).doubleValue()); if (maxValueInMapConcept > 0) for (final Entry<String, Double> entry : rulesetSimilaritiesConcept.entrySet()) if (entry.getValue().doubleValue() == maxValueInMapConcept) System.out.println(entry.getKey() + " (" + maxValueInMapConcept + ")"); // Print the rulesets with max concept similarity rulesetSimilaritiesConcept.values().removeIf(value -> (value.doubleValue() == maxValueInMapConcept)); } } System.out.println(); System.out.println("Closest geographical rulesets:"); if (new HashSet<Double>(rulesetSimilaritiesGeographical.values()).size() > 1) { for(int i = 0; i < NUM_TO_PRINT; i++) { final double maxValueInMapConcept = (Collections.max(rulesetSimilaritiesGeographical.values()).doubleValue()); if (maxValueInMapConcept > 0) for (final Entry<String, Double> entry : rulesetSimilaritiesGeographical.entrySet()) if (entry.getValue().doubleValue() == maxValueInMapConcept) System.out.println(entry.getKey() + " (" + maxValueInMapConcept + ")"); // Print the rulesets with max geographic similarity rulesetSimilaritiesGeographical.values().removeIf(value -> (value.doubleValue() == maxValueInMapConcept)); } } System.out.println(); System.out.println("Closest year rulesets:"); if (new HashSet<Double>(rulesetSimilaritiesYears.values()).size() > 1) { for(int i = 0; i < NUM_TO_PRINT; i++) { final double maxValueInMapConcept = (Collections.max(rulesetSimilaritiesYears.values()).doubleValue()); if (maxValueInMapConcept > 0) for (final Entry<String, Double> entry : rulesetSimilaritiesYears.entrySet()) if (entry.getValue().doubleValue() == maxValueInMapConcept) System.out.println(entry.getKey() + " (" + maxValueInMapConcept + ")"); // Print the rulesets with max year similarity rulesetSimilaritiesYears.values().removeIf(value -> (value.doubleValue() == maxValueInMapConcept)); } } } else if (source.getText().equals("Reconstruction Dialog")) { ReconstructionDialog.createAndShowGUI(app); } else if (((JMenu)((JPopupMenu) source.getParent()).getInvoker()).getText().equals("Load Recent")) { // Check if a recent game has been selected try { if (source.getText().contains(".lud")) // load game from external file GameLoading.loadGameFromFilePath(app, source.getText()); else GameLoading.loadGameFromName(app, source.getText() + ".lud", new ArrayList<String>(), false); } catch (final Exception E) { System.out.println("This game no longer exists"); } } else if (source.getText().equals("Portfolio Parameters (external)")) { final Map<String, Map<String, Double>> portfolioParameterPredictions = AgentPredictionExternal.predictPortfolioParameters(game); System.out.println("\n" + portfolioParameterPredictions + "\n"); for (final String parameterName : portfolioParameterPredictions.keySet()) { double highestPredictionProb = -1.0; String bestPredictionLabel = ""; for (final String paramValue : portfolioParameterPredictions.get(parameterName).keySet()) { if (portfolioParameterPredictions.get(parameterName).get(paramValue).doubleValue() > highestPredictionProb) { highestPredictionProb = portfolioParameterPredictions.get(parameterName).get(paramValue).doubleValue(); bestPredictionLabel = paramValue; } } System.out.println(parameterName + ": " + bestPredictionLabel + " (" + highestPredictionProb + ")"); } } else if (getParentTitle(source, 2).equals("Predict Metrics (external)")) { final boolean useCompilationOnly = getParentTitle(source, 1).equals("Compilation"); final String modelFilePath = source.getText() + "-Regression" + "-Metrics" + "-" + (useCompilationOnly ? "True" : "False"); final Map<String, Double> metricPredictions = MetricPredictionExternal.predictMetrics(game, modelFilePath, useCompilationOnly); displayPredictionResults(app, metricPredictions, false, false); } else if (getParentTitle(source, 3).equals("Predict Best Agent (external)")) { // Agent prediction final boolean useHeuristics = false; final boolean useClassifier = getParentTitle(source, 2).equals("Classification"); final boolean useCompilationOnly = getParentTitle(source, 1).equals("Compilation"); // Determine the file path for the model final String modelFilePath = AgentPredictionExternal.getModelPath(source.getText(), useClassifier, useHeuristics, useCompilationOnly); System.out.println("Predicting...\n"); final Map<String, Double> agentPredictions = AgentPredictionExternal.predictBestAgent(game, modelFilePath, useClassifier, useHeuristics, useCompilationOnly); displayPredictionResults(app, agentPredictions, useClassifier, true); } else if (getParentTitle(source, 3).equals("Predict Best Heuristic (external)")) { // Heuristic prediction final boolean useHeuristics = true; final boolean useClassifier = getParentTitle(source, 2).equals("Classification"); final boolean useCompilationOnly = getParentTitle(source, 1).equals("Compilation"); // Determine the file path for the model final String modelFilePath = AgentPredictionExternal.getModelPath(source.getText(), useClassifier, useHeuristics, useCompilationOnly); System.out.println("Predicting...\n"); final Map<String, Double> heuristicPredictions = AgentPredictionExternal.predictBestAgent(game, modelFilePath, useClassifier, useHeuristics, useCompilationOnly); displayPredictionResults(app, heuristicPredictions, useClassifier, true); } EventQueue.invokeLater(() -> { app.resetMenuGUI(); app.repaint(); }); } private static void displayPredictionResults(final PlayerApp app, final Map<String, Double> agentPredictions, final boolean useClassifier, final boolean printHighestValue) { app.manager().getPlayerInterface().selectAnalysisTab(); String bestPredictedAgentName = "None"; double bestPredictedValue = -99999; for (final String agentName : agentPredictions.keySet()) { final double score = agentPredictions.get(agentName).doubleValue(); if (useClassifier) app.manager().getPlayerInterface().addTextToAnalysisPanel("Predicted probability for " + agentName + ": " + score + "\n"); else app.manager().getPlayerInterface().addTextToAnalysisPanel("Predicted value for " + agentName + ": " + score + "\n"); if (score > bestPredictedValue) { bestPredictedValue = score; bestPredictedAgentName = agentName; } } if (printHighestValue) app.manager().getPlayerInterface().addTextToAnalysisPanel("Best Predicted Agent/Heuristic is " + bestPredictedAgentName + "\n"); app.manager().getPlayerInterface().addTextToAnalysisPanel("//-------------------------------------------------------------------------\n"); System.out.println("Prediction complete.\n"); } //------------------------------------------------------------------------- public static void checkItemStateChanges(final PlayerApp app, final ItemEvent e) { final JMenuItem source = (JMenuItem) (e.getSource()); final Context context = app.contextSnapshot().getContext(app); JMenuItem rootParent = (JMenu)((JPopupMenu)source.getParent()).getInvoker(); while (rootParent.getParent() instanceof JPopupMenu) rootParent = (JMenu)((JPopupMenu)rootParent.getParent()).getInvoker(); if (rootParent.getText().equals("Options")) { // Check if an in-game option or ruleset has been selected if (e.getStateChange() == ItemEvent.SELECTED) { final Game game = context.game(); final GameOptions gameOptions = game.description().gameOptions(); // First, check if a predefined ruleset has been selected. Also check parent in case default ruleset variation selected. final JMenu sourceParent = (JMenu)((JPopupMenu)source.getParent()).getInvoker(); final boolean rulesetSelected = GameUtil.checkMatchingRulesets(app, game, source.getText()) || GameUtil.checkMatchingRulesets(app, game, sourceParent.getText()); // Second, check if an option has been selected if (!rulesetSelected && gameOptions.numCategories() > 0 && source.getParent() != null) { final JMenu parent = (JMenu)((JPopupMenu)source.getParent()).getInvoker(); final List<String> currentOptions = app.manager().settingsManager().userSelections().selectedOptionStrings(); for (int cat = 0; cat < gameOptions.numCategories(); cat++) { final List<Option> options = gameOptions.categories().get(cat).options(); if (options.isEmpty()) continue; // no options in this group if (!options.get(0).menuHeadings().get(0).equals(parent.getText())) continue; // not this option group for (final Option option : options) { if (option.menuHeadings().get(1).equals(source.getText())) { // Match! final String selectedOptString = StringRoutines.join("/", option.menuHeadings()); // Remove any other selected options in the same category for (int i = 0; i < currentOptions.size(); ++i) { final String currOption = currentOptions.get(i); if ( currOption.substring(0, currOption.lastIndexOf("/")).equals( selectedOptString.substring(0, selectedOptString.lastIndexOf("/")) ) ) { // Found one in same category, so remove it currentOptions.remove(i); break; // Should be no more than just this one } } // Now add the option we newly selected currentOptions.add(selectedOptString); app.manager().settingsManager().userSelections().setSelectOptionStrings(currentOptions); gameOptions.setOptionsLoaded(true); // Since we selected an option, we should try to auto-select ruleset app.manager().settingsManager().userSelections().setRuleset ( game.description().autoSelectRuleset ( app.manager().settingsManager().userSelections().selectedOptionStrings() ) ); try { GameSetup.compileAndShowGame(app, game.description().raw(), false); } catch (final Exception exception) { GameUtil.resetGame(app, false); } break; } } } } } } else if (source.getText().equals("Show Legal Moves")) { app.bridge().settingsVC().setShowPossibleMoves(!app.bridge().settingsVC().showPossibleMoves()); } else if (source.getText().equals("Show Board")) { app.settingsPlayer().setShowBoard(!app.settingsPlayer().showBoard()); } else if (source.getText().equals("Show dev tooltip")) { app.settingsPlayer().setCursorTooltipDev(!app.settingsPlayer().cursorTooltipDev()); } else if (source.getText().equals("Show Pieces")) { app.settingsPlayer().setShowPieces(!app.settingsPlayer().showPieces()); } else if (source.getText().equals("Show Graph")) { app.settingsPlayer().setShowGraph(!app.settingsPlayer().showGraph()); } else if (source.getText().equals("Show Cell Connections")) { app.settingsPlayer().setShowConnections(!app.settingsPlayer().showConnections()); } else if (source.getText().equals("Show Axes")) { app.settingsPlayer().setShowAxes(!app.settingsPlayer().showAxes()); } else if (source.getText().equals("Show Container Indices")) { app.bridge().settingsVC().setShowContainerIndices(!app.bridge().settingsVC().showContainerIndices()); } else if (source.getText().equals("Sandbox")) { app.settingsPlayer().setSandboxMode(!app.settingsPlayer().sandboxMode()); app.addTextToStatusPanel("Warning! Using sandbox mode may result in illegal game states.\n"); } else if (source.getText().equals("Show Indices")) { app.bridge().settingsVC().setShowIndices(!app.bridge().settingsVC().showIndices()); if (app.bridge().settingsVC().showCoordinates()) app.bridge().settingsVC().setShowCoordinates(false); if (app.bridge().settingsVC().showIndices()) { app.bridge().settingsVC().setShowVertexIndices(false); app.bridge().settingsVC().setShowEdgeIndices(false); app.bridge().settingsVC().setShowCellIndices(false); } } else if (source.getText().equals("Show Coordinates")) { app.bridge().settingsVC().setShowCoordinates(!app.bridge().settingsVC().showCoordinates()); if (app.bridge().settingsVC().showIndices()) app.bridge().settingsVC().setShowIndices(false); if (app.bridge().settingsVC().showCoordinates()) { app.bridge().settingsVC().setShowVertexCoordinates(false); app.bridge().settingsVC().setShowEdgeCoordinates(false); app.bridge().settingsVC().setShowCellCoordinates(false); } } else if (source.getText().equals("Show Cell Indices")) { app.bridge().settingsVC().setShowCellIndices(!app.bridge().settingsVC().showCellIndices()); if (app.bridge().settingsVC().showCellCoordinates()) app.bridge().settingsVC().setShowCellCoordinates(false); if (app.bridge().settingsVC().showCellIndices()) app.bridge().settingsVC().setShowIndices(false); } else if (source.getText().equals("Show Edge Indices")) { app.bridge().settingsVC().setShowEdgeIndices(!app.bridge().settingsVC().showEdgeIndices()); if (app.bridge().settingsVC().showEdgeCoordinates()) app.bridge().settingsVC().setShowEdgeCoordinates(false); if (app.bridge().settingsVC().showEdgeIndices()) app.bridge().settingsVC().setShowIndices(false); } else if (source.getText().equals("Show Vertex Indices")) { app.bridge().settingsVC().setShowVertexIndices(!app.bridge().settingsVC().showVertexIndices()); if (app.bridge().settingsVC().showVertexCoordinates()) app.bridge().settingsVC().setShowVertexCoordinates(false); if (app.bridge().settingsVC().showVertexIndices()) app.bridge().settingsVC().setShowIndices(false); } else if (source.getText().equals("Show Cell Coordinates")) { app.bridge().settingsVC().setShowCellCoordinates(!app.bridge().settingsVC().showCellCoordinates()); if (app.bridge().settingsVC().showCellIndices()) app.bridge().settingsVC().setShowCellIndices(false); if (app.bridge().settingsVC().showCellCoordinates()) app.bridge().settingsVC().setShowCoordinates(false); } else if (source.getText().equals("Show Edge Coordinates")) { app.bridge().settingsVC().setShowEdgeCoordinates(!app.bridge().settingsVC().showEdgeCoordinates()); if (app.bridge().settingsVC().showEdgeIndices()) app.bridge().settingsVC().setShowEdgeIndices(false); if (app.bridge().settingsVC().showEdgeCoordinates()) app.bridge().settingsVC().setShowCoordinates(false); } else if (source.getText().equals("Show Vertex Coordinates")) { app.bridge().settingsVC().setShowVertexCoordinates(!app.bridge().settingsVC().showVertexCoordinates()); if (app.bridge().settingsVC().showVertexIndices()) app.bridge().settingsVC().setShowVertexIndices(false); if (app.bridge().settingsVC().showVertexCoordinates()) app.bridge().settingsVC().setShowCoordinates(false); } else if (source.getText().equals("Show Magnifying Glass")) { app.settingsPlayer().setShowZoomBox(!app.settingsPlayer().showZoomBox()); } else if (source.getText().equals("Show AI Distribution")) { app.settingsPlayer().setShowAIDistribution(!app.settingsPlayer().showAIDistribution()); } else if (source.getText().equals("Show Last Move")) { app.settingsPlayer().setShowLastMove(!app.settingsPlayer().showLastMove()); } else if (source.getText().equals("Show Repetitions")) { app.manager().settingsManager().setShowRepetitions(!app.manager().settingsManager().showRepetitions()); if (app.manager().settingsManager().showRepetitions()) app.addTextToStatusPanel("Please restart the game to display repetitions correctly.\n"); } else if (source.getText().equals("Show Ending Moves")) { app.settingsPlayer().setShowEndingMove(!app.settingsPlayer().showEndingMove()); } else if (source.getText().contains("Show Track")) { for (int i = 0; i < app.bridge().settingsVC().trackNames().size(); i++) if (source.getText().equals(app.bridge().settingsVC().trackNames().get(i))) app.bridge().settingsVC().trackShown().set(i, Boolean.valueOf(!app.bridge().settingsVC().trackShown().get(i).booleanValue())); } else if (source.getText().equals("Swap Rule")) { app.settingsPlayer().setSwapRule(!app.settingsPlayer().swapRule()); context.game().metaRules().setUsesSwapRule(app.settingsPlayer().swapRule()); GameUtil.resetGame(app, false); } else if (source.getText().equals("No Repetition Of Game State")) { app.settingsPlayer().setNoRepetition(!app.settingsPlayer().noRepetition()); if (app.settingsPlayer().noRepetition()) context.game().metaRules().setRepetitionType(RepetitionType.Positional); GameUtil.resetGame(app, false); } else if (source.getText().equals("No Repetition Within A Turn")) { app.settingsPlayer().setNoRepetitionWithinTurn(!app.settingsPlayer().noRepetitionWithinTurn()); if (app.settingsPlayer().noRepetition()) context.game().metaRules().setRepetitionType(RepetitionType.PositionalInTurn); GameUtil.resetGame(app, false); } else if (source.getText().equals("Save Heuristics")) { app.settingsPlayer().setSaveHeuristics(!app.settingsPlayer().saveHeuristics()); } else if (source.getText().equals("Print Move Features")) { app.settingsPlayer().setPrintMoveFeatures(!app.settingsPlayer().printMoveFeatures()); } else if (source.getText().equals("Print Move Feature Instances")) { app.settingsPlayer().setPrintMoveFeatureInstances(!app.settingsPlayer().printMoveFeatureInstances()); } else if (source.getText().equals("Automatic")) { app.settingsPlayer().setPuzzleDialogOption(PuzzleSelectionType.Automatic); } else if (source.getText().equals("Dialog")) { app.settingsPlayer().setPuzzleDialogOption(PuzzleSelectionType.Dialog); } else if (source.getText().equals("Cycle")) { app.settingsPlayer().setPuzzleDialogOption(PuzzleSelectionType.Cycle); } else if (source.getText().equals("Illegal Moves Allowed")) { app.settingsPlayer().setIllegalMovesValid(!app.settingsPlayer().illegalMovesValid()); } else if (source.getText().equals("Show Possible Values")) { app.bridge().settingsVC().setShowCandidateValues(!app.bridge().settingsVC().showCandidateValues()); } else { System.out.println("NO MATCHING MENU OPTION FOUND"); } EventQueue.invokeLater(() -> { app.resetMenuGUI(); app.repaint(); }); } //--------------------------------------------------------------------- // Returns the parent menu title of a JMenuItem a certain number of steps back (depth). private static String getParentTitle(final JMenuItem source, final int depth) { if (depth <= 0) return source.getText(); Container currentContainer = source; for (int i = 0; i < depth; i++) currentContainer = ((JMenu)((JPopupMenu) currentContainer.getParent()).getInvoker()); return ((JMenu)currentContainer).getText(); } public static StartVisualEditor getStartVisualEditor() { return startVisualEditor; } public static void setStartVisualEditor(final StartVisualEditor startVisualEditor) { MainMenuFunctions.startVisualEditor = startVisualEditor; } //--------------------------------------------------------------------- }
66,349
34.367804
332
java
Ludii
Ludii-master/PlayerDesktop/src/app/menu/MenuScroller.java
package app.menu; import java.awt.Color; import java.awt.Component; import java.awt.Dimension; import java.awt.Graphics; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.Icon; import javax.swing.JComponent; import javax.swing.JMenu; import javax.swing.JMenuItem; import javax.swing.JPopupMenu; import javax.swing.MenuSelectionManager; import javax.swing.Timer; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import javax.swing.event.PopupMenuEvent; import javax.swing.event.PopupMenuListener; /** * A class that provides scrolling capabilities to a long menu dropdown or * popup menu. A number of items can optionally be frozen at the top and/or * bottom of the menu. * <P> * <B>Implementation note:</B> The default number of items to display * at a time is 15, and the default scrolling interval is 125 milliseconds. * <P> * * @version 1.5.0 04/05/12 * @author Darryl */ public class MenuScroller { //private JMenu menu; JPopupMenu menu; Component[] menuItems; private final MenuScrollItem upItem; private final MenuScrollItem downItem; private final MenuScrollListener menuListener = new MenuScrollListener(); int scrollCount; int interval; int topFixedCount; int bottomFixedCount; int firstIndex = 0; int keepVisibleIndex = -1; /** * Registers a menu to be scrolled with the default number of items to * display at a time and the default scrolling interval. * * @param menu the menu * @return the MenuScroller */ public static MenuScroller setScrollerFor(JMenu menu) { return new MenuScroller(menu); } /** * Registers a popup menu to be scrolled with the default number of items to * display at a time and the default scrolling interval. * * @param menu the popup menu * @return the MenuScroller */ public static MenuScroller setScrollerFor(JPopupMenu menu) { return new MenuScroller(menu); } /** * Registers a menu to be scrolled with the default number of items to * display at a time and the specified scrolling interval. * * @param menu the menu * @param scrollCount the number of items to display at a time * @return the MenuScroller * @throws IllegalArgumentException if scrollCount is 0 or negative */ public static MenuScroller setScrollerFor(JMenu menu, int scrollCount) { return new MenuScroller(menu, scrollCount); } /** * Registers a popup menu to be scrolled with the default number of items to * display at a time and the specified scrolling interval. * * @param menu the popup menu * @param scrollCount the number of items to display at a time * @return the MenuScroller * @throws IllegalArgumentException if scrollCount is 0 or negative */ public static MenuScroller setScrollerFor(JPopupMenu menu, int scrollCount) { return new MenuScroller(menu, scrollCount); } /** * Registers a menu to be scrolled, with the specified number of items to * display at a time and the specified scrolling interval. * * @param menu the menu * @param scrollCount the number of items to be displayed at a time * @param interval the scroll interval, in milliseconds * @return the MenuScroller * @throws IllegalArgumentException if scrollCount or interval is 0 or negative */ public static MenuScroller setScrollerFor(JMenu menu, int scrollCount, int interval) { return new MenuScroller(menu, scrollCount, interval); } /** * Registers a popup menu to be scrolled, with the specified number of items to * display at a time and the specified scrolling interval. * * @param menu the popup menu * @param scrollCount the number of items to be displayed at a time * @param interval the scroll interval, in milliseconds * @return the MenuScroller * @throws IllegalArgumentException if scrollCount or interval is 0 or negative */ public static MenuScroller setScrollerFor(JPopupMenu menu, int scrollCount, int interval) { return new MenuScroller(menu, scrollCount, interval); } /** * Registers a menu to be scrolled, with the specified number of items * to display in the scrolling region, the specified scrolling interval, * and the specified numbers of items fixed at the top and bottom of the * menu. * * @param menu the menu * @param scrollCount the number of items to display in the scrolling portion * @param interval the scroll interval, in milliseconds * @param topFixedCount the number of items to fix at the top. May be 0. * @param bottomFixedCount the number of items to fix at the bottom. May be 0 * @throws IllegalArgumentException if scrollCount or interval is 0 or * negative or if topFixedCount or bottomFixedCount is negative * @return the MenuScroller */ public static MenuScroller setScrollerFor(JMenu menu, int scrollCount, int interval, int topFixedCount, int bottomFixedCount) { return new MenuScroller(menu, scrollCount, interval, topFixedCount, bottomFixedCount); } /** * Registers a popup menu to be scrolled, with the specified number of items * to display in the scrolling region, the specified scrolling interval, * and the specified numbers of items fixed at the top and bottom of the * popup menu. * * @param menu the popup menu * @param scrollCount the number of items to display in the scrolling portion * @param interval the scroll interval, in milliseconds * @param topFixedCount the number of items to fix at the top. May be 0 * @param bottomFixedCount the number of items to fix at the bottom. May be 0 * @throws IllegalArgumentException if scrollCount or interval is 0 or * negative or if topFixedCount or bottomFixedCount is negative * @return the MenuScroller */ public static MenuScroller setScrollerFor(JPopupMenu menu, int scrollCount, int interval, int topFixedCount, int bottomFixedCount) { return new MenuScroller(menu, scrollCount, interval, topFixedCount, bottomFixedCount); } /** * Constructs a <code>MenuScroller</code> that scrolls a menu with the * default number of items to display at a time, and default scrolling * interval. * * @param menu the menu */ public MenuScroller(JMenu menu) { this(menu, 15); } /** * Constructs a <code>MenuScroller</code> that scrolls a popup menu with the * default number of items to display at a time, and default scrolling * interval. * * @param menu the popup menu */ public MenuScroller(JPopupMenu menu) { this(menu, 15); } /** * Constructs a <code>MenuScroller</code> that scrolls a menu with the * specified number of items to display at a time, and default scrolling * interval. * * @param menu the menu * @param scrollCount the number of items to display at a time * @throws IllegalArgumentException if scrollCount is 0 or negative */ public MenuScroller(JMenu menu, int scrollCount) { this(menu, scrollCount, 150); } /** * Constructs a <code>MenuScroller</code> that scrolls a popup menu with the * specified number of items to display at a time, and default scrolling * interval. * * @param menu the popup menu * @param scrollCount the number of items to display at a time * @throws IllegalArgumentException if scrollCount is 0 or negative */ public MenuScroller(JPopupMenu menu, int scrollCount) { this(menu, scrollCount, 150); } /** * Constructs a <code>MenuScroller</code> that scrolls a menu with the * specified number of items to display at a time, and specified scrolling * interval. * * @param menu the menu * @param scrollCount the number of items to display at a time * @param interval the scroll interval, in milliseconds * @throws IllegalArgumentException if scrollCount or interval is 0 or negative */ public MenuScroller(JMenu menu, int scrollCount, int interval) { this(menu, scrollCount, interval, 0, 0); } /** * Constructs a <code>MenuScroller</code> that scrolls a popup menu with the * specified number of items to display at a time, and specified scrolling * interval. * * @param menu the popup menu * @param scrollCount the number of items to display at a time * @param interval the scroll interval, in milliseconds * @throws IllegalArgumentException if scrollCount or interval is 0 or negative */ public MenuScroller(JPopupMenu menu, int scrollCount, int interval) { this(menu, scrollCount, interval, 0, 0); } /** * Constructs a <code>MenuScroller</code> that scrolls a menu with the * specified number of items to display in the scrolling region, the * specified scrolling interval, and the specified numbers of items fixed at * the top and bottom of the menu. * * @param menu the menu * @param scrollCount the number of items to display in the scrolling portion * @param interval the scroll interval, in milliseconds * @param topFixedCount the number of items to fix at the top. May be 0 * @param bottomFixedCount the number of items to fix at the bottom. May be 0 * @throws IllegalArgumentException if scrollCount or interval is 0 or * negative or if topFixedCount or bottomFixedCount is negative */ public MenuScroller(JMenu menu, int scrollCount, int interval, int topFixedCount, int bottomFixedCount) { this(menu.getPopupMenu(), scrollCount, interval, topFixedCount, bottomFixedCount); } /** * Constructs a <code>MenuScroller</code> that scrolls a popup menu with the * specified number of items to display in the scrolling region, the * specified scrolling interval, and the specified numbers of items fixed at * the top and bottom of the popup menu. * * @param menu the popup menu * @param scrollCount the number of items to display in the scrolling portion * @param interval the scroll interval, in milliseconds * @param topFixedCount the number of items to fix at the top. May be 0 * @param bottomFixedCount the number of items to fix at the bottom. May be 0 * @throws IllegalArgumentException if scrollCount or interval is 0 or * negative or if topFixedCount or bottomFixedCount is negative */ public MenuScroller(JPopupMenu menu, int scrollCount, int interval, int topFixedCount, int bottomFixedCount) { if (scrollCount <= 0 || interval <= 0) { throw new IllegalArgumentException("scrollCount and interval must be greater than 0"); } if (topFixedCount < 0 || bottomFixedCount < 0) { throw new IllegalArgumentException("topFixedCount and bottomFixedCount cannot be negative"); } upItem = new MenuScrollItem(MenuIcon.UP, -1); downItem = new MenuScrollItem(MenuIcon.DOWN, +1); setScrollCount(scrollCount); setInterval(interval); setTopFixedCount(topFixedCount); setBottomFixedCount(bottomFixedCount); this.menu = menu; menu.addPopupMenuListener(menuListener); } /** * Returns the scroll interval in milliseconds * * @return the scroll interval in milliseconds */ public int getInterval() { return interval; } /** * Sets the scroll interval in milliseconds * * @param interval the scroll interval in milliseconds * @throws IllegalArgumentException if interval is 0 or negative */ public void setInterval(int interval) { if (interval <= 0) { throw new IllegalArgumentException("interval must be greater than 0"); } upItem.setInterval(interval); downItem.setInterval(interval); this.interval = interval; } /** * Returns the number of items in the scrolling portion of the menu. * * @return the number of items to display at a time */ public int getscrollCount() { return scrollCount; } /** * Sets the number of items in the scrolling portion of the menu. * * @param scrollCount the number of items to display at a time * @throws IllegalArgumentException if scrollCount is 0 or negative */ public void setScrollCount(int scrollCount) { if (scrollCount <= 0) { throw new IllegalArgumentException("scrollCount must be greater than 0"); } this.scrollCount = scrollCount; MenuSelectionManager.defaultManager().clearSelectedPath(); } /** * Returns the number of items fixed at the top of the menu or popup menu. * * @return the number of items */ public int getTopFixedCount() { return topFixedCount; } /** * Sets the number of items to fix at the top of the menu or popup menu. * * @param topFixedCount the number of items */ public void setTopFixedCount(int topFixedCount) { if (firstIndex <= topFixedCount) { firstIndex = topFixedCount; } else { firstIndex += (topFixedCount - this.topFixedCount); } this.topFixedCount = topFixedCount; } /** * Returns the number of items fixed at the bottom of the menu or popup menu. * * @return the number of items */ public int getBottomFixedCount() { return bottomFixedCount; } /** * Sets the number of items to fix at the bottom of the menu or popup menu. * * @param bottomFixedCount the number of items */ public void setBottomFixedCount(int bottomFixedCount) { this.bottomFixedCount = bottomFixedCount; } /** * Scrolls the specified item into view each time the menu is opened. Call this method with * <code>null</code> to restore the default behavior, which is to show the menu as it last * appeared. * * @param item the item to keep visible * @see #keepVisible(int) */ public void keepVisible(JMenuItem item) { if (item == null) { keepVisibleIndex = -1; } else { final int index = menu.getComponentIndex(item); keepVisibleIndex = index; } } /** * Scrolls the item at the specified index into view each time the menu is opened. Call this * method with <code>-1</code> to restore the default behavior, which is to show the menu as * it last appeared. * * @param index the index of the item to keep visible * @see #keepVisible(javax.swing.JMenuItem) */ public void keepVisible(int index) { keepVisibleIndex = index; } /** * Removes this MenuScroller from the associated menu and restores the * default behavior of the menu. */ public void dispose() { if (menu != null) { menu.removePopupMenuListener(menuListener); menu = null; } } /** * Ensures that the <code>dispose</code> method of this MenuScroller is * called when there are no more references to it. * * @exception Throwable if an error occurs. * @see MenuScroller#dispose() */ @Override public void finalize() throws Throwable { dispose(); } void refreshMenu() { if (menuItems != null && menuItems.length > 0) { firstIndex = Math.max(topFixedCount, firstIndex); firstIndex = Math.min(menuItems.length - bottomFixedCount - scrollCount, firstIndex); upItem.setEnabled(firstIndex > topFixedCount); downItem.setEnabled(firstIndex + scrollCount < menuItems.length - bottomFixedCount); menu.removeAll(); for (int i = 0; i < topFixedCount; i++) { menu.add(menuItems[i]); } if (topFixedCount > 0) { menu.addSeparator(); } menu.add(upItem); for (int i = firstIndex; i < scrollCount + firstIndex; i++) { menu.add(menuItems[i]); } menu.add(downItem); if (bottomFixedCount > 0) { menu.addSeparator(); } for (int i = menuItems.length - bottomFixedCount; i < menuItems.length; i++) { menu.add(menuItems[i]); } final JComponent parent = (JComponent) upItem.getParent(); parent.revalidate(); parent.repaint(); } } private class MenuScrollListener implements PopupMenuListener { public MenuScrollListener() { // TODO Auto-generated constructor stub } @Override public void popupMenuWillBecomeVisible(PopupMenuEvent e) { setMenuItems(); } @Override public void popupMenuWillBecomeInvisible(PopupMenuEvent e) { restoreMenuItems(); } @Override public void popupMenuCanceled(PopupMenuEvent e) { restoreMenuItems(); } private void setMenuItems() { menuItems = menu.getComponents(); if (keepVisibleIndex >= topFixedCount && keepVisibleIndex <= menuItems.length - bottomFixedCount && (keepVisibleIndex > firstIndex + scrollCount || keepVisibleIndex < firstIndex)) { firstIndex = Math.min(firstIndex, keepVisibleIndex); firstIndex = Math.max(firstIndex, keepVisibleIndex - scrollCount + 1); } if (menuItems.length > topFixedCount + scrollCount + bottomFixedCount) { refreshMenu(); } } private void restoreMenuItems() { menu.removeAll(); for (final Component component : menuItems) { menu.add(component); } } } private class MenuScrollTimer extends Timer { private static final long serialVersionUID = 1L; public MenuScrollTimer(final int increment, int interval) { super(interval, new ActionListener() { @Override public void actionPerformed(ActionEvent e) { firstIndex += increment; refreshMenu(); } }); } } private class MenuScrollItem extends JMenuItem implements ChangeListener { private static final long serialVersionUID = 1L; private final MenuScrollTimer timer; public MenuScrollItem(MenuIcon icon, int increment) { setIcon(icon); setDisabledIcon(icon); timer = new MenuScrollTimer(increment, interval); addChangeListener(this); } public void setInterval(int interval) { timer.setDelay(interval); } @Override public void stateChanged(ChangeEvent e) { if (isArmed() && !timer.isRunning()) { timer.start(); } if (!isArmed() && timer.isRunning()) { timer.stop(); } } } private static enum MenuIcon implements Icon { UP(9, 1, 9), DOWN(1, 9, 1); final int[] xPoints = {1, 5, 9}; final int[] yPoints; MenuIcon(int... yPoints) { this.yPoints = yPoints; } @Override public void paintIcon(Component c, Graphics g, int x, int y) { final Dimension size = c.getSize(); final Graphics g2 = g.create(size.width / 2 - 5, size.height / 2 - 5, 10, 10); g2.setColor(Color.GRAY); g2.drawPolygon(xPoints, yPoints, 3); if (c.isEnabled()) { g2.setColor(Color.BLACK); g2.fillPolygon(xPoints, yPoints, 3); } g2.dispose(); } @Override public int getIconWidth() { return 0; } @Override public int getIconHeight() { return 10; } } }
18,915
30.845118
98
java
Ludii
Ludii-master/PlayerDesktop/src/app/util/CountRulesetsDone.java
package app.util;// import java.util.ArrayList; import java.util.List; import java.util.regex.Pattern; import game.Game; import main.FileHandling; import main.StringRoutines; import main.collections.ListUtils; import main.options.Option; import main.options.Ruleset; import other.GameLoader; /** * To count the number of rulesets implemented. * * @author Eric.Piette */ public final class CountRulesetsDone { public static void main(final String[] args) { countRuleSets(); } //------------------------------------------------------------------------- private static void countRuleSets() { int count = 0; int countOptionCombinations = 0; final String[] gameNames = FileHandling.listGames(); for (int index = 0; index < gameNames.length; index++) { final String gameName = gameNames[index]; if (gameName.replaceAll(Pattern.quote("\\"), "/").contains("/lud/bad/")) continue; if (gameName.replaceAll(Pattern.quote("\\"), "/").contains("/lud/wip/")) continue; if (gameName.replaceAll(Pattern.quote("\\"), "/").contains("/lud/WishlistDLP/")) continue; if (gameName.replaceAll(Pattern.quote("\\"), "/").contains("/lud/test/")) continue; if (gameName.replaceAll(Pattern.quote("\\"), "/").contains("subgame")) continue; if (gameName.replaceAll(Pattern.quote("\\"), "/").contains("reconstruction/pending/")) continue; if (gameName.replaceAll(Pattern.quote("\\"), "/").contains("reconstruction/validation/")) continue; final Game game = GameLoader.loadGameFromName(gameName); final List<Ruleset> rulesetsInGame = game.description().rulesets(); final List<List<String>> optionCategories = new ArrayList<List<String>>(); for (int o = 0; o < game.description().gameOptions().numCategories(); o++) { final List<Option> options = game.description().gameOptions().categories().get(o).options(); final List<String> optionCategory = new ArrayList<String>(); for (int j = 0; j < options.size(); j++) { final Option option = options.get(j); optionCategory.add(StringRoutines.join("/", option.menuHeadings().toArray(new String[0]))); } if (optionCategory.size() > 0) optionCategories.add(optionCategory); } List<List<String>> optionCombinations = ListUtils.generateTuples(optionCategories); //System.out.println(game.name() + " combi = " + optionCombinations.size()); countOptionCombinations += optionCombinations.size(); // Get all the rulesets of the game if it has some. if (rulesetsInGame != null && !rulesetsInGame.isEmpty()) { for (int rs = 0; rs < rulesetsInGame.size(); rs++) { final Ruleset ruleset = rulesetsInGame.get(rs); if (!ruleset.optionSettings().isEmpty()&& !ruleset.heading().contains("Incomplete")) // We check if the ruleset is implemented. { // final Game rulesetGame = GameLoader.loadGameFromName(gameName, ruleset.optionSettings()); // if(rulesetGame.computeRequirementReport()) // { // System.out.println("WILL CRASH OR MISSING REQUIREMENT"); // System.out.println(rulesetGame.name() + " RULESET + " + ruleset.heading()); // } count++; } } } else { // if(game.computeRequirementReport()) // { // System.out.println("WILL CRASH OR MISSING REQUIREMENT"); // System.out.println(game.name()); // } count++; } } System.out.println(count + " rulesets implemented"); System.out.println(countOptionCombinations + " option combinations implemented"); } }
3,547
29.324786
132
java
Ludii
Ludii-master/PlayerDesktop/src/app/util/SettingsDesktop.java
package app.util; import java.awt.Toolkit; import javax.swing.JDialog; /** * Desktop specific settings * * @author Matthew.Stephenson */ public class SettingsDesktop { /** Default display width for the program (in pixels). */ public static int defaultWidth = (int) (Toolkit.getDefaultToolkit().getScreenSize().getWidth() * .75); /** Default display height for the program (in pixels). */ public static int defaultHeight = (int) (Toolkit.getDefaultToolkit().getScreenSize().getHeight() * .75); /** Whether a separate dialog (settings, puzzle, etc.) is open. */ public static JDialog openDialog = null; }
623
23.96
105
java
Ludii
Ludii-master/PlayerDesktop/src/app/util/TodoRulesets.java
package app.util; import java.util.List; import java.util.regex.Pattern; import game.Game; import main.FileHandling; import main.options.Ruleset; import other.GameLoader; /** * To print the rulesets not implemented in the games which are not Reconstructed or Incomplete * * @author Eric.Piette */ public final class TodoRulesets { public static void main(final String[] args) { missingRulesets(); } //------------------------------------------------------------------------- private static void missingRulesets() { int countNotIncomplete = 0; int countIncomplete = 0; final String[] gameNames = FileHandling.listGames(); for (int index = 0; index < gameNames.length; index++) { final String gameName = gameNames[index]; if (gameName.replaceAll(Pattern.quote("\\"), "/").contains("/lud/bad/")) continue; if (gameName.replaceAll(Pattern.quote("\\"), "/").contains("/lud/wip/")) continue; if (gameName.replaceAll(Pattern.quote("\\"), "/").contains("/lud/WishlistDLP/")) continue; if (gameName.replaceAll(Pattern.quote("\\"), "/").contains("/lud/test/")) continue; if (gameName.replaceAll(Pattern.quote("\\"), "/").contains("subgame")) continue; if (gameName.replaceAll(Pattern.quote("\\"), "/").contains("reconstruction/pending/")) continue; if (gameName.replaceAll(Pattern.quote("\\"), "/").contains("reconstruction/validation/")) continue; final Game game = GameLoader.loadGameFromName(gameName); final List<Ruleset> rulesetsInGame = game.description().rulesets(); // Get all the rulesets of the game if it has some. if (rulesetsInGame != null && !rulesetsInGame.isEmpty()) { for (int rs = 0; rs < rulesetsInGame.size(); rs++) { final Ruleset ruleset = rulesetsInGame.get(rs); if (ruleset.optionSettings().isEmpty()) // We check if the ruleset is implemented. { System.out.println("TODO: " + game.name() + " " + ruleset.heading()); if(ruleset.heading().contains("Incomplete")) countIncomplete++; else countNotIncomplete++; } } } } System.out.println(countNotIncomplete + " complete rulesets TODO."); System.out.println(countIncomplete + " incomplete rulesets TODO."); } }
2,255
27.556962
95
java
Ludii
Ludii-master/PlayerDesktop/src/app/util/UserPreferences.java
package app.util; import java.awt.Dimension; import java.awt.Frame; import java.awt.Toolkit; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.attribute.FileTime; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.json.JSONArray; import org.json.JSONObject; import org.json.JSONTokener; import app.DesktopApp; import app.PlayerApp; import app.move.MoveFormat; import app.utils.AnimationVisualsType; import app.utils.PuzzleSelectionType; import main.Constants; import manager.ai.AIDetails; import manager.ai.AIRegistry; /** * The values of various options and settings that are to be retained throughout multiple loadings of the application. * * @author Matthew.Stephenson */ public class UserPreferences { //------------------------------------------------------------------------- /** * Save all relevant variables in an external preferences file. * Only called when the app is closed. */ public static void savePreferences(final PlayerApp app) { BufferedWriter bw = null; try { app.manager().settingsNetwork().restoreAiPlayers(app.manager()); final File file = new File("." + File.separator + "ludii_preferences.json"); if (!file.exists()) file.createNewFile(); final JSONObject json = new JSONObject(); // Ludii version number json.put("VersionNumber", Constants.LUDEME_VERSION); // Game Options final List<String> gameOptionStrings = app.manager().settingsManager().userSelections().selectedOptionStrings(); final JSONArray jsonArray = new JSONArray(gameOptionStrings); json.put("OptionStrings", jsonArray); json.put("SelectedRuleset", app.manager().settingsManager().userSelections().ruleset()); // If loaded from memory json.put("LoadedFromMemory", app.settingsPlayer().loadedFromMemory()); // lud filename for the last loaded game (used for checking last modified time on external lud files). json.put("savedLudName", app.manager().savedLudName()); // Store the last time the external lud file was modified, if not loaded from memory. if (!app.settingsPlayer().loadedFromMemory()) { final Path path = Paths.get(app.manager().savedLudName()); FileTime fileTime = null; try { fileTime = Files.getLastModifiedTime(path); json.put("SavedLudLastModifiedTime", fileTime.toString()); } catch (final IOException e) { System.err.println("Cannot get the last modified time - " + e); } } // Settings Desktop json.put("FrameMaximizedBoth", DesktopApp.frame().getExtendedState() == Frame.MAXIMIZED_BOTH); // Settings Manager/Network json.put("networkPolling", app.manager().settingsNetwork().longerNetworkPolling()); json.put("networkRefresh", app.manager().settingsNetwork().noNetworkRefresh()); json.put("TickLength", app.manager().settingsManager().tickLength()); json.put("alwaysAutoPass", app.manager().settingsManager().alwaysAutoPass()); // Settings Player json.put("moveFormat", app.settingsPlayer().moveFormat().name()); json.put("CursorTooltip", app.settingsPlayer().cursorTooltipDev()); json.put("tabFontSize", app.settingsPlayer().tabFontSize()); json.put("editorFontSize", app.settingsPlayer().editorFontSize()); json.put("editorParseText", app.settingsPlayer().isEditorParseText()); json.put("testLudeme1", app.settingsPlayer().testLudeme1()); json.put("testLudeme2", app.settingsPlayer().testLudeme2()); json.put("testLudeme3", app.settingsPlayer().testLudeme3()); json.put("testLudeme4", app.settingsPlayer().testLudeme4()); json.put("showZoomBox", app.settingsPlayer().showZoomBox()); json.put("AnimationVisualsType", app.settingsPlayer().animationType().name()); json.put("SwapRule", app.settingsPlayer().swapRule()); json.put("NoRepetition", app.settingsPlayer().noRepetition()); json.put("NoRepetitionWithinTurn", app.settingsPlayer().noRepetitionWithinTurn()); json.put("SaveHeuristics", app.settingsPlayer().saveHeuristics()); json.put("ShowLastMove", app.settingsPlayer().showLastMove()); json.put("ShowRepetitions", app.manager().settingsManager().showRepetitions()); json.put("ShowEndingMove", app.settingsPlayer().showEndingMove()); json.put("ShowAIDistribution", app.settingsPlayer().showAIDistribution()); json.put("PuzzleValueSelection", app.settingsPlayer().puzzleDialogOption().name()); json.put("IllegalMoves", app.settingsPlayer().illegalMovesValid()); json.put("moveSoundEffect", app.settingsPlayer().isMoveSoundEffect()); json.put("saveTrialAfterMove", app.settingsPlayer().saveTrialAfterMove()); json.put("ShowBoard", app.settingsPlayer().showBoard()); json.put("ShowPieces", app.settingsPlayer().showPieces()); json.put("ShowGraph", app.settingsPlayer().showGraph()); json.put("ShowConnections", app.settingsPlayer().showConnections()); json.put("ShowAxes", app.settingsPlayer().showAxes()); json.put("HideAiMoves", app.settingsPlayer().hideAiMoves()); json.put("devMode",app.settingsPlayer().devMode()); json.put("editorAutocomplete", app.settingsPlayer().editorAutocomplete()); json.put("MoveCoord", app.settingsPlayer().isMoveCoord()); json.put("PhaseTitle", app.settingsPlayer().showPhaseInTitle()); // Settings VC json.put("FlatBoard", app.bridge().settingsVC().flatBoard()); json.put("ShowCellIndices", app.bridge().settingsVC().showCellIndices()); json.put("ShowEdgeIndices", app.bridge().settingsVC().showEdgeIndices()); json.put("ShowFaceIndices", app.bridge().settingsVC().showVertexIndices()); json.put("ShowContainerIndices", app.bridge().settingsVC().showContainerIndices()); json.put("ShowVertexCoordinates", app.bridge().settingsVC().showCellCoordinates()); json.put("ShowEdgeCoordinates", app.bridge().settingsVC().showEdgeCoordinates()); json.put("ShowFaceCoordinates", app.bridge().settingsVC().showVertexCoordinates()); json.put("ShowIndices", app.bridge().settingsVC().showIndices()); json.put("ShowCoordinates", app.bridge().settingsVC().showCoordinates()); json.put("drawBottomCells", app.bridge().settingsVC().drawBottomCells()); json.put("drawCornersCells", app.bridge().settingsVC().drawCornerCells()); json.put("drawCornerConcaveCells", app.bridge().settingsVC().drawCornerConcaveCells()); json.put("drawCornerConvexCells", app.bridge().settingsVC().drawCornerConvexCells()); json.put("drawMajorCells", app.bridge().settingsVC().drawMajorCells()); json.put("drawMinorCells", app.bridge().settingsVC().drawMinorCells()); json.put("drawInnerCells", app.bridge().settingsVC().drawInnerCells()); json.put("drawLeftCells", app.bridge().settingsVC().drawLeftCells()); json.put("drawOuterCells", app.bridge().settingsVC().drawOuterCells()); json.put("drawPerimeterCells", app.bridge().settingsVC().drawPerimeterCells()); json.put("drawRightCells", app.bridge().settingsVC().drawRightCells()); json.put("drawCenterCells", app.bridge().settingsVC().drawCenterCells()); json.put("drawTopCells", app.bridge().settingsVC().drawTopCells()); json.put("drawPhasesCells", app.bridge().settingsVC().drawPhasesCells()); json.put("drawNeighboursCells", app.bridge().settingsVC().drawNeighboursCells()); json.put("drawRadialsCells", app.bridge().settingsVC().drawRadialsCells()); json.put("drawDistanceCells", app.bridge().settingsVC().drawDistanceCells()); json.put("drawBottomVertices", app.bridge().settingsVC().drawBottomVertices()); json.put("drawCornersVertices", app.bridge().settingsVC().drawCornerVertices()); json.put("drawCornerConcaveVertices", app.bridge().settingsVC().drawCornerConcaveVertices()); json.put("drawCornerConvexVertices", app.bridge().settingsVC().drawCornerConvexVertices()); json.put("drawMajorVertices", app.bridge().settingsVC().drawMajorVertices()); json.put("drawMinorVertices", app.bridge().settingsVC().drawMinorVertices()); json.put("drawInnerVertices", app.bridge().settingsVC().drawInnerVertices()); json.put("drawLeftVertices", app.bridge().settingsVC().drawLeftVertices()); json.put("drawOuterVertices", app.bridge().settingsVC().drawOuterVertices()); json.put("drawPerimeterVertices", app.bridge().settingsVC().drawPerimeterVertices()); json.put("drawRightVertices", app.bridge().settingsVC().drawRightVertices()); json.put("drawCenterVertices", app.bridge().settingsVC().drawCenterVertices()); json.put("drawTopVertices", app.bridge().settingsVC().drawTopVertices()); json.put("drawPhasesVertices", app.bridge().settingsVC().drawPhasesVertices()); json.put("drawSideNumberVertices", app.bridge().settingsVC().drawSideVertices().size()); json.put("drawNeighboursVertices", app.bridge().settingsVC().drawNeighboursVertices()); json.put("drawRadialsVertices", app.bridge().settingsVC().drawRadialsVertices()); json.put("drawDistanceVertices", app.bridge().settingsVC().drawDistanceVertices()); json.put("drawCornerEdges", app.bridge().settingsVC().drawCornerEdges()); json.put("drawCornerConcaveEdges", app.bridge().settingsVC().drawCornerConcaveEdges()); json.put("drawCornerConvexEdges", app.bridge().settingsVC().drawCornerConvexEdges()); json.put("drawMajorEdges", app.bridge().settingsVC().drawMajorEdges()); json.put("drawMinorEdges", app.bridge().settingsVC().drawMinorEdges()); json.put("drawBottomEdges", app.bridge().settingsVC().drawBottomEdges()); json.put("drawInnerEdges", app.bridge().settingsVC().drawInnerEdges()); json.put("drawLeftEdges", app.bridge().settingsVC().drawLeftEdges()); json.put("drawOuterEdges", app.bridge().settingsVC().drawOuterEdges()); json.put("drawPerimeterEdges", app.bridge().settingsVC().drawPerimeterEdges()); json.put("drawRightEdges", app.bridge().settingsVC().drawRightEdges()); json.put("drawTopEdges", app.bridge().settingsVC().drawTopEdges()); json.put("drawCentreEdges", app.bridge().settingsVC().drawCentreEdges()); json.put("drawPhasesEdges", app.bridge().settingsVC().drawPhasesEdges()); json.put("drawDistanceEdges", app.bridge().settingsVC().drawDistanceEdges()); json.put("drawAxialEdges", app.bridge().settingsVC().drawAxialEdges()); json.put("drawHorizontalEdges", app.bridge().settingsVC().drawHorizontalEdges()); json.put("drawVerticalEdges", app.bridge().settingsVC().drawVerticalEdges()); json.put("drawAngledEdges", app.bridge().settingsVC().drawAngledEdges()); json.put("drawSlashEdges", app.bridge().settingsVC().drawSlashEdges()); json.put("drawSloshEdges", app.bridge().settingsVC().drawSloshEdges()); json.put("ShowPossibleMoves", app.bridge().settingsVC().showPossibleMoves()); json.put("CandidateMoves", app.bridge().settingsVC().showCandidateValues()); //json.put("abstractPriority", app.bridge().settingsVC().abstractPriority()); json.put("coordWithOutline", app.bridge().settingsVC().coordWithOutline()); for (int i = 0; i < app.bridge().settingsVC().trackNames().size(); i++) json.put(app.bridge().settingsVC().trackNames().get(i), app.bridge().settingsVC().trackShown().get(i)); for (int p = 0; p < app.settingsPlayer().recentGames().length; p++) json.put("RecentGames_" + p, app.settingsPlayer().recentGames()[p]); // Settings network if (app.manager().settingsNetwork().rememberDetails()) { json.put("LoginUsername", app.manager().settingsNetwork().loginUsername()); json.put("RememberDetails", app.manager().settingsNetwork().rememberDetails()); } // Save frame parameters json.put("FrameWidth", DesktopApp.frame().getWidth()); json.put("FrameHeight", DesktopApp.frame().getHeight()); json.put("FrameLocX", DesktopApp.frame().getLocation().x); json.put("FrameLocY", DesktopApp.frame().getLocation().y); // Save the Name and AI preferences for (int p = 0; p < app.manager().aiSelected().length; ++p) { json.put("Names_" + p, app.manager().aiSelected()[p].name()); json.put("MenuNames_" + p, app.manager().aiSelected()[p].menuItemName()); if (app.manager().aiSelected()[p].ai() != null) { json.put("AI_" + p, app.manager().aiSelected()[p].object()); json.put("SearchTime_" + p, app.manager().aiSelected()[p].thinkTime()); } } // Save filepaths of filechoosers final File selectedJsonFile = DesktopApp.jsonFileChooser().getSelectedFile(); if (selectedJsonFile != null && selectedJsonFile.exists()) json.put("LastSelectedJsonFile", selectedJsonFile.getCanonicalPath()); final File selectedJarFile = DesktopApp.jarFileChooser().getSelectedFile(); if (selectedJarFile != null && selectedJarFile.exists()) json.put("LastSelectedJarFile", selectedJarFile.getCanonicalPath()); final File selectedAiDefFile = DesktopApp.aiDefFileChooser().getSelectedFile(); if (selectedAiDefFile != null && selectedAiDefFile.exists()) json.put("LastSelectedAiDefFile", selectedAiDefFile.getCanonicalPath()); final File selectedGameFile = DesktopApp.gameFileChooser().getSelectedFile(); if (selectedGameFile != null && selectedGameFile.exists()) json.put("LastSelectedGameFile", selectedGameFile.getCanonicalPath()); final File selectedSaveGameFile = DesktopApp.saveGameFileChooser().getSelectedFile(); if (selectedSaveGameFile != null && selectedSaveGameFile.exists()) json.put("LastSelectedSaveGameFile", selectedSaveGameFile.getCanonicalPath()); final File selectedLoadTrialFile = DesktopApp.loadTrialFileChooser().getSelectedFile(); if (selectedLoadTrialFile != null && selectedLoadTrialFile.exists()) json.put("LastSelectedLoadTrialFile", selectedLoadTrialFile.getCanonicalPath()); final File selectedLoadTournamentFile = DesktopApp.loadTournamentFileChooser().getSelectedFile(); if (selectedLoadTournamentFile != null && selectedLoadTournamentFile.exists()) json.put("LastSelectedLoadTournamentFile", selectedLoadTournamentFile.getCanonicalPath()); // Game turn limits for (final String gameName : app.manager().settingsManager().turnLimits().keySet()) { json.put("MAXTURN" + gameName, app.manager().settingsManager().turnLimits().get(gameName)); } // Game piece families for (final String gameName : app.bridge().settingsVC().pieceFamilies().keySet()) { json.put("PIECEFAMILY" + gameName, app.bridge().settingsVC().pieceFamilies().get(gameName)); } final FileWriter fw = new FileWriter(file); bw = new BufferedWriter(fw); bw.write(json.toString(4)); } catch (final Exception e) { e.printStackTrace(); System.out.println("Problem while saving preferences."); } finally { app.manager().databaseFunctionsPublic().logout(app.manager()); try { if (bw != null) bw.close(); } catch (final Exception ex) { System.out.println("Error in closing the BufferedWriter" + ex); } } } //------------------------------------------------------------------------- /** * Load all relevant variables from an external preferences file (if exists). * Only called when the app is opened. */ public static void loadPreferences(final PlayerApp app) { app.settingsPlayer().setPreferencesLoaded(false); try (final InputStream inputStream = new FileInputStream(new File("." + File.separator + "ludii_preferences.json"))) { final JSONObject json = new JSONObject(new JSONTokener(inputStream)); // if (!(json.optString("VersionNumber").equals(Constants.LUDEME_VERSION))) // throw new Exception("Incorrect version number"); // Game Options final List<String> listdata = new ArrayList<String>(); final JSONArray jArray = json.optJSONArray("OptionStrings"); if (jArray != null) { for (int i = 0; i < jArray.length(); i++) listdata.add(jArray.getString(i)); // ** FIXME: Not thread-safe. app.manager().settingsManager().userSelections().setSelectOptionStrings(listdata); } // Game Ruleset app.manager().settingsManager().userSelections().setRuleset(json.optInt("SelectedRuleset", app.manager().settingsManager().userSelections().ruleset())); // If loaded from memory app.settingsPlayer().setLoadedFromMemory(json.optBoolean("LoadedFromMemory", app.settingsPlayer().loadedFromMemory())); // If not loading from memory, check that the file hasn't been modified since the last time it was loaded. // If it has, don't try to load the trial. if (!app.settingsPlayer().loadedFromMemory()) { try { final String fileModifiedTime = json.optString("SavedLudLastModifiedTime"); final Path path = Paths.get(json.optString("savedLudName", app.manager().savedLudName())); FileTime fileTime = null; fileTime = Files.getLastModifiedTime(path); if (fileModifiedTime.matches(fileTime.toString())) DesktopApp.setLoadTrial(true); else System.out.println("External .lud has been modified since last load."); } catch (final Exception E) { System.out.println("Failed to load external .lud from preferences"); } } else { DesktopApp.setLoadTrial(true); } // Settings General app.settingsPlayer().setMoveCoord(json.optBoolean("MoveCoord", app.settingsPlayer().isMoveCoord())); // Settings Manager app.settingsPlayer().setShowLastMove ( json.optBoolean("ShowLastMove", app.settingsPlayer().showLastMove()) ); app.manager().settingsManager().setShowRepetitions ( json.optBoolean("ShowRepetitions", app.manager().settingsManager().showRepetitions()) ); app.settingsPlayer().setShowEndingMove ( json.optBoolean("ShowEndingMove", app.settingsPlayer().showEndingMove()) ); app.settingsPlayer().setShowAIDistribution ( json.optBoolean("ShowAIDistribution", app.settingsPlayer().showAIDistribution()) ); app.settingsPlayer().setShowBoard(json.optBoolean("ShowBoard", app.settingsPlayer().showBoard())); app.settingsPlayer().setShowPieces(json.optBoolean("ShowPieces", app.settingsPlayer().showPieces())); app.settingsPlayer().setShowGraph(json.optBoolean("ShowGraph", app.settingsPlayer().showGraph())); app.settingsPlayer().setShowConnections(json.optBoolean("ShowConnections", app.settingsPlayer().showConnections())); app.settingsPlayer().setShowAxes(json.optBoolean("ShowAxes", app.settingsPlayer().showAxes())); app.settingsPlayer().setHideAiMoves ( json.optBoolean("HideAiMoves", app.settingsPlayer().hideAiMoves()) ); app.settingsPlayer().setDevMode ( json.optBoolean("devMode", app.settingsPlayer().devMode()) ); app.manager().settingsNetwork().setLongerNetworkPolling(json.optBoolean("networkPolling", app.manager().settingsNetwork().longerNetworkPolling())); app.manager().settingsNetwork().setNoNetworkRefresh(json.optBoolean("networkRefresh", app.manager().settingsNetwork().noNetworkRefresh())); app.settingsPlayer().setEditorAutocomplete(json.optBoolean("editorAutocomplete", app.settingsPlayer().editorAutocomplete())); app.manager().settingsManager().setTickLength ( json.optDouble("TickLength", app.manager().settingsManager().tickLength()) ); app.manager().settingsManager().setAlwaysAutoPass ( json.optBoolean("alwaysAutoPass", app.manager().settingsManager().alwaysAutoPass()) ); app.settingsPlayer().setSwapRule ( json.optBoolean("SwapRule", app.settingsPlayer().swapRule()) ); app.settingsPlayer().setNoRepetition ( json.optBoolean("NoRepetition", app.settingsPlayer().noRepetition()) ); app.settingsPlayer().setNoRepetitionWithinTurn ( json.optBoolean("NoRepetitionWithinTurn", app.settingsPlayer().noRepetitionWithinTurn()) ); app.settingsPlayer().setSaveHeuristics ( json.optBoolean("SaveHeuristics", app.settingsPlayer().saveHeuristics()) ); app.settingsPlayer().setPuzzleDialogOption ( PuzzleSelectionType.getPuzzleSelectionType ( json.optString("PuzzleValueSelection", app.settingsPlayer().puzzleDialogOption().name()) ) ); app.settingsPlayer().setIllegalMovesValid(json.optBoolean("IllegalMoves", app.settingsPlayer().illegalMovesValid())); app.settingsPlayer().setMoveSoundEffect ( json.optBoolean("moveSoundEffect", app.settingsPlayer().isMoveSoundEffect()) ); app.settingsPlayer().setSaveTrialAfterMove ( json.optBoolean("saveTrialAfterMove", app.settingsPlayer().saveTrialAfterMove()) ); // Settings Desktop app.settingsPlayer().setCursorTooltipDev(json.optBoolean("CursorTooltip", app.settingsPlayer().cursorTooltipDev())); app.settingsPlayer().setTabFontSize(json.optInt("tabFontSize", app.settingsPlayer().tabFontSize())); app.settingsPlayer().setEditorFontSize(json.optInt("editorFontSize", app.settingsPlayer().editorFontSize())); app.settingsPlayer().setEditorParseText(json.optBoolean("editorParseText", app.settingsPlayer().isEditorParseText())); app.settingsPlayer().setMoveFormat(MoveFormat.valueOf(json.optString("moveFormat", app.settingsPlayer().moveFormat().name()))); app.settingsPlayer().setFrameMaximised(json.optBoolean("FrameMaximizedBoth", app.settingsPlayer().frameMaximised())); app.settingsPlayer().setTestLudeme1(json.optString("testLudeme1", app.settingsPlayer().testLudeme1())); app.settingsPlayer().setTestLudeme2(json.optString("testLudeme2", app.settingsPlayer().testLudeme2())); app.settingsPlayer().setTestLudeme3(json.optString("testLudeme3", app.settingsPlayer().testLudeme3())); app.settingsPlayer().setTestLudeme4(json.optString("testLudeme4", app.settingsPlayer().testLudeme4())); app.settingsPlayer().setShowZoomBox(json.optBoolean("showZoomBox", app.settingsPlayer().showZoomBox())); app.settingsPlayer().setAnimationType(AnimationVisualsType.getAnimationVisualsType(json.optString("AnimationVisualsType", app.settingsPlayer().animationType().name()))); app.settingsPlayer().setShowPhaseInTitle(json.optBoolean("PhaseTitle", app.settingsPlayer().showPhaseInTitle())); // Settings VC app.bridge().settingsVC().setFlatBoard(json.optBoolean("FlatBoard", app.bridge().settingsVC().flatBoard())); app.bridge().settingsVC().setShowPossibleMoves(json.optBoolean("ShowPossibleMoves", app.bridge().settingsVC().showPossibleMoves())); app.bridge().settingsVC().setShowCellIndices(json.optBoolean("ShowCellIndices", app.bridge().settingsVC().showCellIndices())); app.bridge().settingsVC().setShowEdgeIndices(json.optBoolean("ShowEdgeIndices", app.bridge().settingsVC().showEdgeIndices())); app.bridge().settingsVC().setShowVertexIndices(json.optBoolean("ShowFaceIndices", app.bridge().settingsVC().showVertexIndices())); app.bridge().settingsVC().setShowContainerIndices(json.optBoolean("ShowContainerIndices", app.bridge().settingsVC().showContainerIndices())); app.bridge().settingsVC().setShowCellCoordinates(json.optBoolean("ShowVertexCoordinates", app.bridge().settingsVC().showCellCoordinates())); app.bridge().settingsVC().setShowEdgeCoordinates(json.optBoolean("ShowEdgeCoordinates", app.bridge().settingsVC().showEdgeCoordinates())); app.bridge().settingsVC().setShowVertexCoordinates(json.optBoolean("ShowFaceCoordinates", app.bridge().settingsVC().showVertexCoordinates())); app.bridge().settingsVC().setShowIndices(json.optBoolean("ShowIndices", app.bridge().settingsVC().showIndices())); app.bridge().settingsVC().setShowCoordinates(json.optBoolean("ShowCoordinates", app.bridge().settingsVC().showCoordinates())); app.bridge().settingsVC().setDrawBottomCells(json.optBoolean("drawBottomCells", app.bridge().settingsVC().drawBottomCells())); app.bridge().settingsVC().setDrawCornerCells(json.optBoolean("drawCornerCells", app.bridge().settingsVC().drawCornerCells())); app.bridge().settingsVC().setDrawCornerConcaveCells(json.optBoolean("drawCornerConcaveCells", app.bridge().settingsVC().drawCornerConcaveCells())); app.bridge().settingsVC().setDrawCornerConvexCells(json.optBoolean("drawCornerConvexCells", app.bridge().settingsVC().drawCornerConvexCells())); app.bridge().settingsVC().setDrawMajorCells(json.optBoolean("drawMajorCells", app.bridge().settingsVC().drawMajorCells())); app.bridge().settingsVC().setDrawMinorCells(json.optBoolean("drawMinorCells", app.bridge().settingsVC().drawMinorCells())); app.bridge().settingsVC().setDrawInnerCells(json.optBoolean("drawInnerCells", app.bridge().settingsVC().drawInnerCells())); app.bridge().settingsVC().setDrawLeftCells(json.optBoolean("drawLeftCells", app.bridge().settingsVC().drawLeftCells())); app.bridge().settingsVC().setDrawOuterCells(json.optBoolean("drawOuterCells", app.bridge().settingsVC().drawOuterCells())); app.bridge().settingsVC().setDrawPerimeterCells(json.optBoolean("drawPerimeterCells", app.bridge().settingsVC().drawPerimeterCells())); app.bridge().settingsVC().setDrawRightCells(json.optBoolean("drawRightCells", app.bridge().settingsVC().drawRightCells())); app.bridge().settingsVC().setDrawTopCells(json.optBoolean("drawTopCells", app.bridge().settingsVC().drawTopCells())); app.bridge().settingsVC().setDrawCenterCells(json.optBoolean("drawCenterCells", app.bridge().settingsVC().drawCenterCells())); app.bridge().settingsVC().setDrawPhasesCells(json.optBoolean("drawPhasesCells", app.bridge().settingsVC().drawPhasesCells())); app.bridge().settingsVC().setDrawNeighboursCells(json.optBoolean("drawNeighboursCells", app.bridge().settingsVC().drawNeighboursCells())); app.bridge().settingsVC().setDrawRadialsCells(json.optBoolean("drawRadialsCells", app.bridge().settingsVC().drawRadialsCells())); app.bridge().settingsVC().setDrawDistanceCells(json.optBoolean("drawDistanceCells", app.bridge().settingsVC().drawDistanceCells())); app.bridge().settingsVC().setDrawBottomVertices(json.optBoolean("drawBottomVertices", app.bridge().settingsVC().drawBottomVertices())); app.bridge().settingsVC().setDrawCornerVertices(json.optBoolean("drawCornerVertices", app.bridge().settingsVC().drawCornerVertices())); app.bridge().settingsVC().setDrawCornerConcaveVertices(json.optBoolean("drawCornerConcaveVertices", app.bridge().settingsVC().drawCornerConcaveVertices())); app.bridge().settingsVC().setDrawCornerConvexVertices(json.optBoolean("drawCornerConvexVertices", app.bridge().settingsVC().drawCornerConvexVertices())); app.bridge().settingsVC().setDrawMajorVertices(json.optBoolean("drawMajorVertices", app.bridge().settingsVC().drawMajorVertices())); app.bridge().settingsVC().setDrawMinorVertices(json.optBoolean("drawMinorVertices", app.bridge().settingsVC().drawMinorVertices())); app.bridge().settingsVC().setDrawInnerVertices(json.optBoolean("drawInnerVertices", app.bridge().settingsVC().drawInnerVertices())); app.bridge().settingsVC().setDrawLeftVertices(json.optBoolean("drawLeftVertices", app.bridge().settingsVC().drawLeftVertices())); app.bridge().settingsVC().setDrawOuterVertices(json.optBoolean("drawOuterVertices", app.bridge().settingsVC().drawOuterVertices())); app.bridge().settingsVC().setDrawPerimeterVertices(json.optBoolean("drawPerimeterVertices", app.bridge().settingsVC().drawPerimeterVertices())); app.bridge().settingsVC().setDrawRightVertices(json.optBoolean("drawRightVertices", app.bridge().settingsVC().drawRightVertices())); app.bridge().settingsVC().setDrawTopVertices(json.optBoolean("drawTopVertices", app.bridge().settingsVC().drawTopVertices())); app.bridge().settingsVC().setDrawCenterVertices(json.optBoolean("drawCenterVertices", app.bridge().settingsVC().drawCenterVertices())); app.bridge().settingsVC().setDrawPhasesVertices(json.optBoolean("drawPhasesVertices", app.bridge().settingsVC().drawPhasesVertices())); app.bridge().settingsVC().setDrawCornerEdges(json.optBoolean("drawCornerEdges", app.bridge().settingsVC().drawCornerEdges())); app.bridge().settingsVC().setDrawCornerConcaveEdges(json.optBoolean("drawCornerConcaveEdges", app.bridge().settingsVC().drawCornerConcaveEdges())); app.bridge().settingsVC().setDrawCornerConvexEdges(json.optBoolean("drawCornerConvexEdges", app.bridge().settingsVC().drawCornerConvexEdges())); app.bridge().settingsVC().setDrawMajorEdges(json.optBoolean("drawMajorEdges", app.bridge().settingsVC().drawMajorEdges())); app.bridge().settingsVC().setDrawMinorEdges(json.optBoolean("drawMinorEdges", app.bridge().settingsVC().drawMinorEdges())); app.bridge().settingsVC().setDrawBottomEdges(json.optBoolean("drawBottomEdges", app.bridge().settingsVC().drawBottomEdges())); app.bridge().settingsVC().setDrawInnerEdges(json.optBoolean("drawInnerEdges", app.bridge().settingsVC().drawInnerEdges())); app.bridge().settingsVC().setDrawLeftEdges(json.optBoolean("drawLeftEdges", app.bridge().settingsVC().drawLeftEdges())); app.bridge().settingsVC().setDrawOuterEdges(json.optBoolean("drawOuterEdges", app.bridge().settingsVC().drawOuterEdges())); app.bridge().settingsVC().setDrawPerimeterEdges(json.optBoolean("drawPerimeterEdges", app.bridge().settingsVC().drawPerimeterEdges())); app.bridge().settingsVC().setDrawRightEdges(json.optBoolean("drawRightEdges", app.bridge().settingsVC().drawRightEdges())); app.bridge().settingsVC().setDrawTopEdges(json.optBoolean("drawTopEdges", app.bridge().settingsVC().drawTopEdges())); app.bridge().settingsVC().setDrawCentreEdges(json.optBoolean("drawCentreEdges", app.bridge().settingsVC().drawCentreEdges())); app.bridge().settingsVC().setDrawPhasesEdges(json.optBoolean("drawPhasesEdges", app.bridge().settingsVC().drawPhasesEdges())); app.bridge().settingsVC().setDrawDistanceEdges(json.optBoolean("drawDistanceEdges", app.bridge().settingsVC().drawDistanceEdges())); app.bridge().settingsVC().setDrawAxialEdges(json.optBoolean("drawAxialEdges", app.bridge().settingsVC().drawAxialEdges())); app.bridge().settingsVC().setDrawHorizontalEdges(json.optBoolean("drawHorizontalEdges", app.bridge().settingsVC().drawHorizontalEdges())); app.bridge().settingsVC().setDrawVerticalEdges(json.optBoolean("drawVerticalEdges", app.bridge().settingsVC().drawVerticalEdges())); app.bridge().settingsVC().setDrawAngledEdges(json.optBoolean("drawAngledEdges", app.bridge().settingsVC().drawAngledEdges())); app.bridge().settingsVC().setDrawSlashEdges(json.optBoolean("drawSlashEdges", app.bridge().settingsVC().drawSlashEdges())); app.bridge().settingsVC().setDrawSloshEdges(json.optBoolean("drawSloshEdges", app.bridge().settingsVC().drawSloshEdges())); app.bridge().settingsVC().setDrawNeighboursVertices(json.optBoolean("drawNeighboursVertices", app.bridge().settingsVC().drawNeighboursVertices())); app.bridge().settingsVC().setDrawRadialsVertices(json.optBoolean("drawRadialsVertices", app.bridge().settingsVC().drawRadialsVertices())); app.bridge().settingsVC().setDrawDistanceVertices(json.optBoolean("drawDistanceVertices", app.bridge().settingsVC().drawDistanceVertices())); app.bridge().settingsVC().setShowCandidateValues(json.optBoolean("CandidateMoves", app.bridge().settingsVC().showCandidateValues())); //app.bridge().settingsVC().setAbstractPriority(json.optBoolean("abstractPriority", app.bridge().settingsVC().abstractPriority())); app.bridge().settingsVC().setCoordWithOutline(json.optBoolean("coordWithOutline", app.bridge().settingsVC().coordWithOutline())); // Settings Network app.manager().settingsNetwork().setLoginUsername(json.optString("LoginUsername", app.manager().settingsNetwork().loginUsername())); app.manager().settingsNetwork().setRememberDetails(json.optBoolean("RememberDetails", app.manager().settingsNetwork().rememberDetails())); // Load last-selected filepaths in filechoosers DesktopApp.setLastSelectedJsonPath(json.optString("LastSelectedJsonFile", DesktopApp.lastSelectedJsonPath())); DesktopApp.setLastSelectedJarPath(json.optString("LastSelectedJarFile", DesktopApp.lastSelectedJarPath())); DesktopApp.setLastSelectedAiDefPath(json.optString("LastSelectedAiDefFile", DesktopApp.lastSelectedAiDefPath())); DesktopApp.setLastSelectedGamePath(json.optString("LastSelectedGameFile", DesktopApp.lastSelectedGamePath())); DesktopApp.setLastSelectedSaveGamePath(json.optString("LastSelectedSaveGameFile", DesktopApp.lastSelectedSaveGamePath())); DesktopApp.setLastSelectedLoadTrialPath(json.optString("LastSelectedLoadTrialFile", DesktopApp.lastSelectedLoadTrialPath())); DesktopApp.setLastSelectedLoadTournamentPath(json.optString("LastSelectedLoadTournamentFile", DesktopApp.lastSelectedLoadTournamentPath())); // Recent games for (int p = 0; p < app.settingsPlayer().recentGames().length; p++) if (json.has("RecentGames_" + p)) app.settingsPlayer().recentGames()[p] = json.optString("RecentGames_" + p, app.settingsPlayer().recentGames()[p]); // load the frame preferences final int frameWidth = json.optInt("FrameWidth", SettingsDesktop.defaultWidth); final int frameHeight = json.optInt("FrameHeight", SettingsDesktop.defaultHeight); final int frameX = json.optInt("FrameLocX", app.settingsPlayer().defaultX()); final int frameY = json.optInt("FrameLocY", app.settingsPlayer().defaultY()); final Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); if ((frameX + frameWidth <= screenSize.getWidth()) && (frameY + frameHeight <= screenSize.getHeight())) { SettingsDesktop.defaultWidth = frameWidth; SettingsDesktop.defaultHeight = frameHeight; app.settingsPlayer().setDefaultX(frameX); app.settingsPlayer().setDefaultY(frameY); } // Load the AI preferences for (int p = 0; p < app.manager().aiSelected().length; ++p) { app.manager().aiSelected()[p].setName(json.optString("Names_" + p, app.manager().aiSelected()[p].name())); try { final JSONObject jsonAI = json.optJSONObject("AI_" + p); AIRegistry.processJson(jsonAI); if (jsonAI != null) { app.manager().aiSelected()[p] = new AIDetails(app.manager(), jsonAI, p, json.optString("MenuNames_" + p, app.manager().aiSelected()[p].menuItemName())); app.manager().aiSelected()[p].setThinkTime(json.optDouble("SearchTime_" + p, app.manager().aiSelected()[p].thinkTime())); } } catch (final Exception error) { // invalid AI error.printStackTrace(); } } // Game specific preferences final Iterator<?> keysToCopyIterator = json.keys(); final List<String> keysList = new ArrayList<>(); while (keysToCopyIterator.hasNext()) { final String key = (String) keysToCopyIterator.next(); keysList.add(key); } final String[] keysArray = keysList.toArray(new String[keysList.size()]); for (int i = 0; i < keysArray.length; i++) { // game turn limits if (keysArray[i].length() > 7 && keysArray[i].substring(0, 7).contentEquals("MAXTURN")) { app.manager().settingsManager().setTurnLimit(keysArray[i].substring(7), json.optInt(keysArray[i], app.manager().settingsManager().turnLimit(keysArray[i].substring(7)))); } // game piece style. if (keysArray[i].length() > 11 && keysArray[i].substring(0, 11).contentEquals("PIECEFAMILY")) { app.bridge().settingsVC().setPieceFamily ( keysArray[i].substring(11), json.optString(keysArray[i], app.bridge().settingsVC().pieceFamily(keysArray[i].substring(11))) ); } } app.manager().settingsNetwork().backupAiPlayers(app.manager()); app.settingsPlayer().setPreferencesLoaded(true); } catch (final Exception e) { //e.printStackTrace(); // Problem loading preferences System.out.println("Loading default preferences."); // Try to delete preferences final File brokenPreferences = new File("." + File.separator + "ludii_preferences.json"); brokenPreferences.delete(); } } //------------------------------------------------------------------------- }
36,058
56.236508
174
java
Ludii
Ludii-master/PlayerDesktop/src/kilothon/Kilothon.java
package kilothon; import java.io.File; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Properties; import javax.activation.DataHandler; import javax.activation.DataSource; import javax.activation.FileDataSource; import javax.mail.BodyPart; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.Multipart; import javax.mail.PasswordAuthentication; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeBodyPart; import javax.mail.internet.MimeMessage; import javax.mail.internet.MimeMultipart; import game.Game; import main.Constants; import main.FileHandling; import main.StringRoutines; import main.UnixPrintWriter; import manager.ai.AIRegistry; import other.AI; import other.GameLoader; import other.RankUtils; import other.context.Context; import other.model.Model; import other.trial.Trial; import utils.AIFactory; /** * To start a kilothon without a GUI (beat a weak ai on all games and send report to a mail). * Note: All games except, match, hidden information, simultaneous games or simulation games. * * @author Eric.Piette */ public class Kilothon { /** * Method to run a kilothon * @param args 1-Login 2-AgentName */ @SuppressWarnings("resource") public static void main(final String[] args) { final String login = args.length == 0 ? "No Name" : args[0]; final String agentName = args.length < 2 ? "UCT" : args[1]; final double startTime = System.currentTimeMillis(); final double timeToThink = 60000; // Time for the challenger to think smartly (in ms). final int movesLimitPerPlayer = 500; // Max number of moves per player. final int numGamesToPlay = Constants.INFINITY; // Infinity is all games. double sumUtilities = 0; int numWins = 0; int sumNumMoves = 0; int sumP1Moves = 0; System.out.println("Kilothon is starting. Login = " + login + " Agent = " + agentName + "\n"); // Get the list of games. final String[] gameList = FileHandling.listGames(); final ArrayList<String> validChoices = new ArrayList<>(); for (final String s : gameList) { if (s.contains("/lud/plex")) continue; if (s.contains("/lud/wip")) continue; if (s.contains("/lud/wishlist")) continue; if (s.contains("/lud/reconstruction")) continue; if (s.contains("/lud/WishlistDLP")) continue; if (s.contains("/lud/test")) continue; if (s.contains("/res/lud/bad")) continue; if (s.contains("/res/lud/bad_playout")) continue; validChoices.add(s); } // Random order for the games. Collections.shuffle(validChoices); int idGame = 0; // index of the game. final String output = "KilothonResults.csv"; try (final PrintWriter writer = new UnixPrintWriter(new File(output), "UTF-8")) { final List<String> header = new ArrayList<String>(); header.add("GAME NAME"); // game name header.add("NUM PLAYERS"); // num players header.add("WIN?"); // 1 if winning header.add("RANK P1"); // ranking of P1 header.add("UTILITY P1"); // reward of P1 header.add("NUM MOVES"); // game length header.add("NUM P1 MOVES"); // number of P1 moves writer.println(StringRoutines.join(",", header)); for (final String gameName : validChoices) { final Game game = GameLoader.loadGameFromName(gameName); final int numPlayers = game.players().count(); // look only the games we want in the Kilothon. if(!game.hasSubgames() && !game.hiddenInformation() && !game.isSimultaneousMoveGame() && !game.isSimulationMoveGame()) { idGame++; System.out.println("game " + idGame + ": " + game.name() + " is running"); // Set the AIs. final List<AI> ais = new ArrayList<AI>(); ais.add(null); for(int pid = 1; pid <= numPlayers; pid++) { if(pid == 1) { final AI challenger = AIRegistry.fromRegistry(agentName); ais.add(challenger); } else if(pid == 2) { AI UCT = AIFactory.createAI("UCT"); UCT.setMaxSecondsPerMove(0.5); ais.add(UCT); } else ais.add(new utils.RandomAI()); } // Start the game. game.setMaxMoveLimit(numPlayers*movesLimitPerPlayer); // Limit of moves per player. final Context context = new Context(game, new Trial(game)); final Trial trial = context.trial(); game.start(context); // Init the ais. for (int p = 1; p <= game.players().count(); ++p) ais.get(p).initAI(game, p); final Model model = context.model(); // Run the game. int numP1Moves = 0; double remainingTimeP1 = timeToThink; // One minute double remainingTimeP2 = timeToThink; // One minute while (!trial.over()) { final int mover = context.state().mover(); final double thinkingTime = (mover == 1) ? ais.get(1).maxSecondsPerMove() : (mover == 2) ? ais.get(2).maxSecondsPerMove() : 1.0; final double time = System.currentTimeMillis(); model.startNewStep(context, ais, thinkingTime); final double timeUsed = System.currentTimeMillis() - time; // We check the remaining time to be able to think smartly for the challenger. if(remainingTimeP1 > 0) { if(mover == 1) { remainingTimeP1 = remainingTimeP1 - timeUsed; if(remainingTimeP1 <= 0) { System.out.println("switch P1 to Random at move number " + trial.numberRealMoves()); ais.get(1).closeAI(); ais.set(1, new utils.RandomAI()); ais.get(1).initAI(game, 1); } } } // We check the remaining time to be able to think smartly for the "smart" opponent. if(remainingTimeP2 > 0) { if(mover == 2) { remainingTimeP2 = remainingTimeP2 - timeUsed; if(remainingTimeP2 <= 0) { System.out.println("switch P2 to Random at move number " + trial.numberRealMoves()); ais.get(2).closeAI(); ais.set(2, new utils.RandomAI()); ais.get(2).initAI(game, 2); } } } if(context.state().mover() == 1) numP1Moves++; } // Get results. final double numMoves = trial.numberRealMoves(); final double rankingP1 = trial.ranking()[1]; final boolean win = rankingP1 == 1; final double rewardP1 = RankUtils.rankToUtil(rankingP1, numPlayers); System.out.println("Reward of P1 = " + rewardP1 + " (ranking = " + rankingP1 + ") finished in " + trial.numberRealMoves() + " moves."); System.out.println("\n**************NEXT GAME***********\n"); sumUtilities += rewardP1; sumNumMoves += numMoves; sumP1Moves += numP1Moves; if(win) numWins++; final List<String> lineToWrite = new ArrayList<String>(); lineToWrite.add(game.name() + ""); // game name lineToWrite.add(game.players().count() + ""); // num players lineToWrite.add(win + ""); // 1 if winning lineToWrite.add(rankingP1 + ""); // ranking of P1 lineToWrite.add(rewardP1 + ""); // reward of P1 lineToWrite.add(numMoves + ""); // game length lineToWrite.add(numP1Moves + ""); // num P1 moves writer.println(StringRoutines.join(",", lineToWrite)); } if((idGame + 1) > numGamesToPlay) // To stop the kilothon after a specific number of games (for test). break; } } catch (final FileNotFoundException | UnsupportedEncodingException e) { e.printStackTrace(); } final double kilothonTime = System.currentTimeMillis() - startTime; int seconds = (int) (kilothonTime / 1000) % 60 ; int minutes = (int) ((kilothonTime / (1000*60)) % 60); int hours = (int) ((kilothonTime / (1000*60*60)) % 24); System.out.println("\nKilothon done in " + hours + " hours " + minutes + " minutes " + seconds + " seconds."); System.out.println("........Computation of the results...."); // Sent results. String to = "[email protected]"; String from = "[email protected]"; Properties properties = System.getProperties(); properties = new Properties(); properties.put("mail.smtp.user", from); properties.put("mail.smtp.host", "smtp.gmail.com"); properties.put("mail.smtp.port", "587"); properties.put("mail.smtp.starttls.enable","true"); properties.put("mail.smtp.debug", "true"); properties.put("mail.smtp.auth", "true"); properties.put("mail.smtp.socketFactory.port", "587"); properties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); properties.put("mail.smtp.socketFactory.fallback", "false"); // creating session object to get properties Session session = Session.getInstance(properties, new javax.mail.Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(from, "sendResultCompetition"); } }); try { // MimeMessage object. MimeMessage message = new MimeMessage(session); // Set Subject: subject of the email message.setSubject("Results of kilothon"); // Set From Field: adding senders email to from field. message.setFrom(new InternetAddress(from)); // Make the body message. BodyPart messageBodyPart1 = new MimeBodyPart(); String bodyMsg = "Kilothon run by " + login; bodyMsg += "\nAgent name = " + agentName; bodyMsg += "\nSmart thinking time (in ms) = " + timeToThink; bodyMsg += "\nMoves limit per player = " + movesLimitPerPlayer; bodyMsg += "\nGames played = " + idGame; bodyMsg += "\nAVG utility = " + (sumUtilities/idGame); bodyMsg += "\nNum Wins = " + numWins; bodyMsg += "\nAVG Wins = " + ((double)numWins/(double)idGame) *100.0 + " %"; bodyMsg += "\nNum Moves = " + sumNumMoves; bodyMsg += "\nAVG Moves = " + (sumNumMoves/idGame); bodyMsg += "\nNum P1 Moves = " + sumP1Moves; bodyMsg += "\nAVG P1 Moves = " + (sumP1Moves/idGame); bodyMsg += "\nDone in " + hours + " hours " + minutes + " minutes " + seconds + " seconds."; messageBodyPart1.setText(bodyMsg); // Add the attachment. MimeBodyPart messageBodyPart2 = new MimeBodyPart(); DataSource source = new FileDataSource(output); messageBodyPart2.setDataHandler(new DataHandler(source)); messageBodyPart2.setFileName(output); // Set up the full message. Multipart multipart = new MimeMultipart(); multipart.addBodyPart(messageBodyPart1); multipart.addBodyPart(messageBodyPart2); message.setContent(multipart); // Set To Field: adding recipient's email to from field. message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); // Send email. Transport transport = session.getTransport("smtps"); transport.connect("smtp.gmail.com", 465, from, "sendResultCompetition"); transport.sendMessage(message, message.getAllRecipients()); transport.close(); System.out.println("Mail successfully sent! Congratulations to have played a complete kilothon!"); } catch (MessagingException mex) { mex.printStackTrace(); } } }
11,755
34.732523
141
java
Ludii
Ludii-master/PlayerDesktop/src/kilothon/KilothonGUI.java
package kilothon; import java.io.File; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Properties; import javax.activation.DataHandler; import javax.activation.DataSource; import javax.activation.FileDataSource; import javax.mail.BodyPart; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.Multipart; import javax.mail.PasswordAuthentication; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeBodyPart; import javax.mail.internet.MimeMessage; import javax.mail.internet.MimeMultipart; import app.DesktopApp; import game.Game; import main.Constants; import main.FileHandling; import main.StringRoutines; import main.UnixPrintWriter; import other.GameLoader; import other.RankUtils; import other.trial.Trial; /** * To start a kilothon with a GUI (beat a weak ai on all games and send report to a mail). * Note: All games except, match, hidden information, simultaneous games or simulation games. * * @author Eric.Piette */ public class KilothonGUI { /** * Main method * @param args */ @SuppressWarnings("resource") public static void main(final String[] args) { final double startTime = System.currentTimeMillis(); final int sleepTime = 1; // Sleep time before to update the game (in ms). final double timeToThink = 60000; // Time for the challenger to think smartly (in ms). final int movesLimitPerPlayer = 200; // Max number of moves per player. final int numGamesToPlay = Constants.INFINITY; final String login = "Challenger"; double sumUtilities = 0; int sumNumMoves = 0; final DesktopApp app = new DesktopApp(); app.createDesktopApp(); final String[] choices = FileHandling.listGames(); final ArrayList<String> validChoices = new ArrayList<>(); for (final String s : choices) { if (s.contains("/lud/plex")) continue; if (s.contains("/lud/wip")) continue; if (s.contains("/lud/wishlist")) continue; if (s.contains("/lud/reconstruction")) continue; if (s.contains("/lud/WishlistDLP")) continue; if (s.contains("/lud/test")) continue; if (s.contains("/res/lud/bad")) continue; if (s.contains("/res/lud/bad_playout")) continue; validChoices.add(s); } // Random order for the games. Collections.shuffle(validChoices); int idGame = 0; // index of the game. final String output = "KilothonResults.csv"; try (final PrintWriter writer = new UnixPrintWriter(new File(output), "UTF-8")) { for (final String gameName : validChoices) { final Game game = GameLoader.loadGameFromName(gameName); final int numPlayers = game.players().count(); // look only the games we want in the Kilothon. if(!game.hasSubgames() && !game.hiddenInformation() && !game.isSimultaneousMoveGame() && !game.isSimulationMoveGame()) { idGame++; System.out.println("game " + idGame + ": " + game.name() + " is running"); // Start the game. final RunGame thread = new RunGame(app, gameName, numPlayers, movesLimitPerPlayer); double time = System.currentTimeMillis(); double remainingTime = timeToThink; // One minute // Run the game. thread.run(); while (!thread.isOver()) { try { Thread.sleep(sleepTime); if(remainingTime > 0) // We check the remaining time to be able to think smartly for the challenger. { final double timeUsed = System.currentTimeMillis() - time; if(thread.mover() == 1) // If that's the challenger we decrement the time used. { remainingTime = remainingTime - timeUsed; //System.out.println("remaining Time = " + remainingTime/1000 + " s"); } time = System.currentTimeMillis(); if(remainingTime <= 0) thread.setFirstPlayerToRandom(); } } catch (InterruptedException e) { e.printStackTrace(); } } // Print the results. final Trial trial = thread.trial(); final double numMoves = trial.numberRealMoves(); final double rankingP1 = trial.ranking()[1]; final double rewardP1 = RankUtils.rankToUtil(rankingP1, numPlayers); System.out.println("Reward of P1 = " + rewardP1 + " (ranking = " + rankingP1 + ") finished in " + trial.numberRealMoves() + " moves."); sumUtilities += rewardP1; sumNumMoves += numMoves; final List<String> lineToWrite = new ArrayList<String>(); lineToWrite.add(game.name() + ""); // game name lineToWrite.add(rankingP1 + ""); // ranking of P1 lineToWrite.add(rewardP1 + ""); // reward of P1 lineToWrite.add(numMoves + ""); // game length writer.println(StringRoutines.join(",", lineToWrite)); } if((idGame + 1) > numGamesToPlay) // To stop the kilothon after a specific number of games (for test). break; } } catch (final FileNotFoundException | UnsupportedEncodingException e) { e.printStackTrace(); } app.appClosedTasks(); final double kilothonTime = System.currentTimeMillis() - startTime; int seconds = (int) (kilothonTime / 1000) % 60 ; int minutes = (int) ((kilothonTime / (1000*60)) % 60); int hours = (int) ((kilothonTime / (1000*60*60)) % 24); System.out.println("Kilothon done in " + hours + " hours " + minutes + " minutes " + seconds + " seconds."); // Sent results. String to = "[email protected]"; String from = "[email protected]"; Properties properties = System.getProperties(); properties = new Properties(); properties.put("mail.smtp.user", from); properties.put("mail.smtp.host", "smtp.gmail.com"); properties.put("mail.smtp.port", "587"); properties.put("mail.smtp.starttls.enable","true"); properties.put("mail.smtp.debug", "true"); properties.put("mail.smtp.auth", "true"); properties.put("mail.smtp.socketFactory.port", "587"); properties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); properties.put("mail.smtp.socketFactory.fallback", "false"); // creating session object to get properties Session session = Session.getInstance(properties, new javax.mail.Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(from, "sendResultCompetition"); } }); try { // MimeMessage object. MimeMessage message = new MimeMessage(session); // Set Subject: subject of the email message.setSubject("Results of kilothon"); // Set From Field: adding senders email to from field. message.setFrom(new InternetAddress(from)); // Make the body message. BodyPart messageBodyPart1 = new MimeBodyPart(); String bodyMsg = "Kilothon run by " + login; bodyMsg += "\nAgent name = " + "UCT"; bodyMsg += "\nSmart thinking time (in ms) = " + timeToThink; bodyMsg += "\nMoves limit per player = " + movesLimitPerPlayer; bodyMsg += "\nGames played = " + idGame; bodyMsg += "\nAVG utility = " + (sumUtilities/idGame); bodyMsg += "\nNum Moves = " + sumNumMoves; bodyMsg += "\nAVG Moves = " + (sumNumMoves/idGame); bodyMsg += "\nDone in " + hours + " hours " + minutes + " minutes " + seconds + " seconds."; messageBodyPart1.setText(bodyMsg); // Add the attachment. MimeBodyPart messageBodyPart2 = new MimeBodyPart(); DataSource source = new FileDataSource(output); messageBodyPart2.setDataHandler(new DataHandler(source)); messageBodyPart2.setFileName(output); // Set up the full message. Multipart multipart = new MimeMultipart(); multipart.addBodyPart(messageBodyPart1); multipart.addBodyPart(messageBodyPart2); message.setContent(multipart); // Set To Field: adding recipient's email to from field. message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); // Send email. Transport transport = session.getTransport("smtps"); transport.connect("smtp.gmail.com", 465, from, "sendResultCompetition"); transport.sendMessage(message, message.getAllRecipients()); transport.close(); System.out.println("Mail successfully sent"); } catch (MessagingException mex) { mex.printStackTrace(); } } }
8,883
33.703125
141
java
Ludii
Ludii-master/PlayerDesktop/src/kilothon/RunGame.java
package kilothon; import static org.junit.Assert.fail; import java.awt.EventQueue; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import org.json.JSONObject; import app.PlayerApp; import app.loading.GameLoading; import app.utils.GameUtil; import manager.Manager; import manager.ai.AIDetails; import manager.ai.AIUtil; import other.trial.Trial; /** * Method used to run a game in the killothon. * * @author Eric.Piette */ public class RunGame extends Thread { /** The name of the game. */ private final String gameName; /** The number of players. */ private final int numPlayers; /** The limit of moves per player. */ private final int moveLimitPerPlayer; /** The graphical app used to show the game. */ private final PlayerApp app; /** * @param app The app. * @param name The game name. * @param numPlayers The number of players. */ public RunGame ( final PlayerApp app, final String name, final int numPlayers, final int moveLimit ) { this.app = app; gameName = name; this.numPlayers = numPlayers; this.moveLimitPerPlayer = moveLimit; } @Override public void run() { final Manager manager = app.manager(); try { EventQueue.invokeAndWait(() -> { GameLoading.loadGameFromName(app, gameName, new ArrayList<String>(), false); manager.ref().context().game().setMaxMoveLimit(numPlayers*moveLimitPerPlayer); // limit of moves per player. for(int pid = 1; pid <= numPlayers; pid++) { final String AIName = pid == 1 ? "UCT" : "Random"; final JSONObject json = new JSONObject().put("AI", new JSONObject().put("algorithm", AIName)); AIUtil.updateSelectedAI(app.manager(), json, pid, AIName); if (manager.aiSelected()[pid].ai() != null) manager.aiSelected()[pid].ai().closeAI(); manager.aiSelected()[pid] = new AIDetails(manager, json, pid, "Random"); } GameUtil.startGame(app); app.manager().settingsManager().setAgentsPaused(app.manager(), false); app.manager().ref().nextMove(app.manager(), false); }); } catch (InvocationTargetException | InterruptedException e) { e.printStackTrace(); fail(); } } /** * Set the first player to random. */ public void setFirstPlayerToRandom() { final Manager manager = app.manager(); final JSONObject json = new JSONObject().put("AI", new JSONObject().put("algorithm", "Random")); AIUtil.updateSelectedAI(app.manager(), json, 1, "Random"); if (manager.aiSelected()[1].ai() != null) manager.aiSelected()[1].ai().closeAI(); manager.aiSelected()[1] = new AIDetails(manager, json, 1, "Random"); app.manager().settingsManager().setAgentsPaused(app.manager(), false); app.manager().ref().nextMove(app.manager(), false); } /** * @return True if the game is over. */ public boolean isOver() { return app.manager().ref().context().trial().over(); } /** * @return The trial of the current game. */ public Trial trial() { return app.manager().ref().context().trial(); } /** * @return The current mover. */ public int mover() { return app.manager().ref().context().state().mover(); } }
3,192
23.007519
112
java
Ludii
Ludii-master/PlayerDesktop/src/test/gui/TestGUI.java
package test.gui; import static org.junit.Assert.fail; import java.awt.EventQueue; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.Collections; import org.junit.Test; import app.DesktopApp; import app.PlayerApp; import app.loading.GameLoading; import main.FileHandling; /** * Unit Test to run all the games and the gui on each of them. * * @author Eric.Piette */ public class TestGUI { @Test public void test() throws InterruptedException { System.out.println( "\n=========================================\nTest: Compile all .lud from memory and load the GUI:\n"); final DesktopApp app = new DesktopApp(); app.createDesktopApp(); final String[] choices = FileHandling.listGames(); final ArrayList<String> validChoices = new ArrayList<>(); for (final String s : choices) { if (!s.contains("/bad/") && !s.contains("/bad_playout/") && !s.contains("/test/") && !s.contains("/wip/") && !s.contains("/wishlist/")) { validChoices.add(s); } } Collections.shuffle(validChoices); final String gameToReach = ""; boolean reached = (gameToReach.equals("") ? true : false); for (final String gameName : validChoices) { if (reached) { final ThreadRunningGame thread = new ThreadRunningGame(app, gameName); thread.run(); while (!thread.isOver()) Thread.sleep(100); } else if (gameName.contains(gameToReach)) { reached = true; } } } /** * The thread running the game with the GUI. * * @author Eric.Piette */ public class ThreadRunningGame extends Thread { private final String gameName; private boolean over = false; private final PlayerApp app; public ThreadRunningGame(final PlayerApp app, final String name) { this.app = app; gameName = name; } @Override public void run() { try { EventQueue.invokeAndWait(() -> { System.out.println("TEST GUI FOR " + gameName); GameLoading.loadGameFromName(app, gameName, new ArrayList<String>(), false); app.manager().ref().context().game().toEnglish(app.manager().ref().context().game()); //InstructionGeneration.instructionGeneration(app); over = true; }); } catch (InvocationTargetException | InterruptedException e) { e.printStackTrace(); fail(); } } public boolean isOver() { return over; } } }
2,395
20.781818
108
java
Ludii
Ludii-master/PlayerDesktop/src/test/instructionGeneration/TestInstructionGeneration.java
package test.instructionGeneration; import static org.junit.Assert.fail; import java.awt.EventQueue; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import app.DesktopApp; import app.loading.GameLoading; import app.manualGeneration.ManualGeneration; import main.FileHandling; /** * Generates instruction websites for all games. * * @author Matthew.Stephenson */ public class TestInstructionGeneration { //------------------------------------------------------------------------- public void test() { System.out.println( "\n=========================================\nTest: Compile all .lud from memory and load the GUI:\n"); final DesktopApp app = new DesktopApp(); app.createDesktopApp(); final String[] choices = FileHandling.listGames(); final ArrayList<String> validChoices = new ArrayList<>(); for (final String s : choices) { if (!s.contains("/bad/") && !s.contains("/bad_playout/") && !s.contains("/test/") && !s.contains("/wip/") && !s.contains("/wishlist/")) { validChoices.add(s); } } final String gameToReach = ""; boolean reached = (gameToReach.equals("") ? true : false); for (final String gameName : validChoices) { if (reached) { final ThreadRunningGame thread = new ThreadRunningGame(app, gameName); thread.run(); while (!ManualGeneration.isProcessComplete()) { try { Thread.sleep(1000); } catch (final InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } else if (gameName.contains(gameToReach)) { reached = true; } } } //------------------------------------------------------------------------- /** * The thread generating the instructions for a game. * * @author Matthew.Stephenson */ public class ThreadRunningGame extends Thread { private final String gameName; private final DesktopApp app; public ThreadRunningGame(final DesktopApp app, final String name) { this.app = app; gameName = name; } @Override public void run() { try { EventQueue.invokeAndWait(() -> { System.out.println("TEST GUI FOR " + gameName); GameLoading.loadGameFromName(app, gameName, new ArrayList<String>(), false); ManualGeneration.manualGeneration(app); }); } catch (InvocationTargetException | InterruptedException e) { e.printStackTrace(); fail(); } } } //------------------------------------------------------------------------- public static void main(final String[] args) { final TestInstructionGeneration temp = new TestInstructionGeneration(); temp.test(); } //------------------------------------------------------------------------- }
2,778
21.778689
108
java
Ludii
Ludii-master/ViewController/src/bridge/Bridge.java
package bridge; import java.util.ArrayList; import controllers.Controller; import util.SettingsColour; import util.SettingsVC; import view.component.ComponentStyle; import view.container.ContainerStyle; /** * Bridge Object, for linking the ViewController entities (component/container styles/controllers) with the PlayerDesktop. * * @author Matthew.Stephenson */ public class Bridge { private PlatformGraphics graphicsRenderer; private final ArrayList<ContainerStyle> containerStyles = new ArrayList<>(); private final ArrayList<ComponentStyle> componentStyles = new ArrayList<>(); private final ArrayList<Controller> containerControllers = new ArrayList<>(); private final SettingsVC settingsVC = new SettingsVC(); private final SettingsColour settingsColour = new SettingsColour(); //------------------------------------------------------------------------- /** * Constructor. */ public Bridge() { } //------------------------------------------------------------------------- public void setGraphicsRenderer(final PlatformGraphics g) { graphicsRenderer = g; } public PlatformGraphics graphicsRenderer() { return graphicsRenderer; } //------------------------------------------------------------------------- public void addContainerStyle(final ContainerStyle containerStyle, final int index) { for (int i = containerStyles.size(); i <= index; i++) { containerStyles.add(null); } containerStyles.set(index, containerStyle); } public void clearContainerStyles() { containerStyles.clear(); } public ContainerStyle getContainerStyle(final int index) { return containerStyles.get(index); } public ArrayList<ContainerStyle> getContainerStyles() { return containerStyles; } //------------------------------------------------------------------------- public void addComponentStyle(final ComponentStyle componentStyle, final int index) { for (int i = componentStyles.size(); i <= index; i++) { componentStyles.add(null); } componentStyles.set(index, componentStyle); } public void clearComponentStyles() { componentStyles.clear(); } public ComponentStyle getComponentStyle(final int index) { return componentStyles.get(index); } public ArrayList<ComponentStyle> getComponentStyles() { return componentStyles; } //------------------------------------------------------------------------- public void addContainerController(final Controller containerController, final int index) { for (int i = containerControllers.size(); i <= index; i++) { containerControllers.add(null); } containerControllers.set(index, containerController); } public void clearContainerControllers() { containerControllers.clear(); } public Controller getContainerController(final int index) { return containerControllers.get(index); } public SettingsVC settingsVC() { return settingsVC; } public SettingsColour settingsColour() { return settingsColour; } //------------------------------------------------------------------------- }
3,072
22.105263
122
java
Ludii
Ludii-master/ViewController/src/bridge/PlatformGraphics.java
package bridge; import java.awt.Graphics2D; import java.awt.Point; import java.awt.geom.Rectangle2D; import org.jfree.graphics2d.svg.SVGGraphics2D; import other.context.Context; import other.location.Location; import util.ImageInfo; /** * Interface for linking with the Graphics of different platforms (e.g. PlayerDesktop/DesktopGraphics) * * @author Matthew.Stephenson */ public interface PlatformGraphics { /** * Returns the Full location of the component associated with the image clicked on. */ Location locationOfClickedImage(Point pt); /** * Draws a component based on the specified ImageInfo. * @param g2d * @param context * @param imageInfo */ void drawComponent(Graphics2D g2d, final Context context, ImageInfo imageInfo); /** * Draws the game board. * @param g2d * @param boardDimensions */ void drawBoard(final Context context, Graphics2D g2d, Rectangle2D boardDimensions); /** * Draws the game board's graph. * @param g2d * @param boardDimensions */ void drawGraph(final Context context, Graphics2D g2d, Rectangle2D boardDimensions); /** * * @param g2d * @param boardDimensions */ void drawConnections(final Context context, Graphics2D g2d, Rectangle2D boardDimensions); /** * Draws a single specified image. * @param componentStyle */ void drawSVG(final Context context, Graphics2D g2d, SVGGraphics2D svg, ImageInfo imageInfo); }
1,420
22.683333
102
java
Ludii
Ludii-master/ViewController/src/bridge/ViewControllerFactory.java
package bridge; import controllers.BaseController; import controllers.container.BasicController; import controllers.container.PyramidalController; import game.equipment.component.Component; import game.equipment.container.Container; import metadata.graphics.util.ComponentStyleType; import metadata.graphics.util.ContainerStyleType; import metadata.graphics.util.ControllerType; import other.context.Context; import view.component.ComponentStyle; import view.component.custom.CardStyle; import view.component.custom.DieStyle; import view.component.custom.ExtendedShogiStyle; import view.component.custom.ExtendedXiangqiStyle; import view.component.custom.NativeAmericanDiceStyle; import view.component.custom.PieceStyle; import view.component.custom.large.DominoStyle; import view.component.custom.large.LargePieceStyle; import view.component.custom.large.TileStyle; import view.container.ContainerStyle; import view.container.styles.BoardStyle; import view.container.styles.HandStyle; import view.container.styles.board.BackgammonStyle; import view.container.styles.board.BoardlessStyle; import view.container.styles.board.ChessStyle; import view.container.styles.board.Connect4Style; import view.container.styles.board.ConnectiveGoalStyle; import view.container.styles.board.GoStyle; import view.container.styles.board.HoundsAndJackalsStyle; import view.container.styles.board.IsometricStyle; import view.container.styles.board.JanggiStyle; import view.container.styles.board.LascaStyle; import view.container.styles.board.MancalaStyle; import view.container.styles.board.ShibumiStyle; import view.container.styles.board.ShogiStyle; import view.container.styles.board.SnakesAndLaddersStyle; import view.container.styles.board.SpiralStyle; import view.container.styles.board.SurakartaStyle; import view.container.styles.board.TableStyle; import view.container.styles.board.TaflStyle; import view.container.styles.board.UltimateTicTacToeStyle; import view.container.styles.board.XiangqiStyle; import view.container.styles.board.graph.GraphStyle; import view.container.styles.board.graph.PenAndPaperStyle; import view.container.styles.board.puzzle.FutoshikiStyle; import view.container.styles.board.puzzle.HashiStyle; import view.container.styles.board.puzzle.KakuroStyle; import view.container.styles.board.puzzle.PuzzleStyle; import view.container.styles.board.puzzle.SudokuStyle; import view.container.styles.hand.DeckStyle; import view.container.styles.hand.DiceStyle; /** * Factory for creating specified graphics Style for an Item. * @author matthew.stephenson and cambolbro */ public class ViewControllerFactory { public static ContainerStyle createStyle ( final Bridge bridge, final Container container, final ContainerStyleType type, final Context context ) { if (type == null) return new BoardStyle(bridge, container); switch(type) { // core types case Board: return new BoardStyle(bridge, container); case Hand: return new HandStyle(bridge, container); case Deck: return new DeckStyle(bridge, container); case Dice: return new DiceStyle(bridge, container); // puzzle types case Puzzle: return new PuzzleStyle(bridge, container, context); case Sudoku: return new SudokuStyle(bridge, container, context); case Kakuro: return new KakuroStyle(bridge, container, context); case Futoshiki: return new FutoshikiStyle(bridge, container, context); case Hashi: return new HashiStyle(bridge, container, context); // graph types case Graph: return new GraphStyle(bridge, container, context); case PenAndPaper: return new PenAndPaperStyle(bridge, container, context); // custom types case Backgammon: return new BackgammonStyle(bridge, container); case Boardless: return new BoardlessStyle(bridge, container); case Chess: return new ChessStyle(bridge, container, context); case ConnectiveGoal: return new ConnectiveGoalStyle(bridge, container); case Go: return new GoStyle(bridge, container); case HoundsAndJackals: return new HoundsAndJackalsStyle(bridge, container); case Janggi: return new JanggiStyle(bridge, container); case Lasca: return new LascaStyle(bridge, container); case Mancala: return new MancalaStyle(bridge, container); case Shibumi: return new ShibumiStyle(bridge, container); case Shogi: return new ShogiStyle(bridge, container); case SnakesAndLadders: return new SnakesAndLaddersStyle(bridge, container); case Tafl: return new TaflStyle(bridge, container); case Xiangqi: return new XiangqiStyle(bridge, container); case Connect4: return new Connect4Style(bridge, container); case Spiral: return new SpiralStyle(bridge, container); case Surakarta: return new SurakartaStyle(bridge, container); case UltimateTicTacToe: return new UltimateTicTacToeStyle(bridge, container); case Isometric: return new IsometricStyle(bridge, container); case Table: return new TableStyle(bridge, container); default: return new BoardStyle(bridge, container); } } //------------------------------------------------------------------------- public static ComponentStyle createStyle ( final Bridge bridge, final Component component, final ComponentStyleType type ) { if (type == null) return new PieceStyle(bridge, component); switch(type) { case Piece: return new PieceStyle(bridge, component, false); case Text: return new PieceStyle(bridge, component, true); case Card: return new CardStyle(bridge, component); case Die: return new DieStyle(bridge, component); case Domino: return new DominoStyle(bridge, component); case Tile: return new TileStyle(bridge, component); case LargePiece: return new LargePieceStyle(bridge, component); case ExtendedShogi: return new ExtendedShogiStyle(bridge, component); case ExtendedXiangqi: return new ExtendedXiangqiStyle(bridge, component); case NativeAmericanDice: return new NativeAmericanDiceStyle(bridge, component); default: return new PieceStyle(bridge, component); } } //------------------------------------------------------------------------- public static BaseController createController(final Bridge bridge, final Container container, final ControllerType type) { if (type == null) return new BasicController(bridge, container); switch(type) { case BasicController: return new BasicController(bridge, container); case PyramidalController: return new PyramidalController(bridge, container); default: return new BasicController(bridge, container); } } //------------------------------------------------------------------------- }
6,702
31.697561
122
java
Ludii
Ludii-master/ViewController/src/controllers/BaseController.java
package controllers; import java.awt.Point; import java.awt.geom.Point2D; import java.util.ArrayList; import java.util.List; import bridge.Bridge; import game.equipment.container.Container; import game.types.board.SiteType; import main.Constants; import main.math.MathRoutines; import metadata.graphics.util.PieceStackType; import metadata.graphics.util.StackPropertyType; import other.context.Context; import other.location.FullLocation; import other.location.Location; import other.move.Move; import other.state.container.ContainerState; import other.topology.TopologyElement; import other.topology.Vertex; import util.StackVisuals; import util.WorldLocation; import view.container.ContainerStyle; /** * Implementation of container controllers. * * @author matthew.stephenson and mrraow and cambolbro */ public abstract class BaseController implements Controller { protected final Container container; protected Bridge bridge; //------------------------------------------------------------------------- /** * @param container */ public BaseController(final Bridge bridge, final Container container) { this.container = container; this.bridge = bridge; } //------------------------------------------------------------------------- /** * @return The nearest Location for a given point, based on all possible locations. */ @Override public Location calculateNearestLocation(final Context context, final Point pt, final List<Location> legalLocations) { // Calculate information for all moves that could be made final ArrayList<WorldLocation> allLocations = new ArrayList<>(); final ContainerStyle containerStyle = bridge.getContainerStyle(container.index()); final ContainerState cs = context.state().containerStates()[container.index()]; for (final Location location : legalLocations) { try { final int stackSize = cs.sizeStack(location.site(), location.siteType()); final TopologyElement graphElement = bridge.getContainerStyle(container.index()).drawnGraphElement(location.site(), location.siteType()); final PieceStackType componentStackType = PieceStackType.getTypeFromValue((int) context.metadata().graphics().stackMetadata(context, container, location.site(), location.siteType(), cs.state(location.site(), location.level(), location.siteType()), cs.value(location.site(), location.level(), location.siteType()), StackPropertyType.Type)); final Point2D.Double offsetDistance = StackVisuals.calculateStackOffset(bridge, context,container, componentStackType, containerStyle.cellRadiusPixels(), location.level(), location.site(), location.siteType(), stackSize, cs.state(location.site(), location.level(), location.siteType()), cs.value(location.site(), location.level(), location.siteType())); final Point2D clickablePosition = new Point2D.Double(graphElement.centroid().getX() + offsetDistance.getX()/containerStyle.placement().getWidth(), graphElement.centroid().getY() - offsetDistance.getY()/containerStyle.placement().getHeight()); if (legalLocations == null || legalLocations.contains(new FullLocation(location.site(), location.level(), location.siteType()))) allLocations.add(new WorldLocation(new FullLocation(location.site(), location.level(), location.siteType()), clickablePosition)); } catch (final Exception E) { // Probably just an invalid location for this container. } } return translateClicktoSite(pt, context, allLocations); } //------------------------------------------------------------------------- /** * Return the maximum distance that a click can be from a graph element. */ private double calculateFurthestDistance(final Context context) { double furthestPossibleDistance = 0; ContainerStyle containerStyle = bridge.getContainerStyle(container.index()); if (containerStyle.ignorePieceSelectionLimit()) { if (containerStyle.placement() != null) furthestPossibleDistance = Math.max(containerStyle.placement().getWidth(), containerStyle.placement().getHeight()); } else { final double furthestDistanceMultiplier = bridge.settingsVC().furthestDistanceMultiplier(); containerStyle = bridge.getContainerStyle(container.index()); final double cellDistance = containerStyle.cellRadiusPixels() * furthestDistanceMultiplier; furthestPossibleDistance = Math.max(furthestPossibleDistance, cellDistance); } return furthestPossibleDistance; } //------------------------------------------------------------------------- /** * Returns the Location for the site closest to pt, which was also in the legal Moves. */ protected Location translateClicktoSite(final Point pt, final Context context, final ArrayList<WorldLocation> validLocations) { Location location = bridge.graphicsRenderer().locationOfClickedImage(pt); for (final WorldLocation w : validLocations) if (w.location().equals(location)) return location; location = new FullLocation(Constants.UNDEFINED); final ContainerStyle containerStyle = bridge.getContainerStyle(container.index()); final double furthestPossibleDistance = calculateFurthestDistance(context); // if image not selected, then determine the closest site double minDist = 1000.0; for (int i = 0; i < validLocations.size(); i++) { double dist = 99999; final int site = validLocations.get(i).location().site(); if (validLocations.get(i).location().siteType() == SiteType.Edge) { if (validLocations.get(i).location().site() < context.board().topology().edges().size()) { final Vertex va = context.board().topology().edges().get(validLocations.get(i).location().site()).vA(); final Vertex vb = context.board().topology().edges().get(validLocations.get(i).location().site()).vB(); final Point vaPoint = containerStyle.screenPosn(containerStyle.drawnVertices().get(va.index()).centroid()); final Point vbPoint = containerStyle.screenPosn(containerStyle.drawnVertices().get(vb.index()).centroid()); final Point2D.Double vaPointDouble = new Point2D.Double(vaPoint.getX(),vaPoint.getY()); final Point2D.Double vbPointDouble = new Point2D.Double(vbPoint.getX(),vbPoint.getY()); final Point2D.Double clickedPoint = new Point2D.Double(pt.getX(), pt.getY()); dist = MathRoutines.distanceToLineSegment(clickedPoint, vaPointDouble, vbPointDouble); dist += bridge.getContainerStyle(container.index()).cellRadiusPixels() / 4; } } else { final Point sitePosn = containerStyle.screenPosn(validLocations.get(i).position()); final int dx = pt.x - sitePosn.x; final int dy = pt.y - sitePosn.y; dist = Math.sqrt(dx * dx + dy * dy); // Check if any large pieces are selected // final ContainerState cs = context.state().containerStates()[container.index()]; // if (validLocations.get(i).location().siteType().equals(SiteType.Cell) && validLocations.get(i).location().level() == 0) // { // final int localState = cs.state(site, 0, SiteType.Cell); // for (final Component component : context.equipment().components()) // { // for (final Integer cellIndex : ContainerUtil.cellsCoveredByPiece(context, container, component, site, localState)) // { // sitePosn = containerStyle.screenPosn(context.board().topology().cells().get(cellIndex).centroid()); // dx = pt.x - sitePosn.x; // dy = pt.y - sitePosn.y; // dist = Math.min(dist, Math.sqrt(dx * dx + dy * dy)); // } // } // } } if (dist < minDist && dist < furthestPossibleDistance) { location = new FullLocation(site, validLocations.get(i).location().level(), validLocations.get(i).location().siteType()); minDist = dist; } } return location; } //------------------------------------------------------------------------- /** * @param m * @return * Returns whether the move involves a single edge */ public static boolean isEdgeMove(final Move m) { return (m.fromType() == SiteType.Edge && m.toType() == SiteType.Edge && m.from() == m.to()); } //------------------------------------------------------------------------- }
8,117
40.418367
357
java
Ludii
Ludii-master/ViewController/src/controllers/Controller.java
package controllers; import java.awt.Point; import java.util.List; import other.context.Context; import other.location.Location; /** * Controller interface for controlling piece movement. * * @author Matthew.Stephenson */ public interface Controller { Location calculateNearestLocation(Context context, Point pt, List<Location> legalLocations); }
356
18.833333
93
java
Ludii
Ludii-master/ViewController/src/controllers/container/BasicController.java
package controllers.container; import bridge.Bridge; import controllers.BaseController; import game.equipment.container.Container; /** * Basic controller for moving pieces. Used in most games. * * @author Matthew.Stephenson */ public class BasicController extends BaseController { public BasicController(final Bridge bridge, final Container container) { super(bridge, container); } }
397
19.947368
72
java
Ludii
Ludii-master/ViewController/src/controllers/container/PyramidalController.java
package controllers.container; import java.awt.Point; import java.util.ArrayList; import bridge.Bridge; import controllers.BaseController; import game.equipment.container.Container; import game.rules.play.moves.Moves; import gnu.trove.list.array.TIntArrayList; import other.action.Action; import other.action.ActionType; import other.context.Context; import other.location.FullLocation; import other.location.Location; import other.move.Move; import other.topology.Cell; import util.WorldLocation; import view.container.ContainerStyle; /** * Controller for pyramidal boards/games (e.g. Shibumi) * * @author Matthew.Stephenson */ public class PyramidalController extends BaseController { //------------------------------------------------------------------------- public PyramidalController(final Bridge bridge, final Container container) { super(bridge, container); } //------------------------------------------------------------------------- @Override protected Location translateClicktoSite(final Point pt, final Context context, final ArrayList<WorldLocation> allLocations) { Location location = super.translateClicktoSite(pt, context, allLocations); final Moves legal = context.moves(context); if (location.site() != -1) { final ContainerStyle containerStyle = bridge.getContainerStyle(container.index()); // If using a Shibumi board and have selected a piece, check that there are no add moves on the sites above it. int newCid = -1; final Cell selectedVertex = containerStyle.drawnCells().get(location.site()); final TIntArrayList possibleCid = new TIntArrayList(); for (final Cell vertex : containerStyle.drawnCells()) if (Math.abs(vertex.centroid().getX()-selectedVertex.centroid().getX()) < 0.001 && Math.abs(vertex.centroid().getY()-selectedVertex.centroid().getY()) < 0.001) possibleCid.add(vertex.index()); for (int m = 0; m < legal.moves().size(); m++) { Action decisionAction = null; final Move move = legal.moves().get(m); for (int a = 0; a < move.actions().size(); a++) { if (move.actions().get(a).isDecision()) { decisionAction = move.actions().get(a); break; } } if (decisionAction.actionType() == ActionType.Add) { for (int i = 0; i < possibleCid.size(); i++) { final int moveIndex = possibleCid.getQuick(i); if (decisionAction.from() == moveIndex && decisionAction.to() == moveIndex) { newCid = moveIndex; break; } } if (newCid != -1) { location = new FullLocation(newCid, location.level(), location.siteType()); break; } } } } return location; } //------------------------------------------------------------------------- }
2,789
28.0625
163
java
Ludii
Ludii-master/ViewController/src/util/ArrowUtil.java
package util; import java.awt.BasicStroke; import java.awt.Graphics2D; import java.awt.Stroke; /** * Function for drawing arrows on the view. * * @author Matthew.Stephenson */ public class ArrowUtil { /** * Helper method to draw a straight arrow. * https://stackoverflow.com/a/27461352/6735980 */ public static void drawArrow(final Graphics2D g2d, final int startX, final int startY, final int endX, final int endY, final int lineWidth, final int headWidth, final int headHeight) { final int dx = endX - startX; final int dy = endY - startY; final double D = Math.sqrt(dx * dx + dy * dy); double xm = D - headHeight; double xn = xm; double ym = headWidth; double yn = -headWidth; final double sin = dy / D; final double cos = dx / D; double x = xm * cos - ym * sin + startX; ym = xm * sin + ym * cos + startY; xm = x; x = xn * cos - yn * sin + startX; yn = xn * sin + yn * cos + startY; xn = x; final int[] xpoints = { endX, (int) xm, (int) xn }; final int[] ypoints = { endY, (int) ym, (int) yn }; final Stroke oldStroke = g2d.getStroke(); g2d.setStroke(new BasicStroke(lineWidth, BasicStroke.CAP_ROUND, BasicStroke.JOIN_MITER)); g2d.drawLine(startX, startY, (int) ((xm + xn) / 2), (int) ((ym + yn) / 2)); g2d.setStroke(oldStroke); g2d.fillPolygon(xpoints, ypoints, 3); } //------------------------------------------------------------------------- }
1,431
24.571429
119
java
Ludii
Ludii-master/ViewController/src/util/ContainerUtil.java
package util; import java.awt.geom.Point2D; import java.util.ArrayList; import java.util.List; import game.equipment.component.Component; import game.equipment.container.Container; import game.equipment.other.Regions; import game.types.board.SiteType; import gnu.trove.list.array.TIntArrayList; import main.Constants; import other.context.Context; import other.location.Location; import other.topology.Edge; import other.topology.Topology; import other.topology.TopologyElement; /** * Functions that assist with container graphics. * * @author Matthew.Stephenson and cambolbro */ public class ContainerUtil { /** * Get the container site that a specified location is on. */ public static int getContainerSite(final Context context, final int site, final SiteType graphElementType) { if (site == Constants.UNDEFINED) return Constants.UNDEFINED; if (graphElementType == SiteType.Cell) { final int contianerId = getContainerId(context, site, graphElementType); final int containerSite = site - context.sitesFrom()[contianerId]; return containerSite; } return site; } //------------------------------------------------------------------------- /** * Get the container index that a specified location is on. */ public static int getContainerId(final Context context, final int site, final SiteType graphElementType) { if (site == Constants.UNDEFINED) return Constants.UNDEFINED; // vertices and edges are only on board! if (graphElementType != SiteType.Cell) return context.board().index(); return context.containerId()[site]; } //------------------------------------------------------------------------- /** * Normalise the graph to fill the world space. */ public static void normaliseGraphElements(final Topology graph) { double minX = Double.POSITIVE_INFINITY; double minY = Double.POSITIVE_INFINITY; double maxX = Double.NEGATIVE_INFINITY; double maxY = Double.NEGATIVE_INFINITY; for (int i = 0; i < graph.vertices().size(); i++) { final Point2D centroid = graph.vertices().get(i).centroid(); final double cx = centroid.getX(); final double cy = centroid.getY(); if (cx < minX) minX = cx; if (cy < minY) minY = cy; if (cx > maxX) maxX = cx; if (cy > maxY) maxY = cy; } // Choose smallest range to normalise on double min = minX; double max = maxX; if (maxX - minX < maxY - minY) { min = minY; max = maxY; } // Normalise elements normaliseGraphElements((ArrayList<? extends TopologyElement>)graph.vertices(), min, max); normaliseGraphElements((ArrayList<? extends TopologyElement>)graph.edges(), min, max); normaliseGraphElements((ArrayList<? extends TopologyElement>)graph.cells(), min, max); } //------------------------------------------------------------------------- /** * Normalise graph elements to the provided range. */ private static void normaliseGraphElements ( final ArrayList<? extends TopologyElement> graphElements, final double min, final double max ) { for (int i = 0; i < graphElements.size(); i++) { final double oldX = graphElements.get(i).centroid().getX(); final double oldY = graphElements.get(i).centroid().getY(); final double newX = (oldX - min) / (max - min); final double newY = (oldY - min) / (max - min); graphElements.get(i).setCentroid(newX, newY, 0); } } //------------------------------------------------------------------------- /** * Center the graph within the world space. */ public static void centerGraphElements(final Topology graph) { double minX = 9999999; double minY = 99999999; double maxX = -99999999; double maxY = -99999999; for (int i = 0; i < graph.vertices().size(); i++) { if (graph.vertices().get(i).centroid().getX() < minX) minX = graph.vertices().get(i).centroid().getX(); if (graph.vertices().get(i).centroid().getY() < minY) minY = graph.vertices().get(i).centroid().getY(); if (graph.vertices().get(i).centroid().getX() > maxX) maxX = graph.vertices().get(i).centroid().getX(); if (graph.vertices().get(i).centroid().getY() > maxY) maxY = graph.vertices().get(i).centroid().getY(); } centerGraphElementsBetween((ArrayList<? extends TopologyElement>) graph.vertices(), minX, maxX, minY, maxY); centerGraphElementsBetween((ArrayList<? extends TopologyElement>) graph.edges(), minX, maxX, minY, maxY); centerGraphElementsBetween((ArrayList<? extends TopologyElement>) graph.cells(), minX, maxX, minY, maxY); } //------------------------------------------------------------------------- /** * Centers the provided list of graph elements between the minimum and maximum values along both dimensions. */ private static void centerGraphElementsBetween(final ArrayList<? extends TopologyElement> graphElements, final double minX, final double maxX, final double minY, final double maxY) { final double currentMidX = (maxX + minX) / 2; final double currentMidY = (maxY + minY) / 2; final double differenceX = currentMidX - 0.5; final double differenceY = currentMidY - 0.5; for (int i = 0; i < graphElements.size(); i++) { final double oldX = graphElements.get(i).centroid().getX(); final double oldY = graphElements.get(i).centroid().getY(); final double newX = oldX - differenceX; final double newY = oldY - differenceY; graphElements.get(i).setCentroid(newX, newY, 0); } } //------------------------------------------------------------------------- /** * @return Cell indices of a container that a component is covering. */ public static ArrayList<Integer> cellsCoveredByPiece(final Context context, final Container container, final Component component, final int site, final int localState) { final ArrayList<Integer> cellsCoveredByPiece = new ArrayList<>(); if (component.isLargePiece()) { final TIntArrayList largePieceSites = component.locs(context,site,localState,container.topology()); for (int i = 0; i < largePieceSites.size(); i++) { cellsCoveredByPiece.add(Integer.valueOf(container.topology().cells().get(largePieceSites.get(i)).index())); } } else { cellsCoveredByPiece.add(Integer.valueOf(site)); } return cellsCoveredByPiece; } //------------------------------------------------------------------------- /** * @return A region from equipment that this edge belongs to. */ public static Regions getRegionOfEdge(final Context context, final Edge e) { for (final Regions region : context.game().equipment().regions()) for (final int site : region.eval(context)) for (final Edge edge : context.board().topology().cells().get(site).edges()) if (edge.index() == e.index()) return region; return null; } //------------------------------------------------------------------------- /** * @return Edges of cellIndex and are on the perimeter of surroundedRegions. */ public static List<Edge> getOuterRegionEdges(final List<Location> region, final Topology topology) { final ArrayList<Edge> regionLines = new ArrayList<>(); final ArrayList<Edge> outsideRegionLines = new ArrayList<>(); for (final Location loctation : region) for (final Edge e : topology.getGraphElement(SiteType.Cell, loctation.site()).regionEdges()) regionLines.add(e); for (final Edge edge1 : regionLines) { int numContains = 0; for (final Edge edge2 : regionLines) { if ( Math.abs(edge1.vA().centroid().getX() - edge2.vA().centroid().getX()) < 0.0001 && Math.abs(edge1.vB().centroid().getX() - edge2.vB().centroid().getX()) < 0.0001 && Math.abs(edge1.vA().centroid().getY() - edge2.vA().centroid().getY()) < 0.0001 && Math.abs(edge1.vB().centroid().getY() - edge2.vB().centroid().getY()) < 0.0001 ) { numContains++; } else if ( Math.abs(edge1.vA().centroid().getX() - edge2.vB().centroid().getX()) < 0.0001 && Math.abs(edge1.vB().centroid().getX() - edge2.vA().centroid().getX()) < 0.0001 && Math.abs(edge1.vA().centroid().getY() - edge2.vB().centroid().getY()) < 0.0001 && Math.abs(edge1.vB().centroid().getY() - edge2.vA().centroid().getY()) < 0.0001 ) { numContains++; } } if (numContains == 1) { outsideRegionLines.add(edge1); } } return outsideRegionLines; } //------------------------------------------------------------------------- }
8,488
29.869091
182
java
Ludii
Ludii-master/ViewController/src/util/DeveloperGUI.java
package util; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Graphics2D; import java.awt.Point; import java.awt.geom.Rectangle2D; import java.util.ArrayList; import java.util.List; import java.util.Map.Entry; import bridge.Bridge; import game.types.board.SiteType; import game.util.directions.AbsoluteDirection; import game.util.directions.DirectionFacing; import game.util.graph.Radial; import other.context.Context; import other.topology.Cell; import other.topology.Edge; import other.topology.Topology; import other.topology.TopologyElement; import other.topology.Vertex; import view.container.ContainerStyle; /** * Functions for drawing various graphical aspects which are only intended for developers. * * @author Matthew.Stephenson */ public class DeveloperGUI { /** * Draw the pre-generated sites of the container. */ public static void drawPregeneration(final Bridge bridge, final Graphics2D g2d, final Context context, final ContainerStyle containerStyle) { try { final int cellRadiusPixels = containerStyle.cellRadiusPixels(); if (bridge.settingsVC().lastClickedSite() != null) { final Topology graph = context.board().topology(); if (bridge.settingsVC().lastClickedSite().siteType() == SiteType.Cell) { if (bridge.settingsVC().drawNeighboursCells()) { drawNeighbours(g2d, bridge.settingsVC().lastClickedSite().site(), true, containerStyle); } if (bridge.settingsVC().drawRadialsCells()) { drawRadials(bridge, g2d, context, bridge.settingsVC().lastClickedSite().site(), containerStyle, SiteType.Cell); } if (bridge.settingsVC().drawDistanceCells()) { drawDistance(bridge, g2d, context, bridge.settingsVC().lastClickedSite().site(), bridge.settingsVC().lastClickedSite().siteType(), containerStyle); } } if (bridge.settingsVC().lastClickedSite().siteType() == SiteType.Vertex) { if (bridge.settingsVC().drawNeighboursVertices()) { drawNeighbours(g2d, bridge.settingsVC().lastClickedSite().site(), false, containerStyle); } if (bridge.settingsVC().drawRadialsVertices()) { drawRadials(bridge, g2d, context, bridge.settingsVC().lastClickedSite().site(), containerStyle, SiteType.Vertex); } if (bridge.settingsVC().drawDistanceVertices()) { drawDistance(bridge, g2d, context, bridge.settingsVC().lastClickedSite().site(), bridge.settingsVC().lastClickedSite().siteType(), containerStyle); } } if (bridge.settingsVC().lastClickedSite().siteType() == SiteType.Edge) { if (bridge.settingsVC().drawDistanceEdges()) { drawDistance(bridge, g2d, context, bridge.settingsVC().lastClickedSite().site(), bridge.settingsVC().lastClickedSite().siteType(), containerStyle); } } if (bridge.settingsVC().drawVerticesOfEdges() && bridge.settingsVC().lastClickedSite().siteType() == SiteType.Edge) { for (final Vertex v : graph.edges().get(bridge.settingsVC().lastClickedSite().site()).vertices()) { g2d.setColor(new Color(0,255,255,125)); final Point drawPosn = containerStyle.screenPosn(v.centroid()); g2d.fillOval(drawPosn.x - cellRadiusPixels / 2, drawPosn.y - cellRadiusPixels / 2, cellRadiusPixels, cellRadiusPixels); } } if (bridge.settingsVC().drawVerticesOfFaces() && bridge.settingsVC().lastClickedSite().siteType() == SiteType.Cell) { for (final Vertex v : graph.cells().get(bridge.settingsVC().lastClickedSite().site()).vertices()) { g2d.setColor(new Color(0,255,255,125)); final Point drawPosn = containerStyle.screenPosn(v.centroid()); g2d.fillOval(drawPosn.x - cellRadiusPixels / 2, drawPosn.y - cellRadiusPixels / 2, cellRadiusPixels, cellRadiusPixels); } } if (bridge.settingsVC().drawEdgesOfFaces() && bridge.settingsVC().lastClickedSite().siteType() == SiteType.Cell) { for (final Edge e : graph.cells().get(bridge.settingsVC().lastClickedSite().site()).edges()) { g2d.setColor(new Color(0,255,255,125)); final Point drawPosn = containerStyle.screenPosn(e.centroid()); g2d.fillOval(drawPosn.x - cellRadiusPixels / 2, drawPosn.y - cellRadiusPixels / 2, cellRadiusPixels, cellRadiusPixels); } } if (bridge.settingsVC().drawEdgesOfVertices() && bridge.settingsVC().lastClickedSite().siteType() == SiteType.Vertex) { for (final Edge e : graph.vertices().get(bridge.settingsVC().lastClickedSite().site()).edges()) { g2d.setColor(new Color(0,255,255,125)); final Point drawPosn = containerStyle.screenPosn(e.centroid()); g2d.fillOval(drawPosn.x - cellRadiusPixels / 2, drawPosn.y - cellRadiusPixels / 2, cellRadiusPixels, cellRadiusPixels); } } if (bridge.settingsVC().drawFacesOfEdges() && bridge.settingsVC().lastClickedSite().siteType() == SiteType.Edge) { for (final Cell c : graph.edges().get(bridge.settingsVC().lastClickedSite().site()).cells()) { g2d.setColor(new Color(0,255,255,125)); final Point drawPosn = containerStyle.screenPosn(c.centroid()); g2d.fillOval(drawPosn.x - cellRadiusPixels / 2, drawPosn.y - cellRadiusPixels / 2, cellRadiusPixels, cellRadiusPixels); } } if (bridge.settingsVC().drawFacesOfVertices() && bridge.settingsVC().lastClickedSite().siteType() == SiteType.Vertex) { for (final Cell c : graph.vertices().get(bridge.settingsVC().lastClickedSite().site()).cells()) { g2d.setColor(new Color(0,255,255,125)); final Point drawPosn = containerStyle.screenPosn(c.centroid()); g2d.fillOval(drawPosn.x - cellRadiusPixels / 2, drawPosn.y - cellRadiusPixels / 2, cellRadiusPixels, cellRadiusPixels); } } } } catch(final Exception E) { // something went wrong, probably changed an option or the game. return; } drawPregenerationRegions(bridge, g2d, context, containerStyle); } //------------------------------------------------------------------------- /** * Draw the pre-generated regions of the container. */ private static void drawPregenerationRegions(final Bridge bridge, final Graphics2D g2d, final Context context, final ContainerStyle containerStyle) { final Topology graph = context.board().topology(); g2d.setStroke(new BasicStroke((2), BasicStroke.CAP_BUTT, BasicStroke.JOIN_ROUND)); // Cells final List<TopologyElement> allGraphElementsToDraw = new ArrayList<>(); if (bridge.settingsVC().drawCornerCells()) { for (final TopologyElement v : graph.corners(SiteType.Cell)) { allGraphElementsToDraw.add(v); } } g2d.setColor(new Color(255,0,0,125)); drawGraphElementList(g2d, allGraphElementsToDraw, containerStyle); allGraphElementsToDraw.clear(); if (bridge.settingsVC().drawCornerConcaveCells()) { for (final TopologyElement v : graph.cornersConcave(SiteType.Cell)) { allGraphElementsToDraw.add(v); } } g2d.setColor(new Color(255, 0, 0, 125)); drawGraphElementList(g2d, allGraphElementsToDraw, containerStyle); allGraphElementsToDraw.clear(); if (bridge.settingsVC().drawCornerConvexCells()) { for (final TopologyElement v : graph.cornersConvex(SiteType.Cell)) { allGraphElementsToDraw.add(v); } } g2d.setColor(new Color(255, 0, 0, 125)); drawGraphElementList(g2d, allGraphElementsToDraw, containerStyle); allGraphElementsToDraw.clear(); if (bridge.settingsVC().drawOuterCells()) { for (final TopologyElement v : graph.outer(SiteType.Cell)) { allGraphElementsToDraw.add(v); } } g2d.setColor(new Color(0,255,0,125)); drawGraphElementList(g2d, allGraphElementsToDraw, containerStyle); allGraphElementsToDraw.clear(); if (bridge.settingsVC().drawMajorCells()) { for (final TopologyElement v : graph.major(SiteType.Cell)) { allGraphElementsToDraw.add(v); } } g2d.setColor(new Color(0, 255, 0, 125)); drawGraphElementList(g2d, allGraphElementsToDraw, containerStyle); allGraphElementsToDraw.clear(); if (bridge.settingsVC().drawMinorCells()) { for (final TopologyElement v : graph.minor(SiteType.Cell)) { allGraphElementsToDraw.add(v); } } g2d.setColor(new Color(0, 255, 0, 125)); drawGraphElementList(g2d, allGraphElementsToDraw, containerStyle); allGraphElementsToDraw.clear(); if (bridge.settingsVC().drawPerimeterCells()) { for (final TopologyElement v : graph.perimeter(SiteType.Cell)) { allGraphElementsToDraw.add(v); } } g2d.setColor(new Color(0, 255, 0, 125)); drawGraphElementList(g2d, allGraphElementsToDraw, containerStyle); allGraphElementsToDraw.clear(); if (bridge.settingsVC().drawInnerCells()) { for (final TopologyElement v : graph.inner(SiteType.Cell)) { allGraphElementsToDraw.add(v); } } g2d.setColor(new Color(127,0,0,125)); drawGraphElementList(g2d, allGraphElementsToDraw, containerStyle); allGraphElementsToDraw.clear(); if (bridge.settingsVC().drawTopCells()) { for (final TopologyElement v : graph.top(SiteType.Cell)) { allGraphElementsToDraw.add(v); } } g2d.setColor(new Color(0,127,0,125)); drawGraphElementList(g2d, allGraphElementsToDraw, containerStyle); allGraphElementsToDraw.clear(); if (bridge.settingsVC().drawBottomCells()) { for (final TopologyElement v : graph.bottom(SiteType.Cell)) { allGraphElementsToDraw.add(v); } } g2d.setColor(new Color(0,0,127,125)); drawGraphElementList(g2d, allGraphElementsToDraw, containerStyle); allGraphElementsToDraw.clear(); if (bridge.settingsVC().drawLeftCells()) { for (final TopologyElement v : graph.left(SiteType.Cell)) { allGraphElementsToDraw.add(v); } } g2d.setColor(new Color(255,255,0,125)); drawGraphElementList(g2d, allGraphElementsToDraw, containerStyle); allGraphElementsToDraw.clear(); if (bridge.settingsVC().drawRightCells()) { for (final TopologyElement v : graph.right(SiteType.Cell)) { allGraphElementsToDraw.add(v); } } g2d.setColor(new Color(255,0,255,125)); drawGraphElementList(g2d, allGraphElementsToDraw, containerStyle); allGraphElementsToDraw.clear(); if (bridge.settingsVC().drawCenterCells()) { for (final TopologyElement v : graph.centre(SiteType.Cell)) { allGraphElementsToDraw.add(v); } } g2d.setColor(new Color(0,127,127,125)); drawGraphElementList(g2d, allGraphElementsToDraw, containerStyle); if (bridge.settingsVC().drawPhasesCells()) { g2d.setColor(new Color(255, 0, 0, 125)); drawPhase(bridge, g2d, context, SiteType.Cell, containerStyle); } allGraphElementsToDraw.clear(); for (final Entry<DirectionFacing, List<TopologyElement>> entry : graph.sides(SiteType.Cell).entrySet()) { final String DirectionName = entry.getKey().uniqueName().toString(); if (bridge.settingsVC().drawSideCells().containsKey(DirectionName) && bridge.settingsVC().drawSideCells().get(DirectionName).booleanValue()) { try { for (final TopologyElement c : entry.getValue()) { allGraphElementsToDraw.add(c); } } catch (final Exception e) { // carry on } } } g2d.setColor(new Color(255,50,50,125)); drawGraphElementList(g2d, allGraphElementsToDraw, containerStyle); // Vertices allGraphElementsToDraw.clear(); if (bridge.settingsVC().drawCornerVertices()) { for (final TopologyElement v : graph.corners(SiteType.Vertex)) { allGraphElementsToDraw.add(v); } } g2d.setColor(new Color(255,0,0,125)); drawGraphElementList(g2d, allGraphElementsToDraw, containerStyle); allGraphElementsToDraw.clear(); if (bridge.settingsVC().drawCornerConcaveVertices()) { for (final TopologyElement v : graph.cornersConcave(SiteType.Vertex)) { allGraphElementsToDraw.add(v); } } g2d.setColor(new Color(255, 0, 0, 125)); drawGraphElementList(g2d, allGraphElementsToDraw, containerStyle); allGraphElementsToDraw.clear(); if (bridge.settingsVC().drawCornerConvexVertices()) { for (final TopologyElement v : graph.cornersConvex(SiteType.Vertex)) { allGraphElementsToDraw.add(v); } } g2d.setColor(new Color(255, 0, 0, 125)); drawGraphElementList(g2d, allGraphElementsToDraw, containerStyle); allGraphElementsToDraw.clear(); if (bridge.settingsVC().drawMajorVertices()) { for (final TopologyElement v : graph.major(SiteType.Vertex)) { allGraphElementsToDraw.add(v); } } g2d.setColor(new Color(255, 0, 0, 125)); drawGraphElementList(g2d, allGraphElementsToDraw, containerStyle); allGraphElementsToDraw.clear(); if (bridge.settingsVC().drawMinorVertices()) { for (final TopologyElement v : graph.minor(SiteType.Vertex)) { allGraphElementsToDraw.add(v); } } g2d.setColor(new Color(255, 0, 0, 125)); drawGraphElementList(g2d, allGraphElementsToDraw, containerStyle); allGraphElementsToDraw.clear(); if (bridge.settingsVC().drawPerimeterVertices()) { for (final TopologyElement v : graph.perimeter(SiteType.Vertex)) { allGraphElementsToDraw.add(v); } } g2d.setColor(new Color(0, 255, 0, 125)); drawGraphElementList(g2d, allGraphElementsToDraw, containerStyle); allGraphElementsToDraw.clear(); if (bridge.settingsVC().drawOuterVertices()) { for (final TopologyElement v : graph.outer(SiteType.Vertex)) { allGraphElementsToDraw.add(v); } } g2d.setColor(new Color(0,255,0,125)); drawGraphElementList(g2d, allGraphElementsToDraw, containerStyle); allGraphElementsToDraw.clear(); if (bridge.settingsVC().drawInnerVertices()) { for (final TopologyElement v : graph.inner(SiteType.Vertex)) { allGraphElementsToDraw.add(v); } } g2d.setColor(new Color(127,0,0,125)); drawGraphElementList(g2d, allGraphElementsToDraw, containerStyle); allGraphElementsToDraw.clear(); if (bridge.settingsVC().drawTopVertices()) { for (final TopologyElement v : graph.top(SiteType.Vertex)) { allGraphElementsToDraw.add(v); } } g2d.setColor(new Color(0,127,0,125)); drawGraphElementList(g2d, allGraphElementsToDraw, containerStyle); allGraphElementsToDraw.clear(); if (bridge.settingsVC().drawBottomVertices()) { for (final TopologyElement v : graph.bottom(SiteType.Vertex)) { allGraphElementsToDraw.add(v); } } g2d.setColor(new Color(0,0,127,125)); drawGraphElementList(g2d, allGraphElementsToDraw, containerStyle); allGraphElementsToDraw.clear(); if (bridge.settingsVC().drawLeftVertices()) { for (final TopologyElement v : graph.left(SiteType.Vertex)) { allGraphElementsToDraw.add(v); } } g2d.setColor(new Color(255,255,0,125)); drawGraphElementList(g2d, allGraphElementsToDraw, containerStyle); allGraphElementsToDraw.clear(); if (bridge.settingsVC().drawRightVertices()) { for (final TopologyElement v : graph.right(SiteType.Vertex)) { allGraphElementsToDraw.add(v); } } g2d.setColor(new Color(255,0,255,125)); drawGraphElementList(g2d, allGraphElementsToDraw, containerStyle); allGraphElementsToDraw.clear(); if (bridge.settingsVC().drawCenterVertices()) { for (final TopologyElement v : graph.centre(SiteType.Vertex)) { allGraphElementsToDraw.add(v); } } drawGraphElementList(g2d, allGraphElementsToDraw, containerStyle); if (bridge.settingsVC().drawPhasesVertices()) { g2d.setColor(new Color(0, 255, 0, 125)); drawPhase(bridge, g2d, context, SiteType.Vertex, containerStyle); } allGraphElementsToDraw.clear(); for (final Entry<DirectionFacing, List<TopologyElement>> entry : graph.sides(SiteType.Vertex).entrySet()) { final String DirectionName = entry.getKey().uniqueName().toString(); if (bridge.settingsVC().drawSideVertices().containsKey(DirectionName) && bridge.settingsVC().drawSideVertices().get(DirectionName).booleanValue()) { try { for (final TopologyElement v : entry.getValue()) { allGraphElementsToDraw.add(v); } } catch (final Exception e) { // carry on } } } g2d.setColor(new Color(255,50,50,125)); drawGraphElementList(g2d, allGraphElementsToDraw, containerStyle); allGraphElementsToDraw.clear(); for (int i = 0; i < bridge.settingsVC().drawColumnsCells().size(); i++) { if (bridge.settingsVC().drawColumnsCells().get(i).booleanValue()) { try { for (final TopologyElement v : graph.columns(SiteType.Cell).get(i)) { allGraphElementsToDraw.add(v); } } catch (final Exception e) { // carry on } } } g2d.setColor(new Color(0,255,255,125)); drawGraphElementList(g2d, allGraphElementsToDraw, containerStyle); allGraphElementsToDraw.clear(); for (int i = 0; i < bridge.settingsVC().drawColumnsVertices().size(); i++) { if (bridge.settingsVC().drawColumnsVertices().get(i).booleanValue()) { try { for (final TopologyElement v : graph.columns(SiteType.Vertex).get(i)) { allGraphElementsToDraw.add(v); } } catch (final Exception e) { // carry on } } } g2d.setColor(new Color(0,255,255,125)); drawGraphElementList(g2d, allGraphElementsToDraw, containerStyle); allGraphElementsToDraw.clear(); for (int i = 0; i < bridge.settingsVC().drawRowsCells().size(); i++) { if (bridge.settingsVC().drawRowsCells().get(i).booleanValue()) { try { for (final TopologyElement v : graph.rows(SiteType.Cell).get(i)) { allGraphElementsToDraw.add(v); } } catch (final Exception e) { // carry on } } } g2d.setColor(new Color(0,255,255,125)); drawGraphElementList(g2d, allGraphElementsToDraw, containerStyle); allGraphElementsToDraw.clear(); for (int i = 0; i < bridge.settingsVC().drawRowsVertices().size(); i++) { if (bridge.settingsVC().drawRowsVertices().get(i).booleanValue()) { try { for (final TopologyElement v : graph.rows(SiteType.Vertex).get(i)) { allGraphElementsToDraw.add(v); } } catch (final Exception e) { // carry on } } } g2d.setColor(new Color(0,255,255,125)); drawGraphElementList(g2d, allGraphElementsToDraw, containerStyle); // Edges allGraphElementsToDraw.clear(); if (bridge.settingsVC().drawCornerEdges()) { for (final TopologyElement v : graph.corners(SiteType.Edge)) { allGraphElementsToDraw.add(v); } } g2d.setColor(new Color(0, 255, 0, 125)); drawGraphElementList(g2d, allGraphElementsToDraw, containerStyle); allGraphElementsToDraw.clear(); if (bridge.settingsVC().drawCornerConcaveEdges()) { for (final TopologyElement v : graph.cornersConcave(SiteType.Edge)) { allGraphElementsToDraw.add(v); } } g2d.setColor(new Color(0, 255, 0, 125)); drawGraphElementList(g2d, allGraphElementsToDraw, containerStyle); allGraphElementsToDraw.clear(); if (bridge.settingsVC().drawCornerConvexEdges()) { for (final TopologyElement v : graph.cornersConvex(SiteType.Edge)) { allGraphElementsToDraw.add(v); } } g2d.setColor(new Color(0, 255, 0, 125)); drawGraphElementList(g2d, allGraphElementsToDraw, containerStyle); allGraphElementsToDraw.clear(); if (bridge.settingsVC().drawMajorEdges()) { for (final TopologyElement v : graph.major(SiteType.Edge)) { allGraphElementsToDraw.add(v); } } g2d.setColor(new Color(0, 255, 0, 125)); drawGraphElementList(g2d, allGraphElementsToDraw, containerStyle); allGraphElementsToDraw.clear(); if (bridge.settingsVC().drawMinorEdges()) { for (final TopologyElement v : graph.minor(SiteType.Edge)) { allGraphElementsToDraw.add(v); } } g2d.setColor(new Color(0, 255, 0, 125)); drawGraphElementList(g2d, allGraphElementsToDraw, containerStyle); allGraphElementsToDraw.clear(); if (bridge.settingsVC().drawAxialEdges()) { for (final TopologyElement v : graph.axial(SiteType.Edge)) { allGraphElementsToDraw.add(v); } } g2d.setColor(new Color(0, 255, 0, 125)); drawGraphElementList(g2d, allGraphElementsToDraw, containerStyle); allGraphElementsToDraw.clear(); if (bridge.settingsVC().drawHorizontalEdges()) { for (final TopologyElement v : graph.horizontal(SiteType.Edge)) { allGraphElementsToDraw.add(v); } } g2d.setColor(new Color(0, 255, 0, 125)); drawGraphElementList(g2d, allGraphElementsToDraw, containerStyle); allGraphElementsToDraw.clear(); if (bridge.settingsVC().drawVerticalEdges()) { for (final TopologyElement v : graph.vertical(SiteType.Edge)) { allGraphElementsToDraw.add(v); } } g2d.setColor(new Color(0, 255, 0, 125)); drawGraphElementList(g2d, allGraphElementsToDraw, containerStyle); allGraphElementsToDraw.clear(); if (bridge.settingsVC().drawAngledEdges()) { for (final TopologyElement v : graph.angled(SiteType.Edge)) { allGraphElementsToDraw.add(v); } } g2d.setColor(new Color(0, 255, 0, 125)); drawGraphElementList(g2d, allGraphElementsToDraw, containerStyle); allGraphElementsToDraw.clear(); if (bridge.settingsVC().drawSlashEdges()) { for (final TopologyElement v : graph.slash(SiteType.Edge)) { allGraphElementsToDraw.add(v); } } g2d.setColor(new Color(0, 255, 0, 125)); drawGraphElementList(g2d, allGraphElementsToDraw, containerStyle); allGraphElementsToDraw.clear(); if (bridge.settingsVC().drawSloshEdges()) { for (final TopologyElement v : graph.slosh(SiteType.Edge)) { allGraphElementsToDraw.add(v); } } g2d.setColor(new Color(0, 255, 0, 125)); drawGraphElementList(g2d, allGraphElementsToDraw, containerStyle); allGraphElementsToDraw.clear(); if (bridge.settingsVC().drawPerimeterEdges()) { for (final TopologyElement v : graph.perimeter(SiteType.Edge)) { allGraphElementsToDraw.add(v); } } g2d.setColor(new Color(0, 255, 0, 125)); drawGraphElementList(g2d, allGraphElementsToDraw, containerStyle); allGraphElementsToDraw.clear(); if (bridge.settingsVC().drawOuterEdges()) { for (final TopologyElement v : graph.outer(SiteType.Edge)) { allGraphElementsToDraw.add(v); } } g2d.setColor(new Color(0, 255, 0, 125)); drawGraphElementList(g2d, allGraphElementsToDraw, containerStyle); allGraphElementsToDraw.clear(); if (bridge.settingsVC().drawInnerEdges()) { for (final TopologyElement v : graph.inner(SiteType.Edge)) { allGraphElementsToDraw.add(v); } } g2d.setColor(new Color(127, 0, 0, 125)); drawGraphElementList(g2d, allGraphElementsToDraw, containerStyle); allGraphElementsToDraw.clear(); if (bridge.settingsVC().drawTopEdges()) { for (final TopologyElement v : graph.top(SiteType.Edge)) { allGraphElementsToDraw.add(v); } } g2d.setColor(new Color(0, 127, 0, 125)); drawGraphElementList(g2d, allGraphElementsToDraw, containerStyle); allGraphElementsToDraw.clear(); if (bridge.settingsVC().drawBottomEdges()) { for (final TopologyElement v : graph.bottom(SiteType.Edge)) { allGraphElementsToDraw.add(v); } } g2d.setColor(new Color(0, 0, 127, 125)); drawGraphElementList(g2d, allGraphElementsToDraw, containerStyle); allGraphElementsToDraw.clear(); if (bridge.settingsVC().drawLeftEdges()) { for (final TopologyElement v : graph.left(SiteType.Edge)) { allGraphElementsToDraw.add(v); } } g2d.setColor(new Color(255, 255, 0, 125)); drawGraphElementList(g2d, allGraphElementsToDraw, containerStyle); allGraphElementsToDraw.clear(); if (bridge.settingsVC().drawRightEdges()) { for (final TopologyElement v : graph.right(SiteType.Edge)) { allGraphElementsToDraw.add(v); } } g2d.setColor(new Color(255, 0, 255, 125)); drawGraphElementList(g2d, allGraphElementsToDraw, containerStyle); allGraphElementsToDraw.clear(); if (bridge.settingsVC().drawCentreEdges()) { for (final TopologyElement v : graph.centre(SiteType.Edge)) { allGraphElementsToDraw.add(v); } } g2d.setColor(new Color(255, 0, 255, 125)); drawGraphElementList(g2d, allGraphElementsToDraw, containerStyle); if (bridge.settingsVC().drawPhasesEdges()) { g2d.setColor(new Color(0, 0, 255, 125)); drawPhase(bridge, g2d, context, SiteType.Edge, containerStyle); } allGraphElementsToDraw.clear(); for (final Entry<DirectionFacing, List<TopologyElement>> entry : graph.sides(SiteType.Edge).entrySet()) { final String DirectionName = entry.getKey().uniqueName().toString(); if (bridge.settingsVC().drawSideEdges().containsKey(DirectionName) && bridge.settingsVC().drawSideEdges().get(DirectionName).booleanValue()) { try { for (final TopologyElement c : entry.getValue()) { allGraphElementsToDraw.add(c); } } catch (final Exception e) { // carry on } } } g2d.setColor(new Color(255, 50, 50, 125)); drawGraphElementList(g2d, allGraphElementsToDraw, containerStyle); } //------------------------------------------------------------------------- /** * Draw a circle at each of the specific vertices in the vertexList. */ private static void drawGraphElementList(final Graphics2D g2d, final List<TopologyElement> graphElementList, final ContainerStyle containerStyle) { for (int i = 0; i < graphElementList.size(); i++) { final int circleSize = 20; final Point drawPosn = containerStyle.screenPosn(graphElementList.get(i).centroid()); g2d.drawOval(drawPosn.x - circleSize / 2, drawPosn.y - circleSize / 2, circleSize, circleSize); } } //------------------------------------------------------------------------- /** * Draws container phases. */ public static void drawPhase(final Bridge bridge, final Graphics2D g2d, final Context context, final SiteType type, final ContainerStyle containerStyle) { try { g2d.setFont(bridge.settingsVC().displayFont()); final List<List<TopologyElement>> phases = context.topology().phases(type); for (int phase = 0; phase < phases.size(); phase++) { for (final TopologyElement elementToPrint : phases.get(phase)) { final String str = phase + ""; final Point drawPosn = containerStyle.screenPosn(elementToPrint.centroid()); g2d.drawString(str, drawPosn.x, drawPosn.y); } } } catch (final Exception E) { // probably invalid vertexIndex } } //------------------------------------------------------------------------- /** * Draws distance from a given site. */ public static void drawDistance(final Bridge bridge, final Graphics2D g2d, final Context context, final int index, final SiteType type, final ContainerStyle containerStyle) { try { g2d.setFont(bridge.settingsVC().displayFont()); final TopologyElement element = context.board().topology().getGraphElement(type, index); final int[] distance = context.board().topology().distancesToOtherSite(type)[element.index()]; for(int i = 0; i < distance.length;i++) { final TopologyElement elementToPrint = context.board().topology().getGraphElement(type, i); final String str = distance[i] + ""; final Rectangle2D bounds = g2d.getFontMetrics().getStringBounds(str, g2d); final Point drawPosn = containerStyle.screenPosn(elementToPrint.centroid()); g2d.drawString(str, (int) (drawPosn.x - bounds.getWidth()), (int) (drawPosn.y + bounds.getHeight())); } } catch (final Exception E) { // probably invalid vertexIndex } } //------------------------------------------------------------------------- /** * Draws radials from a given graph element. */ public static void drawRadials(final Bridge bridge, final Graphics2D g2d, final Context context, final int indexElem, final ContainerStyle containerStyle, final SiteType type) { try { final Topology topology = context.board().topology(); final List<DirectionFacing> directions = topology.supportedDirections(type); for (final DirectionFacing direction : directions) { final AbsoluteDirection absDirection = direction.toAbsolute(); final List<Radial> radials = topology.trajectories().radials(type, indexElem, absDirection); final String directionString = direction.toString(); g2d.setFont(bridge.settingsVC().displayFont()); g2d.setColor(Color.BLACK); for (final Radial radial : radials) { for (int distance = 1; distance < radial.steps().length; distance++) { final int indexElementRadial = radial.steps()[distance].id(); final TopologyElement elementRadial = topology.getGraphElement(type, indexElementRadial); final Rectangle2D bounds = g2d.getFontMetrics().getStringBounds(directionString + distance, g2d); final Point drawPosn = containerStyle.screenPosn(elementRadial.centroid()); g2d.drawString(directionString + distance, (int) (drawPosn.x - bounds.getWidth() / 2), (int) (drawPosn.y + bounds.getHeight() / 2)); } } } } catch (final Exception E) { // probably invalid vertexIndex } } //------------------------------------------------------------------------- /** * Draws neighbours of a given vertex index. */ public static void drawNeighbours(final Graphics2D g2d, final int vertexIndex, final boolean drawCells, final ContainerStyle containerStyle) { try { // neighbours final List<? extends TopologyElement> adjacentNeighbours; final List<? extends TopologyElement> orthogonalNeighbours; final List<? extends TopologyElement> secondaryNeighbours; final List<? extends TopologyElement> diagonalNeighbours; if (drawCells) { final Cell cell = containerStyle.drawnCells().get(vertexIndex); adjacentNeighbours = cell.adjacent(); orthogonalNeighbours = cell.orthogonal(); secondaryNeighbours = cell.off(); diagonalNeighbours = cell.diagonal(); } else { final Vertex vertex = containerStyle.drawnVertices().get(vertexIndex); adjacentNeighbours = vertex.adjacent(); orthogonalNeighbours = vertex.orthogonal(); secondaryNeighbours = vertex.off(); diagonalNeighbours = vertex.diagonal(); } final int circleSize = containerStyle.cellRadiusPixels(); if (adjacentNeighbours != null) { for (final TopologyElement v : adjacentNeighbours) { g2d.setColor(new Color(255,0,0,125)); final Point drawPosn = containerStyle.screenPosn(v.centroid()); g2d.fillOval(drawPosn.x - circleSize / 2, drawPosn.y - circleSize / 2, circleSize, circleSize); } } if (orthogonalNeighbours != null) { for (final TopologyElement v : orthogonalNeighbours) { g2d.setColor(new Color(0,255,0,125)); final Point drawPosn = containerStyle.screenPosn(v.centroid()); g2d.fillOval(drawPosn.x - circleSize / 2, drawPosn.y - circleSize / 2, circleSize, circleSize); } } if (secondaryNeighbours != null) { for (final TopologyElement v : secondaryNeighbours) { g2d.setColor(new Color(0,0,255,125)); final Point drawPosn = containerStyle.screenPosn(v.centroid()); g2d.fillOval(drawPosn.x - circleSize / 2, drawPosn.y - circleSize / 2, circleSize, circleSize); } } if (diagonalNeighbours != null) { for (final TopologyElement v : diagonalNeighbours) { g2d.setColor(new Color(0,255,255,125)); final Point drawPosn = containerStyle.screenPosn(v.centroid()); g2d.fillOval(drawPosn.x - circleSize / 2, drawPosn.y - circleSize / 2, circleSize, circleSize); } } } catch (final Exception E) { // probably invalid vertexIndex } } //------------------------------------------------------------------------- }
32,740
30.512031
151
java
Ludii
Ludii-master/ViewController/src/util/GraphUtil.java
package util; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Point; import java.awt.Stroke; import java.awt.geom.Line2D; import java.awt.geom.Point2D; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import org.jfree.graphics2d.svg.SVGGraphics2D; import game.types.board.SiteType; import game.util.graph.Properties; import other.context.Context; import other.topology.Cell; import other.topology.Edge; import other.topology.Topology; import other.topology.TopologyElement; import other.topology.Vertex; import view.container.BaseContainerStyle; /** * Functions relating to Graphs. * * @author Matthew.Stephenson */ public class GraphUtil { /** * Returns a list of orthogonal cell connections within a given topology. */ public static List<Edge> orthogonalCellConnections(final Topology topology) { final List<Edge> connections = new ArrayList<>(); for (final Cell va : topology.cells()) { final Point2D drawPosnA = va.centroid(); for (final Cell vb : va.orthogonal()) { if (vb.index() > va.index()) { final Point2D drawPosnB = vb.centroid(); connections.add(new Edge(new Vertex(-1, drawPosnA.getX(), drawPosnA.getY(), 0), new Vertex(-1, drawPosnB.getX(), drawPosnB.getY(), 0))); } } } return connections; } //------------------------------------------------------------------------- /** * Returns a list of diagonal cell connections within a given topology. */ public static List<Edge> diagonalCellConnections(final Topology topology) { final List<Edge> connections = new ArrayList<>(); for (final Cell va : topology.cells()) { final Point2D drawPosnA = va.centroid(); for (final Cell vb : va.diagonal()) { if (vb.index() > va.index()) { final Point2D drawPosnB = vb.centroid(); connections.add(new Edge(new Vertex(-1, drawPosnA.getX(), drawPosnA.getY(), 0), new Vertex(-1, drawPosnB.getX(), drawPosnB.getY(), 0))); } } } return connections; } //------------------------------------------------------------------------- /** * Returns a list of off-diagonal cell connections within a given topology. */ public static List<Edge> offCellConnections(final Topology topology) { final List<Edge> connections = new ArrayList<>(); for (final Cell va : topology.cells()) { final Point2D drawPosnA = va.centroid(); for (final Cell vb : va.off()) { if (vb.index() > va.index()) { final Point2D drawPosnB = vb.centroid(); connections.add(new Edge(new Vertex(-1, drawPosnA.getX(), drawPosnA.getY(), 0), new Vertex(-1, drawPosnB.getX(), drawPosnB.getY(), 0))); } } } return connections; } //------------------------------------------------------------------------- /** * Returns a list of orthogonal edges within a given topology. */ public static List<Edge> orthogonalEdgeRelations(final Topology topology) { final List<Edge> connections = new ArrayList<>(); for (final Vertex va : topology.vertices()) { final Point2D drawPosnA = va.centroid(); for (final Vertex vb : va.orthogonal()) { if (vb.index() > va.index()) { final Point2D drawPosnB = vb.centroid(); connections.add(new Edge(new Vertex(-1, drawPosnA.getX(), drawPosnA.getY(), 0), new Vertex(-1, drawPosnB.getX(), drawPosnB.getY(), 0))); } } } return connections; } //------------------------------------------------------------------------- /** * Returns a list of diagonal edges within a given topology. */ public static List<Edge> diagonalEdgeRelations(final Topology topology) { final List<Edge> connections = new ArrayList<>(); for (final Vertex va : topology.vertices()) { final Point2D drawPosnA = va.centroid(); for (final Vertex vb : va.diagonal()) { if (vb.index() > va.index()) { final Point2D drawPosnB = vb.centroid(); connections.add(new Edge(new Vertex(va.index(), drawPosnA.getX(), drawPosnA.getY(), 0), new Vertex(vb.index(), drawPosnB.getX(), drawPosnB.getY(), 0))); } } } return connections; } //------------------------------------------------------------------------- /** * Returns a list of inner edges within a given topology. */ public static List<Edge> innerEdgeRelations(final Topology topology) { final List<Edge> connections = new ArrayList<>(); for (final Edge edge : topology.edges()) if (!edge.properties().get(Properties.OUTER)) connections.add(edge); return connections; } //------------------------------------------------------------------------- /** * Returns a list of outer edges within a given topology. */ public static List<Edge> outerEdgeRelations(final Topology topology) { final List<Edge> connections = new ArrayList<>(); for (final Edge edge : topology.edges()) if (edge.properties().get(Properties.OUTER)) connections.add(edge); return connections; } //------------------------------------------------------------------------- /** * Creates an SVG graph image for a given container style. */ public static String createSVGGraphImage(final BaseContainerStyle boardStyle) { final SVGGraphics2D g2d = boardStyle.setSVGRenderingValues(); g2d.setBackground(new Color(0, 0, 0, 0)); g2d.setColor(new Color(120, 120, 120)); final Stroke solid = new BasicStroke(2, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND); final Stroke dashed = new BasicStroke(2, BasicStroke.CAP_BUTT, BasicStroke.JOIN_ROUND, 0, new float[]{10}, 0); final Stroke dotted = new BasicStroke(2, BasicStroke.CAP_BUTT, BasicStroke.JOIN_ROUND, 0, new float[]{3}, 0); g2d.setStroke(solid); for (final Edge e : boardStyle.drawnEdges()) { final Point drawPosnA = boardStyle.screenPosn(e.vA().centroid()); final Point drawPosnB = boardStyle.screenPosn(e.vB().centroid()); final java.awt.Shape line = new Line2D.Double(drawPosnA.x, drawPosnA.y, drawPosnB.x, drawPosnB.y); g2d.draw(line); } g2d.setStroke(dashed); for (final Vertex vA : boardStyle.drawnVertices()) { for (final Vertex vB : vA.diagonal()) { if (vA.index() > vB.index()) { final Point drawPosnA = boardStyle.screenPosn(vA.centroid()); final Point drawPosnB = boardStyle.screenPosn(vB.centroid()); final java.awt.Shape line = new Line2D.Double(drawPosnA.x, drawPosnA.y, drawPosnB.x, drawPosnB.y); g2d.draw(line); } } } g2d.setStroke(dotted); for (final Vertex vA : boardStyle.drawnVertices()) { for (final Vertex vB : vA.off()) { if (vA.index() > vB.index()) { final Point drawPosnA = boardStyle.screenPosn(vA.centroid()); final Point drawPosnB = boardStyle.screenPosn(vB.centroid()); final java.awt.Shape line = new Line2D.Double(drawPosnA.x, drawPosnA.y, drawPosnB.x, drawPosnB.y); g2d.draw(line); } } } g2d.setStroke(solid); for (final Vertex va : boardStyle.drawnVertices()) { // Draw vertices final int r = 4; final Point drawPosn = boardStyle.screenPosn(va.centroid()); g2d.fillArc(drawPosn.x - r, drawPosn.y - r, 2 * r + 1, 2 * r + 1, 0, 360); } return g2d.getSVGDocument(); } //------------------------------------------------------------------------- /** * Creates an SVG connections image for a given container style. */ public static String createSVGConnectionsImage(final BaseContainerStyle boardStyle) { final SVGGraphics2D g2d = boardStyle.setSVGRenderingValues(); g2d.setBackground(new Color(0, 0, 0, 0)); g2d.setColor(new Color(127, 127, 255)); final Stroke solid = new BasicStroke(2, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND); final Stroke dashed = new BasicStroke(2, BasicStroke.CAP_BUTT, BasicStroke.JOIN_ROUND, 0, new float[]{10}, 0); final Stroke dotted = new BasicStroke(2, BasicStroke.CAP_BUTT, BasicStroke.JOIN_ROUND, 0, new float[]{3}, 0); g2d.setStroke(solid); for (final Cell vA : boardStyle.drawnCells()) { if (vA.centroid().getX() < 0 || vA.centroid().getY() < 0) continue; for (final Cell vB : vA.orthogonal()) { final Cell vBDrawn = boardStyle.drawnCells().get(vB.index()); if (vBDrawn.centroid().getX() < 0 || vBDrawn.centroid().getY() < 0) continue; if (vA.index() > vBDrawn.index()) { final Point drawPosnA = boardStyle.screenPosn(vA.centroid()); final Point drawPosnB = boardStyle.screenPosn(vBDrawn.centroid()); final java.awt.Shape line = new Line2D.Double(drawPosnA.x, drawPosnA.y, drawPosnB.x, drawPosnB.y); g2d.draw(line); } } } g2d.setStroke(dashed); for (final Cell vA : boardStyle.drawnCells()) { if (vA.centroid().getX() < 0 || vA.centroid().getY() < 0) continue; for (final Cell vB : vA.diagonal()) { final Cell vBDrawn = boardStyle.drawnCells().get(vB.index()); if (vBDrawn.centroid().getX() < 0 || vBDrawn.centroid().getY() < 0) continue; if (vA.index() > vBDrawn.index()) { final Point drawPosnA = boardStyle.screenPosn(vA.centroid()); final Point drawPosnB = boardStyle.screenPosn(vBDrawn.centroid()); final java.awt.Shape line = new Line2D.Double(drawPosnA.x, drawPosnA.y, drawPosnB.x, drawPosnB.y); g2d.draw(line); } } } g2d.setStroke(dotted); for (final Cell vA : boardStyle.drawnCells()) { if (vA.centroid().getX() < 0 || vA.centroid().getY() < 0) continue; for (final Cell vB : vA.off()) { final Cell vBDrawn = boardStyle.drawnCells().get(vB.index()); if (vBDrawn.centroid().getX() < 0 || vBDrawn.centroid().getY() < 0) continue; if (vA.index() > vBDrawn.index()) { final Point drawPosnA = boardStyle.screenPosn(vA.centroid()); final Point drawPosnB = boardStyle.screenPosn(vBDrawn.centroid()); final java.awt.Shape line = new Line2D.Double(drawPosnA.x, drawPosnA.y, drawPosnB.x, drawPosnB.y); g2d.draw(line); } } } g2d.setStroke(solid); for (final Cell vA : boardStyle.drawnCells()) { if (vA.centroid().getX() < 0 || vA.centroid().getY() < 0) continue; // Draw vertices final int r = 4; final Point drawPosn = boardStyle.screenPosn(vA.centroid()); g2d.fillArc(drawPosn.x - r, drawPosn.y - r, 2 * r + 1, 2 * r + 1, 0, 360); } return g2d.getSVGDocument(); } //------------------------------------------------------------------------- /** * Reorders the graph elements of a give topology to be top-down, based on their Y-position and layer value (z-position). */ public static List<TopologyElement> reorderGraphElementsTopDown(final List<TopologyElement> allGraphElements, final Context context) { // Reorder the elements based on their Y position. if (context.game().isStacking()) { Collections.sort(allGraphElements, new Comparator<TopologyElement>() { @Override public int compare(final TopologyElement o1, final TopologyElement o2) { final Double obj1 = Double.valueOf(o1.centroid().getY()); final Double obj2 = Double.valueOf(o2.centroid().getY()); return obj1.compareTo(obj2); } }); Collections.reverse(allGraphElements); } // Reorder the elements based on their layer value. else if (context.board().topology().layers(SiteType.Vertex).size() > 1) { Collections.sort(allGraphElements, new Comparator<TopologyElement>() { @Override public int compare(final TopologyElement o1, final TopologyElement o2) { final Double obj1 = Double.valueOf(o1.layer()); final Double obj2 = Double.valueOf(o2.layer()); return obj1.compareTo(obj2); } }); } return allGraphElements; } //------------------------------------------------------------------------- /** * Calculates the radius of a given cell. */ public static double calculateCellRadius(final Cell cell) { double acc = 0; if (cell.edges().size() > 0) { for (final Edge edge : cell.edges()) { final Point2D midpoint = edge.centroid(); final double dx = midpoint.getX() - cell.centroid().getX(); final double dy = midpoint.getY() - cell.centroid().getY(); final double dist = Math.sqrt(dx * dx + dy * dy); acc += dist; } acc /= cell.edges().size(); } return acc; } //------------------------------------------------------------------------- }
12,460
28.882494
133
java
Ludii
Ludii-master/ViewController/src/util/HiddenUtil.java
package util; import java.util.BitSet; import game.types.board.SiteType; import main.Constants; import other.context.Context; import other.state.container.ContainerState; /** * Functions to deal with hidden information * * @author Matthew.Stephenson */ public class HiddenUtil { public final static int hiddenIndex = 0; public final static int hiddenWhatIndex = 1; public final static int hiddenWhoIndex = 2; public final static int hiddenStateIndex = 3; public final static int hiddenValueIndex = 4; public final static int hiddenCountIndex = 5; public final static int hiddenRotationIndex = 6; //----------------------------------------------------------------------------- /** * Return true if the location is hidden from a specific who. */ public static boolean siteHidden(final Context context, final ContainerState cs, final int site, final int level, final int who, final SiteType type) { if (who > Constants.MAX_PLAYERS) { // If a spectator, check if info is hidden from ANY player for (int i = 1; i <= context.game().players().count(); i++) if (cs.isHidden(i, site, level, type)) return true; return false; } else { return cs.isHidden(who, site, level, type); } } //----------------------------------------------------------------------------- /** * Return true if the location's what is hidden from a specific who. */ public static boolean siteWhatHidden(final Context context, final ContainerState cs, final int site, final int level, final int who, final SiteType type) { // System.out.println("site = " + site); if (who > Constants.MAX_PLAYERS) { // If a spectator, check if info is hidden from ANY player for (int i = 1; i <= context.game().players().count(); i++) { if (cs.isHiddenWhat(i, site, level, type)) return true; } return false; } else { return cs.isHiddenWhat(who, site, level, type); } } //----------------------------------------------------------------------------- /** * Return true if the location's who is hidden from a specific who. */ public static boolean siteWhoHidden(final Context context, final ContainerState cs, final int site, final int level, final int who, final SiteType type) { if (who > Constants.MAX_PLAYERS) { // If a spectator, check if info is hidden from ANY player for (int i = 1; i <= context.game().players().count(); i++) { if (cs.isHiddenWho(i, site, level, type)) return true; } return false; } else { return cs.isHiddenWho(who, site, level, type); } } //----------------------------------------------------------------------------- /** * Return true if the location's state is hidden from a specific who. */ public static boolean siteStateHidden(final Context context, final ContainerState cs, final int site, final int level, final int who, final SiteType type) { if (who > Constants.MAX_PLAYERS) { // If a spectator, check if info is hidden from ANY player for (int i = 1; i <= context.game().players().count(); i++) { if (cs.isHiddenState(i, site, level, type)) return true; } return false; } else { return cs.isHiddenState(who, site, level, type); } } //----------------------------------------------------------------------------- /** * Return true if the location's count is hidden from a specific who. */ public static boolean siteCountHidden(final Context context, final ContainerState cs, final int site, final int level, final int who, final SiteType type) { if (who > Constants.MAX_PLAYERS) { // If a spectator, check if info is hidden from ANY player for (int i = 1; i <= context.game().players().count(); i++) { if (cs.isHiddenCount(i, site, level, type)) return true; } return false; } else { return cs.isHiddenCount(who, site, level, type); } } //----------------------------------------------------------------------------- /** * Return true if the location's value is hidden from a specific who. */ public static boolean siteValueHidden(final Context context, final ContainerState cs, final int site, final int level, final int who, final SiteType type) { if (who > Constants.MAX_PLAYERS) { // If a spectator, check if info is hidden from ANY player for (int i = 1; i <= context.game().players().count(); i++) { if (cs.isHiddenValue(i, site, level, type)) return true; } return false; } else { return cs.isHiddenValue(who, site, level, type); } } //----------------------------------------------------------------------------- /** * Return true if the location's rotation is hidden from a specific who. */ public static boolean siteRotationHidden(final Context context, final ContainerState cs, final int site, final int level, final int who, final SiteType type) { if (who > Constants.MAX_PLAYERS) { // If a spectator, check if info is hidden from ANY player for (int i = 1; i <= context.game().players().count(); i++) { if (cs.isHiddenRotation(i, site, level, type)) return true; } return false; } else { return cs.isHiddenRotation(who, site, level, type); } } //----------------------------------------------------------------------------- /** * Return an integer value representing the hidden information about a location for a specific who. */ public static int siteHiddenBitsetInteger(final Context context, final ContainerState cs, final int site, final int level, final int who, final SiteType type) { int hiddenInteger = 0; if (who != 0) { hiddenInteger += (siteHidden(context, cs, site, level, who, type) ? 1 : 0); hiddenInteger += ((siteWhatHidden(context, cs, site, level, who, type) ? 1 : 0) * Math.pow(2, hiddenWhatIndex)); hiddenInteger += ((siteWhoHidden(context, cs, site, level, who, type) ? 1 : 0) * Math.pow(2, hiddenWhoIndex)); hiddenInteger += ((siteStateHidden(context, cs, site, level, who, type) ? 1 : 0) * Math.pow(2, hiddenStateIndex)); hiddenInteger += ((siteValueHidden(context, cs, site, level, who, type) ? 1 : 0) * Math.pow(2, hiddenValueIndex)); hiddenInteger += ((siteCountHidden(context, cs, site, level, who, type) ? 1 : 0) * Math.pow(2, hiddenCountIndex)); hiddenInteger += ((siteRotationHidden(context, cs, site, level, who, type) ? 1 : 0) * Math.pow(2, hiddenRotationIndex)); } return hiddenInteger; } //----------------------------------------------------------------------------- /** * Converts a hidden integer value into a bitset. */ public static BitSet intToBitSet(final int valueInput) { int value = valueInput; final BitSet bits = new BitSet(); int index = 0; while (value != 0) { if (value % 2 != 0) { bits.set(index); } ++index; value = value >>> 1; } return bits; } //----------------------------------------------------------------------------- }
7,044
29.236052
159
java
Ludii
Ludii-master/ViewController/src/util/ImageInfo.java
package util; import java.awt.Point; import game.equipment.component.Component; import game.types.board.SiteType; /** * Object for storing all relevant information about a component image. * * @author Matthew.Stephenson */ public class ImageInfo { /** World position of image. */ private final Point drawPosn; /** Image transparency. */ private final double transparency; /** Image rotation */ private final int rotation; /** The site (index) of the image. */ private final int site; /** The level of the image. */ private final int level; /** The GraphElementType that the image is placed on. */ private final SiteType graphElementType; /** The component associated with this image. */ private final Component component; /** The local state of the component associated with this image. */ private final int localState; /** The value of the component associated with this image. */ private final int value; /** The index of the container where the image is drawn. */ private final int containerIndex; /** The size of the image (in pixels). */ private final int imageSize; /** the count for the image (including the minus one if dragged)*/ private final int count; //------------------------------------------------------------------------- /** * Constructor for specifying all information about image. * @param drawPosn * @param site * @param level * @param graphElementType * @param component * @param localState * @param value * @param transparency * @param rotation * @param containerIndex * @param imageSize * @param count */ public ImageInfo(final Point drawPosn, final int site, final int level, final SiteType graphElementType, final Component component, final int localState, final int value, final double transparency, final int rotation, final int containerIndex, final int imageSize, final int count) { this.drawPosn = drawPosn; this.transparency = transparency; this.rotation = rotation; this.site = site; this.level = level; this.graphElementType = graphElementType; this.component = component; this.localState = localState; this.containerIndex = containerIndex; this.imageSize = imageSize; this.count = count; this.value = value; } /** * Constructor for specifying minimum information about image. * @param drawPosn * @param site * @param level * @param graphElementType */ public ImageInfo(final Point drawPosn, final int site, final int level, final SiteType graphElementType) { this.drawPosn = drawPosn; transparency = 0; rotation = 0; this.site = site; this.level = level; this.graphElementType = graphElementType; component = null; localState = 0; containerIndex = 0; imageSize = 0; count = 0; value = 0; } //------------------------------------------------------------------------- public Point drawPosn() { return drawPosn; } public double transparency() { return transparency; } public int rotation() { return rotation; } public int site() { return site; } public int level() { return level; } public SiteType graphElementType() { return graphElementType; } public Component component() { return component; } public int localState() { return localState; } public int containerIndex() { return containerIndex; } public int imageSize() { return imageSize; } public int count() { return count; } public int value() { return value; } //------------------------------------------------------------------------- }
3,581
19.947368
282
java
Ludii
Ludii-master/ViewController/src/util/LocationUtil.java
package util; import java.awt.Point; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import bridge.Bridge; import game.equipment.container.Container; import main.Constants; import other.context.Context; import other.location.FullLocation; import other.location.Location; import other.move.Move; import other.state.container.ContainerState; import other.topology.Cell; import other.topology.Edge; import other.topology.Vertex; import view.container.ContainerStyle; /** * Functions relating to Locations. * * @author Matthew.Stephenson */ public class LocationUtil { //------------------------------------------------------------------------- /** * Get all locations across all containers. */ public static List<Location> getAllLocations(final Context context, final Bridge bridge) { final List<Location> allLocations = new ArrayList<>(); for (final Container container : context.containers()) { final ContainerState cs = context.state().containerStates()[container.index()]; final ContainerStyle containerStyle = bridge.getContainerStyle(container.index()); // if is an edge game, then vertices can also be selected if (container.index() == 0 && (context.isVertexGame() || context.isEdgeGame())) for (final Vertex v : containerStyle.drawnVertices()) for (int i = 0; i <= cs.sizeStack(v.index(), v.elementType()); i++) allLocations.add(new FullLocation(v.index(), i, v.elementType())); if (container.index() == 0 && context.isEdgeGame()) for (final Edge e : containerStyle.drawnEdges()) for (int i = 0; i <= cs.sizeStack(e.index(), e.elementType()); i++) allLocations.add(new FullLocation(e.index(), i, e.elementType())); if (context.isCellGame()) for (final Cell c : containerStyle.drawnCells()) for (int i = 0; i <= cs.sizeStack(c.index(), c.elementType()); i++) allLocations.add(new FullLocation(c.index(), i, c.elementType())); } return allLocations; } //------------------------------------------------------------------------- /** * Get all valid From locations in the set of legal moves. */ public static List<Location> getLegalFromLocations(final Context context) { final Set<Location> allLocations = new HashSet<>(); for (final Move m : context.moves(context).moves()) allLocations.add(m.getFromLocation()); return new ArrayList<>(allLocations); } //------------------------------------------------------------------------- /** * Get all valid To locations in the set of legal moves. */ public static List<Location> getLegalToLocations(final Bridge bridge, final Context context) { final Set<Location> allLocations = new HashSet<>(); for (final Move m : context.moves(context).moves()) if (m.getFromLocation().equals(bridge.settingsVC().selectedFromLocation())) allLocations.add(m.getToLocation()); return new ArrayList<>(allLocations); } //------------------------------------------------------------------------- /** * Get the nearest location to the released point. */ public static Location calculateNearestLocation(final Context context, final Bridge bridge, final Point pt, final List<Location> legalLocations) { Location location = new FullLocation(Constants.UNDEFINED); for (final Container container : context.equipment().containers()) { location = bridge.getContainerController(container.index()).calculateNearestLocation(context, pt, legalLocations); if (!location.equals(new FullLocation(Constants.UNDEFINED))) return location; } return location; } //------------------------------------------------------------------------- }
3,695
32
145
java
Ludii
Ludii-master/ViewController/src/util/PlaneType.java
package util; /** * Graphics planes to be drawn in main window. * * @author cambolbro and matthew.stephenson */ public enum PlaneType { BOARD, AXES, TRACK, GRAPH, CONNECTIONS, HINTS, CANDIDATES, COMPONENTS, PREGENERATION, INDICES, POSSIBLEMOVES, COSTS, }
289
8.666667
46
java
Ludii
Ludii-master/ViewController/src/util/SettingsColour.java
package util; import java.awt.Color; import java.util.Arrays; import main.Constants; import other.context.Context; /** * Colour settings. * * @author matthewStephenson and cambolbro */ public class SettingsColour { /** * Original player colours. Used as a reference when we want to reset the player colours to default. */ public final static Color[] ORIGINAL_PLAYER_COLOURS = { new Color(250, 250, 250), new Color(250, 250, 250), new Color(50, 50, 50), new Color(190, 0, 0), new Color(0, 190, 0), new Color(0, 0, 190), new Color(190, 0, 190), new Color(0, 190, 190), new Color(255, 153, 0), new Color(255, 255, 153), new Color(153, 204, 255), new Color(255, 153, 204), new Color(204, 153, 255), new Color(255, 204, 153), new Color(153, 204, 0), new Color(255, 204, 0), new Color(255, 102, 0), new Color(250, 250, 250)}; /** * Current player colours. */ private final Color[] playerColours = { new Color(250, 250, 250), new Color(250, 250, 250), new Color(50, 50, 50), new Color(190, 0, 0), new Color(0, 190, 0), new Color(0, 0, 190), new Color(190, 0, 190), new Color(0, 190, 190), new Color(255, 153, 0), new Color(255, 255, 153), new Color(153, 204, 255), new Color(255, 153, 204), new Color(204, 153, 255), new Color(255, 204, 153), new Color(153, 204, 0), new Color(255, 204, 0), new Color(255, 102, 0), new Color(250, 250, 250)}; /** * array of possible board colours (single tile colour) 0 = inner edge, 1 = outer edge, * 2 = first phase, 3 = second phase, 4 = third phase, 5 = fourth phase, 6 = third phase, * 7 = fourth phase, 8 = symbols, 9 = vertices, 10 = outer vertices */ private final Color[] boardColours = { null, null, null, null, null, null, null, null, null, null, null }; //------------------------------------------------------------------------- /** * Use this function to get the player colour, has check for shared player. */ public final Color playerColour(final Context context, final int playerId) { if (playerId > context.game().players().count()) return playerColours[Constants.MAX_PLAYERS+1]; return playerColours[playerId]; } //------------------------------------------------------------------------- public void setPlayerColour(final int playerId, final Color colour) { playerColours[playerId] = colour; } public Color[] getBoardColours() { return boardColours; } public void resetColours() { for (int i = 0; i < ORIGINAL_PLAYER_COLOURS.length; i++) playerColours[i] = ORIGINAL_PLAYER_COLOURS[i]; Arrays.fill(boardColours, null); } //------------------------------------------------------------------------- }
2,688
32.6125
108
java
Ludii
Ludii-master/ViewController/src/util/SettingsVC.java
package util; import java.awt.Font; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import main.Constants; import other.action.Action; import other.location.FullLocation; import other.location.Location; import other.move.Move; /** * User settings specific to the ViewController. * * @author matthew.stephenson and cambolbro and Eric.Piette */ public final class SettingsVC { //------------------------------------------------------------------------- // User settings /** Show indices of every cell. */ private boolean showCellIndices = false; /** Show indices of every edge. */ private boolean showEdgeIndices = false; /** Show indices of every vertex. */ private boolean showVertexIndices = false; /** Show indices of every container. */ private boolean showContainerIndices = false; /** Show coordinates of every cell */ private boolean showCellCoordinates = false; /** Show coordinates of every cell */ private boolean showEdgeCoordinates = false; /** Show coordinates of every cell */ private boolean showVertexCoordinates = false; /** Show indices of every relevant graph element for this game */ private boolean showIndices = false; /** Show coordinates of every relevant graph element for this game */ private boolean showCoordinates = false; /** Whether to show all possible moves that the player can select*/ private boolean showPossibleMoves = false; /** Whether to display certain tracks */ private ArrayList<String> trackNames = new ArrayList<>(); private ArrayList<Boolean> trackShown = new ArrayList<>(); /** The location that is currently selected by the user. */ private Location selectedFromLocation = new FullLocation(Constants.UNDEFINED); /** Extension text to add onto the end of piece names when searching for the correct SVG image. */ private String pieceStyleExtension = ""; /** Font used when displaying text. */ private Font displayFont; /** Whether the board should be drawn flat. */ private boolean flatBoard = false; //------------------------------------------------------------------------- // Developer pre-generation display settings private boolean drawCornerCells = false; private boolean drawCornerConcaveCells = false; private boolean drawCornerConvexCells = false; private boolean drawMajorCells = false; private boolean drawMinorCells = false; private boolean drawOuterCells = false; private boolean drawPerimeterCells = false; private boolean drawInnerCells = false; private boolean drawTopCells = false; private boolean drawBottomCells = false; private boolean drawLeftCells = false; private boolean drawRightCells = false; private boolean drawCenterCells = false; private boolean drawPhasesCells = false; private Map<String, Boolean> drawSideCells = new HashMap<String, Boolean>(); private boolean drawNeighboursCells = false; private boolean drawRadialsCells = false; private boolean drawDistanceCells = false; private boolean drawCornerVertices = false; private boolean drawCornerConcaveVertices = false; private boolean drawCornerConvexVertices = false; private boolean drawMajorVertices = false; private boolean drawMinorVertices = false; private boolean drawOuterVertices = false; private boolean drawPerimeterVertices = false; private boolean drawInnerVertices = false; private boolean drawTopVertices = false; private boolean drawBottomVertices = false; private boolean drawLeftVertices = false; private boolean drawRightVertices = false; private boolean drawCenterVertices = false; private boolean drawPhasesVertices = false; private Map<String, Boolean> drawSideVertices = new HashMap<String, Boolean>(); private boolean drawNeighboursVertices = false; private boolean drawRadialsVertices = false; private boolean drawDistanceVertices = false; private boolean drawCentreEdges = false; private boolean drawCornerEdges = false; private boolean drawCornerConcaveEdges = false; private boolean drawCornerConvexEdges = false; private boolean drawMajorEdges = false; private boolean drawMinorEdges = false; private boolean drawOuterEdges = false; private boolean drawPerimeterEdges = false; private boolean drawInnerEdges = false; private boolean drawTopEdges = false; private boolean drawBottomEdges = false; private boolean drawLeftEdges = false; private boolean drawRightEdges = false; private boolean drawDistanceEdges = false; private boolean drawPhasesEdges = false; private Map<String, Boolean> drawSideEdges = new HashMap<String, Boolean>(); private boolean drawAxialEdges = false; private boolean drawHorizontalEdges = false; private boolean drawVerticalEdges = false; private boolean drawAngledEdges = false; private boolean drawSlashEdges = false; private boolean drawSloshEdges = false; private boolean drawFacesOfVertices = false; private boolean drawEdgesOfVertices = false; private boolean drawVerticesOfFaces = false; private boolean drawEdgesOfFaces = false; private boolean drawVerticesOfEdges = false; private boolean drawFacesOfEdges = false; private Location lastClickedSite = new FullLocation(Constants.UNDEFINED); private ArrayList<Boolean> drawColumnsCells = new ArrayList<>(); private ArrayList<Boolean> drawRowsCells = new ArrayList<>(); private ArrayList<Boolean> drawColumnsVertices = new ArrayList<>(); private ArrayList<Boolean> drawRowsVertices = new ArrayList<>(); //------------------------------------------------------------------------- // Variables used for multiple consequence selection. /** If the user is currently selecting a possible consequence to the prior move. */ private boolean selectingConsequenceMove = false; /** List of possible consequence locations. */ private ArrayList<Location> possibleConsequenceLocations = new ArrayList<>(); //------------------------------------------------------------------------- // Animation /** If the animation for the current Frame has already started. */ private boolean thisFrameIsAnimated = false; /** If all movement animation is disabled for the current game. */ private boolean noAnimation = false; /** From index for the animation. */ private Move animationMove = new Move(new ArrayList<Action>()); //------------------------------------------------------------------------- // Other /** If a piece is being dragged. */ private boolean pieceBeingDragged = false; /** Whether to show candidate values on puzzle boards. */ private boolean showCandidateValues = false; /** The last error message that was reported. Stored to prevent the same error message being repeated multiple times. */ private String lastErrorMessage = ""; /** If the coordinates/indices should be drawn with a white outline. */ private boolean coordWithOutline = false; /** Errors that were recorded when rendering or painting some VC aspect. **/ private String errorReport = ""; /** Map of all piece families for displaying different piece styles, e.g. Chess. */ private HashMap<String,String> pieceFamilies = new HashMap<String,String>(); /** Multiplier, applied to cell radius, for determining minimal click distance. */ private double furthestDistanceMultiplier = 0.9; //------------------------------------------------------------------------- // Getters and setters public boolean showCellIndices() { return showCellIndices; } public void setShowCellIndices(final boolean showCellIndices) { this.showCellIndices = showCellIndices; } public boolean showEdgeIndices() { return showEdgeIndices; } public void setShowEdgeIndices(final boolean show) { showEdgeIndices = show; } public boolean showVertexIndices() { return showVertexIndices; } public void setShowVertexIndices(final boolean show) { showVertexIndices = show; } public boolean showContainerIndices() { return showContainerIndices; } public void setShowContainerIndices(final boolean show) { showContainerIndices = show; } public boolean showCellCoordinates() { return showCellCoordinates; } public void setShowCellCoordinates(final boolean show) { showCellCoordinates = show; } public boolean showEdgeCoordinates() { return showEdgeCoordinates; } public void setShowEdgeCoordinates(final boolean show) { showEdgeCoordinates = show; } public boolean showVertexCoordinates() { return showVertexCoordinates; } public void setShowVertexCoordinates(final boolean show) { showVertexCoordinates = show; } public boolean showIndices() { return showIndices; } public void setShowIndices(final boolean show) { showIndices = show; } public boolean showCoordinates() { return showCoordinates; } public void setShowCoordinates(final boolean show) { showCoordinates = show; } public boolean showPossibleMoves() { return showPossibleMoves; } public void setShowPossibleMoves(final boolean show) { showPossibleMoves = show; } public ArrayList<String> trackNames() { return trackNames; } public void setTrackNames(final ArrayList<String> names) { trackNames = names; } public ArrayList<Boolean> trackShown() { return trackShown; } public void setTrackShown(final ArrayList<Boolean> shown) { trackShown = shown; } public Location selectedFromLocation() { return selectedFromLocation; } public void setSelectedFromLocation(final Location selected) { selectedFromLocation = selected; } public String pieceStyleExtension() { return pieceStyleExtension; } public void setPieceStyleExtension(final String extension) { pieceStyleExtension = extension; } public Font displayFont() { return displayFont; } public void setDisplayFont(final Font font) { displayFont = font; } public boolean flatBoard() { return flatBoard; } public void setFlatBoard(final boolean flat) { flatBoard = flat; } public boolean drawCornerCells() { return drawCornerCells; } public void setDrawCornerCells(final boolean draw) { drawCornerCells = draw; } public boolean drawCornerConcaveCells() { return drawCornerConcaveCells; } public void setDrawCornerConcaveCells(final boolean draw) { drawCornerConcaveCells = draw; } public boolean drawCornerConvexCells() { return drawCornerConvexCells; } public void setDrawCornerConvexCells(final boolean draw) { drawCornerConvexCells = draw; } public boolean drawMajorCells() { return drawMajorCells; } public void setDrawMajorCells(final boolean draw) { drawMajorCells = draw; } public boolean drawMinorCells() { return drawMinorCells; } public void setDrawMinorCells(final boolean draw) { drawMinorCells = draw; } public boolean drawOuterCells() { return drawOuterCells; } public void setDrawOuterCells(final boolean draw) { drawOuterCells = draw; } public boolean drawPerimeterCells() { return drawPerimeterCells; } public void setDrawPerimeterCells(final boolean draw) { drawPerimeterCells = draw; } public boolean drawInnerCells() { return drawInnerCells; } public void setDrawInnerCells(final boolean draw) { drawInnerCells = draw; } public boolean drawTopCells() { return drawTopCells; } public void setDrawTopCells(final boolean draw) { drawTopCells = draw; } public boolean drawBottomCells() { return drawBottomCells; } public void setDrawBottomCells(final boolean draw) { drawBottomCells = draw; } public boolean drawLeftCells() { return drawLeftCells; } public void setDrawLeftCells(final boolean draw) { drawLeftCells = draw; } public boolean drawRightCells() { return drawRightCells; } public void setDrawRightCells(final boolean draw) { drawRightCells = draw; } public boolean drawCenterCells() { return drawCenterCells; } public void setDrawCenterCells(final boolean draw) { drawCenterCells = draw; } public boolean drawPhasesCells() { return drawPhasesCells; } public void setDrawPhasesCells(final boolean draw) { drawPhasesCells = draw; } public Map<String, Boolean> drawSideCells() { return drawSideCells; } public void setDrawSideCells(final Map<String, Boolean> draw) { drawSideCells = draw; } public boolean drawNeighboursCells() { return drawNeighboursCells; } public void setDrawNeighboursCells(final boolean draw) { drawNeighboursCells = draw; } public boolean drawRadialsCells() { return drawRadialsCells; } public void setDrawRadialsCells(final boolean draw) { drawRadialsCells = draw; } public boolean drawDistanceCells() { return drawDistanceCells; } public void setDrawDistanceCells(final boolean draw) { drawDistanceCells = draw; } public boolean drawCornerVertices() { return drawCornerVertices; } public void setDrawCornerVertices(final boolean draw) { drawCornerVertices = draw; } public boolean drawCornerConcaveVertices() { return drawCornerConcaveVertices; } public void setDrawCornerConcaveVertices(final boolean draw) { drawCornerConcaveVertices = draw; } public boolean drawCornerConvexVertices() { return drawCornerConvexVertices; } public void setDrawCornerConvexVertices(final boolean draw) { drawCornerConvexVertices = draw; } public boolean drawMajorVertices() { return drawMajorVertices; } public void setDrawMajorVertices(final boolean draw) { drawMajorVertices = draw; } public boolean drawMinorVertices() { return drawMinorVertices; } public void setDrawMinorVertices(final boolean draw) { drawMinorVertices = draw; } public boolean drawOuterVertices() { return drawOuterVertices; } public void setDrawOuterVertices(final boolean draw) { drawOuterVertices = draw; } public boolean drawPerimeterVertices() { return drawPerimeterVertices; } public void setDrawPerimeterVertices(final boolean draw) { drawPerimeterVertices = draw; } public boolean drawInnerVertices() { return drawInnerVertices; } public void setDrawInnerVertices(final boolean draw) { drawInnerVertices = draw; } public boolean drawTopVertices() { return drawTopVertices; } public void setDrawTopVertices(final boolean draw) { drawTopVertices = draw; } public boolean drawBottomVertices() { return drawBottomVertices; } public void setDrawBottomVertices(final boolean draw) { drawBottomVertices = draw; } public boolean drawLeftVertices() { return drawLeftVertices; } public void setDrawLeftVertices(final boolean draw) { drawLeftVertices = draw; } public boolean drawRightVertices() { return drawRightVertices; } public void setDrawRightVertices(final boolean draw) { drawRightVertices = draw; } public boolean drawCenterVertices() { return drawCenterVertices; } public void setDrawCenterVertices(final boolean draw) { drawCenterVertices = draw; } public boolean drawPhasesVertices() { return drawPhasesVertices; } public void setDrawPhasesVertices(final boolean draw) { drawPhasesVertices = draw; } public Map<String, Boolean> drawSideVertices() { return drawSideVertices; } public void setDrawSideVertices(final Map<String, Boolean> draw) { drawSideVertices = draw; } public boolean drawNeighboursVertices() { return drawNeighboursVertices; } public void setDrawNeighboursVertices(final boolean draw) { drawNeighboursVertices = draw; } public boolean drawRadialsVertices() { return drawRadialsVertices; } public void setDrawRadialsVertices(final boolean draw) { drawRadialsVertices = draw; } public boolean drawDistanceVertices() { return drawDistanceVertices; } public void setDrawDistanceVertices(final boolean draw) { drawDistanceVertices = draw; } public boolean drawCentreEdges() { return drawCentreEdges; } public void setDrawCentreEdges(final boolean draw) { drawCentreEdges = draw; } public boolean drawCornerEdges() { return drawCornerEdges; } public void setDrawCornerEdges(final boolean draw) { drawCornerEdges = draw; } public boolean drawCornerConcaveEdges() { return drawCornerConcaveEdges; } public void setDrawCornerConcaveEdges(final boolean draw) { drawCornerConcaveEdges = draw; } public boolean drawCornerConvexEdges() { return drawCornerConvexEdges; } public void setDrawCornerConvexEdges(final boolean draw) { drawCornerConvexEdges = draw; } public boolean drawMajorEdges() { return drawMajorEdges; } public void setDrawMajorEdges(final boolean draw) { drawMajorEdges = draw; } public boolean drawMinorEdges() { return drawMinorEdges; } public void setDrawMinorEdges(final boolean draw) { drawMinorEdges = draw; } public boolean drawOuterEdges() { return drawOuterEdges; } public void setDrawOuterEdges(final boolean draw) { drawOuterEdges = draw; } public boolean drawPerimeterEdges() { return drawPerimeterEdges; } public void setDrawPerimeterEdges(final boolean draw) { drawPerimeterEdges = draw; } public boolean drawInnerEdges() { return drawInnerEdges; } public void setDrawInnerEdges(final boolean draw) { drawInnerEdges = draw; } public boolean drawTopEdges() { return drawTopEdges; } public void setDrawTopEdges(final boolean draw) { drawTopEdges = draw; } public boolean drawBottomEdges() { return drawBottomEdges; } public void setDrawBottomEdges(final boolean draw) { drawBottomEdges = draw; } public boolean drawLeftEdges() { return drawLeftEdges; } public void setDrawLeftEdges(final boolean draw) { drawLeftEdges = draw; } public boolean drawRightEdges() { return drawRightEdges; } public void setDrawRightEdges(final boolean draw) { drawRightEdges = draw; } public boolean drawDistanceEdges() { return drawDistanceEdges; } public void setDrawDistanceEdges(final boolean draw) { drawDistanceEdges = draw; } public boolean drawPhasesEdges() { return drawPhasesEdges; } public void setDrawPhasesEdges(final boolean draw) { drawPhasesEdges = draw; } public Map<String, Boolean> drawSideEdges() { return drawSideEdges; } public void setDrawSideEdges(final Map<String, Boolean> draw) { drawSideEdges = draw; } public boolean drawAxialEdges() { return drawAxialEdges; } public void setDrawAxialEdges(final boolean draw) { drawAxialEdges = draw; } public boolean drawHorizontalEdges() { return drawHorizontalEdges; } public void setDrawHorizontalEdges(final boolean draw) { drawHorizontalEdges = draw; } public boolean drawVerticalEdges() { return drawVerticalEdges; } public void setDrawVerticalEdges(final boolean draw) { drawVerticalEdges = draw; } public boolean drawAngledEdges() { return drawAngledEdges; } public void setDrawAngledEdges(final boolean draw) { drawAngledEdges = draw; } public boolean drawSlashEdges() { return drawSlashEdges; } public void setDrawSlashEdges(final boolean draw) { drawSlashEdges = draw; } public boolean drawSloshEdges() { return drawSloshEdges; } public void setDrawSloshEdges(final boolean draw) { drawSloshEdges = draw; } public boolean drawFacesOfVertices() { return drawFacesOfVertices; } public void setDrawFacesOfVertices(final boolean draw) { drawFacesOfVertices = draw; } public boolean drawEdgesOfVertices() { return drawEdgesOfVertices; } public void setDrawEdgesOfVertices(final boolean draw) { drawEdgesOfVertices = draw; } public boolean drawVerticesOfFaces() { return drawVerticesOfFaces; } public void setDrawVerticesOfFaces(final boolean draw) { drawVerticesOfFaces = draw; } public boolean drawEdgesOfFaces() { return drawEdgesOfFaces; } public void setDrawEdgesOfFaces(final boolean draw) { drawEdgesOfFaces = draw; } public boolean drawVerticesOfEdges() { return drawVerticesOfEdges; } public void setDrawVerticesOfEdges(final boolean draw) { drawVerticesOfEdges = draw; } public boolean drawFacesOfEdges() { return drawFacesOfEdges; } public void setDrawFacesOfEdges(final boolean draw) { drawFacesOfEdges = draw; } public Location lastClickedSite() { return lastClickedSite; } public void setLastClickedSite(final Location last) { lastClickedSite = last; } public ArrayList<Boolean> drawColumnsCells() { return drawColumnsCells; } public void setDrawColumnsCells(final ArrayList<Boolean> draw) { drawColumnsCells = draw; } public ArrayList<Boolean> drawRowsCells() { return drawRowsCells; } public void setDrawRowsCells(final ArrayList<Boolean> draw) { drawRowsCells = draw; } public ArrayList<Boolean> drawColumnsVertices() { return drawColumnsVertices; } public void setDrawColumnsVertices(final ArrayList<Boolean> draw) { drawColumnsVertices = draw; } public ArrayList<Boolean> drawRowsVertices() { return drawRowsVertices; } public void setDrawRowsVertices(final ArrayList<Boolean> draw) { drawRowsVertices = draw; } public boolean selectingConsequenceMove() { return selectingConsequenceMove; } public void setSelectingConsequenceMove(final boolean selecting) { selectingConsequenceMove = selecting; } public ArrayList<Location> possibleConsequenceLocations() { return possibleConsequenceLocations; } public void setPossibleConsequenceLocations(final ArrayList<Location> possible) { possibleConsequenceLocations = possible; } public boolean pieceBeingDragged() { return pieceBeingDragged; } public void setPieceBeingDragged(final boolean dragged) { pieceBeingDragged = dragged; } public boolean thisFrameIsAnimated() { return thisFrameIsAnimated; } public void setThisFrameIsAnimated(final boolean animated) { thisFrameIsAnimated = animated; } public boolean showCandidateValues() { return showCandidateValues; } public void setShowCandidateValues(final boolean show) { showCandidateValues = show; } public String lastErrorMessage() { return lastErrorMessage; } public void setLastErrorMessage(final String last) { lastErrorMessage = last; } public boolean noAnimation() { return noAnimation; } public void setNoAnimation(final boolean no) { noAnimation = no; } public boolean coordWithOutline() { return coordWithOutline; } public void setCoordWithOutline(final boolean outline) { coordWithOutline = outline; } public String errorReport() { return errorReport; } public void setErrorReport(final String report) { errorReport = report; } public HashMap<String, String> pieceFamilies() { return pieceFamilies; } public void setPieceFamilies(final HashMap<String, String> families) { pieceFamilies = families; } public String pieceFamily(final String gameName) { if (pieceFamilies.containsKey(gameName)) return pieceFamilies.get(gameName); return ""; } public void setPieceFamily(final String gameName, final String pieceFamily) { pieceFamilies.put(gameName, pieceFamily); } public Move getAnimationMove() { return animationMove; } public void setAnimationMove(final Move animationMove) { this.animationMove = animationMove; } public double furthestDistanceMultiplier() { return furthestDistanceMultiplier; } public void setFurthestDistanceMultiplier(final double furthestDistanceMultiplier) { this.furthestDistanceMultiplier = furthestDistanceMultiplier; } }
23,470
18.924448
121
java
Ludii
Ludii-master/ViewController/src/util/ShadedCells.java
package util; import java.awt.Color; import java.awt.Graphics2D; import java.awt.geom.GeneralPath; import java.awt.geom.PathIterator; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; import java.util.BitSet; import game.types.board.SiteType; import main.Constants; import main.math.MathRoutines; import other.topology.Cell; import other.topology.Topology; /** * Code for determining cell colours for "sunken" effect. * * @author cambolbro */ public class ShadedCells { public static void drawShadedCell ( final Graphics2D g2d, final Cell cell, final GeneralPath path, final Color[][] colours, final boolean checkeredBoard, final Topology topology ) { final int phase = !checkeredBoard ? 0 : topology.phaseByElementIndex(SiteType.Cell, cell.index()); final Point2D centre = pathCentre(path); //System.out.println("Centre is " + centre); final double[] coords = new double[6]; // if (colours[phase][1].getAlpha() == 0) // return; // user does not want this cell shown // Fill full cell dark g2d.setColor(colours[phase][0]); g2d.fill(path); // Fill light half of cell final BitSet highlights = determineHighlightedSides(path); //System.out.println(highlights); final GeneralPath pathLight = new GeneralPath(); double currX = 0; double currY = 0; int side = 0; for (final PathIterator pi = path.getPathIterator(null); !pi.isDone(); pi.next()) { switch (pi.currentSegment(coords)) { case PathIterator.SEG_CLOSE: pathLight.closePath(); break; case PathIterator.SEG_CUBICTO: if (highlights.get(side)) { pathLight.moveTo(centre.getX(), centre.getY()); pathLight.lineTo(currX, currY); pathLight.curveTo(coords[0], coords[1], coords[2], coords[3], coords[4], coords[5]); pathLight.closePath(); //pathLight.moveTo(centre.getX(), centre.getY()); } currX = coords[4]; currY = coords[5]; break; case PathIterator.SEG_LINETO: if (highlights.get(side)) { pathLight.moveTo(centre.getX(), centre.getY()); pathLight.lineTo(currX, currY); pathLight.lineTo(coords[0], coords[1]); pathLight.closePath(); } currX = coords[0]; currY = coords[1]; break; case PathIterator.SEG_MOVETO: //pathLight.moveTo(coords[0], coords[1]); currX = coords[0]; currY = coords[1]; break; case PathIterator.SEG_QUADTO: if (highlights.get(side)) { pathLight.moveTo(centre.getX(), centre.getY()); pathLight.lineTo(currX, currY); pathLight.quadTo(coords[0], coords[1], coords[2], coords[3]); pathLight.closePath(); } currX = coords[2]; currY = coords[3]; break; } side++; } g2d.setColor(colours[phase][2]); g2d.fill(pathLight); // Fill shrunken cell offset in base colour final GeneralPath pathInner = new GeneralPath(); final double amount = 1; for (final PathIterator pi = path.getPathIterator(null); !pi.isDone(); pi.next()) { switch (pi.currentSegment(coords)) { case PathIterator.SEG_CLOSE: pathInner.closePath(); break; case PathIterator.SEG_CUBICTO: { final double distA = MathRoutines.distance(centre.getX(), centre.getY(), coords[0], coords[1]); final double distB = MathRoutines.distance(centre.getX(), centre.getY(), coords[2], coords[3]); final double distC = MathRoutines.distance(centre.getX(), centre.getY(), coords[4], coords[5]); final double offA = (distA - amount) / distA; final double offB = (distB - amount) / distB; final double offC = (distC - amount) / distC; coords[0] = centre.getX() + offA * (coords[0] - centre.getX()); coords[1] = centre.getY() + offA * (coords[1] - centre.getY()); coords[2] = centre.getX() + offB * (coords[2] - centre.getX()); coords[3] = centre.getY() + offB * (coords[3] - centre.getY()); coords[4] = centre.getX() + offC * (coords[4] - centre.getX()); coords[5] = centre.getY() + offC * (coords[5] - centre.getY()); pathInner.curveTo(coords[0], coords[1], coords[2], coords[3], coords[4], coords[5]); } break; case PathIterator.SEG_LINETO: { final double dist = MathRoutines.distance(centre.getX(), centre.getY(), coords[0], coords[1]); final double off = (dist - amount) / dist; coords[0] = centre.getX() + off * (coords[0] - centre.getX()); coords[1] = centre.getY() + off * (coords[1] - centre.getY()); pathInner.lineTo(coords[0], coords[1]); } break; case PathIterator.SEG_MOVETO: { final double dist = MathRoutines.distance(centre.getX(), centre.getY(), coords[0], coords[1]); final double off = (dist - amount) / dist; coords[0] = centre.getX() + off * (coords[0] - centre.getX()); coords[1] = centre.getY() + off * (coords[1] - centre.getY()); pathInner.moveTo(coords[0], coords[1]); } break; case PathIterator.SEG_QUADTO: { final double distA = MathRoutines.distance(centre.getX(), centre.getY(), coords[0], coords[1]); final double distB = MathRoutines.distance(centre.getX(), centre.getY(), coords[2], coords[3]); final double offA = (distA - amount) / distA; final double offB = (distB - amount) / distB; coords[0] = centre.getX() + offA * (coords[0] - centre.getX()); coords[1] = centre.getY() + offA * (coords[1] - centre.getY()); coords[3] = centre.getX() + offB * (coords[3] - centre.getX()); coords[4] = centre.getY() + offB * (coords[4] - centre.getY()); pathInner.quadTo(coords[0], coords[1], coords[2], coords[3]); } break; } } g2d.setColor(colours[phase][1]); g2d.fill(pathInner); } /** * @return Bit set indicating which sides of the path should be highlighted. */ private static BitSet determineHighlightedSides(final GeneralPath path) { final Point2D centre = pathCentre(path); //System.out.println("Centre is " + centre); final double[] coords = new double[6]; // Determine shading of cells final BitSet highlights = new BitSet(); int side = 0; double currX = 0; double currY = 0; for (final PathIterator pi = path.getPathIterator(null); !pi.isDone(); pi.next()) { switch (pi.currentSegment(coords)) { case PathIterator.SEG_CLOSE: { break; } case PathIterator.SEG_CUBICTO: { final double mx = (currX + coords[4]) / 2.0; final double my = (currY + coords[5]) / 2.0; final Point2D vec = MathRoutines.normalisedVector(centre.getX(), centre.getY(), mx, my); final double theta = Math.atan2(vec.getY(), vec.getX()); if (theta > 0.1 * Math.PI || theta < -0.9 * Math.PI) highlights.set(side); currX = coords[4]; currY = coords[5]; break; } case PathIterator.SEG_LINETO: { final double mx = (currX + coords[0]) / 2.0; final double my = (currY + coords[1]) / 2.0; final Point2D vec = MathRoutines.normalisedVector(centre.getX(), centre.getY(), mx, my); final double theta = Math.atan2(vec.getY(), vec.getX()); //System.out.println("Side " + side + " has vec " + vec); if (theta > 0.9 * Math.PI || theta < -0.1 * Math.PI) highlights.set(side); currX = coords[0]; currY = coords[1]; break; } case PathIterator.SEG_MOVETO: { currX = coords[0]; currY = coords[1]; break; } case PathIterator.SEG_QUADTO: { final double mx = (currX + coords[2]) / 2.0; final double my = (currY + coords[3]) / 2.0; final Point2D vec = MathRoutines.normalisedVector(centre.getX(), centre.getY(), mx, my); final double theta = Math.atan2(vec.getY(), vec.getX()); if (theta > 0.1 * Math.PI || theta < -0.9 * Math.PI) highlights.set(side); currX = coords[2]; currY = coords[3]; break; } } side++; } return highlights; } /** * @return Approximately central point within path (if convex). */ private static Point2D pathCentre(final GeneralPath path) { final Rectangle2D bounds = path.getBounds2D(); return new Point2D.Double(bounds.getCenterX(), bounds.getCenterY()); } // private static String pathDetails(final GeneralPath path) // { // final StringBuffer sb = new StringBuffer(); // final double[] coords = new double[6]; // for (final PathIterator pi = path.getPathIterator(null); !pi.isDone(); pi.next()) // { // switch (pi.currentSegment(coords)) // { // case PathIterator.SEG_CLOSE: // sb.append("Z\n"); // break; // case PathIterator.SEG_CUBICTO: // sb.append("C " + coords[0] + " " + coords[1] + " " + coords[2] + " " + coords[3] + " " + coords[4] + " " + coords[5] + "\n"); // break; // case PathIterator.SEG_LINETO: // sb.append("L " + coords[0] + " " + coords[1] + "\n"); // break; // case PathIterator.SEG_MOVETO: // sb.append("M " + coords[0] + " " + coords[1] + "\n"); // break; // case PathIterator.SEG_QUADTO: // sb.append("Q " + coords[0] + " " + coords[1] + " " + coords[2] + " " + coords[3] + "\n"); // break; // } // } // return sb.toString(); // } //------------------------------------------------------------------------- public static void setCellColourByPhase ( final Graphics2D g2d, final int index, final Topology topology, final Color colorFillPhase0, final Color colorFillPhase1, final Color colorFillPhase2, final Color colorFillPhase3, final Color colorFillPhase4, final Color colorFillPhase5 ) { switch (topology.elementPhase(SiteType.Cell, index)) { case 0: g2d.setColor(colorFillPhase0); break; case 1: g2d.setColor(colorFillPhase1); break; case 2: g2d.setColor(colorFillPhase2); break; case 3: g2d.setColor(colorFillPhase3); break; case 4: g2d.setColor(colorFillPhase4); break; case 5: g2d.setColor(colorFillPhase5); break; default: System.out.println("** Error: Bad phase for cell " + index + "."); } } public static Color[][] shadedPhaseColours ( final Color colorFillPhase0, final Color colorFillPhase1, final Color colorFillPhase2, final Color colorFillPhase3, final Color colorFillPhase4, final Color colorFillPhase5 ) { // [c][0] = low, [c][1] = fill, [c][2] = high final Color[][] colours = new Color[Constants.MAX_CELL_COLOURS][3]; colours[0][1] = colorFillPhase0; colours[1][1] = colorFillPhase1; colours[2][1] = colorFillPhase2; colours[3][1] = colorFillPhase3; colours[4][1] = colorFillPhase4; colours[5][1] = colorFillPhase5; // Check that all phases have a base colour for (int c = 0; c < Constants.MAX_CELL_COLOURS; c++) { if (colours[c][1] != null) continue; // everything's fine if (c == 0) { // Set default light colour for phase 0 colours[0][1] = new Color(250, 221, 144, colours[0][1].getAlpha()); continue; } // Successively darken from previous phase final int r = colours[c - 1][1].getRed(); final int g = colours[c - 1][1].getGreen(); final int b = colours[c - 1][1].getBlue(); final int a = colours[c - 1][1].getAlpha(); // Darken slightly final double darken = 0.8; colours[c][1] = new Color((int)(darken * r), (int)(darken * g), (int)(darken * b), a); } for (int c = 0; c < Constants.MAX_CELL_COLOURS; c++) { final int r = colours[c][1].getRed(); final int g = colours[c][1].getGreen(); final int b = colours[c][1].getBlue(); final int a = colours[c][1].getAlpha(); // Calculate lowlight colour from base colour final double darken = 0.75; colours[c][0] = new Color((int)(darken * r), (int)(darken * g), (int)(darken * b), a); // Calculate highlight colour from base colour colours[c][2] = new Color ( // Math.min(255, 127 + r), // Math.min(255, 127 + g), // Math.min(255, 127 + b) Math.min(255, 32 + (int)(Math.sqrt(r / 255.0) * 255.0)), Math.min(255, 32 + (int)(Math.sqrt(g / 255.0) * 255.0)), Math.min(255, 32 + (int)(Math.sqrt(b / 255.0) * 255.0)), a ); } return colours; } }
13,152
33.52231
143
java
Ludii
Ludii-master/ViewController/src/util/StackVisuals.java
package util; import java.awt.geom.Point2D; import java.util.ArrayList; import bridge.Bridge; import game.equipment.container.Container; import game.rules.play.moves.Moves; import game.types.board.SiteType; import metadata.graphics.util.PieceStackType; import metadata.graphics.util.StackPropertyType; import other.context.Context; import other.location.Location; import other.move.Move; /** * Functions relating to the visuals of pieces in a stack. * * @author Matthew.Stephenson */ public class StackVisuals { //------------------------------------------------------------------------- /** * Get the offset distance to draw the piece as determined by its stack type. */ public static Point2D.Double calculateStackOffset(final Bridge bridge, final Context context, final Container container, final PieceStackType componentStackType, final int cellRadiusPixelsOriginal, final int level, final int site, final SiteType siteType, final int stackSize, final int state, final int value) { double stackOffsetX = 0.0; double stackOffsetY = 0.0; final int cellRadiusPixels = (int) (cellRadiusPixelsOriginal * context.game().metadata().graphics().stackMetadata(context, container, site, siteType, state, value, StackPropertyType.Scale)); final int stackLimit = (int) context.game().metadata().graphics().stackMetadata(context, container, site, siteType, state, value, StackPropertyType.Limit); final int stackOffsetAmount = (int)(0.4 * cellRadiusPixels); final double fullPieceStackScale = 4.8; if (componentStackType == PieceStackType.GroundDynamic) { if (stackSize == 2) { // Stack the pieces side by side. if (level == 0) { stackOffsetX = cellRadiusPixels / 2; } if (level == 1) { stackOffsetX = -cellRadiusPixels / 2; } } if (stackSize > 2) { if (level == 0) { stackOffsetX = cellRadiusPixels / 2; stackOffsetY = cellRadiusPixels / 2; } if (level == 1) { stackOffsetX = -cellRadiusPixels / 2; stackOffsetY = cellRadiusPixels / 2; } if (level == 2) { stackOffsetX = cellRadiusPixels / 2; stackOffsetY = -cellRadiusPixels / 2; } if (level == 3) { stackOffsetX = -cellRadiusPixels / 2; stackOffsetY = -cellRadiusPixels / 2; } } } else if (componentStackType == PieceStackType.Ground) { // Stack the pieces in a square arrangement around the middle of the site. if (level == 0) { stackOffsetX = cellRadiusPixels / 2; stackOffsetY = cellRadiusPixels / 2; } if (level == 1) { stackOffsetX = -cellRadiusPixels / 2; stackOffsetY = cellRadiusPixels / 2; } if (level == 2) { stackOffsetX = cellRadiusPixels / 2; stackOffsetY = -cellRadiusPixels / 2; } if (level == 3) { stackOffsetX = -cellRadiusPixels / 2; stackOffsetY = -cellRadiusPixels / 2; } } else if (componentStackType == PieceStackType.None || componentStackType == PieceStackType.Count || componentStackType == PieceStackType.CountColoured) { // do nothing } else if (componentStackType == PieceStackType.Fan) { // Stack the piece horizontally stackOffsetX = level * stackOffsetAmount; } else if (componentStackType == PieceStackType.TowardsCenter) { // Stack the piece towards the center of the board final Point2D currentPoint = container.topology().getGraphElement(siteType, ContainerUtil.getContainerSite(context, site, siteType)).centroid(); final double xDistanceToCenter = container.topology().centrePoint().getX() - currentPoint.getX(); final double yDistanceToCenter = container.topology().centrePoint().getY() - currentPoint.getY(); final double currentPointAngle = Math.atan(Math.abs(xDistanceToCenter)/Math.abs(yDistanceToCenter)); stackOffsetX = Math.sin(currentPointAngle) * stackOffsetAmount * fullPieceStackScale * level; stackOffsetY = Math.cos(currentPointAngle) * stackOffsetAmount * fullPieceStackScale * level; if (xDistanceToCenter < 0) stackOffsetX *= -1; if (yDistanceToCenter > 0) stackOffsetY *= -1; } else if (componentStackType == PieceStackType.FanAlternating) { // Stack the piece horizontally if (level%2 == 0) stackOffsetX = level * (stackOffsetAmount/2) + stackOffsetAmount/2; else stackOffsetX = (level+1) * -(stackOffsetAmount/2) + stackOffsetAmount/2; } else if (componentStackType == PieceStackType.Ring) { int cellRadiusStack = cellRadiusPixels; // If on a cell, recompute cell radius specifically for this cell. if (siteType.equals(SiteType.Cell)) cellRadiusStack = (int) (GraphUtil.calculateCellRadius(container.topology().cells().get(site)) * bridge.getContainerStyle(container.index()).placement().getWidth()); int stackSizeNew = stackSize; if (stackSizeNew == 0) stackSizeNew = 1; stackOffsetX = 0.7 * cellRadiusStack * Math.cos(Math.PI*2 * level / stackSizeNew); stackOffsetY = 0.7 * cellRadiusStack * Math.sin(Math.PI*2 * level / stackSizeNew); } else if (componentStackType == PieceStackType.Backgammon) { // Stack the pieces in columns of 5, repeated on top of each other. final int lineNumber = level%stackLimit; final int repeatNumber = level/stackLimit; if (site < container.numSites()/2) { stackOffsetY = -lineNumber * stackOffsetAmount*fullPieceStackScale - repeatNumber*stackOffsetAmount; } else { stackOffsetY = lineNumber * stackOffsetAmount*fullPieceStackScale - repeatNumber*stackOffsetAmount; } } else if (container.isHand()) { // Stack the pieces in a deck like fashion stackOffsetX = level * stackOffsetAmount/30; stackOffsetY = level * stackOffsetAmount/30; } else { // Stack the piece normally stackOffsetY = -level * stackOffsetAmount; } return new Point2D.Double(stackOffsetX, stackOffsetY); } //------------------------------------------------------------------------- /** * Returns the min and max level for a selected location, to be used when drawing stacked pieces. */ public static int[] getLevelMinAndMax(final Moves legal, final Location selectedLocation) { final ArrayList<Move> allMovesFromThisSite = new ArrayList<>(); for (final Move m : legal.moves()) { if ( m.getFromLocation().site() == selectedLocation.site() && m.getFromLocation().siteType() == selectedLocation.siteType() && m.levelMinNonDecision() == selectedLocation.level() && m.levelMaxNonDecision() >= selectedLocation.level() ) { allMovesFromThisSite.add(m); } } int levelMax = selectedLocation.level(); if (allMovesFromThisSite.size() > 0) { levelMax = allMovesFromThisSite.get(0).levelMaxNonDecision(); for (final Move m : allMovesFromThisSite) { if (m.levelMaxNonDecision() != levelMax) { levelMax = selectedLocation.level(); break; } } } final int[] levelMinMax = {selectedLocation.level(), levelMax}; return levelMinMax; } //------------------------------------------------------------------------- }
7,095
30.820628
312
java
Ludii
Ludii-master/ViewController/src/util/StringUtil.java
package util; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Graphics2D; import java.awt.RenderingHints; import java.awt.Shape; import java.awt.font.FontRenderContext; import java.awt.font.TextLayout; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; import metadata.graphics.util.colour.ColourRoutines; import other.topology.TopologyElement; /** * Functions relating strings visuals and manipulation. * * @author Matthew.Stephenson */ public class StringUtil { /** * Draws a string at a specified point (graphElement can be null if not important). */ public static void drawStringAtPoint(final Graphics2D g2d, final String string, final TopologyElement graphElement, final Point2D drawPosn, final boolean withOutline) { final Rectangle2D rect = g2d.getFont().getStringBounds(string, g2d.getFontRenderContext()); int posnX = 0; int posnY = 0; if (graphElement != null && graphElement.layer() > 1) { posnX = (int) ((drawPosn.getX() - rect.getWidth() / 2) + (graphElement.layer() / 2) * rect.getWidth() + 5); posnY = (int) (drawPosn.getY() + rect.getHeight() / 2.7); } else { posnX = (int) (drawPosn.getX() - rect.getWidth() / 2); posnY = (int) (drawPosn.getY() + rect.getHeight() / 2.7); // No idea why 2.7 is needed to center vertically properly. } if (!withOutline) g2d.drawString(string, posnX, posnY); else drawStringWithOutline(g2d, string, posnX, posnY); } //------------------------------------------------------------------------- /** * Draws a string at a specified position with a contrasting outline. */ private static void drawStringWithOutline(final Graphics2D g2d, final String string, final int posnX, final int posnY) { final Color originalFontColour = g2d.getColor(); final Graphics2D g2dNew = (Graphics2D) g2d.create(); g2dNew.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g2dNew.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); g2dNew.translate(posnX, posnY); g2dNew.setColor(ColourRoutines.getContrastColorFavourDark(g2d.getColor())); final FontRenderContext frc = g2d.getFontRenderContext(); final TextLayout tl = new TextLayout(string, g2d.getFont(), frc); final Shape shape = tl.getOutline(null); g2dNew.setStroke(new BasicStroke(g2d.getFont().getSize()/5)); g2dNew.draw(shape); g2dNew.draw(shape); g2dNew.setColor(originalFontColour); g2dNew.fill(shape); } //------------------------------------------------------------------------- /** * Calculate a consistent hashcode of a String. */ public static int hashCode(final String string) { int h = 0; final int len = string.length(); if (len > 0) { int off = 0; final char val[] = string.toCharArray(); for (int i = 0; i < len; i++) h = 31*h + val[off++]; } return h; } //------------------------------------------------------------------------- /** * Returns true if a string can be parsed to an integer. */ public static boolean isInteger(final String strNum) { if (strNum == null) { return false; } try { Integer.parseInt(strNum); } catch (final NumberFormatException nfe) { return false; } return true; } //------------------------------------------------------------------------- }
3,522
29.111111
167
java
Ludii
Ludii-master/ViewController/src/util/StrokeUtil.java
package util; import java.awt.BasicStroke; import metadata.graphics.util.LineStyle; /** * Routines for getting strokes with specified properties. * * @author matthew.stephenson and cambolbro */ public class StrokeUtil { public static BasicStroke getStrokeFromStyle ( final LineStyle lineStyle, final BasicStroke strokeThin, final BasicStroke strokeThick ) { switch(lineStyle) { case Hidden: return new BasicStroke(0); case Thick: return strokeThick; case ThickDashed: return getDashedStroke(strokeThick.getLineWidth()); case ThickDotted: return getDottedStroke(strokeThick.getLineWidth()); case Thin: return strokeThin; case ThinDashed: return getDashedStroke(strokeThin.getLineWidth()); case ThinDotted: return getDottedStroke(strokeThin.getLineWidth()); } return null; } //------------------------------------------------------------------------- public static BasicStroke getDashedStroke(final float strokeWidth) { final float dash[] = { strokeWidth*3, strokeWidth*3 }; return new BasicStroke ( strokeWidth, BasicStroke.CAP_BUTT, BasicStroke.JOIN_ROUND, 0.0f, dash, 0.0f ); } //------------------------------------------------------------------------- public static BasicStroke getDottedStroke(final float strokeWidth) { final float dash[] = { 0.0f, strokeWidth * 2.5f }; return new BasicStroke ( strokeWidth, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND, 0.0f, dash, 0.0f ); } //------------------------------------------------------------------------- }
1,591
23.875
88
java
Ludii
Ludii-master/ViewController/src/util/WorldLocation.java
package util; import java.awt.geom.Point2D; import java.io.Serializable; import other.location.Location; /** * World Location of a component * * @author Matthew.Stephenson and Eric.Piette */ public class WorldLocation implements Serializable { private static final long serialVersionUID = 1L; //------------------------------------------------------------------------- /** Internal location of the component. */ private final Location location; /** World position of the component. */ private final Point2D position; //------------------------------------------------------------------------- public WorldLocation(final Location location, final Point2D position) { this.location = location; this.position = position; } //------------------------------------------------------------------------- public Location location() { return this.location; } public Point2D position() { return this.position; } //-------------------------------------------------------------------------- }
1,027
20.416667
77
java
Ludii
Ludii-master/ViewController/src/view/component/BaseComponentStyle.java
package view.component; import java.awt.Color; import java.awt.Font; import java.awt.Point; import java.awt.Rectangle; import java.awt.geom.Point2D; import java.util.ArrayList; import java.util.Arrays; import java.util.BitSet; import org.jfree.graphics2d.svg.SVGGraphics2D; import bridge.Bridge; import game.equipment.component.Component; import graphics.ImageConstants; import graphics.ImageUtil; import graphics.svg.SVGtoImage; import metadata.graphics.Graphics; import metadata.graphics.util.MetadataImageInfo; import metadata.graphics.util.PieceColourType; import metadata.graphics.util.ValueDisplayInfo; import metadata.graphics.util.colour.ColourRoutines; import other.context.Context; import util.HiddenUtil; import util.StringUtil; /** * Base style for drawing components. * * @author Matthew.Stephenson */ public abstract class BaseComponentStyle implements ComponentStyle { protected Bridge bridge; protected Component component; protected String svgName; /** Component SVG image. */ private final ArrayList<SVGGraphics2D> imageSVG = new ArrayList<>(); /** Piece scale. */ protected double scaleX = 1.0; // Used as the default scale for cases where a piece cannot be scaled in one direction, e.g. for Ball components. protected double scaleY = 1.0; protected double maxBackgroundScale = 1.0; protected double maxForegroundScale = 1.0; /** Fill colour. */ protected Color fillColour; /** Edge colour. */ protected Color edgeColour = Color.BLACK; /** Secondary colour. E.g. for displaying numbers on pieces. */ protected Color secondaryColour; /** If the piece image should be rotated. */ protected int metadataRotation = 0; /** If the value or local state of the piece should be shown on it. */ protected ValueDisplayInfo showValue = new ValueDisplayInfo(); protected ValueDisplayInfo showLocalState = new ValueDisplayInfo(); // Force all visuals to be drawn as strings (used for N puzzles) protected boolean drawStringVisuals = false; //------------------------------------------------------------------------- /** * Returns an SVG image from a given file path. */ protected abstract SVGGraphics2D getSVGImageFromFilePath(SVGGraphics2D g2d, Context context, int imageSize, String sVGPath, int containerIndex, int localState, int value, int hiddenValue, final int rotation, final boolean secondary); //------------------------------------------------------------------------- public BaseComponentStyle(final Bridge bridge, final Component component) { this.component = component; this.bridge = bridge; } //---------------------------------------------------------------------------- @Override public void renderImageSVG(final Context context, final int containerIndex, final int imageSize, final int localState, final int value, final boolean secondary, final int hiddenValue, final int rotation) { edgeColour = new Color(0, 0, 0); fillColour = null; final int g2dSize = (int) (imageSize * scale(context, containerIndex, localState, value)); SVGGraphics2D g2d = new SVGGraphics2D(g2dSize, g2dSize); final BitSet hiddenBitset = HiddenUtil.intToBitSet(hiddenValue); g2d = hiddenCheck(context, hiddenBitset, g2d); final int imageState = hiddenStateCheck(context, hiddenBitset, localState); final int imageValue = hiddenValueCheck(context, hiddenBitset, value); String SVGNameLocal = component.getNameWithoutNumber(); SVGNameLocal = genericMetadataChecks(context, containerIndex, imageState, imageValue); String SVGPath = ImageUtil.getImageFullPath(SVGNameLocal); if (drawStringVisuals) SVGPath = null; SVGPath = hiddenWhatCheck(context, hiddenBitset, SVGPath); hiddenWhoCheck(context, hiddenBitset); int maxNumRotations = context.currentInstanceContext().game().maximalRotationStates(); if (maxNumRotations == 0) maxNumRotations = 1; final int maxRotation = 360 / maxNumRotations; final int degreesRotation = rotation * maxRotation + metadataRotation; while (imageSVG.size() <= localState) imageSVG.add(null); imageSVG.set(localState, getSVGImageFromFilePath(g2d, context, imageSize, SVGPath, containerIndex, imageState, imageValue, hiddenValue, degreesRotation, secondary)); } //------------------------------------------------------------------------- private static SVGGraphics2D hiddenCheck(final Context context, final BitSet hiddenBitset, final SVGGraphics2D g2d) { if (hiddenBitset.get(HiddenUtil.hiddenIndex)) return new SVGGraphics2D(0, 0); return g2d; } private static int hiddenValueCheck(final Context context, final BitSet hiddenBitset, final int value) { if (hiddenBitset.get(HiddenUtil.hiddenValueIndex)) return -1; return value; } private static int hiddenStateCheck(final Context context, final BitSet hiddenBitset, final int localState) { if (hiddenBitset.get(HiddenUtil.hiddenStateIndex)) return -1; return localState; } private void hiddenWhoCheck(final Context context, final BitSet hiddenBitset) { if (hiddenBitset.get(HiddenUtil.hiddenWhoIndex)) { fillColour = Color.GRAY; edgeColour = Color.GRAY; } } private String hiddenWhatCheck(final Context context, final BitSet hiddenBitset, final String sVGPath) { String filePath = sVGPath; if (hiddenBitset.get(HiddenUtil.hiddenWhatIndex)) { final String hiddenImageName = context.game().metadata().graphics().pieceHiddenImage(); if (hiddenImageName != null) { filePath = ImageUtil.getImageFullPath(hiddenImageName); svgName = hiddenImageName; } else { filePath = null; svgName = "?"; } } return filePath; } //------------------------------------------------------------------------- /** * Performs all graphics metadata checks that apply to all piece types. */ public String genericMetadataChecks(final Context context, final int containerIndex, final int localState, final int value) { svgName = component.getNameWithoutNumber(); final Graphics metadataGraphics = context.game().metadata().graphics(); final Point2D.Float scale = metadataGraphics.pieceScale(context, component.owner(), component.name(), containerIndex, localState, value); scaleX = scale.getX(); scaleY = scale.getY(); // Check the .lud metadata for piece name extension final String nameExtension = metadataGraphics.pieceNameExtension(context, component.owner(), component.name(), containerIndex, localState, value); if (nameExtension != null) svgName = svgName + nameExtension; final String nameReplacement = metadataGraphics.pieceNameReplacement(context, component.owner(), component.name(), containerIndex, localState, value); if (nameReplacement != null) svgName = nameReplacement; final boolean addLocalStateToName = metadataGraphics.addStateToName(context, component.owner(), component.name(), containerIndex, localState, value); if (addLocalStateToName) svgName = svgName + localState; // Check the .lud metadata for piece colour final Color pieceColour = metadataGraphics.pieceColour(context, component.owner(), component.name(), containerIndex, localState, value, PieceColourType.Fill); if (pieceColour != null) fillColour = pieceColour; final Color pieceEdgeColour = metadataGraphics.pieceColour(context, component.owner(), component.name(), containerIndex, localState, value, PieceColourType.Edge); if (pieceEdgeColour != null) edgeColour = pieceEdgeColour; final Color pieceSecondaryColour = metadataGraphics.pieceColour(context, component.owner(), component.name(), containerIndex, localState, value, PieceColourType.Secondary); if (pieceSecondaryColour != null) secondaryColour = pieceSecondaryColour; metadataRotation = metadataGraphics.pieceRotate(context, component.owner(), component.name(), containerIndex, localState, value); showValue = metadataGraphics.displayPieceValue(context, component.owner(), component.name()); showLocalState = metadataGraphics.displayPieceState(context, component.owner(), component.name()); if (component.isDie()) showLocalState = new ValueDisplayInfo(); if ( !component.isDie() && ( bridge.settingsVC().pieceFamily(context.game().name()).equals(ImageConstants.abstractFamilyKeyword) || ( bridge.settingsVC().pieceFamily(context.game().name()).equals("") && metadataGraphics.pieceFamilies() != null && Arrays.asList(metadataGraphics.pieceFamilies()).contains(ImageConstants.abstractFamilyKeyword) ) ) ) { svgName = ImageConstants.customImageKeywords[0]; } bridge.settingsVC().setPieceStyleExtension(bridge.settingsVC().pieceFamily(context.game().name())); if (bridge.settingsVC().pieceStyleExtension().equals("")) if (metadataGraphics.pieceFamilies() != null) bridge.settingsVC().setPieceStyleExtension(metadataGraphics.pieceFamilies()[0]); if (!Arrays.asList(ImageConstants.defaultFamilyKeywords).contains(bridge.settingsVC().pieceStyleExtension()) && !bridge.settingsVC().pieceStyleExtension().equals(ImageConstants.abstractFamilyKeyword) && !bridge.settingsVC().pieceStyleExtension().equals("")) svgName = svgName + "_" + bridge.settingsVC().pieceStyleExtension(); if (fillColour == null) fillColour = bridge.settingsColour().playerColour(context, component.owner()); // if (svgName.length() == 1) // { // edgeColour = fillColour; // fillColour = null; // } if (secondaryColour == null) secondaryColour = ColourRoutines.getContrastColorFavourDark(fillColour); return svgName; } //---------------------------------------------------------------------------- /** * Returns an SVG image for the component style background. */ protected SVGGraphics2D getBackground(final SVGGraphics2D g2d, final Context context, final int containerIndex, final int localState, final int value, final int dim) { final Graphics metadataGraphics = context.game().metadata().graphics(); for (final MetadataImageInfo backgroundImageInfo : metadataGraphics.pieceBackground(context, component.owner(), component.name(), containerIndex, localState, value)) { if (backgroundImageInfo.path() != null) { final String backgroundPath = ImageUtil.getImageFullPath(backgroundImageInfo.path()); final double backgroundScaleX = backgroundImageInfo.scaleX(); final double backgroundScaleY = backgroundImageInfo.scaleY(); maxForegroundScale = Math.max(Math.max(backgroundScaleX, backgroundScaleY), maxBackgroundScale); Color backgroundColour = backgroundImageInfo.mainColour(); Color backgroundEdgeColour = backgroundImageInfo.secondaryColour(); final int rotation = backgroundImageInfo.rotation(); final double offsetX = backgroundImageInfo.offestX(); final double offsetY = backgroundImageInfo.offestY(); if (backgroundColour == null) backgroundColour = bridge.settingsColour().playerColour(context, component.owner()); if (backgroundEdgeColour == null) backgroundEdgeColour = Color.BLACK; final int tileSizeX = (int) (dim * backgroundScaleX); final int tileOffsetX = (dim-tileSizeX)/2; final int tileSizeY = (int) (dim * backgroundScaleY); final int tileOffsetY = (dim-tileSizeY)/2; SVGtoImage.loadFromFilePath ( g2d, backgroundPath, new Rectangle((int) (tileOffsetX + tileOffsetX*offsetX), (int) (tileOffsetY + tileOffsetY*offsetY), tileSizeX, tileSizeY), backgroundEdgeColour, backgroundColour, rotation ); } if (backgroundImageInfo.text() != null) { final Font valueFont = new Font("Arial", Font.BOLD, (int) (dim * backgroundImageInfo.scale())); g2d.setColor(backgroundImageInfo.mainColour()); g2d.setFont(valueFont); StringUtil.drawStringAtPoint(g2d, backgroundImageInfo.text(), null, new Point(g2d.getWidth()/2,g2d.getHeight()/2), true); } } return g2d; } //---------------------------------------------------------------------------- /** * Returns an SVG image for the component style foreground. */ protected SVGGraphics2D getForeground(final SVGGraphics2D g2d, final Context context, final int containerIndex, final int localState, final int value, final int dim) { final Graphics metadataGraphics = context.game().metadata().graphics(); for (final MetadataImageInfo foregroundImageInfo : metadataGraphics.pieceForeground(context, component.owner(), component.name(), containerIndex, localState, value)) { if (foregroundImageInfo.path() != null) { final String foregroundPath = ImageUtil.getImageFullPath(foregroundImageInfo.path()); final double foregroundScaleX = foregroundImageInfo.scaleX(); final double foregroundScaleY = foregroundImageInfo.scaleY(); maxForegroundScale = Math.max(Math.max(foregroundScaleX, foregroundScaleY), maxForegroundScale); Color foregroundColour = foregroundImageInfo.mainColour(); Color foregroundEdgeColour = foregroundImageInfo.secondaryColour(); final int rotation = foregroundImageInfo.rotation(); final double offsetX = foregroundImageInfo.offestX(); final double offsetY = foregroundImageInfo.offestY(); if (foregroundColour == null) foregroundColour = bridge.settingsColour().playerColour(context, component.owner()); if (foregroundEdgeColour == null) foregroundEdgeColour = Color.BLACK; final int tileSizeX = (int) (dim * foregroundScaleX); final int tileOffsetX = (dim-tileSizeX)/2; final int tileSizeY = (int) (dim * foregroundScaleY); final int tileOffsetY = (dim-tileSizeY)/2; SVGtoImage.loadFromFilePath ( g2d, foregroundPath, new Rectangle((int) (tileOffsetX + tileOffsetX*offsetX), (int) (tileOffsetY + tileOffsetY*offsetY), tileSizeX, tileSizeY), foregroundEdgeColour, foregroundColour, rotation ); } if (foregroundImageInfo.text() != null) { final Font valueFont = new Font("Arial", Font.BOLD, (int) (dim * foregroundImageInfo.scale())); g2d.setColor(foregroundImageInfo.mainColour()); g2d.setFont(valueFont); StringUtil.drawStringAtPoint(g2d, foregroundImageInfo.text(), null, new Point(g2d.getWidth()/2,g2d.getHeight()/2), true); } } return g2d; } //---------------------------------------------------------------------------- @Override public SVGGraphics2D getImageSVG(final int localState) { if (localState >= imageSVG.size()) { if (imageSVG.size() > 0) return imageSVG.get(0); else return null; } return imageSVG.get(localState); } //------------------------------------------------------------------------- @Override public double scale(final Context context, final int containerIndex, final int localState, final int value) { // Need to check metadata for any adjusted piece scales, as the same component style may have different scales based on state and value (e.g. Mig Mang). final Graphics metadataGraphics = context.game().metadata().graphics(); final Point2D.Float scale = metadataGraphics.pieceScale(context, component.owner(), component.name(), containerIndex, localState, value); scaleX = scale.getX(); scaleY = scale.getY(); return Math.max(Math.max(Math.max(scaleX, scaleY), maxBackgroundScale),maxForegroundScale); } @Override public ArrayList<Point> origin() { return new ArrayList<>(); } @Override public ArrayList<Point2D> getLargeOffsets() { return new ArrayList<>(); } @Override public Point largePieceSize() { return new Point(); } //------------------------------------------------------------------------- @Override public Color getSecondaryColour() { return secondaryColour; } //------------------------------------------------------------------------- }
15,923
36.118881
260
java
Ludii
Ludii-master/ViewController/src/view/component/ComponentStyle.java
package view.component; import java.awt.Color; import java.awt.Point; import java.awt.geom.Point2D; import java.util.ArrayList; import org.jfree.graphics2d.svg.SVGGraphics2D; import other.context.Context; /** * Something to be drawn. * View part of MVC for equipment. * @author matthew.stephenson and cambolbro */ public interface ComponentStyle { /** Sets the (localState specific) image for the component. */ void renderImageSVG(final Context context, final int containerIndex, final int imageSize, final int localState, final int value, final boolean secondary, final int maskedValue, final int rotation); /** Gets the SVG image for this component for a given localState value. */ SVGGraphics2D getImageSVG(final int localState); // Functions for large pieces ArrayList<Point> origin(); Point largePieceSize(); ArrayList<Point2D> getLargeOffsets(); // Getters Color getSecondaryColour(); double scale(final Context context, final int containerIndex, final int localState, final int value); }
1,019
29
198
java
Ludii
Ludii-master/ViewController/src/view/component/custom/CardStyle.java
package view.component.custom; import bridge.Bridge; import game.equipment.component.Component; /** * Implementation of card component style. * * @author cambolbro */ public class CardStyle extends PieceStyle { // /** // * Temporary storage for base card images when a card deck is loaded. // */ // private final BaseCardImages baseCardImages = new BaseCardImages(); // //---------------------------------------------------------------------------- public CardStyle(final Bridge bridge, final Component component) { super(bridge, component); } //---------------------------------------------------------------------------- // // @Override // protected SVGGraphics2D getSVGImageFromFilePath(final SVGGraphics2D g2dOriginal, final Context context, final int imageSize, // final String filePath, final int localState, final int value, final int hiddenValue, final int rotation, final boolean secondary) // { // final Point2D.Double[][] pts = // { // { // Joker // }, // { // Ace // new Point2D.Double(0.5, 0.5) // }, // { // 2 // new Point2D.Double(0.5, 0.225), new Point2D.Double(0.5, 0.775) // }, // { // 3 // new Point2D.Double(0.5, 0.225), new Point2D.Double(0.5, 0.5), // new Point2D.Double(0.5, 0.775) // }, // { // 4 // new Point2D.Double(0.31, 0.225), new Point2D.Double(0.69, 0.225), // new Point2D.Double(0.31, 0.775), new Point2D.Double(0.69, 0.775) // }, // { // 5 // new Point2D.Double(0.31, 0.225), new Point2D.Double(0.69, 0.225), // new Point2D.Double(0.5, 0.5), // new Point2D.Double(0.31, 0.775), new Point2D.Double(0.69, 0.775) // }, // { // 6 // new Point2D.Double(0.31, 0.225), new Point2D.Double(0.69, 0.225), // new Point2D.Double(0.31, 0.5), new Point2D.Double(0.69, 0.5), // new Point2D.Double(0.31, 0.775), new Point2D.Double(0.69, 0.775) // }, // { // 7 // new Point2D.Double(0.31, 0.225), new Point2D.Double(0.69, 0.225), // new Point2D.Double(0.5, 0.35), // new Point2D.Double(0.31, 0.5), new Point2D.Double(0.69, 0.5), // new Point2D.Double(0.31, 0.775), new Point2D.Double(0.69, 0.775) // }, // { // 8 // new Point2D.Double(0.31, 0.225), new Point2D.Double(0.69, 0.225), // new Point2D.Double(0.5, 0.35), // new Point2D.Double(0.31, 0.5), new Point2D.Double(0.69, 0.5), // new Point2D.Double(0.5, 0.65), // new Point2D.Double(0.31, 0.775), new Point2D.Double(0.69, 0.775) // }, // { // 9 // new Point2D.Double(0.31, 0.225), new Point2D.Double(0.69, 0.225), // new Point2D.Double(0.31, 0.41), new Point2D.Double(0.69, 0.41), // new Point2D.Double(0.5, 0.5), // new Point2D.Double(0.31, 0.59), new Point2D.Double(0.69, 0.59), // new Point2D.Double(0.31, 0.775), new Point2D.Double(0.69, 0.775) // }, // { // 10 // new Point2D.Double(0.31, 0.225), new Point2D.Double(0.69, 0.225), // new Point2D.Double(0.5, 0.31), // new Point2D.Double(0.31, 0.41), new Point2D.Double(0.69, 0.41), // new Point2D.Double(0.31, 0.59), new Point2D.Double(0.69, 0.59), // new Point2D.Double(0.5, 0.69), // new Point2D.Double(0.31, 0.775), new Point2D.Double(0.69, 0.775) // }, // { // Jack // new Point2D.Double(0.81, 0.135) // }, // { // Queen // new Point2D.Double(0.81, 0.135) // }, // { // King // new Point2D.Double(0.81, 0.135) // }, // }; // // final int cardSize = imageSize; // // if (!baseCardImages.areLoaded()) // baseCardImages.loadImages(cardSize); // // final int ht = cardSize; // final int wd = (int)(55 / 85.0 * ht + 0.5) / 2 * 2; // // // Load the relevant large suit image from file // final String suitSVGLarge = baseCardImages.getPath(BaseCardImages.SUIT_LARGE, getCardSuitValue(context)); // // final Rectangle2D suitRectLarge = SVGtoImage.getBounds(suitSVGLarge, baseCardImages.getSuitSizeBig()); // final int lx = (int) suitRectLarge.getWidth(); // final int ly = (int) suitRectLarge.getHeight(); // // // Create the small suit image from the large one // final String suitSVGSmall = baseCardImages.getPath(BaseCardImages.SUIT_SMALL, getCardSuitValue(context)); // // final Rectangle2D suitRectSmall = SVGtoImage.getBounds(suitSVGSmall, baseCardImages.getSuitSizeSmall()); // final int sy = (int) suitRectSmall.getHeight(); //suitSizeSmall; // final int sx = (int)(sy * lx / (double)ly + 0.5); // // // Assemble the card image // final SVGGraphics2D g2d = new SVGGraphics2D(cardSize, cardSize); // g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); // g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); // // Color cardFillColour = Color.white; // if (hiddenValue == 1) // cardFillColour = new Color(180,0,0); // // // Draw and fill card outline // final int round = (int)(0.1 * cardSize + 0.5); // // g2d.setColor(cardFillColour); // g2d.fillRoundRect(cardSize/2-wd/2, 1, wd, ht-2, round, round); // // g2d.setStroke(new BasicStroke()); // g2d.setColor(Color.black); // g2d.drawRoundRect(cardSize/2-wd/2, 1, wd, ht-2, round, round); // // // don't draw the images on the card if its masked // if (hiddenValue == 0) // { // // Margin offset from the edges // final int off = (int)(0.03 * cardSize + 0.5); // // // Draw the left margin label // final int fontSize = (int)(0.11 * cardSize + 0.5); // final Font cardFont = new Font("Arial", Font.BOLD, fontSize); // g2d.setFont(cardFont); // // final String label = component.cardType().label(); // final Rectangle2D bounds = g2d.getFontMetrics().getStringBounds(label, g2d); // // final int tx = cardSize / 2 - wd / 2 + 2 * off - (int)(bounds.getWidth()/2 + 0.5); // final int ty = 5 * off; // // final Color color = isBlack(context) ? Color.BLACK : Color.RED; // g2d.setColor(color); // g2d.drawString(label, tx, ty); // // // Draw the left margin suit image (small) //// SVGtoImage.loadFromString //// ( //// g2d, suitSVGSmall, baseCardImages.getSuitSizeSmall(cardSize), //// baseCardImages.getSuitSizeSmall(cardSize), //// cardSize/2-wd/2+2*off-sx/2, 6*off, color, null, false, //// 0, false, false //// ); // // final int number = component.cardType().number(); //ordinal(); // // if (component.cardType().isRoyal()) //id > 10) // { // // Is a royal card // final int ry = (int)(0.6 * cardSize + 0.5); // // final String royalSVG = // isBlack(context) // ? baseCardImages.getPath(BaseCardImages.BLACK_ROYAL, number) // : // baseCardImages.getPath(BaseCardImages.RED_ROYAL, number); // // // Draw the royal image // if (royalSVG != null) // { //// SVGtoImage.loadFromString //// ( //// g2d, royalSVG, ry, ry, cardSize/2-ry/2, cardSize/2-ry/2, color, null, true, //// 0, false, false //// ); // } // } // // // Draw the interior suit images (large) // if (number < pts.length) // { // for (int n = 0; n < pts[number].length; n++) // { // final Point2D.Double pt = pts[number][n]; // final int x = cardSize / 2 - wd / 2 + (int)(pt.x * wd + 0.5); // final int y = (int)(pt.y * ht + 0.5); //// SVGtoImage.loadFromString //// ( //// g2d, suitSVGLarge, baseCardImages.getSuitSizeBig(cardSize), //// baseCardImages.getSuitSizeBig(cardSize), x-lx/2, y-ly/2, color, null, false, //// 0, false, false //// ); // } // } // } // // return g2d; // } // // //---------------------------------------------------------------------------- // // /** // * Returns True if this card should be black. // */ // private boolean isBlack(final Context context) // { // if (SuitType.values()[getCardSuitValue(context)-1] == SuitType.Diamonds || SuitType.values()[getCardSuitValue(context)-1] == SuitType.Hearts) // return false; // return true; // } // // //---------------------------------------------------------------------------- // // /** // * Returns the value of this card's suit (considering the metadata ranking). // */ // private int getCardSuitValue(final Context context) // { // if (!component.isCard()) // return Constants.UNDEFINED; // // final Card card = (Card)component; // if (context.game().metadata().graphics().suitRanking() == null) // return card.suit(); // // final int initValue = card.suit(); // int cardValue = 0; // for (final SuitType suit : context.game().metadata().graphics().suitRanking()) // { // cardValue++; // if (suit == SuitType.Clubs && initValue == SuitType.Clubs.value) // return cardValue; // if (suit == SuitType.Spades && initValue == SuitType.Spades.value) // return cardValue; // if (suit == SuitType.Diamonds && initValue == SuitType.Diamonds.value) // return cardValue; // if (suit == SuitType.Hearts && initValue == SuitType.Hearts.value) // return cardValue; // } // return card.suit(); // } //---------------------------------------------------------------------------- }
8,962
33.473077
145
java