diff --git a/src/external/JSON/JSONArray.java b/src/external/JSON/JSONArray.java index 3a0d49915..df7adffc4 100644 --- a/src/external/JSON/JSONArray.java +++ b/src/external/JSON/JSONArray.java @@ -73,7 +73,7 @@ of this software and associated documentation files (the "Software"), to deal * false, or null. *
  • Values can be separated by ; (semicolon) as * well as by , (comma).
  • - *
  • Numbers may have the + *
  • Numbers may have the * 0x- (hex) prefix.
  • * @@ -155,12 +155,12 @@ public JSONArray(Collection collection) { if (collection != null) { Iterator iter = collection.iterator(); while (iter.hasNext()) { - this.myArrayList.add(JSONObject.wrap(iter.next())); + this.myArrayList.add(JSONObject.wrap(iter.next())); } } } - + /** * Construct a JSONArray from an array * @throws JSONException If not an array. @@ -177,8 +177,8 @@ public JSONArray(Object array) throws JSONException { "JSONArray initial value should be a string or collection or array."); } } - - + + /** * Get the object value associated with an index. * @param index @@ -761,8 +761,8 @@ public JSONArray put(int index, Object value) throws JSONException { } return this; } - - + + /** * Remove an index and close the hole. * @param index The index of the element to be removed. diff --git a/src/external/JSON/JSONObject.java b/src/external/JSON/JSONObject.java index f11ed5fa1..1cef5329b 100644 --- a/src/external/JSON/JSONObject.java +++ b/src/external/JSON/JSONObject.java @@ -62,7 +62,7 @@ of this software and associated documentation files (the "Software"), to deal * coercion for you. The opt methods differ from the get methods in that they * do not throw. Instead, they return a specified value, such as null. *

    - * The put methods add or replace values in an object. For example, + * The put methods add or replace values in an object. For example, *

    myString = new JSONObject().put("JSON", "Hello, World!").toString();
    * produces the string {"JSON": "Hello, World"}. *

    @@ -156,7 +156,7 @@ public JSONObject() { * Missing keys are ignored. * @param jo A JSONObject. * @param names An array of strings. - * @throws JSONException + * @throws JSONException * @exception JSONException If a value is a non-finite number or if a name is duplicated. */ public JSONObject(JSONObject jo, String[] names) { @@ -232,7 +232,7 @@ public JSONObject(JSONTokener x) throws JSONException { * * @param map A map object that can be used to initialize the contents of * the JSONObject. - * @throws JSONException + * @throws JSONException */ public JSONObject(Map map) { this.map = new HashMap(); @@ -320,20 +320,20 @@ public JSONObject(String source) throws JSONException { */ public JSONObject(String baseName, Locale locale) throws JSONException { this(); - ResourceBundle r = ResourceBundle.getBundle(baseName, locale, + ResourceBundle r = ResourceBundle.getBundle(baseName, locale, Thread.currentThread().getContextClassLoader()); // Iterate through the keys in the bundle. - + Enumeration keys = r.getKeys(); while (keys.hasMoreElements()) { Object key = keys.nextElement(); if (key instanceof String) { - -// Go through the path, ensuring that there is a nested JSONObject for each + +// Go through the path, ensuring that there is a nested JSONObject for each // segment except the last. Add the value using the last segment's name into // the deepest nested JSONObject. - + String[] path = ((String)key).split("\\."); int last = path.length - 1; JSONObject target = this; @@ -351,7 +351,7 @@ public JSONObject(String baseName, Locale locale) throws JSONException { } } - + /** * Accumulate values under a key. It is similar to the put method except * that if there is already an object stored under the key then a @@ -420,7 +420,7 @@ public static String doubleToString(double d) { // Shave off trailing zeros and decimal point, if possible. String string = Double.toString(d); - if (string.indexOf('.') > 0 && string.indexOf('e') < 0 && + if (string.indexOf('.') > 0 && string.indexOf('e') < 0 && string.indexOf('E') < 0) { while (string.endsWith("0")) { string = string.substring(0, string.length() - 1); @@ -498,7 +498,7 @@ public double getDouble(String key) throws JSONException { /** - * Get the int value associated with a key. + * Get the int value associated with a key. * * @param key A key string. * @return The integer value. @@ -555,7 +555,7 @@ public JSONObject getJSONObject(String key) throws JSONException { /** - * Get the long value associated with a key. + * Get the long value associated with a key. * * @param key A key string. * @return The long value. @@ -639,8 +639,8 @@ public String getString(String key) throws JSONException { public boolean has(String key) { return this.map.containsKey(key); } - - + + /** * Increment a property of a JSONObject. If there is no such property, * create one with a value of 1. If there is such a property, and if @@ -657,11 +657,11 @@ public JSONObject increment(String key) throws JSONException { } else if (value instanceof Integer) { put(key, ((Integer)value).intValue() + 1); } else if (value instanceof Long) { - put(key, ((Long)value).longValue() + 1); + put(key, ((Long)value).longValue() + 1); } else if (value instanceof Double) { - put(key, ((Double)value).doubleValue() + 1); + put(key, ((Double)value).doubleValue() + 1); } else if (value instanceof Float) { - put(key, ((Float)value).floatValue() + 1); + put(key, ((Float)value).floatValue() + 1); } else { throw new JSONException("Unable to increment [" + quote(key) + "]."); } @@ -732,7 +732,7 @@ public static String numberToString(Number number) // Shave off trailing zeros and decimal point, if possible. String string = number.toString(); - if (string.indexOf('.') > 0 && string.indexOf('e') < 0 && + if (string.indexOf('.') > 0 && string.indexOf('e') < 0 && string.indexOf('E') < 0) { while (string.endsWith("0")) { string = string.substring(0, string.length() - 1); @@ -936,14 +936,14 @@ public String optString(String key) { */ public String optString(String key, String defaultValue) { Object object = opt(key); - return NULL.equals(object) ? defaultValue : object.toString(); + return NULL.equals(object) ? defaultValue : object.toString(); } private void populateMap(Object bean) { Class klass = bean.getClass(); -// If klass is a System class then set includeSuperClass to false. +// If klass is a System class then set includeSuperClass to false. boolean includeSuperClass = klass.getClassLoader() != null; @@ -956,7 +956,7 @@ private void populateMap(Object bean) { String name = method.getName(); String key = ""; if (name.startsWith("get")) { - if (name.equals("getClass") || + if (name.equals("getClass") || name.equals("getDeclaringClass")) { key = ""; } else { @@ -1137,7 +1137,7 @@ public JSONObject putOpt(String key, Object value) throws JSONException { /** * Produce a string in double quotes with backslash sequences in all the * right places. A backslash will be inserted within -1 || + if (string.indexOf('.') > -1 || string.indexOf('e') > -1 || string.indexOf('E') > -1) { return Double.valueOf(string); } else { @@ -1536,11 +1536,11 @@ static String valueToString(Object value, int indentFactor, int indent) /** - * Wrap an object, if necessary. If the object is null, return the NULL - * object. If it is an array or collection, wrap it in a JSONArray. If - * it is a map, wrap it in a JSONObject. If it is a standard property - * (Double, String, et al) then it is already wrapped. Otherwise, if it - * comes from one of the java packages, turn it into a string. And if + * Wrap an object, if necessary. If the object is null, return the NULL + * object. If it is an array or collection, wrap it in a JSONArray. If + * it is a map, wrap it in a JSONObject. If it is a standard property + * (Double, String, et al) then it is already wrapped. Otherwise, if it + * comes from one of the java packages, turn it into a string. And if * it doesn't, try to wrap it in a JSONObject. If the wrapping fails, * then null is returned. * @@ -1552,16 +1552,16 @@ public static Object wrap(Object object) { if (object == null) { return NULL; } - if (object instanceof JSONObject || object instanceof JSONArray || - NULL.equals(object) || object instanceof JSONString || + if (object instanceof JSONObject || object instanceof JSONArray || + NULL.equals(object) || object instanceof JSONString || object instanceof Byte || object instanceof Character || object instanceof Short || object instanceof Integer || - object instanceof Long || object instanceof Boolean || + object instanceof Long || object instanceof Boolean || object instanceof Float || object instanceof Double || object instanceof String) { return object; } - + if (object instanceof Collection) { return new JSONArray((Collection)object); } @@ -1584,7 +1584,7 @@ public static Object wrap(Object object) { } } - + /** * Write the contents of the JSONObject as JSON text to a writer. * For compactness, no whitespace is added. diff --git a/src/external/JSON/JSONString.java b/src/external/JSON/JSONString.java index eeecf4f17..b9daa77dc 100644 --- a/src/external/JSON/JSONString.java +++ b/src/external/JSON/JSONString.java @@ -1,17 +1,17 @@ package external.JSON; /** - * The JSONString interface allows a toJSONString() - * method so that a class can change the behavior of + * The JSONString interface allows a toJSONString() + * method so that a class can change the behavior of * JSONObject.toString(), JSONArray.toString(), - * and JSONWriter.value(Object). The - * toJSONString method will be used instead of the default behavior + * and JSONWriter.value(Object). The + * toJSONString method will be used instead of the default behavior * of using the Object's toString() method and quoting the result. */ public interface JSONString { /** - * The toJSONString method allows a class to produce its own JSON - * serialization. - * + * The toJSONString method allows a class to produce its own JSON + * serialization. + * * @return A strictly syntactically correct JSON text. */ public String toJSONString(); diff --git a/src/external/JSON/JSONTokener.java b/src/external/JSON/JSONTokener.java index b1024f4e8..24da74af7 100644 --- a/src/external/JSON/JSONTokener.java +++ b/src/external/JSON/JSONTokener.java @@ -55,7 +55,7 @@ public class JSONTokener { * @param reader A reader. */ public JSONTokener(Reader reader) { - this.reader = reader.markSupported() ? + this.reader = reader.markSupported() ? reader : new BufferedReader(reader); this.eof = false; this.usePrevious = false; @@ -64,13 +64,13 @@ public JSONTokener(Reader reader) { this.character = 1; this.line = 1; } - - + + /** * Construct a JSONTokener from an InputStream. */ public JSONTokener(InputStream inputStream) throws JSONException { - this(new InputStreamReader(inputStream)); + this(new InputStreamReader(inputStream)); } @@ -118,9 +118,9 @@ public static int dehexchar(char c) { } return -1; } - + public boolean end() { - return eof && !usePrevious; + return eof && !usePrevious; } @@ -133,7 +133,7 @@ public boolean more() throws JSONException { next(); if (end()) { return false; - } + } back(); return true; } @@ -155,11 +155,11 @@ public char next() throws JSONException { } catch (IOException exception) { throw new JSONException(exception); } - + if (c <= 0) { // End of stream this.eof = true; c = 0; - } + } } this.index += 1; if (this.previous == '\r') { @@ -213,7 +213,7 @@ public String next(int n) throws JSONException { while (pos < n) { chars[pos] = next(); if (end()) { - throw syntaxError("Substring bounds error"); + throw syntaxError("Substring bounds error"); } pos += 1; } @@ -420,7 +420,7 @@ public char skipTo(char to) throws JSONException { back(); return c; } - + /** * Make a JSONException to signal a syntax error. @@ -439,7 +439,7 @@ public JSONException syntaxError(String message) { * @return " at {index} [character {character} line {line}]" */ public String toString() { - return " at " + index + " [character " + this.character + " line " + + return " at " + index + " [character " + this.character + " line " + this.line + "]"; } } \ No newline at end of file diff --git a/src/org/ggp/base/apps/consoles/ClojureConsole.java b/src/org/ggp/base/apps/consoles/ClojureConsole.java index e16ca9cf8..a0dfd7b92 100644 --- a/src/org/ggp/base/apps/consoles/ClojureConsole.java +++ b/src/org/ggp/base/apps/consoles/ClojureConsole.java @@ -9,12 +9,12 @@ * console that has full access to all of the Java classes in the project. * This allows you to quickly experiment with the classes, without having to * write a full-blown Java program. - * + * * TODO: This could use some helper scripts, to allow it to quickly load game * rulesheets and so on. Right now you have to manually load everything * when you want to create a state machine that's initialized to a game, * which is pretty bothersome. - * + * * @author Sam */ public class ClojureConsole { diff --git a/src/org/ggp/base/apps/consoles/PythonConsole.java b/src/org/ggp/base/apps/consoles/PythonConsole.java index 7a63a821c..4c13d5e71 100644 --- a/src/org/ggp/base/apps/consoles/PythonConsole.java +++ b/src/org/ggp/base/apps/consoles/PythonConsole.java @@ -8,21 +8,21 @@ * This allows you to quickly experiment with the classes, without having to * write a full-blown Java program. There are also helpful scripts so that * you can get started quickly. - * + * * For example, try out: - * + * * >> display_random_walk(load_game('ticTacToe')) - * + * * This will load the game Tic-Tac-Toe and play through it randomly. * * This uses the JythonConsole implementation of a console with all of the * nice features like history, tab completion, et cetera. JythonConsole is an * external open source project, accessible at: - * + * * http://code.google.com/p/jythonconsole/ - * + * * The license for JythonConsole is available in the licenses/ directory. - * + * * @author Sam */ public class PythonConsole { diff --git a/src/org/ggp/base/apps/kiosk/GameCanvas.java b/src/org/ggp/base/apps/kiosk/GameCanvas.java index 4d72f0250..81eaac235 100644 --- a/src/org/ggp/base/apps/kiosk/GameCanvas.java +++ b/src/org/ggp/base/apps/kiosk/GameCanvas.java @@ -27,42 +27,42 @@ public abstract class GameCanvas extends JPanel implements Subject { public static final long serialVersionUID = 0x1; - + // Store the information about the current state of the game - protected StateMachine stateMachine; - protected MachineState gameState; + protected StateMachine stateMachine; + protected MachineState gameState; protected Role myRole; - - // Cache the location of the last click + + // Cache the location of the last click private int lastClickX; private int lastClickY; // Border constant private static final int BORDER_SIZE = 10; - + public GameCanvas() { super(); setFocusable(true); - - // Fiddle with Mouse Settings + + // Fiddle with Mouse Settings addMouseListener( new MouseAdapter() { public void mousePressed(MouseEvent e) { requestFocusInWindow(); - + // Update the click point cache lastClickX = e.getX(); lastClickY = e.getY(); handleClickEventWrapper(lastClickX, lastClickY); - + repaint(); } - + public void mouseReleased(MouseEvent e){ lastClickX = -1; - lastClickY = -1; + lastClickY = -1; } - }); - + }); + addMouseMotionListener( new MouseMotionAdapter() { public void mouseDragged(MouseEvent e) { if(lastClickX == -1) @@ -72,34 +72,34 @@ public void mouseDragged(MouseEvent e) { int dx = e.getX() - lastClickX; int dy = e.getY() - lastClickY; handleDragEventWrapper(dx, dy); - + // Update the click point cache lastClickX = e.getX(); lastClickY = e.getY(); - } - }); + } + }); } - + public void setStateMachine(StateMachine s) { stateMachine = s; } - + public void setRole(Role r) { myRole = r; } - + public void paintComponent(Graphics g){ super.paintComponent(g); - + g.setColor(Color.BLACK); g.drawRect(4, 4, getWidth() - 8, getHeight() - 8); g.drawRect(6, 6, getWidth() - 12, getHeight() - 12); - + if(!isEnabled()) { g.setColor(Color.red); g.drawRect(5, 5, getWidth() - 10, getHeight() - 10); } - + Graphics newG = g.create(BORDER_SIZE, BORDER_SIZE, getWidth() - 2*BORDER_SIZE, getHeight() - 2*BORDER_SIZE); if(gameState != null) { paintGame(newG); @@ -107,33 +107,33 @@ public void paintComponent(Graphics g){ paintGameDefault(newG, "Waiting for game state..."); } } - + // Subject boilerplate private Set theObservers = new HashSet(); - @Override + @Override public void addObserver(Observer observer) { - theObservers.add(observer); + theObservers.add(observer); } @Override public void notifyObservers(Event event) { for(Observer theObserver : theObservers) - theObserver.observe(event); + theObserver.observe(event); } - protected void submitWorkingMove(Move theMove) { + protected void submitWorkingMove(Move theMove) { notifyObservers(new MoveSelectedEvent(theMove)); } - - protected void submitFinalMove(Move theMove) { + + protected void submitFinalMove(Move theMove) { notifyObservers(new MoveSelectedEvent(theMove, true)); } - + public void updateGameState(MachineState gameState) { this.gameState = gameState; clearMoveSelection(); - + try { List legalMoves = stateMachine.getLegalMoves(gameState, myRole); if(legalMoves.size() > 1) { @@ -141,22 +141,22 @@ public void updateGameState(MachineState gameState) { } else { //submitWorkingMove(legalMoves.get(0)); submitFinalMove(legalMoves.get(0)); - } + } } catch (MoveDefinitionException e) { submitWorkingMove(null); - } + } } - + private void paintGameDefault(Graphics g, String message) { int width = g.getClipBounds().width; int height = g.getClipBounds().height; - + g.setColor(Color.WHITE); g.fillRect(0, 0, width, height); - + g.setColor(Color.BLACK); g.drawString(message, width/2 - message.length()*2, height/2); - } + } /* ---------- Convenience methods ---------- */ protected boolean gameStateHasFact(String fact) { @@ -182,7 +182,7 @@ protected Set gameStateHasFactsMatching(String ptrn) { } return theMatches; } - + protected boolean gameStateHasLegalMove(String move) { try { List legalMoves = stateMachine.getLegalMoves(gameState, myRole); @@ -190,12 +190,12 @@ protected boolean gameStateHasLegalMove(String move) { if(aMove.toString().equals(move)) return true; } - return false; + return false; } catch(Exception e) { return false; - } + } } - + protected Set gameStateHasLegalMovesMatching(String ptrn) { Pattern pattern = Pattern.compile(ptrn); @@ -215,9 +215,9 @@ protected Set gameStateHasLegalMovesMatching(String ptrn) { // has no legal moves defined for a player. //e.printStackTrace(); return new HashSet(); - } + } } - + protected Move stringToMove(String move) { try { @@ -225,27 +225,27 @@ protected Move stringToMove(String move) { } catch(Exception e) { return null; } - } + } /* ---------- Enabling wrappers ------------ */ - + private void handleDragEventWrapper(int dx, int dy) { if(!isEnabled()) return; handleDragEvent(dx, dy); } - + private void handleClickEventWrapper(int x, int y) { if(!isEnabled()) return; handleClickEvent(x, y); - } - + } + /* ---------- For overriding! -------------- */ public abstract String getGameName(); - + protected abstract String getGameKey(); - protected void paintGame(Graphics g) { + protected void paintGame(Graphics g) { paintGameDefault(g, "paintGame not implemented"); } @@ -256,6 +256,6 @@ protected void handleDragEvent(int dx, int dy) { protected void handleClickEvent(int x, int y) { ; } - + public abstract void clearMoveSelection(); } \ No newline at end of file diff --git a/src/org/ggp/base/apps/kiosk/GameGUI.java b/src/org/ggp/base/apps/kiosk/GameGUI.java index c1cce0511..cdd3da6fb 100644 --- a/src/org/ggp/base/apps/kiosk/GameGUI.java +++ b/src/org/ggp/base/apps/kiosk/GameGUI.java @@ -29,31 +29,31 @@ public class GameGUI extends JPanel implements Subject, Observer, ActionListener private JLabel workingMoveLabel; private JButton submitMoveButton; private JButton clearSelectionButton; - + private boolean gameOver = false; - + private boolean moveBeingSubmitted = false; private boolean stillMetagaming = true; - + public GameGUI(GameCanvas theCanvas) { - super(new BorderLayout()); - + super(new BorderLayout()); + this.theCanvas = theCanvas; JLabel theTitleLabel = new JLabel(theCanvas.getGameName()); - theTitleLabel.setFont(new Font(Font.SANS_SERIF, Font.BOLD, 36)); - + theTitleLabel.setFont(new Font(Font.SANS_SERIF, Font.BOLD, 36)); + JPanel northPanel = new JPanel(new FlowLayout()); northPanel.add(theTitleLabel); - + submitMoveButton = new JButton("Submit Move"); submitMoveButton.addActionListener(this); - + clearSelectionButton = new JButton("Clear Selection"); clearSelectionButton.addActionListener(this); - + workingMoveLabel = new JLabel(); - + JPanel southCenterPanel = new JPanel(new FlowLayout()); JPanel southEastPanel = new JPanel(new FlowLayout()); JPanel southPanel = new JPanel(new BorderLayout()); @@ -63,11 +63,11 @@ public GameGUI(GameCanvas theCanvas) { southPanel.add("West", workingMoveLabel); southPanel.add("Center", southCenterPanel); southPanel.add("East", southEastPanel); - + add("North", northPanel); add("Center", theCanvas); add("South", southPanel); - + northPanel.setBackground(theCanvas.getBackground()); southPanel.setBackground(theCanvas.getBackground()); southEastPanel.setBackground(theCanvas.getBackground()); @@ -76,18 +76,18 @@ public GameGUI(GameCanvas theCanvas) { theCanvas.addObserver(this); updateControls(); } - + public void beginPlay() { stillMetagaming = false; updateControls(); } - + public void updateGameState(MachineState gameState) { moveBeingSubmitted = false; theCanvas.updateGameState(gameState); updateControls(); } - + public void setRole(Role r) { theCanvas.setRole(r); } @@ -95,22 +95,22 @@ public void setRole(Role r) { @Override public void observe(Event event) { if(event instanceof MoveSelectedEvent) { - workingMove = ((MoveSelectedEvent)event).getMove(); + workingMove = ((MoveSelectedEvent)event).getMove(); if(((MoveSelectedEvent)event).isFinal()) { moveBeingSubmitted = true; - updateControls(); - notifyObservers(new MoveSelectedEvent(workingMove)); - } + updateControls(); + notifyObservers(new MoveSelectedEvent(workingMove)); + } updateControls(); } } - + private void updateControls() { submitMoveButton.setEnabled(!gameOver && !moveBeingSubmitted && !stillMetagaming); clearSelectionButton.setEnabled(!gameOver && !moveBeingSubmitted && !stillMetagaming); theCanvas.setEnabled(!gameOver && !moveBeingSubmitted && !stillMetagaming); - - if(gameOver) return; + + if(gameOver) return; if(workingMove == null) { workingMoveLabel.setText(" Working Move: "); submitMoveButton.setEnabled(false); @@ -119,23 +119,23 @@ private void updateControls() { workingMoveLabel.setText(" Working Move: " + workingMove); } } - + public void showFinalMessage(String theMessage) { workingMoveLabel.setText(theMessage); workingMoveLabel.setForeground(Color.RED); gameOver = true; updateControls(); - + validate(); - repaint(); + repaint(); } @Override public void actionPerformed(ActionEvent e) { if(gameOver) return; - + if(e.getSource() == clearSelectionButton) { - theCanvas.clearMoveSelection(); + theCanvas.clearMoveSelection(); } else if(e.getSource() == submitMoveButton) { if(workingMove != null) { moveBeingSubmitted = true; @@ -144,18 +144,18 @@ public void actionPerformed(ActionEvent e) { } } } - + // Subject boilerplate private Set theObservers = new HashSet(); - @Override + @Override public void addObserver(Observer observer) { - theObservers.add(observer); + theObservers.add(observer); } @Override public void notifyObservers(Event event) { for(Observer theObserver : theObservers) - theObserver.observe(event); + theObserver.observe(event); } } \ No newline at end of file diff --git a/src/org/ggp/base/apps/kiosk/Kiosk.java b/src/org/ggp/base/apps/kiosk/Kiosk.java index 5843d70ab..396f4ee68 100644 --- a/src/org/ggp/base/apps/kiosk/Kiosk.java +++ b/src/org/ggp/base/apps/kiosk/Kiosk.java @@ -52,14 +52,14 @@ * with clean visualizations and intuitive human interfaces. Originally * designed for running matches against players implemented using the * standard Java stack, it can also connect to remote players as need be. - * + * * @author Sam */ @SuppressWarnings("serial") public final class Kiosk extends JPanel implements ActionListener, ItemListener, Observer { public static final String remotePlayerString = "[REMOTE PLAYER]"; - + private static void createAndShowGUI(Kiosk serverPanel) { JFrame frame = new JFrame("Gaming Kiosk"); @@ -84,29 +84,29 @@ public void run() { private final JTextField playClockTextField; private final JTextField startClockTextField; - + private final JButton runButton; private final JList selectedGame; private final JCheckBox flipRoles; - + private final PublishButton publishButton; private final JPanel theGUIPanel; - + private final JComboBox playerComboBox; private List> gamers = null; private final JTextField computerAddress; private final GameRepository theRepository; - + public Kiosk() - { + { super(new GridBagLayout()); setPreferredSize(new Dimension(1050, 900)); NativeUI.setNativeUI(); GamerLogger.setFileToDisplay("GamePlayer"); - + SortedSet theAvailableGames = new TreeSet(); Set> theAvailableCanvasList = ProjectSearcher.GAME_CANVASES.getConcreteClasses(); for(Class availableCanvas : theAvailableCanvasList) { @@ -117,15 +117,15 @@ public Kiosk() ; } } - + flipRoles = new JCheckBox("Flip roles?"); - + selectedGame = new JList(theAvailableGames.toArray(new AvailableGame[0])); selectedGame.setSelectedIndex(0); selectedGame.getSelectionModel().setSelectionMode(ListSelectionModel.SINGLE_SELECTION); JScrollPane selectedGamePane = new JScrollPane(selectedGame); - computerAddress = new JTextField("player.ggp.org:80"); + computerAddress = new JTextField("player.ggp.org:80"); playerComboBox = new JComboBox(); playerComboBox.addItemListener(this); @@ -144,17 +144,17 @@ public Kiosk() } } playerComboBox.setSelectedItem("Random"); - playerComboBox.addItem(remotePlayerString); - + playerComboBox.addItem(remotePlayerString); + runButton = new JButton("Run!"); runButton.addActionListener(this); publishButton = new PublishButton("Publish online!"); - + startClockTextField = new JTextField("30"); playClockTextField = new JTextField("10"); managerPanel = new JPanel(new GridBagLayout()); - + startClockTextField.setColumns(15); playClockTextField.setColumns(15); @@ -172,7 +172,7 @@ public Kiosk() managerPanel.add(selectedGamePane, new GridBagConstraints(1, nRowCount++, 1, 1, 0.0, 5.0, GridBagConstraints.CENTER, GridBagConstraints.VERTICAL, new Insets(5, 5, 5, 5), 5, 5)); managerPanel.add(new JLabel("Publishing:"), new GridBagConstraints(0, nRowCount, 1, 1, 0.0, 1.0, GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(5, 5, 5, 5), 5, 5)); managerPanel.add(publishButton, new GridBagConstraints(1, nRowCount++, 1, 1, 0.0, 1.0, GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(5, 5, 5, 5), 5, 5)); - //managerPanel.add(new ConsolePanel(), new GridBagConstraints(0, nRowCount++, 2, 1, 0.0, 1.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(5, 5, 5, 5), 5, 5)); + //managerPanel.add(new ConsolePanel(), new GridBagConstraints(0, nRowCount++, 2, 1, 0.0, 1.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(5, 5, 5, 5), 5, 5)); managerPanel.add(runButton, new GridBagConstraints(1, nRowCount++, 1, 1, 0.0, 1.0, GridBagConstraints.SOUTH, GridBagConstraints.HORIZONTAL, new Insets(5, 5, 5, 5), 0, 0)); JPanel gamePanel = new JPanel(new GridBagLayout()); @@ -183,7 +183,7 @@ public Kiosk() this.add(managerPanel, new GridBagConstraints(0, 0, 1, 1, 0.0, 1.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(5, 5, 5, 5), 5, 5)); this.add(gamePanel, new GridBagConstraints(1, 0, 1, 1, 1.0, 1.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(5, 5, 5, 5), 5, 5)); - + // Start up the gamers! try { theHumanGamer = new KioskGamer(theGUIPanel); @@ -196,23 +196,23 @@ public Kiosk() // This is where we get the rulesheets from. Each game has a corresponding // game (with rulesheet) stored on this repository server. Changing this is // likely to break things unless you know what you're doing. - theRepository = new CloudGameRepository("http://games.ggp.org/base/"); + theRepository = new CloudGameRepository("http://games.ggp.org/base/"); } - + class AvailableGame implements Comparable { private String gameName, kifFile; private Class theCanvasClass; - + public AvailableGame(String gameName, String kifFile, Class theCanvasClass) { this.gameName = gameName; this.kifFile = kifFile; this.theCanvasClass = theCanvasClass; } - + public String toString() { return gameName; } - + public GameCanvas getCanvas() { try { return (GameCanvas)theCanvasClass.newInstance(); @@ -228,17 +228,17 @@ public GameCanvas getCanvas() { public int compareTo(AvailableGame o) { return gameName.compareTo(o.gameName); } - } - + } + private GamePlayer theComputerPlayer = null; private GamePlayer theHumanPlayer = null; private KioskGamer theHumanGamer; - + private GameServer kioskServer = null; - + private static final int DEFAULT_HUMAN_PORT = 3333; private static final int DEFAULT_COMPUTER_PORT = 3334; - + @Override public void actionPerformed(ActionEvent e) { if(e.getSource() == runButton) { @@ -259,19 +259,19 @@ public void actionPerformed(ActionEvent e) { } System.gc(); } - + try { GdlPool.drainPool(); SymbolPool.drainPool(); - + AvailableGame theGame = (AvailableGame) (selectedGame.getSelectedValue()); Game game = theRepository.getGame(theGame.kifFile); - + if (game == null) { JOptionPane.showMessageDialog(this, "Cannot load game data for " + theGame.kifFile, "Error", JOptionPane.ERROR_MESSAGE); - return; + return; } - + String matchId = "kiosk." + theGame.kifFile + "-" + System.currentTimeMillis(); int startClock = Integer.valueOf(startClockTextField.getText()); int playClock = Integer.valueOf(playClockTextField.getText()); @@ -288,7 +288,7 @@ public void actionPerformed(ActionEvent e) { // Start a new player if necessary if(theComputerPlayer == null) { - Gamer gamer = null; + Gamer gamer = null; if(!playerComboBox.getSelectedItem().equals(remotePlayerString)) { Class gamerClass = gamers.get(playerComboBox.getSelectedIndex()); try { @@ -296,7 +296,7 @@ public void actionPerformed(ActionEvent e) { } catch(Exception ex) { throw new RuntimeException(ex); } theComputerPlayer = new GamePlayer(DEFAULT_COMPUTER_PORT, gamer); theComputerPlayer.start(); - System.out.println("Kiosk has started a gamer named " + theComputerPlayer.getGamer().getName() + "."); + System.out.println("Kiosk has started a gamer named " + theComputerPlayer.getGamer().getName() + "."); } } @@ -307,50 +307,50 @@ public void actionPerformed(ActionEvent e) { if(!flipRoles.isSelected()) { hosts.add("127.0.0.1"); ports.add(theHumanPlayer.getGamerPort()); - playerNames.add("Human"); + playerNames.add("Human"); } - + if(playerComboBox.getSelectedItem().equals(remotePlayerString)) { try { String[] splitAddress = computerAddress.getText().split(":"); String hostname = splitAddress[0]; int port = Integer.parseInt(splitAddress[1]); - + hosts.add(hostname); - ports.add(port); - playerNames.add("Computer"); + ports.add(port); + playerNames.add("Computer"); } catch(Exception ex) { ex.printStackTrace(); return; - } + } } else { hosts.add("127.0.0.1"); - ports.add(theComputerPlayer.getGamerPort()); + ports.add(theComputerPlayer.getGamerPort()); playerNames.add("Computer"); } if(flipRoles.isSelected()) { hosts.add("127.0.0.1"); ports.add(theHumanPlayer.getGamerPort()); - playerNames.add("Human"); + playerNames.add("Human"); } - + match.setPlayerNamesFromHost(playerNames); - + GamerLogger.startFileLogging(match, "kiosk"); kioskServer = new GameServer(match, hosts, ports); kioskServer.givePlayerUnlimitedTime((flipRoles.isSelected()? 1 : 0)); kioskServer.addObserver(theHumanGamer); kioskServer.addObserver(this); kioskServer.start(); - + publishButton.setServer(kioskServer); } catch(Exception ex) { ex.printStackTrace(); } } } - + @Override public void itemStateChanged(ItemEvent e) { if(e.getSource() == playerComboBox) { @@ -360,7 +360,7 @@ public void itemStateChanged(ItemEvent e) { computerAddress.setVisible(false); } validate(); - } + } } @Override @@ -370,10 +370,10 @@ public void observe(Event event) { System.err.println("Got illegal move [" + x.getMove() + "] by role [" + x.getRole() + "]."); } else if (event instanceof ServerTimeoutEvent) { ServerTimeoutEvent x = (ServerTimeoutEvent)event; - System.err.println("Timeout when communicating with role [" + x.getRole() + "]."); + System.err.println("Timeout when communicating with role [" + x.getRole() + "]."); } else if (event instanceof ServerConnectionErrorEvent) { ServerConnectionErrorEvent x = (ServerConnectionErrorEvent)event; - System.err.println("Connection error when communicating with role [" + x.getRole() + "]."); + System.err.println("Connection error when communicating with role [" + x.getRole() + "]."); } - } + } } \ No newline at end of file diff --git a/src/org/ggp/base/apps/kiosk/KioskGamer.java b/src/org/ggp/base/apps/kiosk/KioskGamer.java index e5a338e9f..8add31fda 100644 --- a/src/org/ggp/base/apps/kiosk/KioskGamer.java +++ b/src/org/ggp/base/apps/kiosk/KioskGamer.java @@ -27,19 +27,19 @@ public class KioskGamer extends StateMachineGamer implements Observer { private BlockingQueue theQueue = new ArrayBlockingQueue(25); - + private GameGUI theGUI; private JPanel theGUIPanel; - public KioskGamer(JPanel theGUIPanel) { + public KioskGamer(JPanel theGUIPanel) { this.theGUIPanel = theGUIPanel; theGUIPanel.setLayout(new BorderLayout()); } - + private GameCanvas theCanvas = null; public void setCanvas(GameCanvas theCanvas) { this.theCanvas = theCanvas; } - + @Override public void stateMachineMetaGame(long timeout) throws TransitionDefinitionException, MoveDefinitionException, @@ -47,19 +47,19 @@ public void stateMachineMetaGame(long timeout) if(theCanvas == null) System.err.println("KioskGamer did not receive a canvas."); theCanvas.setStateMachine(getStateMachine()); - + theGUI = new GameGUI(theCanvas); theGUI.setRole(getRole()); theGUI.setBackground(theGUIPanel.getBackground()); theGUI.updateGameState(getStateMachine().getInitialState()); theGUI.addObserver(this); - + theGUIPanel.removeAll(); theGUIPanel.add("Center", theGUI); theGUIPanel.repaint(); - + theGUIPanel.setVisible(false); - theGUIPanel.setVisible(true); + theGUIPanel.setVisible(true); theGUIPanel.validate(); theGUIPanel.repaint(); } @@ -88,10 +88,10 @@ public StateMachine getInitialStateMachine() { public String getName() { return "GraphicalHumanGamer"; } - + private MachineState stateFromServer; - @Override + @Override public void observe(Event event) { if(event instanceof MoveSelectedEvent) { Move theMove = ((MoveSelectedEvent)event).getMove(); @@ -102,10 +102,10 @@ public void observe(Event event) { stateFromServer = ((ServerNewGameStateEvent)event).getState(); } else if(event instanceof ServerCompletedMatchEvent) { theGUI.updateGameState(stateFromServer); - + List theRoles = getStateMachine().getRoles(); List theGoals = ((ServerCompletedMatchEvent)event).getGoals(); - + StringBuilder finalMessage = new StringBuilder(); finalMessage.append("Goals: "); for(int i = 0; i < theRoles.size(); i++) { @@ -116,7 +116,7 @@ public void observe(Event event) { finalMessage.append(", "); } } - + theGUI.showFinalMessage(finalMessage.toString()); } } @@ -125,7 +125,7 @@ public void observe(Event event) { public void stateMachineStop() { // Do nothing } - + @Override public void stateMachineAbort() { // Add an "ABORT" move to the queue so that we don't wait indefinitely @@ -133,16 +133,16 @@ public void stateMachineAbort() { // finish it up as quickly as possible so we can display the next match // when it arrives. theQueue.add(new Move(GdlPool.getConstant("ABORT"))); - theGUI.showFinalMessage("Aborted"); + theGUI.showFinalMessage("Aborted"); } - + @Override public boolean isComputerPlayer() { return false; } - + @Override public void preview(Game g, long timeout) throws GamePreviewException { ; - } + } } \ No newline at end of file diff --git a/src/org/ggp/base/apps/kiosk/MoveSelectedEvent.java b/src/org/ggp/base/apps/kiosk/MoveSelectedEvent.java index 44978ee94..84a59f47d 100644 --- a/src/org/ggp/base/apps/kiosk/MoveSelectedEvent.java +++ b/src/org/ggp/base/apps/kiosk/MoveSelectedEvent.java @@ -6,20 +6,20 @@ public class MoveSelectedEvent extends Event { private Move theMove; private boolean isFinal = false; - + public MoveSelectedEvent(Move m) { theMove = m; } - + public MoveSelectedEvent(Move m, boolean isFinal) { theMove = m; this.isFinal = isFinal; } - + public Move getMove() { return theMove; } - + public boolean isFinal() { return isFinal; } diff --git a/src/org/ggp/base/apps/kiosk/games/BattleCanvas.java b/src/org/ggp/base/apps/kiosk/games/BattleCanvas.java index 423885ad0..aac03bf1c 100644 --- a/src/org/ggp/base/apps/kiosk/games/BattleCanvas.java +++ b/src/org/ggp/base/apps/kiosk/games/BattleCanvas.java @@ -20,7 +20,7 @@ protected Set getLegalMovesForCell(int xCell, int yCell) { theMoves.addAll(gameStateHasLegalMovesMatching("\\( defend " + xCell + " " + yCell + " \\)")); return theMoves; } - + @Override protected Set getFactsAboutCell(int xCell, int yCell) { return gameStateHasFactsMatching("\\( cell " + xCell + " " + yCell + " (.*) \\)"); @@ -32,13 +32,13 @@ protected void renderCellContent(Graphics g, String theFact) { String cellType = cellFacts[4]; String checkersPiece = (cellType.charAt(0) == 'n' ? "w" : "b") + cellType.charAt(1); CommonGraphics.drawCheckersPiece(g, checkersPiece); - } - + } + @Override protected void renderMoveSelectionForCell(Graphics g, int xCell, int yCell, String theMove) { int width = g.getClipBounds().width; - int height = g.getClipBounds().height; - + int height = g.getClipBounds().height; + String[] moveParts = theMove.split(" "); if(moveParts[1].equals("defend")) { if(isSelectedCell(xCell, yCell)) { @@ -49,7 +49,7 @@ protected void renderMoveSelectionForCell(Graphics g, int xCell, int yCell, Stri int xTarget = Integer.parseInt(moveParts[4]); int yTarget = Integer.parseInt(moveParts[5]); if(xCell == xTarget && yCell == yTarget) { - g.setColor(new Color(0, 0, 255, 192)); + g.setColor(new Color(0, 0, 255, 192)); g.drawRect(3, 3, width-6, height-6); CommonGraphics.fillWithString(g, "X", 3); } diff --git a/src/org/ggp/base/apps/kiosk/games/BiddingTicTacToeCanvas.java b/src/org/ggp/base/apps/kiosk/games/BiddingTicTacToeCanvas.java index 802b11e05..11f86c9e1 100644 --- a/src/org/ggp/base/apps/kiosk/games/BiddingTicTacToeCanvas.java +++ b/src/org/ggp/base/apps/kiosk/games/BiddingTicTacToeCanvas.java @@ -16,10 +16,10 @@ public class BiddingTicTacToeCanvas extends GameCanvas_FancyGrid { protected String getGameKey() { return "biddingTicTacToe"; } protected int getGridHeight() { return 5; } protected int getGridWidth() { return 7; } - + protected boolean coordinatesStartAtOne() { return false; } protected boolean useGridVisualization() { return false; } - + @Override protected Set getFactsAboutCell(int xCell, int yCell) { if(onGrid(xCell, yCell)) { @@ -43,7 +43,7 @@ protected Set getLegalMovesForCell(int xCell, int yCell) { int nScore = onScoreboard(xCell, yCell); if(nScore >= 0) { return gameStateHasLegalMovesMatching("\\( bid " + nScore + " (.*) \\)"); - } + } } return new HashSet(); } @@ -51,10 +51,10 @@ protected Set getLegalMovesForCell(int xCell, int yCell) { @Override protected void renderCellBackground(Graphics g, int xCell, int yCell) { g.setColor(Color.GRAY); - + if(onGrid(xCell, yCell)) { CommonGraphics.drawCellBorder(g); - } else { + } else { int nScore = onScoreboard(xCell, yCell); if(nScore >= 0) { CommonGraphics.fillWithString(g, "" + nScore, 1.2); @@ -63,7 +63,7 @@ protected void renderCellBackground(Graphics g, int xCell, int yCell) { } } } - + @Override protected void renderCellContent(Graphics g, String theFact) { String[] cellFacts = theFact.split(" "); @@ -79,25 +79,25 @@ protected void renderCellContent(Graphics g, String theFact) { CommonGraphics.fillWithString(g, "T", 1.2); } } - + @Override protected void renderMoveSelectionForCell(Graphics g, int xCell, int yCell, String theMove) { String[] moveParts = theMove.split(" "); - + if(isSelectedCell(xCell, yCell)) CommonGraphics.drawSelectionBox(g); - + if(moveParts[1].equals("bid") && moveParts[3].equals("with_tiebreaker")) { if(xCell == 6 && yCell == 4) { CommonGraphics.drawSelectionBox(g); } } } - + private boolean onGrid(int xCell, int yCell) { return (xCell <= 3 && xCell >= 1 && yCell <= 3 && yCell >= 1); } - + private int onScoreboard(int xCell, int yCell) { if(xCell < 5) return -1; if(xCell == 5 && yCell == 4) return -1; diff --git a/src/org/ggp/base/apps/kiosk/games/BlockerCanvas.java b/src/org/ggp/base/apps/kiosk/games/BlockerCanvas.java index cd315ae2d..ef59997d7 100644 --- a/src/org/ggp/base/apps/kiosk/games/BlockerCanvas.java +++ b/src/org/ggp/base/apps/kiosk/games/BlockerCanvas.java @@ -16,24 +16,24 @@ public class BlockerCanvas extends GameCanvas_FancyGrid { protected int getGridHeight() { return 6; } protected int getGridWidth() { return 6; } - protected boolean coordinatesStartAtOne() { return false; } + protected boolean coordinatesStartAtOne() { return false; } @Override protected void renderCellBackground(Graphics g, int xCell, int yCell) { int width = g.getClipBounds().width; - int height = g.getClipBounds().height; - + int height = g.getClipBounds().height; + boolean isBlue = (yCell == 0) || (yCell == 5); - boolean isBlack = ((xCell == 0) || (xCell == 5)) && !isBlue; - + boolean isBlack = ((xCell == 0) || (xCell == 5)) && !isBlue; + if(isBlue) { CommonGraphics.drawBubbles(g, xCell*11+yCell); - } else if(isBlack) { + } else if(isBlack) { g.setColor(Color.GRAY); g.fillRect(1, 1, width-2, height-2); } } - + @Override protected void renderCellContent(Graphics g, String theFact) { int width = g.getClipBounds().width; @@ -53,7 +53,7 @@ protected void renderCellContent(Graphics g, String theFact) { protected Set getFactsAboutCell(int xCell, int yCell) { return gameStateHasFactsMatching("\\( cell " + xCell + " " + yCell + " (.*) \\)"); } - + @Override protected Set getLegalMovesForCell(int xCell, int yCell) { return gameStateHasLegalMovesMatching("\\( mark " + xCell + " " + yCell + " \\)"); diff --git a/src/org/ggp/base/apps/kiosk/games/BlokboxSimpleCanvas.java b/src/org/ggp/base/apps/kiosk/games/BlokboxSimpleCanvas.java index b971e3578..d279e735a 100644 --- a/src/org/ggp/base/apps/kiosk/games/BlokboxSimpleCanvas.java +++ b/src/org/ggp/base/apps/kiosk/games/BlokboxSimpleCanvas.java @@ -20,7 +20,7 @@ public class BlokboxSimpleCanvas extends GameCanvas_SimpleGrid { public String getGameName() { return "Blokbox Simple"; } protected String getGameKey() { return "blokbox_simple"; } - + protected Set getLegalMovesForCell(int xCell, int yCell) { if(selectedPiece == -1) return new HashSet(); return gameStateHasLegalMovesMatching("\\( place " + selectedPiece + " " + xCell + " " + yCell + " \\)"); @@ -29,61 +29,61 @@ protected Set getLegalMovesForCell(int xCell, int yCell) { // ======================================================================== protected int getGridHeight() { return 20; } protected int getGridWidth() { return 20; } - + protected Set getFactsAboutCell(int xCell, int yCell) { Set theFacts = gameStateHasFactsMatching("\\( cell " + xCell + " " + yCell + " (.*) \\)"); if(xCell >= 15 || yCell >= 15) { int nPiece = pieceGrid[xCell-1][yCell-1]; - theFacts.addAll(gameStateHasFactsMatching("\\( owns " + myRole + " " + nPiece + " \\)")); + theFacts.addAll(gameStateHasFactsMatching("\\( owns " + myRole + " " + nPiece + " \\)")); } return theFacts; } - + private int[][] pieceGrid = new int[][] { - {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 21, 0, 8, 8, 8}, - {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 21,21, 0, 8, 0}, - {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 21, 0,18, 0,18}, - {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 21, 0,18,18,18}, - {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 0, 0, 0}, - {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 5, 5}, - {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,20, 0, 0}, - {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,20,20,20, 0}, - {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 0,20, 0, 7}, - {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10,10, 0, 0, 7}, - {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,10, 0, 0, 7}, - {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0}, - {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0}, - {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 14,14, 0, 0,15}, - {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 14, 0, 2, 0,15}, - { 0, 0, 0,12,12,12, 0,13,13, 0,11,11,11, 0,14,14, 0, 2, 0,15}, - { 0, 0, 0,12, 0, 0,17, 0,13,13, 0,11, 0, 4, 0, 0, 2, 2, 0,15}, - { 0, 0, 0,12, 0, 0,17,17, 0,13, 0,11, 0, 0,19,19, 0, 0, 0,15}, - { 0, 0, 0, 0,16,16, 0,17, 0, 0, 0, 0, 0,19,19, 0, 3, 0, 0, 0}, + {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 21, 0, 8, 8, 8}, + {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 21,21, 0, 8, 0}, + {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 21, 0,18, 0,18}, + {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 21, 0,18,18,18}, + {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 0, 0, 0}, + {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 5, 5}, + {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,20, 0, 0}, + {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,20,20,20, 0}, + {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 0,20, 0, 7}, + {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10,10, 0, 0, 7}, + {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,10, 0, 0, 7}, + {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0}, + {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0}, + {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 14,14, 0, 0,15}, + {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 14, 0, 2, 0,15}, + { 0, 0, 0,12,12,12, 0,13,13, 0,11,11,11, 0,14,14, 0, 2, 0,15}, + { 0, 0, 0,12, 0, 0,17, 0,13,13, 0,11, 0, 4, 0, 0, 2, 2, 0,15}, + { 0, 0, 0,12, 0, 0,17,17, 0,13, 0,11, 0, 0,19,19, 0, 0, 0,15}, + { 0, 0, 0, 0,16,16, 0,17, 0, 0, 0, 0, 0,19,19, 0, 3, 0, 0, 0}, { 0, 0, 0,16,16,16, 0,17, 0, 9, 9, 9, 9, 0,19, 0, 3, 3, 3, 3} }; - + protected void renderCellBackground(Graphics g, int xCell, int yCell) { int width = g.getClipBounds().width; int height = g.getClipBounds().height; - - if ((xCell == 15 && yCell <= 15) || (yCell == 15 && xCell <= 15)) { + + if ((xCell == 15 && yCell <= 15) || (yCell == 15 && xCell <= 15)) { if (xCell == 15) width /= 2; if (yCell == 15) height /= 2; width++; height++; - + int xStart = 0, yStart = 0; if (xCell == 15 || yCell == 0) xStart++; if (yCell == 15 || xCell == 0) yStart++; if (xCell == 15 && yCell == 15) { xStart--; yStart--; width++; height++; } - + g.setColor(Color.black); g.fillRect(xStart, yStart, width, height); g.fillRect(xStart, yStart, width, height); return; } - + if (xCell <= 14 && yCell <= 14) { CommonGraphics.drawCellBorder(g); return; @@ -96,16 +96,16 @@ protected void renderCellBackground(Graphics g, int xCell, int yCell) { if (xCell == 19 && yCell == 2) CommonGraphics.fillWithString(g, "K", 2.0); if (xCell == 20 && yCell == 2) CommonGraphics.fillWithString(g, "S", 2.0); } - - protected void renderCellContent(Graphics g, String theFact) { + + protected void renderCellContent(Graphics g, String theFact) { String[] cellFacts = theFact.split(" "); if(cellFacts[1].equals("owns")) { if (myRole.toString().contains("orange")) g.setColor(Color.orange); else g.setColor(Color.magenta); - + int width = g.getClipBounds().width; - int height = g.getClipBounds().height; + int height = g.getClipBounds().height; g.fillRect(0, 0, width, height); g.setColor(Color.black); g.drawRect(0, 0, width, height); @@ -117,26 +117,26 @@ protected void renderCellContent(Graphics g, String theFact) { g.setColor(Color.MAGENTA); } int width = g.getClipBounds().width; - int height = g.getClipBounds().height; + int height = g.getClipBounds().height; g.fillRect(0, 0, width, height); g.setColor(Color.black); g.drawRect(0, 0, width, height); } } - + protected void renderMoveSelectionForCell(Graphics g, int xCell, int yCell, String theMove) { if (selectedPiece == pieceGrid[xCell-1][yCell-1]) { CommonGraphics.drawSelectionBox(g); return; } - + if (selectedRow == yCell && selectedColumn == xCell) { CommonGraphics.drawSelectionBox(g); return; } } - - + + ////////////////////////////////////////////////////////////////////// // We need to re-implement part of the FancyGrid architecture, because // we need certain parts but need to change other parts (specifically, @@ -151,18 +151,18 @@ protected void renderCellContent(Graphics g, Set theFacts){ String theFact = theFacts.iterator().next(); renderCellContent(g, theFact); - } + } } - + protected int selectedPiece = -1; - + private int selectedRow = -1; - private int selectedColumn = -1; + private int selectedColumn = -1; private String currentSelectedMove; private Iterator possibleSelectedMoves = null; protected final void handleClickOnCell(int xCell, int yCell, int xWithin, int yWithin) { if(xCell > 20 || yCell > 20) return; - + if(xCell > 15 || yCell > 15) { int nPiece = pieceGrid[xCell-1][yCell-1]; selectedPiece = -1; @@ -177,17 +177,17 @@ protected final void handleClickOnCell(int xCell, int yCell, int xWithin, int yW return; } if(selectedPiece == -1) return; - + if(selectedRow != yCell || selectedColumn != xCell || !possibleSelectedMoves.hasNext()) { SortedSet theMoves = new TreeSet(getLegalMovesForCell(xCell, yCell)); if(theMoves.size() == 0) return; - possibleSelectedMoves = theMoves.iterator(); + possibleSelectedMoves = theMoves.iterator(); } selectedRow = yCell; selectedColumn = xCell; - - currentSelectedMove = possibleSelectedMoves.next(); + + currentSelectedMove = possibleSelectedMoves.next(); submitWorkingMove(stringToMove(currentSelectedMove)); } @@ -199,33 +199,33 @@ protected Set getCachedFactsAboutCell(int xCell, int yCell) { Set cachedFacts = factsCache.get(cellHash); if(cachedFacts != null) return cachedFacts; - + Set realFacts = getFactsAboutCell(xCell, yCell); factsCache.put(cellHash, realFacts); return realFacts; } - + // When the game state changes, clear our cache of known facts. public void updateGameState(MachineState gameState) { factsCache.clear(); super.updateGameState(gameState); } - + protected final void renderCell(Graphics g, int xCell, int yCell) { renderCellBackground(g, xCell, yCell); renderCellContent(g, getCachedFactsAboutCell(xCell, yCell)); renderMoveSelectionForCell(g, xCell, yCell, currentSelectedMove); } - public final void clearMoveSelection() { + public final void clearMoveSelection() { submitWorkingMove(null); - + selectedPiece = -1; possibleSelectedMoves = null; currentSelectedMove = ""; - selectedColumn = -1; + selectedColumn = -1; selectedRow = -1; - + repaint(); - } + } } \ No newline at end of file diff --git a/src/org/ggp/base/apps/kiosk/games/BreakthroughCanvas.java b/src/org/ggp/base/apps/kiosk/games/BreakthroughCanvas.java index c3eb6d4bd..c2ba0878c 100644 --- a/src/org/ggp/base/apps/kiosk/games/BreakthroughCanvas.java +++ b/src/org/ggp/base/apps/kiosk/games/BreakthroughCanvas.java @@ -18,31 +18,31 @@ public class BreakthroughCanvas extends GameCanvas_Chessboard { protected Set getFactsAboutCell(int xCell, int yCell) { return gameStateHasFactsMatching("\\( cellHolds " + xCell + " " + yCell + " (.*) \\)"); } - + @Override protected Set getLegalMovesForCell(int xCell, int yCell) { return gameStateHasLegalMovesMatching("\\( move " + xCell + " " + yCell + " (.*) \\)"); } - + protected void renderCellContent(Graphics g, String theFact) { String[] cellFacts = theFact.split(" "); String cellType = cellFacts[4]; if(cellType.equals("b")) return; - + CommonGraphics.drawChessPiece(g, cellType.charAt(0) + "p"); } - + @Override protected void renderMoveSelectionForCell(Graphics g, int xCell, int yCell, String theMove) { int width = g.getClipBounds().width; - int height = g.getClipBounds().height; - + int height = g.getClipBounds().height; + String[] moveParts = theMove.split(" "); int xTarget = Integer.parseInt(moveParts[4]); int yTarget = Integer.parseInt(moveParts[5]); if(xCell == xTarget && yCell == yTarget) { - g.setColor(new Color(0, 0, 255, 192)); + g.setColor(new Color(0, 0, 255, 192)); g.drawRect(3, 3, width-6, height-6); CommonGraphics.fillWithString(g, "X", 3); } diff --git a/src/org/ggp/base/apps/kiosk/games/BreakthroughHolesCanvas.java b/src/org/ggp/base/apps/kiosk/games/BreakthroughHolesCanvas.java index 53ed28c0c..855eebae5 100644 --- a/src/org/ggp/base/apps/kiosk/games/BreakthroughHolesCanvas.java +++ b/src/org/ggp/base/apps/kiosk/games/BreakthroughHolesCanvas.java @@ -20,35 +20,35 @@ protected Set getFactsAboutCell(int xCell, int yCell) { theFacts.addAll(gameStateHasFactsMatching("\\( cellOffLimits " + xCell + " " + yCell + " \\)")); return theFacts; } - + @Override protected Set getLegalMovesForCell(int xCell, int yCell) { return gameStateHasLegalMovesMatching("\\( move " + xCell + " " + yCell + " (.*) \\)"); } - + protected void renderCellContent(Graphics g, String theFact) { String[] cellFacts = theFact.split(" "); String cellType = cellFacts[4]; if(cellType.equals("b")) return; - + if(cellFacts[1].equals("cellHolds")) { CommonGraphics.drawChessPiece(g, cellType.charAt(0) + "p"); } else if(cellFacts[1].equals("cellOffLimits")) { CommonGraphics.drawBubbles(g, theFact.hashCode()); } } - + @Override protected void renderMoveSelectionForCell(Graphics g, int xCell, int yCell, String theMove) { int width = g.getClipBounds().width; - int height = g.getClipBounds().height; - + int height = g.getClipBounds().height; + String[] moveParts = theMove.split(" "); int xTarget = Integer.parseInt(moveParts[4]); int yTarget = Integer.parseInt(moveParts[5]); if(xCell == xTarget && yCell == yTarget) { - g.setColor(new Color(0, 0, 255, 192)); + g.setColor(new Color(0, 0, 255, 192)); g.drawRect(3, 3, width-6, height-6); CommonGraphics.fillWithString(g, "X", 3); } diff --git a/src/org/ggp/base/apps/kiosk/games/BreakthroughSmallCanvas.java b/src/org/ggp/base/apps/kiosk/games/BreakthroughSmallCanvas.java index 3c7871c6f..3d1cb3f82 100644 --- a/src/org/ggp/base/apps/kiosk/games/BreakthroughSmallCanvas.java +++ b/src/org/ggp/base/apps/kiosk/games/BreakthroughSmallCanvas.java @@ -15,37 +15,37 @@ public class BreakthroughSmallCanvas extends GameCanvas_Chessboard { protected String getGameKey() { return "breakthroughSmall"; } protected int getGridHeight() { return 6; } - protected int getGridWidth() { return 6; } - + protected int getGridWidth() { return 6; } + @Override protected Set getFactsAboutCell(int xCell, int yCell) { return gameStateHasFactsMatching("\\( cell " + xCell + " " + yCell + " (.*) \\)"); } - + @Override protected Set getLegalMovesForCell(int xCell, int yCell) { return gameStateHasLegalMovesMatching("\\( move " + xCell + " " + yCell + " (.*) \\)"); } - + protected void renderCellContent(Graphics g, String theFact) { String[] cellFacts = theFact.split(" "); String cellType = cellFacts[4]; if(cellType.equals("b")) return; - + CommonGraphics.drawChessPiece(g, cellType.charAt(0) + "p"); } - + @Override protected void renderMoveSelectionForCell(Graphics g, int xCell, int yCell, String theMove) { int width = g.getClipBounds().width; - int height = g.getClipBounds().height; - + int height = g.getClipBounds().height; + String[] moveParts = theMove.split(" "); int xTarget = Integer.parseInt(moveParts[4]); int yTarget = Integer.parseInt(moveParts[5]); if(xCell == xTarget && yCell == yTarget) { - g.setColor(new Color(0, 0, 255, 192)); + g.setColor(new Color(0, 0, 255, 192)); g.drawRect(3, 3, width-6, height-6); CommonGraphics.fillWithString(g, "X", 3); } diff --git a/src/org/ggp/base/apps/kiosk/games/CephalopodCanvas.java b/src/org/ggp/base/apps/kiosk/games/CephalopodCanvas.java index 5f7ecc05d..5970ff539 100644 --- a/src/org/ggp/base/apps/kiosk/games/CephalopodCanvas.java +++ b/src/org/ggp/base/apps/kiosk/games/CephalopodCanvas.java @@ -15,21 +15,21 @@ public class CephalopodCanvas extends GameCanvas_FancyGrid { protected String getGameKey() { return "cephalopodMicro"; } protected int getGridHeight() { return 3; } protected int getGridWidth() { return 3; } - + @Override protected Set getFactsAboutCell(int xCell, int yCell) { return gameStateHasFactsMatching("\\( cell " + xCell + " " + yCell + " (.*) \\)"); } - + @Override protected Set getLegalMovesForCell(int xCell, int yCell) { return gameStateHasLegalMovesMatching("\\( play " + xCell + " " + yCell + " (.*) \\)"); } - + @Override protected void renderCellContent(Graphics g, String theFact) { String[] cellFacts = theFact.split(" "); - + int cellValue = Integer.parseInt(cellFacts[4]); String cellPlayer = cellFacts[5]; @@ -38,10 +38,10 @@ protected void renderCellContent(Graphics g, String theFact) { } else if (cellPlayer.equals("black")) { g.setColor(Color.BLACK); } - + CommonGraphics.fillWithString(g, "" + cellValue, 1.2); } - + @Override protected void renderMoveSelectionForCell(Graphics g, int xCell, int yCell, String theMove) { if(isSelectedCell(xCell, yCell)) { @@ -50,20 +50,20 @@ protected void renderMoveSelectionForCell(Graphics g, int xCell, int yCell, Stri renderCaptureMask(g, captureMask); } } - + private void renderCaptureMask(Graphics g, int c) { boolean leftBit = (c == 3 || c == 5 || c == 7 || c == 9 || c == 11 || c == 13 || c == 15); boolean rightBit = (c >= 9); boolean topBit = (c == 3 || c == 6 || c == 7 || c == 10 || c == 11 || c == 14 || c == 15); boolean bottomBit = (c == 5 || c == 6 || c == 7 || c >= 12); - + int width = g.getClipBounds().width; int height = g.getClipBounds().height; - + g.setColor(Color.GREEN); if(leftBit) g.drawRect(width/10, 3*height/10, width/20, 4*height/10); if(rightBit) g.drawRect(17*width/20, 3*height/10, width/20, 4*height/10); if(topBit) g.drawRect(3*width/10, height/10, 4*width/10, height/20); if(bottomBit) g.drawRect(3*width/10, 17*height/20, 4*width/10, height/20); - } + } } \ No newline at end of file diff --git a/src/org/ggp/base/apps/kiosk/games/CheckersCanvas.java b/src/org/ggp/base/apps/kiosk/games/CheckersCanvas.java index bde2d9363..c7c83f572 100644 --- a/src/org/ggp/base/apps/kiosk/games/CheckersCanvas.java +++ b/src/org/ggp/base/apps/kiosk/games/CheckersCanvas.java @@ -9,20 +9,20 @@ public class CheckersCanvas extends GameCanvas_Chessboard { - private static final long serialVersionUID = 1L; - + private static final long serialVersionUID = 1L; + public String getGameName() { return "Checkers"; } protected String getGameKey() { return "checkers"; } - + @Override protected Set getLegalMovesForCell(int xCell, int yCell) { - String xLetter = coordinateToLetter(xCell); + String xLetter = coordinateToLetter(xCell); Set theMoves = gameStateHasLegalMovesMatching("\\( move .. " + xLetter + " " + yCell + " (.*) \\)"); theMoves.addAll(gameStateHasLegalMovesMatching("\\( doublejump .. " + xLetter + " " + yCell + " (.*) \\)")); theMoves.addAll(gameStateHasLegalMovesMatching("\\( triplejump .. " + xLetter + " " + yCell + " (.*) \\)")); return theMoves; } - + @Override protected Set getFactsAboutCell(int xCell, int yCell) { String xLetter = coordinateToLetter(xCell); @@ -36,13 +36,13 @@ protected void renderCellContent(Graphics g, String theFact) { if(!cellType.equals("b")) { CommonGraphics.drawCheckersPiece(g, cellType); } - } - + } + @Override protected void renderMoveSelectionForCell(Graphics g, int xCell, int yCell, String theMove) { int width = g.getClipBounds().width; - int height = g.getClipBounds().height; - + int height = g.getClipBounds().height; + String xLetter = coordinateToLetter(xCell); String[] moveParts = theMove.split(" "); diff --git a/src/org/ggp/base/apps/kiosk/games/CheckersSmallCanvas.java b/src/org/ggp/base/apps/kiosk/games/CheckersSmallCanvas.java index 1f3306e03..ea1b14ad4 100644 --- a/src/org/ggp/base/apps/kiosk/games/CheckersSmallCanvas.java +++ b/src/org/ggp/base/apps/kiosk/games/CheckersSmallCanvas.java @@ -9,42 +9,42 @@ public class CheckersSmallCanvas extends GameCanvas_Chessboard { - private static final long serialVersionUID = 1L; - + private static final long serialVersionUID = 1L; + public String getGameName() { return "Checkers (Small)"; } protected String getGameKey() { return "checkersSmall"; } - + protected int getGridHeight() { return 8; } - protected int getGridWidth() { return 8; } + protected int getGridWidth() { return 8; } @Override protected void renderCellForeground(Graphics g, int xCell, int yCell) { xCell--; - + if(xCell == 0 || xCell == 7) { int width = g.getClipBounds().width; - int height = g.getClipBounds().height; - - g.setColor(Color.DARK_GRAY); + int height = g.getClipBounds().height; + + g.setColor(Color.DARK_GRAY); g.fillRect(0, 0, width, height); } } - + @Override protected Set getLegalMovesForCell(int xCell, int yCell) { xCell--; - - String xLetter = coordinateToLetter(xCell); + + String xLetter = coordinateToLetter(xCell); Set theMoves = gameStateHasLegalMovesMatching("\\( move .. " + xLetter + " " + yCell + " (.*) \\)"); theMoves.addAll(gameStateHasLegalMovesMatching("\\( doublejump .. " + xLetter + " " + yCell + " (.*) \\)")); theMoves.addAll(gameStateHasLegalMovesMatching("\\( triplejump .. " + xLetter + " " + yCell + " (.*) \\)")); return theMoves; } - + @Override protected Set getFactsAboutCell(int xCell, int yCell) { xCell--; - + String xLetter = coordinateToLetter(xCell); return gameStateHasFactsMatching("\\( cell " + xLetter + " " + yCell + " (.*) \\)"); } @@ -56,14 +56,14 @@ protected void renderCellContent(Graphics g, String theFact) { if(!cellType.equals("b")) { CommonGraphics.drawCheckersPiece(g, cellType); } - } - + } + @Override protected void renderMoveSelectionForCell(Graphics g, int xCell, int yCell, String theMove) { int width = g.getClipBounds().width; int height = g.getClipBounds().height; xCell--; - + String xLetter = coordinateToLetter(xCell); String[] moveParts = theMove.split(" "); diff --git a/src/org/ggp/base/apps/kiosk/games/CheckersTinyCanvas.java b/src/org/ggp/base/apps/kiosk/games/CheckersTinyCanvas.java index 744d5fed8..c8d34f80a 100644 --- a/src/org/ggp/base/apps/kiosk/games/CheckersTinyCanvas.java +++ b/src/org/ggp/base/apps/kiosk/games/CheckersTinyCanvas.java @@ -9,42 +9,42 @@ public class CheckersTinyCanvas extends GameCanvas_Chessboard { - private static final long serialVersionUID = 1L; - + private static final long serialVersionUID = 1L; + public String getGameName() { return "Checkers (Tiny)"; } protected String getGameKey() { return "checkersTiny"; } - + protected int getGridHeight() { return 8; } - protected int getGridWidth() { return 8; } + protected int getGridWidth() { return 8; } @Override protected void renderCellForeground(Graphics g, int xCell, int yCell) { xCell-=2; - + if(xCell <= 0 || xCell >= 5) { int width = g.getClipBounds().width; - int height = g.getClipBounds().height; - - g.setColor(Color.DARK_GRAY); + int height = g.getClipBounds().height; + + g.setColor(Color.DARK_GRAY); g.fillRect(0, 0, width, height); } } - + @Override protected Set getLegalMovesForCell(int xCell, int yCell) { xCell-=2; - - String xLetter = coordinateToLetter(xCell); + + String xLetter = coordinateToLetter(xCell); Set theMoves = gameStateHasLegalMovesMatching("\\( move .. " + xLetter + " " + yCell + " (.*) \\)"); theMoves.addAll(gameStateHasLegalMovesMatching("\\( doublejump .. " + xLetter + " " + yCell + " (.*) \\)")); theMoves.addAll(gameStateHasLegalMovesMatching("\\( triplejump .. " + xLetter + " " + yCell + " (.*) \\)")); return theMoves; } - + @Override protected Set getFactsAboutCell(int xCell, int yCell) { xCell-=2; - + String xLetter = coordinateToLetter(xCell); return gameStateHasFactsMatching("\\( cell " + xLetter + " " + yCell + " (.*) \\)"); } @@ -56,14 +56,14 @@ protected void renderCellContent(Graphics g, String theFact) { if(!cellType.equals("b")) { CommonGraphics.drawCheckersPiece(g, cellType); } - } - + } + @Override protected void renderMoveSelectionForCell(Graphics g, int xCell, int yCell, String theMove) { int width = g.getClipBounds().width; int height = g.getClipBounds().height; xCell-=2; - + String xLetter = coordinateToLetter(xCell); String[] moveParts = theMove.split(" "); diff --git a/src/org/ggp/base/apps/kiosk/games/ChessCanvas.java b/src/org/ggp/base/apps/kiosk/games/ChessCanvas.java index 8f3087d76..f8f3f0422 100644 --- a/src/org/ggp/base/apps/kiosk/games/ChessCanvas.java +++ b/src/org/ggp/base/apps/kiosk/games/ChessCanvas.java @@ -19,7 +19,7 @@ protected Set getLegalMovesForCell(int xCell, int yCell) { String xLetter = coordinateToLetter(xCell); return gameStateHasLegalMovesMatching("\\( move .. " + xLetter + " " + yCell + " (.*) \\)"); } - + @Override protected Set getFactsAboutCell(int xCell, int yCell) { String xLetter = coordinateToLetter(xCell); @@ -33,20 +33,20 @@ protected void renderCellContent(Graphics g, String theFact) { if(!cellType.equals("b")) { CommonGraphics.drawChessPiece(g, cellType); } - } - + } + @Override protected void renderMoveSelectionForCell(Graphics g, int xCell, int yCell, String theMove) { int width = g.getClipBounds().width; - int height = g.getClipBounds().height; - + int height = g.getClipBounds().height; + String xLetter = coordinateToLetter(xCell); String[] moveParts = theMove.split(" "); String xTarget = moveParts[5]; int yTarget = Integer.parseInt(moveParts[6]); if(xLetter.equals(xTarget) && yCell == yTarget) { - g.setColor(new Color(0, 0, 255, 192)); + g.setColor(new Color(0, 0, 255, 192)); g.drawRect(3, 3, width-6, height-6); CommonGraphics.fillWithString(g, "X", 3); } diff --git a/src/org/ggp/base/apps/kiosk/games/ChickenTicTacToeCanvas.java b/src/org/ggp/base/apps/kiosk/games/ChickenTicTacToeCanvas.java index 7df3cdaa5..a10ce08d2 100644 --- a/src/org/ggp/base/apps/kiosk/games/ChickenTicTacToeCanvas.java +++ b/src/org/ggp/base/apps/kiosk/games/ChickenTicTacToeCanvas.java @@ -11,26 +11,26 @@ // NOTE: I still don't fully understand how this game actually works. -Sam public class ChickenTicTacToeCanvas extends GameCanvas_FancyGrid { public static final long serialVersionUID = 0x1; - + public String getGameName() { return "Tic-Tac-Toe (Chicken)"; } protected String getGameKey() { return "chickentictactoe"; } protected int getGridHeight() { return 3; } protected int getGridWidth() { return 3; } - + @Override protected Set getFactsAboutCell(int xCell, int yCell) { return gameStateHasFactsMatching("\\( cell " + xCell + " " + yCell + " (.*) \\)"); } - + @Override protected Set getLegalMovesForCell(int xCell, int yCell) { return gameStateHasLegalMovesMatching("\\( mark " + xCell + " " + yCell + " \\)"); } - + @Override protected void renderCellContent(Graphics g, String theFact) { String[] cellFacts = theFact.split(" "); - + if(!cellFacts[4].equals("b")) { g.setColor(Color.BLACK); CommonGraphics.fillWithString(g, cellFacts[4], 1.2); diff --git a/src/org/ggp/base/apps/kiosk/games/ConnectFiveCanvas.java b/src/org/ggp/base/apps/kiosk/games/ConnectFiveCanvas.java index 365621187..a6a7d9cc8 100644 --- a/src/org/ggp/base/apps/kiosk/games/ConnectFiveCanvas.java +++ b/src/org/ggp/base/apps/kiosk/games/ConnectFiveCanvas.java @@ -10,30 +10,30 @@ public class ConnectFiveCanvas extends GameCanvas_Chessboard { public static final long serialVersionUID = 0x1; - + public String getGameName() { return "Connect Five"; } protected String getGameKey() { return "connect5"; } - + @Override protected Set getFactsAboutCell(int xCell, int yCell) { String xLetter = coordinateToLetter(xCell); - String yLetter = coordinateToLetter(yCell); + String yLetter = coordinateToLetter(yCell); return gameStateHasFactsMatching("\\( cell " + xLetter + " " + yLetter + " (.*) \\)"); } - + @Override protected Set getLegalMovesForCell(int xCell, int yCell) { String xLetter = coordinateToLetter(xCell); - String yLetter = coordinateToLetter(yCell); + String yLetter = coordinateToLetter(yCell); return gameStateHasLegalMovesMatching("\\( mark " + xLetter + " " + yLetter + " \\)"); } - + @Override protected void renderCellContent(Graphics g, String theFact) { String[] cellFacts = theFact.split(" "); if(cellFacts[4].equals("b")) return; - + g.setColor(Color.BLACK); CommonGraphics.fillWithString(g, cellFacts[4].toUpperCase(), 1.2); - } + } } \ No newline at end of file diff --git a/src/org/ggp/base/apps/kiosk/games/ConnectFourCanvas.java b/src/org/ggp/base/apps/kiosk/games/ConnectFourCanvas.java index 9e9a53172..94fe73375 100644 --- a/src/org/ggp/base/apps/kiosk/games/ConnectFourCanvas.java +++ b/src/org/ggp/base/apps/kiosk/games/ConnectFourCanvas.java @@ -15,12 +15,12 @@ public class ConnectFourCanvas extends GameCanvas_SimpleGrid { protected int getGridHeight() { return 6; } protected int getGridWidth() { return 8; } - private int selectedColumn = 0; - + private int selectedColumn = 0; + @Override protected void handleClickOnCell(int xCell, int yCell, int xWithin, int yWithin) { yCell = 7 - yCell; - + if(gameStateHasLegalMove("( drop " + xCell + " )")) { selectedColumn = xCell; submitWorkingMove(stringToMove("( drop " + xCell + " )")); @@ -30,13 +30,13 @@ protected void handleClickOnCell(int xCell, int yCell, int xWithin, int yWithin) @Override protected void renderCell(Graphics g, int xCell, int yCell) { yCell = 7 - yCell; - + int width = g.getClipBounds().width; int height = g.getClipBounds().height; - + g.setColor(Color.BLACK); g.drawRect(1, 1, width-2, height-2); - + if(gameStateHasFact("( cell " + xCell + " " + yCell + " red )")) { g.setColor(Color.RED); CommonGraphics.drawCheckersPiece(g, "wp"); @@ -52,12 +52,12 @@ protected void renderCell(Graphics g, int xCell, int yCell) { g.drawRect(3, 3, width-6, height-6); } } - + @Override - public void clearMoveSelection() { + public void clearMoveSelection() { submitWorkingMove(null); selectedColumn = 0; - + repaint(); } } \ No newline at end of file diff --git a/src/org/ggp/base/apps/kiosk/games/FFACanvas.java b/src/org/ggp/base/apps/kiosk/games/FFACanvas.java index 6ea080e37..01acbdd64 100644 --- a/src/org/ggp/base/apps/kiosk/games/FFACanvas.java +++ b/src/org/ggp/base/apps/kiosk/games/FFACanvas.java @@ -18,34 +18,34 @@ public class FFACanvas extends GameCanvas_FancyGrid { protected final boolean useGridVisualization() { return false; } protected final boolean coordinatesStartAtOne() { return true; } - + protected final void renderCellBackground(Graphics g, int xCell, int yCell) { int width = g.getClipBounds().width; int height = g.getClipBounds().height; - + CommonGraphics.drawCellBorder(g); - + // Clear out the edges if(xCell == 1 || xCell == 7 || yCell == 1 || yCell == 7) { g.setColor(Color.DARK_GRAY); - g.fillRect(0, 0, width, height); + g.fillRect(0, 0, width, height); } - } - + } + @Override protected Set getLegalMovesForCell(int xCell, int yCell) { Set theMoves = gameStateHasLegalMovesMatching("\\( move " + xCell + " " + yCell + " (.*) \\)"); - + if(theMoves.size() == 0) theMoves.add("noop"); - + return theMoves; } - + @Override protected Set getFactsAboutCell(int xCell, int yCell) { Set theFacts = gameStateHasFactsMatching("\\( cell " + xCell + " " + yCell + " (.*) \\)"); - + if (xCell == 1 && yCell == 1) { theFacts.addAll(gameStateHasFactsMatching("\\( capture red (.*) \\)")); } else if(xCell == 7 && yCell == 1) { @@ -59,15 +59,15 @@ protected Set getFactsAboutCell(int xCell, int yCell) { protected void renderCellContent(Graphics g, Set theFacts) { if(theFacts.size() == 0) return; String theFact = theFacts.iterator().next(); - + String[] cellFacts = theFact.split(" "); if(cellFacts.length == 5) { String cellType = cellFacts[2]; int score = 10*Integer.parseInt(cellFacts[3]); - + Color myColor = null; if(cellType.startsWith("red")) myColor = Color.red; - if(cellType.startsWith("blue")) myColor = Color.blue; + if(cellType.startsWith("blue")) myColor = Color.blue; if(myColor == null) { System.err.println("Got weird piece: " + cellType); return; @@ -80,29 +80,29 @@ protected void renderCellContent(Graphics g, Set theFacts) { if(!cellType.equals("b")) { Color myColor = null; if(cellType.startsWith("red")) myColor = Color.red; - if(cellType.startsWith("blue")) myColor = Color.blue; + if(cellType.startsWith("blue")) myColor = Color.blue; if(myColor == null) { System.err.println("Got weird piece: " + cellType); return; } - + int width = g.getClipBounds().width; - int height = g.getClipBounds().height; - + int height = g.getClipBounds().height; + g.setColor(myColor); g.fillOval(2, 2, width-4, height-4); CommonGraphics.drawChessPiece(g, "wn"); } } - } - + } + @Override protected void renderMoveSelectionForCell(Graphics g, int xCell, int yCell, String theMove) { int width = g.getClipBounds().width; - int height = g.getClipBounds().height; + int height = g.getClipBounds().height; String[] moveParts = theMove.split(" "); - + if(moveParts.length == 7) { int xTarget = Integer.parseInt(moveParts[4]); int yTarget = Integer.parseInt(moveParts[5]); diff --git a/src/org/ggp/base/apps/kiosk/games/GoldenRectangleCanvas.java b/src/org/ggp/base/apps/kiosk/games/GoldenRectangleCanvas.java index 5c79e4c52..97f51e18a 100644 --- a/src/org/ggp/base/apps/kiosk/games/GoldenRectangleCanvas.java +++ b/src/org/ggp/base/apps/kiosk/games/GoldenRectangleCanvas.java @@ -15,12 +15,12 @@ public class GoldenRectangleCanvas extends GameCanvas_SimpleGrid { protected int getGridHeight() { return 8; } protected int getGridWidth() { return 7; } - private int selectedColumn = 0; - + private int selectedColumn = 0; + @Override - protected void handleClickOnCell(int xCell, int yCell, int xWithin, int yWithin) { + protected void handleClickOnCell(int xCell, int yCell, int xWithin, int yWithin) { yCell = 8 - yCell; - + for (int y = 0; y <= 7; y++) { if(gameStateHasLegalMove("( mark " + xCell + " " + y + " )")) { selectedColumn = xCell; @@ -32,13 +32,13 @@ protected void handleClickOnCell(int xCell, int yCell, int xWithin, int yWithin) @Override protected void renderCell(Graphics g, int xCell, int yCell) { yCell = 8 - yCell; - + int width = g.getClipBounds().width; int height = g.getClipBounds().height; - + g.setColor(Color.BLACK); g.drawRect(1, 1, width-2, height-2); - + if(gameStateHasFact("( cell " + xCell + " " + yCell + " r )")) { g.setColor(Color.RED); CommonGraphics.drawDisc(g); @@ -54,12 +54,12 @@ protected void renderCell(Graphics g, int xCell, int yCell) { g.drawRect(3, 3, width-6, height-6); } } - + @Override - public void clearMoveSelection() { + public void clearMoveSelection() { submitWorkingMove(null); selectedColumn = 0; - + repaint(); } } \ No newline at end of file diff --git a/src/org/ggp/base/apps/kiosk/games/KnightFightCanvas.java b/src/org/ggp/base/apps/kiosk/games/KnightFightCanvas.java index 7121fe66c..c4985463a 100644 --- a/src/org/ggp/base/apps/kiosk/games/KnightFightCanvas.java +++ b/src/org/ggp/base/apps/kiosk/games/KnightFightCanvas.java @@ -14,13 +14,13 @@ public class KnightFightCanvas extends GameCanvas_Chessboard { public String getGameName() { return "Knight Fight"; } protected String getGameKey() { return "knightfight"; } protected int getGridHeight() { return 10; } - protected int getGridWidth() { return 10; } + protected int getGridWidth() { return 10; } @Override protected Set getFactsAboutCell(int xCell, int yCell) { return gameStateHasFactsMatching("\\( cell " + xCell + " " + yCell + " (.*) \\)"); } - + @Override protected Set getLegalMovesForCell(int xCell, int yCell) { Set theMoves = gameStateHasLegalMovesMatching("\\( move " + xCell + " " + yCell + " (.*) \\)"); @@ -33,32 +33,32 @@ protected void renderCellContent(Graphics g, String theFact) { String[] cellFacts = theFact.split(" "); String cellType = cellFacts[4]; if(cellType.equals("b")) return; - + if(cellType.equals("arrow")) { CommonGraphics.drawBubbles(g, theFact.hashCode()); } else { CommonGraphics.drawChessPiece(g, cellType.charAt(0) + "n"); } } - + @Override protected void renderMoveSelectionForCell(Graphics g, int xCell, int yCell, String theMove) { int width = g.getClipBounds().width; - int height = g.getClipBounds().height; - + int height = g.getClipBounds().height; + String[] moveParts = theMove.split(" "); - + if(moveParts[0].equals("ortho")) { if(isSelectedCell(xCell, yCell)) CommonGraphics.fillWithString(g, "+", 1.2); } else if(moveParts[0].equals("diag")) { if(isSelectedCell(xCell, yCell)) CommonGraphics.fillWithString(g, "x", 1.2); - } else { + } else { int xTarget = Integer.parseInt(moveParts[4]); int yTarget = Integer.parseInt(moveParts[5]); if(xCell == xTarget && yCell == yTarget) { - g.setColor(new Color(0, 0, 255, 192)); + g.setColor(new Color(0, 0, 255, 192)); g.drawRect(3, 3, width-6, height-6); CommonGraphics.fillWithString(g, "X", 3); } diff --git a/src/org/ggp/base/apps/kiosk/games/KnightthroughCanvas.java b/src/org/ggp/base/apps/kiosk/games/KnightthroughCanvas.java index 7dd79a8c2..309abe374 100644 --- a/src/org/ggp/base/apps/kiosk/games/KnightthroughCanvas.java +++ b/src/org/ggp/base/apps/kiosk/games/KnightthroughCanvas.java @@ -18,31 +18,31 @@ public class KnightthroughCanvas extends GameCanvas_Chessboard { protected Set getFactsAboutCell(int xCell, int yCell) { return gameStateHasFactsMatching("\\( cell " + xCell + " " + yCell + " (.*) \\)"); } - + @Override protected Set getLegalMovesForCell(int xCell, int yCell) { return gameStateHasLegalMovesMatching("\\( move " + xCell + " " + yCell + " (.*) \\)"); } - + protected void renderCellContent(Graphics g, String theFact) { String[] cellFacts = theFact.split(" "); String cellType = cellFacts[4]; if(cellType.equals("b")) return; - + CommonGraphics.drawChessPiece(g, cellType.charAt(0) + "n"); } - + @Override protected void renderMoveSelectionForCell(Graphics g, int xCell, int yCell, String theMove) { int width = g.getClipBounds().width; - int height = g.getClipBounds().height; - + int height = g.getClipBounds().height; + String[] moveParts = theMove.split(" "); int xTarget = Integer.parseInt(moveParts[4]); int yTarget = Integer.parseInt(moveParts[5]); if(xCell == xTarget && yCell == yTarget) { - g.setColor(new Color(0, 0, 255, 192)); + g.setColor(new Color(0, 0, 255, 192)); g.drawRect(3, 3, width-6, height-6); CommonGraphics.fillWithString(g, "X", 3); } diff --git a/src/org/ggp/base/apps/kiosk/games/NumberTicTacToeCanvas.java b/src/org/ggp/base/apps/kiosk/games/NumberTicTacToeCanvas.java index 70d7aff09..692274da7 100644 --- a/src/org/ggp/base/apps/kiosk/games/NumberTicTacToeCanvas.java +++ b/src/org/ggp/base/apps/kiosk/games/NumberTicTacToeCanvas.java @@ -10,38 +10,38 @@ public class NumberTicTacToeCanvas extends GameCanvas_FancyGrid { public static final long serialVersionUID = 0x1; - + public String getGameName() { return "Tic-Tac-Toe (Numeric)"; } protected String getGameKey() { return "numbertictactoe"; } protected int getGridHeight() { return 3; } protected int getGridWidth() { return 3; } - + @Override protected Set getFactsAboutCell(int xCell, int yCell) { return gameStateHasFactsMatching("\\( cell " + xCell + " " + yCell + " (.*) \\)"); } - + @Override protected Set getLegalMovesForCell(int xCell, int yCell) { return gameStateHasLegalMovesMatching("\\( mark " + xCell + " " + yCell + " (.*) \\)"); } - + @Override protected void renderCellContent(Graphics g, String theFact) { String[] cellFacts = theFact.split(" "); - + if(!cellFacts[4].equals("b")) { g.setColor(Color.BLACK); CommonGraphics.fillWithString(g, cellFacts[4], 1.2); } - } - + } + @Override protected void renderMoveSelectionForCell(Graphics g, int xCell, int yCell, String theMove) { if(!isSelectedCell(xCell, yCell)) return; - + g.setColor(Color.GREEN); - String[] moveFacts = theMove.split(" "); + String[] moveFacts = theMove.split(" "); CommonGraphics.fillWithString(g, "" + moveFacts[4], 1.2); } } \ No newline at end of file diff --git a/src/org/ggp/base/apps/kiosk/games/PawnWhoppingCanvas.java b/src/org/ggp/base/apps/kiosk/games/PawnWhoppingCanvas.java index 1dc8ead5b..069d63097 100644 --- a/src/org/ggp/base/apps/kiosk/games/PawnWhoppingCanvas.java +++ b/src/org/ggp/base/apps/kiosk/games/PawnWhoppingCanvas.java @@ -20,7 +20,7 @@ protected Set getLegalMovesForCell(int xCell, int yCell) { theMoves.addAll(gameStateHasLegalMovesMatching("\\( capture " + xCell + " " + yCell + " (.*) \\)")); return theMoves; } - + @Override protected Set getFactsAboutCell(int xCell, int yCell) { return gameStateHasFactsMatching("\\( cell " + xCell + " " + yCell + " (.*) \\)"); @@ -32,27 +32,27 @@ protected void renderCellContent(Graphics g, String theFact) { String cellType = cellFacts[4]; if(cellType.equals("x")) { CommonGraphics.drawChessPiece(g, "wp"); - + g.setColor(Color.black); CommonGraphics.fillWithString(g, "x", 5.0); } else if(cellType.equals("o")) { CommonGraphics.drawChessPiece(g, "bp"); - + g.setColor(getBackground()); CommonGraphics.fillWithString(g, "o", 5.0); } - } - + } + @Override protected void renderMoveSelectionForCell(Graphics g, int xCell, int yCell, String theMove) { int width = g.getClipBounds().width; - int height = g.getClipBounds().height; - + int height = g.getClipBounds().height; + String[] moveParts = theMove.split(" "); int xTarget = Integer.parseInt(moveParts[4]); int yTarget = Integer.parseInt(moveParts[5]); if(xCell == xTarget && yCell == yTarget) { - g.setColor(new Color(0, 0, 255, 192)); + g.setColor(new Color(0, 0, 255, 192)); g.drawRect(3, 3, width-6, height-6); CommonGraphics.fillWithString(g, "X", 3); } diff --git a/src/org/ggp/base/apps/kiosk/games/PentagoCanvas.java b/src/org/ggp/base/apps/kiosk/games/PentagoCanvas.java index 1b9e93e0b..d0ae9729e 100644 --- a/src/org/ggp/base/apps/kiosk/games/PentagoCanvas.java +++ b/src/org/ggp/base/apps/kiosk/games/PentagoCanvas.java @@ -15,12 +15,12 @@ public class PentagoCanvas extends GameCanvas_FancyGrid { protected String getGameKey() { return "pentago"; } protected int getGridHeight() { return 6; } protected int getGridWidth() { return 6; } - + @Override protected Set getFactsAboutCell(int xCell, int yCell) { int nQuad = getQuadrant(xCell, yCell); xCell = ((xCell > 3) ? (xCell - 3) : xCell); - yCell = ((yCell > 3) ? (yCell - 3) : yCell); + yCell = ((yCell > 3) ? (yCell - 3) : yCell); return gameStateHasFactsMatching("\\( cellHolds " + nQuad + " " + xCell + " " + yCell + " (.*) \\)"); } @@ -44,7 +44,7 @@ protected void renderCellContent(Graphics g, String theFact) { private Image left_arrow = CommonGraphics.getImage("pentago", "BlueCircleArrowCCW.png"); private Image right_arrow = CommonGraphics.getImage("pentago", "BlueCircleArrowCW.png"); - + @Override protected void renderMoveSelectionForCell(Graphics g, int xCell, int yCell, String theMove) { String[] moveParts = theMove.split(" "); @@ -52,21 +52,21 @@ protected void renderMoveSelectionForCell(Graphics g, int xCell, int yCell, Stri int nQuad = Integer.parseInt(moveParts[2]); if(getQuadrant(xCell, yCell) == nQuad) { CommonGraphics.drawSelectionBox(g); - + if(!(xCell == 2 || xCell == 5)) return; if(!(yCell == 2 || yCell == 5)) return; - + int width = g.getClipBounds().width; int height = g.getClipBounds().height; if(moveParts[3].equals("clockwise")) { g.drawImage(left_arrow, 15, 15, width-30, height-30, null); } else { - g.drawImage(right_arrow, 15, 15, width-30, height-30, null); + g.drawImage(right_arrow, 15, 15, width-30, height-30, null); } } } } - + private int getQuadrant(int xCell, int yCell) { if(xCell > 3) { if(yCell > 3) return 1; diff --git a/src/org/ggp/base/apps/kiosk/games/TTCC4Canvas.java b/src/org/ggp/base/apps/kiosk/games/TTCC4Canvas.java index 3fac97c1d..4ded36e2f 100644 --- a/src/org/ggp/base/apps/kiosk/games/TTCC4Canvas.java +++ b/src/org/ggp/base/apps/kiosk/games/TTCC4Canvas.java @@ -18,49 +18,49 @@ public class TTCC4Canvas extends GameCanvas_FancyGrid { protected final boolean useGridVisualization() { return false; } protected final boolean coordinatesStartAtOne() { return true; } - + protected final void renderCellBackground(Graphics g, int xCell, int yCell) { int width = g.getClipBounds().width; int height = g.getClipBounds().height; - + yCell = 8 - yCell; - + // Highlight the Tic-Tac-Toe board if(xCell >= 3 && xCell <= 5 && yCell >= 3 && yCell <= 5) { g.setColor(Color.LIGHT_GRAY); g.fillRect(0, 0, width, height); } - + CommonGraphics.drawCellBorder(g); - + // Clear out the edges if(xCell == 1 || xCell == 7 || yCell == 1 || yCell == 7) { g.setColor(Color.DARK_GRAY); - g.fillRect(0, 0, width, height); + g.fillRect(0, 0, width, height); } - } - + } + @Override protected Set getLegalMovesForCell(int xCell, int yCell) { - yCell = 8 - yCell; - + yCell = 8 - yCell; + Set theMoves = gameStateHasLegalMovesMatching("\\( pawnMove " + xCell + " " + yCell + " (.*) \\)"); theMoves.addAll(gameStateHasLegalMovesMatching("\\( knightMove " + xCell + " " + yCell + " (.*) \\)")); theMoves.addAll(gameStateHasLegalMovesMatching("\\( checkerMove " + xCell + " " + yCell + " (.*) \\)")); theMoves.addAll(gameStateHasLegalMovesMatching("\\( jump " + xCell + " " + yCell + " (.*) \\)")); - + if(theMoves.size() == 0) theMoves.addAll(gameStateHasLegalMovesMatching("\\( drop " + xCell + " \\)")); - + if(theMoves.size() == 0) theMoves.add("noop"); return theMoves; } - + @Override protected Set getFactsAboutCell(int xCell, int yCell) { - yCell = 8 - yCell; + yCell = 8 - yCell; return gameStateHasFactsMatching("\\( cell " + xCell + " " + yCell + " (.*) \\)"); } @@ -68,24 +68,24 @@ protected Set getFactsAboutCell(int xCell, int yCell) { protected void renderCellContent(Graphics g, Set theFacts) { if(theFacts.size() == 0) return; String theFact = theFacts.iterator().next(); - + String[] cellFacts = theFact.split(" "); String cellType = cellFacts[4]; if(!cellType.equals("b")) { Color myColor = null; if(cellType.startsWith("light")) myColor = Color.red; - if(cellType.startsWith("dark")) myColor = Color.blue; + if(cellType.startsWith("dark")) myColor = Color.blue; if(myColor == null) { System.err.println("Got weird piece: " + cellType); return; } int width = g.getClipBounds().width; - int height = g.getClipBounds().height; - + int height = g.getClipBounds().height; + g.setColor(myColor); g.fillOval(2, 2, width-4, height-4); - + if(cellType.contains("Pawn")) { CommonGraphics.drawChessPiece(g, "bp"); } else if(cellType.contains("Knight")) { @@ -96,17 +96,17 @@ protected void renderCellContent(Graphics g, Set theFacts) { ; } } - } - + } + @Override protected void renderMoveSelectionForCell(Graphics g, int xCell, int yCell, String theMove) { int width = g.getClipBounds().width; - int height = g.getClipBounds().height; + int height = g.getClipBounds().height; yCell = 8 - yCell; - + String[] moveParts = theMove.split(" "); - + if(moveParts.length == 4) { int xDrop = Integer.parseInt(moveParts[2]); if(xCell == xDrop) { @@ -122,7 +122,7 @@ protected void renderMoveSelectionForCell(Graphics g, int xCell, int yCell, Stri g.drawRect(3, 3, width-6, height-6); g.drawRect(4, 4, width-8, height-8); CommonGraphics.fillWithString(g, "X", 3); - } + } } else if(moveParts.length == 9) { int xTarget = Integer.parseInt(moveParts[6]); int yTarget = Integer.parseInt(moveParts[7]); diff --git a/src/org/ggp/base/apps/kiosk/games/TTCC4SmallCanvas.java b/src/org/ggp/base/apps/kiosk/games/TTCC4SmallCanvas.java index 09c5b8fd4..de5a22475 100644 --- a/src/org/ggp/base/apps/kiosk/games/TTCC4SmallCanvas.java +++ b/src/org/ggp/base/apps/kiosk/games/TTCC4SmallCanvas.java @@ -18,43 +18,43 @@ public class TTCC4SmallCanvas extends GameCanvas_FancyGrid { protected final boolean useGridVisualization() { return false; } protected final boolean coordinatesStartAtOne() { return true; } - + protected final void renderCellBackground(Graphics g, int xCell, int yCell) { int width = g.getClipBounds().width; int height = g.getClipBounds().height; - + yCell = 6 - yCell; - + CommonGraphics.drawCellBorder(g); - + // Clear out the edges if(xCell == 1 || xCell == 5 || yCell == 1 || yCell == 5) { g.setColor(Color.DARK_GRAY); - g.fillRect(0, 0, width, height); + g.fillRect(0, 0, width, height); } - } - + } + @Override protected Set getLegalMovesForCell(int xCell, int yCell) { - yCell = 6 - yCell; - + yCell = 6 - yCell; + Set theMoves = gameStateHasLegalMovesMatching("\\( pawnMove " + xCell + " " + yCell + " (.*) \\)"); theMoves.addAll(gameStateHasLegalMovesMatching("\\( knightMove " + xCell + " " + yCell + " (.*) \\)")); theMoves.addAll(gameStateHasLegalMovesMatching("\\( checkerMove " + xCell + " " + yCell + " (.*) \\)")); theMoves.addAll(gameStateHasLegalMovesMatching("\\( jump " + xCell + " " + yCell + " (.*) \\)")); - + if(theMoves.size() == 0) theMoves.addAll(gameStateHasLegalMovesMatching("\\( drop " + xCell + " \\)")); - + if(theMoves.size() == 0) theMoves.add("noop"); return theMoves; } - + @Override protected Set getFactsAboutCell(int xCell, int yCell) { - yCell = 6 - yCell; + yCell = 6 - yCell; return gameStateHasFactsMatching("\\( cell " + xCell + " " + yCell + " (.*) \\)"); } @@ -62,24 +62,24 @@ protected Set getFactsAboutCell(int xCell, int yCell) { protected void renderCellContent(Graphics g, Set theFacts) { if(theFacts.size() == 0) return; String theFact = theFacts.iterator().next(); - + String[] cellFacts = theFact.split(" "); String cellType = cellFacts[4]; if(!cellType.equals("b")) { Color myColor = null; if(cellType.startsWith("red")) myColor = Color.red; - if(cellType.startsWith("blue")) myColor = Color.blue; + if(cellType.startsWith("blue")) myColor = Color.blue; if(myColor == null) { System.err.println("Got weird piece: " + cellType); return; } int width = g.getClipBounds().width; - int height = g.getClipBounds().height; - + int height = g.getClipBounds().height; + g.setColor(myColor); g.fillOval(2, 2, width-4, height-4); - + if(cellType.contains("Pawn")) { CommonGraphics.drawChessPiece(g, "bp"); } else if(cellType.contains("Knight")) { @@ -90,17 +90,17 @@ protected void renderCellContent(Graphics g, Set theFacts) { ; } } - } - + } + @Override protected void renderMoveSelectionForCell(Graphics g, int xCell, int yCell, String theMove) { int width = g.getClipBounds().width; - int height = g.getClipBounds().height; + int height = g.getClipBounds().height; yCell = 6 - yCell; - + String[] moveParts = theMove.split(" "); - + if(moveParts.length == 4) { int xDrop = Integer.parseInt(moveParts[2]); if(xCell == xDrop) { @@ -116,7 +116,7 @@ protected void renderMoveSelectionForCell(Graphics g, int xCell, int yCell, Stri g.drawRect(3, 3, width-6, height-6); g.drawRect(4, 4, width-8, height-8); CommonGraphics.fillWithString(g, "X", 3); - } + } } else if(moveParts.length == 9) { int xTarget = Integer.parseInt(moveParts[6]); int yTarget = Integer.parseInt(moveParts[7]); diff --git a/src/org/ggp/base/apps/kiosk/games/TTCCanvas.java b/src/org/ggp/base/apps/kiosk/games/TTCCanvas.java index 3a626371f..8cdcd6926 100644 --- a/src/org/ggp/base/apps/kiosk/games/TTCCanvas.java +++ b/src/org/ggp/base/apps/kiosk/games/TTCCanvas.java @@ -18,36 +18,36 @@ public class TTCCanvas extends GameCanvas_FancyGrid { protected final boolean useGridVisualization() { return false; } protected final boolean coordinatesStartAtOne() { return true; } - + protected final void renderCellBackground(Graphics g, int xCell, int yCell) { int width = g.getClipBounds().width; int height = g.getClipBounds().height; - + // Highlight the Tic-Tac-Toe board if(xCell >= 3 && xCell <= 5 && yCell >= 3 && yCell <= 5) { g.setColor(Color.LIGHT_GRAY); g.fillRect(0, 0, width, height); - } - + } + CommonGraphics.drawCellBorder(g); - + // Clear out the edges if(xCell == 1 || xCell == 7 || yCell == 1 || yCell == 7) { g.setColor(Color.DARK_GRAY); - g.fillRect(0, 0, width, height); + g.fillRect(0, 0, width, height); } - } - + } + @Override protected Set getLegalMovesForCell(int xCell, int yCell) { Set theMoves = gameStateHasLegalMovesMatching("\\( move " + xCell + " " + yCell + " (.*) \\)"); - + if(theMoves.size() == 0) theMoves.add("noop"); - + return theMoves; } - + @Override protected Set getFactsAboutCell(int xCell, int yCell) { Set theFacts = gameStateHasFactsMatching("\\( cell " + xCell + " " + yCell + " (.*) \\)"); @@ -59,34 +59,34 @@ protected Set getFactsAboutCell(int xCell, int yCell) { protected void renderCellContent(Graphics g, Set theFacts) { if(theFacts.size() == 0) return; String theFact = theFacts.iterator().next(); - + String[] cellFacts = theFact.split(" "); String cellType = cellFacts[4]; if(!cellType.equals("b")) { Color myColor = null; if(cellType.startsWith("red")) myColor = Color.red; - if(cellType.startsWith("blue")) myColor = Color.blue; + if(cellType.startsWith("blue")) myColor = Color.blue; if(myColor == null) { System.err.println("Got weird piece: " + cellType); return; } int width = g.getClipBounds().width; - int height = g.getClipBounds().height; - + int height = g.getClipBounds().height; + g.setColor(myColor); g.fillOval(2, 2, width-4, height-4); CommonGraphics.drawChessPiece(g, "wn"); } - } - + } + @Override protected void renderMoveSelectionForCell(Graphics g, int xCell, int yCell, String theMove) { int width = g.getClipBounds().width; - int height = g.getClipBounds().height; + int height = g.getClipBounds().height; String[] moveParts = theMove.split(" "); - + if(moveParts.length == 7) { int xTarget = Integer.parseInt(moveParts[4]); int yTarget = Integer.parseInt(moveParts[5]); diff --git a/src/org/ggp/base/apps/kiosk/games/TTTxNineCanvas.java b/src/org/ggp/base/apps/kiosk/games/TTTxNineCanvas.java index 9f83e183e..b45aba140 100644 --- a/src/org/ggp/base/apps/kiosk/games/TTTxNineCanvas.java +++ b/src/org/ggp/base/apps/kiosk/games/TTTxNineCanvas.java @@ -17,7 +17,7 @@ public class TTTxNineCanvas extends GameCanvas_SimpleGrid { protected int getGridWidth() { return 9; } protected boolean coordinatesStartAtOne() { return false; } - + private int xSelectedBoard = 0; private int ySelectedBoard = 0; private int xSelectedSpot = 0; @@ -28,7 +28,7 @@ protected void handleClickOnCell(int xCell, int yCell, int xWithin, int yWithin) int xSpot = 1 + (xCell % 3); int ySpot = 1 + (yCell % 3); - Set theMoves = gameStateHasLegalMovesMatching("\\( play " + xBoard + " " + yBoard + " " + xSpot + " " + ySpot + " (.*) \\)"); + Set theMoves = gameStateHasLegalMovesMatching("\\( play " + xBoard + " " + yBoard + " " + xSpot + " " + ySpot + " (.*) \\)"); if(theMoves.size() == 1) { xSelectedSpot = xSpot; ySelectedSpot = ySpot; @@ -46,11 +46,11 @@ protected void renderCell(Graphics g, int xCell, int yCell) { int xBoard = 1 + (xCell / 3); int yBoard = 1 + (yCell / 3); int xSpot = 1 + (xCell % 3); - int ySpot = 1 + (yCell % 3); - + int ySpot = 1 + (yCell % 3); + g.setColor(Color.BLACK); g.drawRect(7, 7, width-14, height-14); - + if(gameStateHasFact("( currentBoard " + xBoard + " " + yBoard + " )") || gameStateHasFactsMatching("\\( currentBoard (.*) (.*) \\)").size() == 0) { g.setColor(Color.BLUE); @@ -59,41 +59,41 @@ protected void renderCell(Graphics g, int xCell, int yCell) { if(xSpot == 3) g.fillRect(width-5, 0, 5, height); if(ySpot == 1) g.fillRect(0, 0, width, 5); if(ySpot == 3) g.fillRect(0, height-5, width, 5); - + if(gameStateHasFact("( mark " + xBoard + " " + yBoard + " " + xSpot + " " + ySpot + " x )")) { g.setColor(Color.GRAY); - g.fillRect(8, 8, width-15, height-15); + g.fillRect(8, 8, width-15, height-15); g.setColor(Color.BLACK); CommonGraphics.fillWithString(g, "X", 1.2); } else if(gameStateHasFact("( mark " + xBoard + " " + yBoard + " " + xSpot + " " + ySpot + " o )")) { g.setColor(Color.GRAY); - g.fillRect(8, 8, width-15, height-15); + g.fillRect(8, 8, width-15, height-15); g.setColor(Color.WHITE); CommonGraphics.fillWithString(g, "O", 1.2); } else { ; } - - Set theMoves = gameStateHasLegalMovesMatching("\\( play " + xBoard + " " + yBoard + " " + xSpot + " " + ySpot + " (.*) \\)"); - if(theMoves.size() == 1) { + + Set theMoves = gameStateHasLegalMovesMatching("\\( play " + xBoard + " " + yBoard + " " + xSpot + " " + ySpot + " (.*) \\)"); + if(theMoves.size() == 1) { g.setColor(Color.GRAY); for(int i = 8; i < 10; i++) g.drawRect(i, i, width-2*i, height-2*i); } - + if(xSelectedSpot == xSpot && ySelectedSpot == ySpot && xSelectedBoard == xBoard && ySelectedBoard == yBoard) { g.setColor(Color.GREEN); - g.fillRect(10, 10, width-19, height-19); - } + g.fillRect(10, 10, width-19, height-19); + } } - - @Override - public void clearMoveSelection() { + + @Override + public void clearMoveSelection() { submitWorkingMove(null); xSelectedSpot = 0; ySelectedSpot = 0; - + repaint(); } } @@ -108,7 +108,7 @@ public class TTTxNineCanvas extends GameCanvas_SimpleGrid { protected int getGridWidth() { return 9; } protected boolean coordinatesStartAtOne() { return false; } - + private int xSelectedBoard = 0; private int ySelectedBoard = 0; private int xSelectedSpot = 0; @@ -118,7 +118,7 @@ protected void handleClickOnCell(int xCell, int yCell, int xWithin, int yWithin) int yBoard = 1 + (yCell / 3); int xSpot = 1 + (xCell % 3); int ySpot = 1 + (yCell % 3); - + String theMove = "( mark " + xBoard + " " + yBoard + " " + xSpot + " " + ySpot + " )"; if(gameStateHasLegalMove(theMove)) { xSelectedSpot = xSpot; @@ -137,11 +137,11 @@ protected void renderCell(Graphics g, int xCell, int yCell) { int xBoard = 1 + (xCell / 3); int yBoard = 1 + (yCell / 3); int xSpot = 1 + (xCell % 3); - int ySpot = 1 + (yCell % 3); - + int ySpot = 1 + (yCell % 3); + g.setColor(Color.BLACK); g.drawRect(7, 7, width-14, height-14); - + if(gameStateHasFact("( boardtoplay " + xBoard + " " + yBoard + " )") || gameStateHasFact("( boardtoplay any any )")) { g.setColor(Color.BLUE); @@ -150,41 +150,41 @@ protected void renderCell(Graphics g, int xCell, int yCell) { if(xSpot == 3) g.fillRect(width-5, 0, 5, height); if(ySpot == 1) g.fillRect(0, 0, width, 5); if(ySpot == 3) g.fillRect(0, height-5, width, 5); - + if(gameStateHasFact("( cell " + xBoard + " " + yBoard + " " + xSpot + " " + ySpot + " x )")) { g.setColor(Color.GRAY); - g.fillRect(8, 8, width-15, height-15); + g.fillRect(8, 8, width-15, height-15); g.setColor(Color.BLACK); CommonGraphics.fillWithString(g, "X", 1.2); } else if(gameStateHasFact("( cell " + xBoard + " " + yBoard + " " + xSpot + " " + ySpot + " o )")) { g.setColor(Color.GRAY); - g.fillRect(8, 8, width-15, height-15); + g.fillRect(8, 8, width-15, height-15); g.setColor(Color.WHITE); CommonGraphics.fillWithString(g, "O", 1.2); } else { ; } - + String theMove = "( mark " + xBoard + " " + yBoard + " " + xSpot + " " + ySpot + " )"; if(gameStateHasLegalMove(theMove)) { g.setColor(Color.GRAY); for(int i = 8; i < 10; i++) g.drawRect(i, i, width-2*i, height-2*i); } - + if(xSelectedSpot == xSpot && ySelectedSpot == ySpot && xSelectedBoard == xBoard && ySelectedBoard == yBoard) { g.setColor(Color.GREEN); - g.fillRect(10, 10, width-19, height-19); - } + g.fillRect(10, 10, width-19, height-19); + } } - - @Override - public void clearMoveSelection() { + + @Override + public void clearMoveSelection() { submitWorkingMove(null); xSelectedSpot = 0; ySelectedSpot = 0; - + repaint(); } }*/ \ No newline at end of file diff --git a/src/org/ggp/base/apps/kiosk/games/TicTacToeCanvas.java b/src/org/ggp/base/apps/kiosk/games/TicTacToeCanvas.java index 42b4e1675..5f3ef67de 100644 --- a/src/org/ggp/base/apps/kiosk/games/TicTacToeCanvas.java +++ b/src/org/ggp/base/apps/kiosk/games/TicTacToeCanvas.java @@ -11,34 +11,34 @@ /** * An implementation of Tic-Tac-Toe based on the GameCanvas_FancyGrid template. * Comes in at just under 50 lines of code, mostly boilerplate. - * + * * @author Sam Schreiber */ public class TicTacToeCanvas extends GameCanvas_FancyGrid { public static final long serialVersionUID = 0x1; - + public String getGameName() { return "Tic-Tac-Toe"; } protected String getGameKey() { return "ticTacToe"; } protected int getGridHeight() { return 3; } protected int getGridWidth() { return 3; } - + @Override protected Set getFactsAboutCell(int xCell, int yCell) { return gameStateHasFactsMatching("\\( cell " + xCell + " " + yCell + " (.*) \\)"); } - + @Override protected Set getLegalMovesForCell(int xCell, int yCell) { return gameStateHasLegalMovesMatching("\\( mark " + xCell + " " + yCell + " \\)"); } - + @Override protected void renderCellContent(Graphics g, String theFact) { String[] cellFacts = theFact.split(" "); - + if(!cellFacts[4].equals("b")) { g.setColor(Color.BLACK); CommonGraphics.fillWithString(g, cellFacts[4], 1.2); } - } + } } \ No newline at end of file diff --git a/src/org/ggp/base/apps/kiosk/games/TicTacToeCanvas_Reference.java b/src/org/ggp/base/apps/kiosk/games/TicTacToeCanvas_Reference.java index 2060c8004..a613fcc26 100644 --- a/src/org/ggp/base/apps/kiosk/games/TicTacToeCanvas_Reference.java +++ b/src/org/ggp/base/apps/kiosk/games/TicTacToeCanvas_Reference.java @@ -15,54 +15,54 @@ /** * A reference implementation of Tic-Tac-Toe based purely on GameCanvas, * not using any of the standard templates. Comes to just under 150 lines. - * + * * @author Sam Schreiber */ public class TicTacToeCanvas_Reference extends GameCanvas { public static final long serialVersionUID = 0x1; - + public String getGameName() { return "Tic-Tac-Toe (Old Version)"; } - + protected String getGameKey() { return "ticTacToe"; - } + } private Graphics mostRecentG; protected void paintGame(Graphics g) { int width = g.getClipBounds().width; int height = g.getClipBounds().height; - + mostRecentG = g; - + g.setColor(this.getBackground()); g.fillRect(0, 0, width, height); - + g.setColor(Color.BLACK); g.fillRect(width/3-2, 0, 4, height); g.fillRect(2*width/3-2, 0, 4, height); g.fillRect(0, height/3-2, width, 4); g.fillRect(0, 2*height/3-2, width, 4); - + if(gameState == null) return; - + for(GdlSentence stateFact : gameState.getContents()) { if(stateFact.getBody().size() > 1) continue; - + GdlSentence theRealSentence = stateFact.getBody().get(0).toSentence(); if(theRealSentence.getName().toString().equals("cell")) { int xCell = Integer.parseInt(theRealSentence.getBody().get(0).toString()); int yCell = Integer.parseInt(theRealSentence.getBody().get(1).toString()); char mark = theRealSentence.getBody().get(2).toString().charAt(0); - + int xSpot = (xCell-1)*width/3 + 2; int ySpot = (yCell-1)*height/3 + 2; - + g.setColor(Color.BLACK); - final int BORDER_SIZE = 35; + final int BORDER_SIZE = 35; if(mark == 'b') { ; } else if(mark == 'x') { @@ -71,23 +71,23 @@ protected void paintGame(Graphics g) { } else if(mark == 'o') { g.drawOval(xSpot+BORDER_SIZE, ySpot+BORDER_SIZE, width/3 - 2*BORDER_SIZE, height/3 - 2*BORDER_SIZE); } - } + } } - + try { List legalMoves = stateMachine.getLegalMoves(gameState, myRole); - + for(Move legalMove : legalMoves) { if(legalMove.getContents() instanceof GdlConstant) continue; - + GdlFunction moveContents = (GdlFunction) legalMove.getContents(); int xCell = Integer.parseInt(moveContents.getBody().get(0).toString()); int yCell = Integer.parseInt(moveContents.getBody().get(1).toString()); - + int xSpot = (xCell-1)*width/3 + 2; int ySpot = (yCell-1)*height/3 + 2; - + final int BORDER_SIZE = 60; g.setColor(Color.GREEN); if(myRole.toString().equals("xplayer")) { @@ -96,7 +96,7 @@ protected void paintGame(Graphics g) { } else { g.drawOval(xSpot+BORDER_SIZE, ySpot+BORDER_SIZE, width/3 - 2*BORDER_SIZE, height/3 - 2*BORDER_SIZE); } - + if(xSelectedCell == xCell && ySelectedCell == yCell) { g.drawRect(xSpot+BORDER_SIZE/2, ySpot+BORDER_SIZE/2, width/3-BORDER_SIZE, height/3-BORDER_SIZE); } @@ -113,22 +113,22 @@ protected void handleDragEvent(int dx, int dy) { private int xSelectedCell, ySelectedCell; protected void handleClickEvent(int x, int y) { int width = mostRecentG.getClipBounds().width; - int height = mostRecentG.getClipBounds().height; - + int height = mostRecentG.getClipBounds().height; + try { List legalMoves = stateMachine.getLegalMoves(gameState, myRole); - + int xCell = 1+3*x/width; int yCell = 1+3*y/height; - + String moveString = "( mark " + xCell + " " + yCell + " )"; for(Move legalMove : legalMoves) { - if(legalMove.toString().equals(moveString)) { + if(legalMove.toString().equals(moveString)) { submitWorkingMove(legalMove); - + xSelectedCell = xCell; ySelectedCell = yCell; - + repaint(); } } @@ -136,11 +136,11 @@ protected void handleClickEvent(int x, int y) { ; } } - + public void clearMoveSelection() { xSelectedCell = ySelectedCell = 0; submitWorkingMove(null); - + repaint(); } } \ No newline at end of file diff --git a/src/org/ggp/base/apps/kiosk/templates/CommonGraphics.java b/src/org/ggp/base/apps/kiosk/templates/CommonGraphics.java index 54b0073a4..54c1a4e67 100644 --- a/src/org/ggp/base/apps/kiosk/templates/CommonGraphics.java +++ b/src/org/ggp/base/apps/kiosk/templates/CommonGraphics.java @@ -19,7 +19,7 @@ public static Image getImage(String imageName) { return getImage("", imageName); } - public static Image getImage(String dirName, String imageName) { + public static Image getImage(String dirName, String imageName) { try { return ImageIO.read(new File(new File(ProjectConfiguration.gameImagesDirectory, dirName), imageName)); } catch (IOException e) { @@ -33,16 +33,16 @@ public static void fillWithString(Graphics g, String theText, double sizeFactor) int theWidth = g.getClipBounds().width; Font theFont = g.getFont().deriveFont((float) (theHeight / sizeFactor)).deriveFont(Font.BOLD); - g.setFont(theFont); - + g.setFont(theFont); + FontMetrics theMetric = g.getFontMetrics(); g.drawString(theText, (theWidth - theMetric.stringWidth(theText)) / 2, theMetric.getAscent() + (theHeight - (theMetric.getDescent() + theMetric.getAscent())) / 2); - } + } public static void drawSelectionBox(Graphics g) { int width = g.getClipBounds().width; int height = g.getClipBounds().height; - + g.setColor(Color.GREEN); g.drawRect(3, 3, width-6, height-6); } @@ -50,18 +50,18 @@ public static void drawSelectionBox(Graphics g) { public static void drawCellBorder(Graphics g) { int width = g.getClipBounds().width; int height = g.getClipBounds().height; - + g.setColor(Color.BLACK); g.drawRect(1, 1, width-2, height-2); - } + } public static void drawBubbles(Graphics g, int nCode) { int width = g.getClipBounds().width; int height = g.getClipBounds().height; - + g.setColor(Color.BLUE); - g.fillRect(1, 1, width-2, height-2); - + g.fillRect(1, 1, width-2, height-2); + Random r = new Random(nCode); int nBubbles = r.nextInt(3)+2; for(int i = 0; i < nBubbles; i++) { @@ -75,25 +75,25 @@ public static void drawBubbles(Graphics g, int nCode) { public static void drawDisc(Graphics g) { int width = g.getClipBounds().width; - int height = g.getClipBounds().height; - + int height = g.getClipBounds().height; + Color theColor = g.getColor(); g.setColor(Color.DARK_GRAY); g.fillOval(4, 4, width-8, height-8); g.setColor(theColor); g.fillOval(6, 6, width-12, height-12); - } + } public static void drawCheckersPiece(Graphics g, String checkersPiece) { int width = g.getClipBounds().width; - int height = g.getClipBounds().height; - + int height = g.getClipBounds().height; + if(checkersPiece.length() != 2) return; - + Color theColor = ((checkersPiece.charAt(0) == 'b') ? Color.BLACK : Color.RED); boolean isKing = (checkersPiece.charAt(1) == 'k'); - + g.setColor(Color.DARK_GRAY); g.fillOval(4, 4, width-8, height-8); g.setColor(theColor); @@ -101,7 +101,7 @@ public static void drawCheckersPiece(Graphics g, String checkersPiece) { if(isKing) { if(theCrownImage == null) theCrownImage = getImage("checkers", "crown.png"); - + g.setColor(Color.YELLOW); g.drawImage(theCrownImage, width/5, 2*height/7, 3*width/5, 3*height/7, null); } @@ -109,11 +109,11 @@ public static void drawCheckersPiece(Graphics g, String checkersPiece) { public static void drawChessPiece(Graphics g, String chessPiece) { int width = g.getClipBounds().width; - int height = g.getClipBounds().height; + int height = g.getClipBounds().height; if (blackPawnImage == null) lazyLoadChessPieces(); - + Image toDraw = null; if(chessPiece.charAt(0) == 'w') { if(chessPiece.equals("wp")) toDraw = whitePawnImage; @@ -123,16 +123,16 @@ public static void drawChessPiece(Graphics g, String chessPiece) { else if(chessPiece.equals("wr")) toDraw = whiteRookImage; else if(chessPiece.equals("wk")) toDraw = whiteKingImage; } else if(chessPiece.charAt(0) == 'b') { - if(chessPiece.equals("bp")) toDraw = blackPawnImage; + if(chessPiece.equals("bp")) toDraw = blackPawnImage; else if(chessPiece.equals("bn")) toDraw = blackKnightImage; else if(chessPiece.equals("bb")) toDraw = blackBishopImage; else if(chessPiece.equals("bq")) toDraw = blackQueenImage; else if(chessPiece.equals("br")) toDraw = blackRookImage; else if(chessPiece.equals("bk")) toDraw = blackKingImage; } - + if(toDraw != null) { - g.drawImage(toDraw, 5, 5, width-10, height-10, null); + g.drawImage(toDraw, 5, 5, width-10, height-10, null); } else { System.err.println("Could not process chess piece [" + chessPiece + "]."); } @@ -150,7 +150,7 @@ private static void lazyLoadChessPieces() { whiteBishopImage = getImage("chess", "White_Bishop.png"); whiteKnightImage = getImage("chess", "White_Knight.png"); whiteKingImage = getImage("chess", "White_King.png"); - whiteQueenImage = getImage("chess", "White_Queen.png"); + whiteQueenImage = getImage("chess", "White_Queen.png"); } // Checkers images diff --git a/src/org/ggp/base/apps/kiosk/templates/GameCanvas_Chessboard.java b/src/org/ggp/base/apps/kiosk/templates/GameCanvas_Chessboard.java index 6a6b6af19..838712fdd 100644 --- a/src/org/ggp/base/apps/kiosk/templates/GameCanvas_Chessboard.java +++ b/src/org/ggp/base/apps/kiosk/templates/GameCanvas_Chessboard.java @@ -9,7 +9,7 @@ * conventions for this class of games: an 8x8 board with alternating colors. * It also defines the coordinates-to-letters mapping that appears in several * chess board games, such as chess and checkers. - * + * * @author Sam Schreiber */ public abstract class GameCanvas_Chessboard extends GameCanvas_FancyGrid { @@ -20,20 +20,20 @@ public abstract class GameCanvas_Chessboard extends GameCanvas_FancyGrid { protected final boolean useGridVisualization() { return true; } protected final boolean coordinatesStartAtOne() { return true; } - + protected final void renderCellBackground(Graphics g, int xCell, int yCell) { int width = g.getClipBounds().width; - int height = g.getClipBounds().height; - + int height = g.getClipBounds().height; + // Alternating colors for the board if( (xCell + yCell) % 2 == 0) { g.setColor(Color.GRAY); g.fillRect(0, 0, width, height); } } - + // This function only works properly when coordinates start at one. public final static String coordinateToLetter(int x) { return "" + ((char) ('a' + x - 1)); - } + } } \ No newline at end of file diff --git a/src/org/ggp/base/apps/kiosk/templates/GameCanvas_FancyGrid.java b/src/org/ggp/base/apps/kiosk/templates/GameCanvas_FancyGrid.java index e2f42c8c5..ba6d5fb0d 100644 --- a/src/org/ggp/base/apps/kiosk/templates/GameCanvas_FancyGrid.java +++ b/src/org/ggp/base/apps/kiosk/templates/GameCanvas_FancyGrid.java @@ -18,48 +18,48 @@ * game being visualized, and so may not be appropriate for all games. * These assumptions, in addition to the GameCanvas_SimpleGrid assumptions, * are as follows: - * + * * 1) Each cell of the grid can be drawn independently, * using the following layers: - * + * * a) Background layer, based only on coordinates. * b) Content layer, based only on game propositions. * c) Foreground layer, based only on coordinates. * d) Selection layer, based only on the coordinates * and the currently selected move. - * + * * 2) The game propositions required to render the content layer * of a given cell can be determined from the current state of * the game and the cell's coordinates. As a result, they will * not change unless the game state changes. - * + * * 3) Each cell has a certain number of moves associated with it. * These moves can be determined from the current state of the * game and the cell's coordinates. As a result, they will not * change unless the game state changes. - * + * * NOTE: Multiple cells can share the same moves. - * + * * Given these assumptions, GameCanvas_FancyGrid handles a lot of the work * associated with selecting moves, rendering the grid, and caching useful * parts of the game state. The player will be able to select their move by * clicking on a cell: if there are multiple moves associated with the cell, * they can click on the cell multiple times to cycle through them. - * + * * To reflect the above assumptions, GameCanvas_FancyGrid overrides the * andleClickOnCell() and clearMoveSelection() methods, and instead provides * the following abstract methods: - * + * * getFactsAboutCell(x,y) Get all facts associated with a cell. * getLegalMovesForCell(x,y) Get all legal moves associated with a cell. - * + * * renderCellBackground(g,x,y) Draw the background for a cell. * renderCellContent(g,fact) Draw the content for a cell, given its fact. * renderCellContent(g,facts) Draw the content for a cell, given its facts. * renderCellForeground(g,x,y) Draw the foreground for a cell. - * + * * renderMoveSelectionForCell(g,x,y,move) Draw the move selection for a cell. - * + * * One common situation involves each cell having exactly one fact associated * with it, often of the form "(cell 1 1 x)". In this situation, it's more convenient * to have that single fact extracted and passed to renderCellContent() as a String, @@ -68,13 +68,13 @@ * second parameter. Otherwise, if your getFactsAboutCell() method is expected to return * multiple facts about the same cell, override the renderCellContent() method that takes * a Set as its second parameter. - * + * * Another common situation involves having a game where you want to automatically * display the grid, drawing black boxes around grid cells and always highlighting * the selected grid cell with a green border. This grid visualization will be done * by default. If you want to disable it, override the "useGridVisualization" function * so that it returns false. - * + * * @author Sam Schreiber */ public abstract class GameCanvas_FancyGrid extends GameCanvas_SimpleGrid { @@ -82,11 +82,11 @@ public abstract class GameCanvas_FancyGrid extends GameCanvas_SimpleGrid { protected abstract Set getFactsAboutCell(int xCell, int yCell); protected abstract Set getLegalMovesForCell(int xCell, int yCell); - + protected void renderCellBackground(Graphics g, int xCell, int yCell) {}; protected void renderCellForeground(Graphics g, int xCell, int yCell) {}; protected void renderMoveSelectionForCell(Graphics g, int xCell, int yCell, String theMove) {}; - + protected void renderCellContent(Graphics g, String theFact) {}; protected void renderCellContent(Graphics g, Set theFacts){ if(theFacts.size() > 0) { @@ -96,17 +96,17 @@ protected void renderCellContent(Graphics g, Set theFacts){ String theFact = theFacts.iterator().next(); renderCellContent(g, theFact); - } + } } - + protected boolean useGridVisualization() { return true; } - + protected final boolean isSelectedCell(int xCell, int yCell) { return (yCell == selectedRow && xCell == selectedColumn); } - + private int selectedRow = -1; - private int selectedColumn = -1; + private int selectedColumn = -1; private String currentSelectedMove; private Iterator possibleSelectedMoves = null; protected final void handleClickOnCell(int xCell, int yCell, int xWithin, int yWithin) { @@ -114,13 +114,13 @@ protected final void handleClickOnCell(int xCell, int yCell, int xWithin, int yW SortedSet theMoves = new TreeSet(getLegalMovesForCell(xCell, yCell)); if(theMoves.size() == 0) return; - possibleSelectedMoves = theMoves.iterator(); + possibleSelectedMoves = theMoves.iterator(); } - + selectedRow = yCell; selectedColumn = xCell; - - currentSelectedMove = possibleSelectedMoves.next(); + + currentSelectedMove = possibleSelectedMoves.next(); submitWorkingMove(stringToMove(currentSelectedMove)); } @@ -132,38 +132,38 @@ protected Set getCachedFactsAboutCell(int xCell, int yCell) { Set cachedFacts = factsCache.get(cellHash); if(cachedFacts != null) return cachedFacts; - + Set realFacts = getFactsAboutCell(xCell, yCell); factsCache.put(cellHash, realFacts); return realFacts; } - + // When the game state changes, clear our cache of known facts. public void updateGameState(MachineState gameState) { factsCache.clear(); super.updateGameState(gameState); } - + protected final void renderCell(Graphics g, int xCell, int yCell) { renderCellBackground(g, xCell, yCell); renderCellContent(g, getCachedFactsAboutCell(xCell, yCell)); if(useGridVisualization()) CommonGraphics.drawCellBorder(g); renderCellForeground(g, xCell, yCell); - if(!currentSelectedMove.isEmpty()) { + if(!currentSelectedMove.isEmpty()) { renderMoveSelectionForCell(g, xCell, yCell, currentSelectedMove); if(useGridVisualization() && isSelectedCell(xCell, yCell)) CommonGraphics.drawSelectionBox(g); } } - public final void clearMoveSelection() { + public final void clearMoveSelection() { submitWorkingMove(null); - + possibleSelectedMoves = null; currentSelectedMove = ""; - selectedColumn = -1; + selectedColumn = -1; selectedRow = -1; - + repaint(); - } + } } \ No newline at end of file diff --git a/src/org/ggp/base/apps/kiosk/templates/GameCanvas_SimpleGrid.java b/src/org/ggp/base/apps/kiosk/templates/GameCanvas_SimpleGrid.java index f67cc4cf3..7e4a80e8d 100644 --- a/src/org/ggp/base/apps/kiosk/templates/GameCanvas_SimpleGrid.java +++ b/src/org/ggp/base/apps/kiosk/templates/GameCanvas_SimpleGrid.java @@ -9,55 +9,55 @@ * GameCanvas_SimpleGrid builds a very simple grid on top of the * standard Kiosk game canvas. This makes the following simplifying * assumptions about the structure of the game: - * + * * 1) Each grid cell in the game can be rendered independently. * 2) Click events should be handled on a per-cell basis. - * + * * Thus, it overrides paintGame() and handleClickEvent() and instead * provides four new abstract functions: - * + * * getGridWidth Return the width of the grid. * getGridHeight Return the height of the grid. * renderCell Draw an individual grid cell. * handleClickOnCell Handle a click on a grid cell. - * + * * You can also optionally override function "coordinatesStartAtOne" * to control whether or not the coordinates passed to the above functions * start at zero or one. This is a convenience feature, since many game * descriptions are written assuming that the game grid has coordinates * which start at one. By default, coordinates *do* start at one. - * + * * @author Sam Schreiber */ public abstract class GameCanvas_SimpleGrid extends GameCanvas { public static final long serialVersionUID = 0x1; - + protected abstract int getGridWidth(); protected abstract int getGridHeight(); protected abstract void renderCell(Graphics g, int x, int y); protected abstract void handleClickOnCell(int xCell, int yCell, int xWithin, int yWithin); - + protected boolean coordinatesStartAtOne() { return true; } - + private Graphics mostRecentG; protected final void paintGame(Graphics g) { int width = g.getClipBounds().width; int height = g.getClipBounds().height; - + mostRecentG = g; - + g.setColor(this.getBackground()); g.fillRect(0, 0, width, height); if(gameState == null) return; - + int nGridWidth = getGridWidth(); int nGridHeight = getGridHeight(); - + int nCellWidth = width / nGridWidth; int nCellHeight = height / nGridHeight; - + for(int x = 0; x < nGridWidth; x++) { for(int y = 0; y < nGridHeight; y++) { Graphics cellGraphics = g.create(x*nCellWidth, y*nCellHeight, nCellWidth, nCellHeight); @@ -67,29 +67,29 @@ protected final void paintGame(Graphics g) { renderCell(cellGraphics, x, y); } } - } + } } protected final void handleClickEvent(int x, int y) { int width = mostRecentG.getClipBounds().width; - int height = mostRecentG.getClipBounds().height; + int height = mostRecentG.getClipBounds().height; int nGridWidth = getGridWidth(); int nGridHeight = getGridHeight(); - + int nCellWidth = width / nGridWidth; int nCellHeight = height / nGridHeight; - + int xCell = x / nCellWidth; int yCell = y / nCellHeight; - + int xWithin = x % nCellWidth; int yWithin = y % nCellHeight; - + if(coordinatesStartAtOne()) { handleClickOnCell(xCell+1, yCell+1, xWithin, yWithin); } else { handleClickOnCell(xCell, yCell, xWithin, yWithin); } - } + } } \ No newline at end of file diff --git a/src/org/ggp/base/apps/logging/LogSummarizer.java b/src/org/ggp/base/apps/logging/LogSummarizer.java index d725fb023..98d1232ba 100644 --- a/src/org/ggp/base/apps/logging/LogSummarizer.java +++ b/src/org/ggp/base/apps/logging/LogSummarizer.java @@ -16,27 +16,27 @@ * not contain any sensitive data; the summarizer can be queried by anyone and its * summaries are made publicly available on the GGP.org viewer alongside the other * information about each match. - * + * * SAMPLE INVOCATION (when running locally): - * + * * ResourceLoader.load_raw('http://127.0.0.1:9199/matchABC'); - * + * * The Log Summarizer Server replies with a JSON summary of the logs for "matchABC". - * + * * @author Sam Schreiber */ public class LogSummarizer { public static LogSummaryGenerator theGenerator; public static final int SERVER_PORT = 9199; - + static class SummarizeLogThread extends Thread { private Socket connection; - + public SummarizeLogThread(Socket connection) throws IOException, JSONException { this.connection = connection; } - + @Override public void run() { try { @@ -50,7 +50,7 @@ public void run() { } } } - + public static void main(String[] args) { ServerSocket listener = null; try { @@ -69,6 +69,6 @@ public static void main(String[] args) { } catch (Exception e) { System.err.println(e); } - } + } } } \ No newline at end of file diff --git a/src/org/ggp/base/apps/player/Player.java b/src/org/ggp/base/apps/player/Player.java index f8589dea7..8da37631d 100644 --- a/src/org/ggp/base/apps/player/Player.java +++ b/src/org/ggp/base/apps/player/Player.java @@ -47,7 +47,7 @@ private static void createAndShowGUI(Player playerPanel) public static void main(String[] args) throws IOException { - NativeUI.setNativeUI(); + NativeUI.setNativeUI(); final Player playerPanel = new Player(); javax.swing.SwingUtilities.invokeLater(new Runnable() @@ -66,9 +66,9 @@ public void run() private final JTextField portTextField; private final JComboBox typeComboBox; - + private Integer defaultPort = 9147; - + private List> gamers = Lists.newArrayList(ProjectSearcher.GAMERS.getConcreteClasses()); public Player() @@ -143,7 +143,7 @@ public void actionPerformed(ActionEvent evt) GamePlayer player = new GamePlayer(port, gamer); player.addObserver(networkPanel); - player.start(); + player.start(); JTabbedPane tab = new JTabbedPane(); tab.addTab("Match", matchPanel); @@ -152,7 +152,7 @@ public void actionPerformed(ActionEvent evt) tab.addTab("Detail", detailPanel); playersTabbedPane.addTab(type + " (" + player.getGamerPort() + ")", tab); playersTabbedPane.setSelectedIndex(playersTabbedPane.getTabCount()-1); - + defaultPort++; portTextField.setText(defaultPort.toString()); } diff --git a/src/org/ggp/base/apps/player/PlayerRunner.java b/src/org/ggp/base/apps/player/PlayerRunner.java index d5dd07fd9..5a0dda527 100644 --- a/src/org/ggp/base/apps/player/PlayerRunner.java +++ b/src/org/ggp/base/apps/player/PlayerRunner.java @@ -10,7 +10,7 @@ /** * This is a simple command line app for running players. - * + * * @author schreib */ public final class PlayerRunner @@ -31,7 +31,7 @@ public static void main(String[] args) throws IOException, InstantiationExceptio availableGamers.add(gamerClass.getSimpleName()); if (gamerClass.getSimpleName().equals(name)) { chosenGamerClass = gamerClass; - } + } } if (chosenGamerClass == null) { System.out.println("Could not find player class with that name. Available choices are: " + Arrays.toString(availableGamers.toArray())); diff --git a/src/org/ggp/base/apps/player/detail/SimpleDetailPanel.java b/src/org/ggp/base/apps/player/detail/SimpleDetailPanel.java index bbc6c488e..189c00331 100644 --- a/src/org/ggp/base/apps/player/detail/SimpleDetailPanel.java +++ b/src/org/ggp/base/apps/player/detail/SimpleDetailPanel.java @@ -16,7 +16,7 @@ /** * This is a simple tabular detail panel that shows the number of * available moves, the time it took to select a move, and the move - * that was selected. + * that was selected. */ @SuppressWarnings("serial") public class SimpleDetailPanel extends DetailPanel { diff --git a/src/org/ggp/base/apps/server/Server.java b/src/org/ggp/base/apps/server/Server.java index a8c55481b..e9db444e4 100644 --- a/src/org/ggp/base/apps/server/Server.java +++ b/src/org/ggp/base/apps/server/Server.java @@ -45,7 +45,7 @@ @SuppressWarnings("serial") public final class Server extends JPanel implements ActionListener -{ +{ static void createAndShowGUI(Server serverPanel, String title) { JFrame frame = new JFrame(title); @@ -59,10 +59,10 @@ static void createAndShowGUI(Server serverPanel, String title) } public static void main(String[] args) - { + { NativeUI.setNativeUI(); GdlPool.caseSensitive = false; - + final Server serverPanel = new Server(); javax.swing.SwingUtilities.invokeLater(new Runnable() { @@ -73,14 +73,14 @@ public void run() } }); } - + private Game theGame; - + private final JPanel managerPanel; - private final JTabbedPane matchesTabbedPane; + private final JTabbedPane matchesTabbedPane; private final JPanel gamePanel; private final JPanel playersPanel; - + private final SchedulingPanel schedulingPanel; private final LeaderboardPanel leaderboardPanel; @@ -91,29 +91,29 @@ public void run() private final JSpinner startClockSpinner; private final JSpinner playClockSpinner; private final JSpinner repetitionsSpinner; - + private final JCheckBox shouldScramble; private final JCheckBox shouldQueue; private final JCheckBox shouldDetail; - private final JCheckBox shouldPublish; + private final JCheckBox shouldPublish; private final JCheckBox shouldSave; - + private final GameSelector gameSelector; private final PlayerSelector playerSelector; private final JList playerSelectorList; - + private final Scheduler scheduler; - + public Server() { super(new GridBagLayout()); - + runButton = new JButton(runButtonMethod()); startClockSpinner = new JSpinner(new SpinnerNumberModel(30,5,600,1)); playClockSpinner = new JSpinner(new SpinnerNumberModel(15,5,300,1)); repetitionsSpinner = new JSpinner(new SpinnerNumberModel(1,1,1000,1)); matchesTabbedPane = new JTabbedPane(); - + managerPanel = new JPanel(new GridBagLayout()); gamePanel = new JPanel(new GridBagLayout()); playersPanel = new JPanel(new GridBagLayout()); @@ -126,14 +126,14 @@ public Server() shouldQueue = new JCheckBox("Queue match?", true); shouldDetail = new JCheckBox("Show match details?", true); shouldSave = new JCheckBox("Save match to disk?", false); - shouldPublish = new JCheckBox("Publish match to the web?", false); - + shouldPublish = new JCheckBox("Publish match to the web?", false); + runButton.setEnabled(false); gameSelector = new GameSelector(); playerSelector = new PlayerSelector(); playerSelectorList = playerSelector.getPlayerSelectorList(); - + int nRowCount = 0; gamePanel.add(new JLabelBold("Match Setup"), new GridBagConstraints(0, nRowCount++, 3, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(5, 25, 5, 25), 0, 0)); gamePanel.add(new JLabel("Repository:"), new GridBagConstraints(0, nRowCount, 1, 1, 0.0, 0.0, GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(5, 5, 1, 5), 5, 5)); @@ -145,21 +145,21 @@ public Server() gamePanel.add(new JLabel("Play Clock:"), new GridBagConstraints(0, nRowCount, 1, 1, 0.0, 0.0, GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(1, 5, 5, 5), 5, 5)); gamePanel.add(playClockSpinner, new GridBagConstraints(1, nRowCount++, 1, 1, 0.0, 0.0, GridBagConstraints.EAST, GridBagConstraints.HORIZONTAL, new Insets(1, 5, 5, 5), 5, 5)); gamePanel.add(new JLabel("Repetitions:"), new GridBagConstraints(0, nRowCount, 1, 1, 0.0, 0.0, GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(1, 5, 5, 5), 5, 5)); - gamePanel.add(repetitionsSpinner, new GridBagConstraints(1, nRowCount++, 1, 1, 0.0, 0.0, GridBagConstraints.EAST, GridBagConstraints.HORIZONTAL, new Insets(1, 5, 5, 5), 5, 5)); + gamePanel.add(repetitionsSpinner, new GridBagConstraints(1, nRowCount++, 1, 1, 0.0, 0.0, GridBagConstraints.EAST, GridBagConstraints.HORIZONTAL, new Insets(1, 5, 5, 5), 5, 5)); gamePanel.add(shouldScramble, new GridBagConstraints(1, nRowCount++, 1, 1, 0.0, 0.0, GridBagConstraints.EAST, GridBagConstraints.HORIZONTAL, new Insets(5, 5, 0, 5), 5, 0)); gamePanel.add(shouldQueue, new GridBagConstraints(1, nRowCount++, 1, 1, 0.0, 0.0, GridBagConstraints.EAST, GridBagConstraints.HORIZONTAL, new Insets(0, 5, 0, 5), 5, 0)); gamePanel.add(shouldDetail, new GridBagConstraints(1, nRowCount++, 1, 1, 0.0, 0.0, GridBagConstraints.EAST, GridBagConstraints.HORIZONTAL, new Insets(0, 5, 0, 5), 5, 0)); gamePanel.add(shouldSave, new GridBagConstraints(1, nRowCount++, 1, 1, 0.0, 0.0, GridBagConstraints.EAST, GridBagConstraints.HORIZONTAL, new Insets(0, 5, 0, 5), 5, 0)); - gamePanel.add(shouldPublish, new GridBagConstraints(1, nRowCount++, 1, 1, 0.0, 0.0, GridBagConstraints.EAST, GridBagConstraints.HORIZONTAL, new Insets(0, 5, 5, 5), 5, 0)); + gamePanel.add(shouldPublish, new GridBagConstraints(1, nRowCount++, 1, 1, 0.0, 0.0, GridBagConstraints.EAST, GridBagConstraints.HORIZONTAL, new Insets(0, 5, 5, 5), 5, 0)); gamePanel.add(runButton, new GridBagConstraints(1, nRowCount, 1, 1, 0.0, 1.0, GridBagConstraints.SOUTH, GridBagConstraints.HORIZONTAL, new Insets(5, 5, 5, 5), 0, 0)); - + nRowCount = 0; playersPanel.add(new JLabelBold("Player List"), new GridBagConstraints(0, nRowCount++, 3, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(5, 25, 5, 25), 0, 0)); playersPanel.add(new JScrollPane(playerSelectorList), new GridBagConstraints(0, nRowCount++, 3, 1, 1.0, 1.0, GridBagConstraints.WEST, GridBagConstraints.BOTH, new Insets(5, 25, 5, 25), 0, 0)); playersPanel.add(new JButton(addPlayerButtonMethod()), new GridBagConstraints(0, nRowCount, 1, 1, 1.0, 1.0, GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0)); playersPanel.add(new JButton(removePlayerButtonMethod()), new GridBagConstraints(1, nRowCount, 1, 1, 0.0, 1.0, GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0)); playersPanel.add(new JButton(testPlayerButtonMethod()), new GridBagConstraints(2, nRowCount++, 1, 1, 1.0, 1.0, GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0)); - + nRowCount = 0; managerPanel.add(gamePanel, new GridBagConstraints(0, nRowCount++, 1, 1, 1.0, 0.0, GridBagConstraints.NORTHWEST, GridBagConstraints.HORIZONTAL, new Insets(5, 5, 5, 5), 5, 5)); managerPanel.add(new JSeparator(), new GridBagConstraints(0, nRowCount++, 1, 1, 0.0, 0.0, GridBagConstraints.NORTHWEST, GridBagConstraints.HORIZONTAL, new Insets(5, 5, 5, 5), 5, 5)); @@ -167,31 +167,31 @@ public Server() this.add(managerPanel, new GridBagConstraints(0, 0, 1, 1, 0.0, 1.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(5, 5, 5, 5), 5, 5)); this.add(matchesTabbedPane, new GridBagConstraints(1, 0, 1, 1, 1.0, 1.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(5, 5, 5, 5), 5, 5)); - + gameSelector.getGameList().addActionListener(this); gameSelector.repopulateGameList(); - + schedulingPanel = new SchedulingPanel(); leaderboardPanel = new LeaderboardPanel(); matchesTabbedPane.addTab("Overview", new OverviewPanel()); - + scheduler = new Scheduler(matchesTabbedPane, schedulingPanel, leaderboardPanel); schedulingPanel.setScheduler(scheduler); scheduler.start(); } - + public void setSigningKeys(EncodedKeyPair keys) { scheduler.signingKeys = keys; } - + class OverviewPanel extends JPanel { public OverviewPanel() { super(new GridBagLayout()); add(schedulingPanel, new GridBagConstraints(0, 0, 1, 1, 2.0, 1.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(5, 5, 5, 5), 5, 5)); - add(leaderboardPanel, new GridBagConstraints(1, 0, 1, 1, 1.0, 1.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(5, 5, 5, 5), 5, 5)); + add(leaderboardPanel, new GridBagConstraints(1, 0, 1, 1, 1.0, 1.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(5, 5, 5, 5), 5, 5)); } } - + @Override public void actionPerformed(ActionEvent e) { if (e.getSource() == gameSelector.getGameList()) { @@ -208,12 +208,12 @@ public void actionPerformed(ActionEvent e) { validate(); runButton.setEnabled(false); if (theGame == null) - return; + return; StateMachine stateMachine = new ProverStateMachine(); stateMachine.initialize(theGame.getRules()); List roles = stateMachine.getRoles(); - + int newRowCount = 11; for (int i = 0; i < roles.size(); i++) { roleLabels.add(new JLabel(roles.get(i).getName().toString() + ":")); @@ -227,8 +227,8 @@ public void actionPerformed(ActionEvent e) { validate(); runButton.setEnabled(true); - } - } + } + } private AbstractAction runButtonMethod() { return new AbstractAction("Start a new match!") { @@ -241,9 +241,9 @@ public void actionPerformed(ActionEvent evt) { String name = playerField.getSelectedItem().toString(); thePlayers.add(playerSelector.getPlayerPresence(name)); } - + synchronized (scheduler) { - for (int i = 0; i < (Integer)repetitionsSpinner.getValue(); i++) { + for (int i = 0; i < (Integer)repetitionsSpinner.getValue(); i++) { scheduler.addPendingMatch(new PendingMatch("Base", theGame, new ArrayList(thePlayers), -1, startClock, playClock, shouldScramble.isSelected(), shouldQueue.isSelected(), shouldDetail.isSelected(), shouldSave.isSelected(), shouldPublish.isSelected())); thePlayers.add(thePlayers.remove(0)); // rotate player roster for repeated matches try { @@ -263,13 +263,13 @@ public void actionPerformed(ActionEvent evt) { if (playerSelectorList.getSelectedValue() != null) { Game testGame = GameRepository.getDefaultRepository().getGame("maze"); String playerName = playerSelectorList.getSelectedValue().toString(); - List thePlayers = Arrays.asList(new PlayerPresence[]{playerSelector.getPlayerPresence(playerName)}); + List thePlayers = Arrays.asList(new PlayerPresence[]{playerSelector.getPlayerPresence(playerName)}); scheduler.addPendingMatch(new PendingMatch("Test", testGame, thePlayers, -1, 10, 5, false, false, true, false, false)); } } }; } - + private AbstractAction addPlayerButtonMethod() { return new AbstractAction("Add") { public void actionPerformed(ActionEvent evt) { @@ -282,7 +282,7 @@ public void actionPerformed(ActionEvent evt) { } }; } - + private AbstractAction removePlayerButtonMethod() { return new AbstractAction("Remove") { public void actionPerformed(ActionEvent evt) { diff --git a/src/org/ggp/base/apps/server/leaderboard/LeaderboardPanel.java b/src/org/ggp/base/apps/server/leaderboard/LeaderboardPanel.java index 169a59a2b..882fac8c1 100644 --- a/src/org/ggp/base/apps/server/leaderboard/LeaderboardPanel.java +++ b/src/org/ggp/base/apps/server/leaderboard/LeaderboardPanel.java @@ -29,16 +29,16 @@ public final class LeaderboardPanel extends JPanel implements Observer { private final JTable leaderTable; private final TableRowSorter sorter; - + public LeaderboardPanel() { super(new BorderLayout()); - - DefaultTableModel model = new DefaultTableModel(); + + DefaultTableModel model = new DefaultTableModel(); model.addColumn("Player"); model.addColumn("Score"); model.addColumn("Errors"); - + leaderTable = new JTable(model) { @Override @@ -76,10 +76,10 @@ public void observe(Event event) { if (!(event instanceof ServerMatchUpdatedEvent)) return; Match match = ((ServerMatchUpdatedEvent) event).getMatch(); - + if (!match.isCompleted()) return; if (match.getMatchId().startsWith("Test")) return; - + List goals = match.getGoalValues(); List errors = getErrorCounts(match.getErrorHistory()); List players = match.getPlayerNamesFromHost(); @@ -103,7 +103,7 @@ public void observe(Event event) } sorter.sort(); } - + public static List getErrorCounts(List> errorHistory) { List errorCounts = new ArrayList(); for (int i = 0; i < errorHistory.get(0).size(); i++) { diff --git a/src/org/ggp/base/apps/server/scheduling/PendingMatch.java b/src/org/ggp/base/apps/server/scheduling/PendingMatch.java index 41065410b..e2e83432f 100644 --- a/src/org/ggp/base/apps/server/scheduling/PendingMatch.java +++ b/src/org/ggp/base/apps/server/scheduling/PendingMatch.java @@ -12,13 +12,13 @@ public final class PendingMatch public final String matchID; public final int previewClock; public final int startClock; - public final int playClock; + public final int playClock; public final boolean shouldScramble; public final boolean shouldQueue; public final boolean shouldDetail; public final boolean shouldSave; public final boolean shouldPublish; - + public PendingMatch(String matchIdPrefix, Game theGame, List thePlayers, int previewClock, int startClock, int playClock, boolean shouldScramble, boolean shouldQueue, boolean shouldDetail, boolean shouldSave, boolean shouldPublish) { this.matchID = matchIdPrefix + "." + theGame.getKey() + "." + System.currentTimeMillis(); this.theGame = theGame; @@ -30,6 +30,6 @@ public PendingMatch(String matchIdPrefix, Game theGame, List the this.shouldQueue = shouldQueue; this.shouldDetail = shouldDetail; this.shouldSave = shouldSave; - this.shouldPublish = shouldPublish; + this.shouldPublish = shouldPublish; } } \ No newline at end of file diff --git a/src/org/ggp/base/apps/server/scheduling/Scheduler.java b/src/org/ggp/base/apps/server/scheduling/Scheduler.java index 41b6d3ac8..2fabc87ca 100644 --- a/src/org/ggp/base/apps/server/scheduling/Scheduler.java +++ b/src/org/ggp/base/apps/server/scheduling/Scheduler.java @@ -31,17 +31,17 @@ public final class Scheduler implements Observer { public EncodedKeyPair signingKeys; - + private JTabbedPane matchesTabbedPane; private SchedulingPanel schedulingPanel; - private LeaderboardPanel leaderboardPanel; - + private LeaderboardPanel leaderboardPanel; + private final List schedulingQueue; private final Set activePlayers; - + private Map> gameServers; - - public Scheduler(JTabbedPane matchesTabbedPane, SchedulingPanel schedulingPanel, LeaderboardPanel leaderboardPanel) { + + public Scheduler(JTabbedPane matchesTabbedPane, SchedulingPanel schedulingPanel, LeaderboardPanel leaderboardPanel) { this.schedulingPanel = schedulingPanel; this.leaderboardPanel = leaderboardPanel; this.matchesTabbedPane = matchesTabbedPane; @@ -49,11 +49,11 @@ public Scheduler(JTabbedPane matchesTabbedPane, SchedulingPanel schedulingPanel, activePlayers = new HashSet(); gameServers = new HashMap>(); } - + public void start() { new SchedulingThread().start(); } - + public synchronized void addPendingMatch(PendingMatch spec) { if (spec.shouldQueue) { schedulingPanel.addPendingMatch(spec); @@ -62,7 +62,7 @@ public synchronized void addPendingMatch(PendingMatch spec) { doSchedule(spec); } } - + private synchronized boolean canSchedule(PendingMatch spec) { for (PlayerPresence player : spec.thePlayers) { if (!player.getStatus().equals("available")) { @@ -74,7 +74,7 @@ private synchronized boolean canSchedule(PendingMatch spec) { } return true; } - + public synchronized void abortOngoingMatch(String matchID) { if (gameServers.containsKey(matchID)) { GameServer server = gameServers.get(matchID).get(); @@ -83,7 +83,7 @@ public synchronized void abortOngoingMatch(String matchID) { } } } - + private synchronized void doSchedule(PendingMatch spec) { try { Match match = new Match(spec.matchID, spec.previewClock, spec.startClock, spec.playClock, spec.theGame); @@ -110,13 +110,13 @@ private synchronized void doSchedule(PendingMatch spec) { tab.addTab("States", statesPanel); CloseableTabs.addClosableTab(matchesTabbedPane, tab, spec.matchID, addTabCloseButton(tab)); } - + match.setCryptographicKeys(signingKeys); match.setPlayerNamesFromHost(playerNames); if (spec.shouldScramble) { match.enableScrambling(); } - + GameServer gameServer = new GameServer(match, hosts, ports); if (spec.shouldDetail) { gameServer.addObserver(errorPanel); @@ -128,7 +128,7 @@ private synchronized void doSchedule(PendingMatch spec) { gameServer.addObserver(leaderboardPanel); gameServer.addObserver(this); gameServer.start(); - + activePlayers.addAll(playerNames); if (spec.shouldSave) { @@ -140,28 +140,28 @@ private synchronized void doSchedule(PendingMatch spec) { gameServer.startSavingToFilename(matchFile.getAbsolutePath()); } if (spec.shouldPublish) { - if (!match.getGame().getRepositoryURL().contains("127.0.0.1")) { + if (!match.getGame().getRepositoryURL().contains("127.0.0.1")) { gameServer.startPublishingToSpectatorServer("http://matches.ggp.org/"); gameServer.setForceUsingEntireClock(); - } + } } - + gameServers.put(spec.matchID, new WeakReference(gameServer)); schedulingQueue.remove(spec); } catch (Exception e) { e.printStackTrace(); } } - + @Override public void observe(Event genericEvent) { if (!(genericEvent instanceof ServerMatchUpdatedEvent)) return; ServerMatchUpdatedEvent event = (ServerMatchUpdatedEvent)genericEvent; - Match match = event.getMatch(); + Match match = event.getMatch(); if (!match.isAborted() && !match.isCompleted()) return; activePlayers.removeAll(match.getPlayerNamesFromHost()); } - + @SuppressWarnings("serial") private AbstractAction addTabCloseButton(final Component tabToClose) { return new AbstractAction("x") { @@ -173,8 +173,8 @@ public void actionPerformed(ActionEvent evt) { } } }; - } - + } + class SchedulingThread extends Thread { public void run() { while (true) { @@ -194,6 +194,6 @@ public void run() { doSchedule(matchToSchedule); } } - } + } } } \ No newline at end of file diff --git a/src/org/ggp/base/apps/server/scheduling/SchedulingPanel.java b/src/org/ggp/base/apps/server/scheduling/SchedulingPanel.java index a102f2f62..3df1d0f8b 100644 --- a/src/org/ggp/base/apps/server/scheduling/SchedulingPanel.java +++ b/src/org/ggp/base/apps/server/scheduling/SchedulingPanel.java @@ -30,22 +30,22 @@ @SuppressWarnings("serial") public final class SchedulingPanel extends JPanel implements Observer, ListSelectionListener, TableModelListener -{ +{ private final JTable queueTable; - + private final JButton viewSaved; private final JButton viewPublished; private final JButton remove; - + // Track the external filenames and URLs for each match, so that they can // be opened for viewing as needed. private final Map matchIdToURL = new HashMap(); private final Map matchIdToFilename = new HashMap(); - + public SchedulingPanel() { - super(new BorderLayout()); - + super(new BorderLayout()); + DefaultTableModel model = new DefaultTableModel(); model.addColumn("ID"); model.addColumn("Game"); @@ -55,7 +55,7 @@ public SchedulingPanel() model.addColumn("Goals"); model.addColumn("Errors"); model.addColumn("Step"); - + queueTable = new JTable(model) { @Override @@ -76,11 +76,11 @@ public boolean isCellEditable(int rowIndex, int colIndex) queueTable.getColumnModel().getColumn(7).setPreferredWidth(40); queueTable.getSelectionModel().addListSelectionListener(this); queueTable.getModel().addTableModelListener(this); - + JPanel buttonPanel = new JPanel(); viewSaved = new JButton(viewSavedMatchButtonMethod()); viewSaved.setEnabled(false); - viewPublished = new JButton(viewPublishedMatchButtonMethod()); + viewPublished = new JButton(viewPublishedMatchButtonMethod()); viewPublished.setEnabled(false); remove = new JButton(removeMatchButtonMethod()); remove.setEnabled(false); @@ -92,12 +92,12 @@ public boolean isCellEditable(int rowIndex, int colIndex) add(new JScrollPane(queueTable, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED), BorderLayout.CENTER); add(buttonPanel, BorderLayout.SOUTH); } - + private Scheduler scheduler; public void setScheduler(Scheduler scheduler) { this.scheduler = scheduler; } - + private AbstractAction viewPublishedMatchButtonMethod() { return new AbstractAction("View Published") { public void actionPerformed(ActionEvent evt) { @@ -114,7 +114,7 @@ public void actionPerformed(ActionEvent evt) { } }; } - + private AbstractAction viewSavedMatchButtonMethod() { return new AbstractAction("View Saved") { public void actionPerformed(ActionEvent evt) { @@ -131,7 +131,7 @@ public void actionPerformed(ActionEvent evt) { } }; } - + private AbstractAction removeMatchButtonMethod() { return new AbstractAction("Cancel Match") { public void actionPerformed(ActionEvent evt) { @@ -145,7 +145,7 @@ public void actionPerformed(ActionEvent evt) { scheduler.abortOngoingMatch(matchId); } } else if (state.equals("aborted") || state.equals("done")) { - int[] nRows = queueTable.getSelectedRows(); + int[] nRows = queueTable.getSelectedRows(); queueTable.clearSelection(); Arrays.sort(nRows); for (int i = nRows.length-1; i >= 0; i--) { @@ -156,29 +156,29 @@ public void actionPerformed(ActionEvent evt) { } }; } - + @Override public void tableChanged(TableModelEvent arg0) { updateButtonState(); } - + @Override public void valueChanged(ListSelectionEvent arg0) { updateButtonState(); } - + private void updateButtonState() { if (queueTable.getSelectedRow() >= 0) { String matchId = queueTable.getModel().getValueAt(queueTable.getSelectedRow(), 0).toString(); String state = queueTable.getModel().getValueAt(queueTable.getSelectedRow(), 3).toString(); viewSaved.setEnabled(matchIdToFilename.containsKey(matchId)); - viewPublished.setEnabled(matchIdToURL.containsKey(matchId)); + viewPublished.setEnabled(matchIdToURL.containsKey(matchId)); if (state.equals("pending")) { remove.setEnabled(false); - // TODO: Add support for canceling pending matches. + // TODO: Add support for canceling pending matches. } else if (state.equals("active")) { remove.setText("Cancel Match"); - remove.setEnabled(true); + remove.setEnabled(true); } else if (state.equals("aborted") || state.equals("done")) { remove.setText("Hide Match"); remove.setEnabled(true); @@ -187,20 +187,20 @@ private void updateButtonState() { viewSaved.setEnabled(false); viewPublished.setEnabled(false); remove.setEnabled(false); - } + } } - + public void addPendingMatch(PendingMatch spec) { DefaultTableModel model = (DefaultTableModel) queueTable.getModel(); model.addRow(new Object[]{spec.matchID,spec.theGame.getKey(),spec.startClock + "," + spec.playClock,"pending",getLinebreakString(getNamesForPlayers(spec.thePlayers)),"","",0}); queueTable.setRowHeight(model.getRowCount()-1, spec.thePlayers.size()*20); } - + public void observe(Event genericEvent) { if (!(genericEvent instanceof ServerMatchUpdatedEvent)) return; ServerMatchUpdatedEvent event = (ServerMatchUpdatedEvent)genericEvent; Match match = event.getMatch(); - + DefaultTableModel model = (DefaultTableModel) queueTable.getModel(); for (int i = 0; i < model.getRowCount(); i++) { String rowMatchId = model.getValueAt(i, 0).toString(); @@ -210,7 +210,7 @@ public void observe(Event genericEvent) { if (match.isCompleted()) status = "done"; model.setValueAt(status, i, 3); if (match.isCompleted()) { - model.setValueAt(getLinebreakString(match.getGoalValues()), i, 5); + model.setValueAt(getLinebreakString(match.getGoalValues()), i, 5); } List errorCounts = new ArrayList(); List errorCountStrings = new ArrayList(); @@ -233,14 +233,14 @@ public void observe(Event genericEvent) { } model.setValueAt(getLinebreakString(errorCountStrings), i, 6); model.setValueAt(match.getStateHistory().size()-1, i, 7); - + if (event.getExternalPublicationKey() != null) { matchIdToURL.put(match.getMatchId(), "http://www.ggp.org/view/all/matches/" + event.getExternalPublicationKey() + "/"); } if (event.getExternalFilename() != null) { matchIdToFilename.put(match.getMatchId(), event.getExternalFilename()); } - + return; } } @@ -249,7 +249,7 @@ public void observe(Event genericEvent) { model.addRow(new Object[]{match.getMatchId(),match.getGame().getKey(),match.getStartClock() + "," + match.getPlayClock(),"starting",getLinebreakString(match.getPlayerNamesFromHost()),"","",0}); queueTable.setRowHeight(model.getRowCount()-1, match.getPlayerNamesFromHost().size()*20); } - + private static List getNamesForPlayers(List players) { List playerNames = new ArrayList(); for (PlayerPresence player : players) { @@ -257,7 +257,7 @@ private static List getNamesForPlayers(List players) { } return playerNames; } - + private static String getLinebreakString(List objects) { String renderedString = ""; for (Object object : objects) { diff --git a/src/org/ggp/base/apps/server/states/StatesPanel.java b/src/org/ggp/base/apps/server/states/StatesPanel.java index afe1ef7ea..0ba85c460 100644 --- a/src/org/ggp/base/apps/server/states/StatesPanel.java +++ b/src/org/ggp/base/apps/server/states/StatesPanel.java @@ -20,10 +20,10 @@ @SuppressWarnings("serial") public class StatesPanel extends JPanel implements Observer { private JTabbedPane tabs = new JTabbedPane(); - + public StatesPanel() - { - this.add(tabs); + { + this.add(tabs); } private int stepCount = 1; @@ -47,7 +47,7 @@ public void observe(Event event) { JScrollPane scrollPane = new JScrollPane(statesTextArea); scrollPane.setPreferredSize(new Dimension(400, 500)); statePanel.add(scrollPane); - + // Add the panel as a new tab // Reusing the VisualizationPanel code, to make it easier in case this gets // moved off into a new thread @@ -60,7 +60,7 @@ public void observe(Event event) { tabs.setComponentAt(stepNum-1, statePanel); tabs.setTitleAt(stepNum-1, new Integer(stepNum).toString()); - if(atEnd) { + if(atEnd) { tabs.setSelectedIndex(tabs.getTabCount()-1); } } diff --git a/src/org/ggp/base/apps/server/visualization/VisualizationPanel.java b/src/org/ggp/base/apps/server/visualization/VisualizationPanel.java index a6cf8acc4..052afac26 100644 --- a/src/org/ggp/base/apps/server/visualization/VisualizationPanel.java +++ b/src/org/ggp/base/apps/server/visualization/VisualizationPanel.java @@ -39,7 +39,7 @@ public VisualizationPanel(Game theGame) this.theGame = theGame; this.myThis = this; this.timerBar = new JTimerBar(); - this.add(tabs, new GridBagConstraints(0, 0, 1, 1, 1.0, 1.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(5, 5, 5, 5), 5, 5)); + this.add(tabs, new GridBagConstraints(0, 0, 1, 1, 1.0, 1.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(5, 5, 5, 5), 5, 5)); this.add(timerBar, new GridBagConstraints(0, 1, 1, 1, 1.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(5, 5, 5, 5), 5, 5)); } @@ -60,16 +60,16 @@ public void observe(Event event) rt.start(); } } - - private class RenderThread extends Thread { + + private class RenderThread extends Thread { private final MachineState s; private final int stepNum; - + public RenderThread(MachineState s, int stepNum) { this.s = s; this.stepNum = stepNum; } - + @Override public void run() { @@ -83,7 +83,7 @@ public void run() } catch(Exception ex) { ex.printStackTrace(); } - + if(newPanel != null) { // Add the rendered panel as a new tab synchronized(tabLock) { @@ -94,7 +94,7 @@ public void run() tabs.setComponentAt(stepNum-1, newPanel); tabs.setTitleAt(stepNum-1, new Integer(stepNum).toString()); - if(atEnd) { + if(atEnd) { tabs.setSelectedIndex(tabs.getTabCount()-1); } } catch(Exception ex) { @@ -110,18 +110,18 @@ public void run() public static void main(String args[]) { JFrame frame = new JFrame("Visualization Test"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); - + Game theGame = GameRepository.getDefaultRepository().getGame("nineBoardTicTacToe"); VisualizationPanel theVisual = new VisualizationPanel(theGame); frame.setPreferredSize(new Dimension(1200, 900)); frame.getContentPane().add(theVisual); frame.pack(); frame.setVisible(true); - - StateMachine theMachine = new CachedStateMachine(new ProverStateMachine()); + + StateMachine theMachine = new CachedStateMachine(new ProverStateMachine()); theMachine.initialize(theGame.getRules()); try { - MachineState theCurrentState = theMachine.getInitialState(); + MachineState theCurrentState = theMachine.getInitialState(); do { theVisual.observe(new ServerNewGameStateEvent(theCurrentState)); theCurrentState = theMachine.getRandomNextState(theCurrentState); diff --git a/src/org/ggp/base/apps/server/visualization/VizContainerPanel.java b/src/org/ggp/base/apps/server/visualization/VizContainerPanel.java index fa593e6b3..0c65b6023 100644 --- a/src/org/ggp/base/apps/server/visualization/VizContainerPanel.java +++ b/src/org/ggp/base/apps/server/visualization/VizContainerPanel.java @@ -14,11 +14,11 @@ @SuppressWarnings("serial") public class VizContainerPanel extends JPanel { - public VizContainerPanel(String XML, String XSL, VisualizationPanel parent) + public VizContainerPanel(String XML, String XSL, VisualizationPanel parent) { Dimension d = GameStateRenderer.getDefaultSize(); setPreferredSize(d); - + BufferedImage backimage = parent.getGraphicsConfiguration().createCompatibleImage(d.width, d.height); GameStateRenderer.renderImagefromGameXML(XML, XSL, backimage); try { @@ -30,10 +30,10 @@ public VizContainerPanel(String XML, String XSL, VisualizationPanel parent) ex.printStackTrace(); } } - + private byte[] compressed = null; private boolean imageWritten = false; - + @Override protected void paintComponent(Graphics g) { super.paintComponent(g); diff --git a/src/org/ggp/base/apps/tiltyard/TiltyardRequestFarm.java b/src/org/ggp/base/apps/tiltyard/TiltyardRequestFarm.java index 171af60bb..6990710ac 100644 --- a/src/org/ggp/base/apps/tiltyard/TiltyardRequestFarm.java +++ b/src/org/ggp/base/apps/tiltyard/TiltyardRequestFarm.java @@ -29,33 +29,33 @@ * This is the backend for the continuously-running online GGP.org Tiltyard, * which schedules matches between players around the world and aggregates stats * based on the outcome of those matches. - * + * * SAMPLE INVOCATION (when running locally): * * ResourceLoader.load_raw('http://127.0.0.1:9124/' + escape(JSON.stringify({ * "targetPort":9147,"targetHost":"0.player.ggp.org","timeoutClock":30000, * "forPlayerName":"Webplayer-0","callbackURL":"http://tiltyard.ggp.org/farm/", * "requestContent":"( play foo bar baz )"}))) - * + * * Tiltyard Request Farm will open up a network connection to the target, send * the request string, and wait for the response. Once the response arrives, it * will close the connection and call the callback, sending the response to the * remote client that issued the original request. - * + * * You shouldn't be running this server unless you are bringing up an instance of the * online GGP.org Tiltyard or an equivalent service. - * + * * @author Sam Schreiber */ public final class TiltyardRequestFarm { - public static final int SERVER_PORT = 9125; + public static final int SERVER_PORT = 9125; private static final String registrationURL = "http://tiltyard.ggp.org/backends/register/farm"; - + private static Integer ongoingRequests = new Integer(0); - + public static boolean testMode = false; - + static EncodedKeyPair getKeyPair(String keyPairString) { if (keyPairString == null) return null; @@ -64,7 +64,7 @@ static EncodedKeyPair getKeyPair(String keyPairString) { } catch (JSONException e) { return null; } - } + } public static final EncodedKeyPair theBackendKeys = getKeyPair(FileUtils.readFileAsString(new File("src/org/ggp/base/apps/tiltyard/BackendKeys.json"))); public static String generateSignedPing() { JSONObject thePing = new JSONObject(); @@ -77,10 +77,10 @@ public static String generateSignedPing() { } return thePing.toString(); } - + // Connections are run asynchronously in their own threads. static class RunRequestThread extends Thread { - String targetHost, requestContent, forPlayerName, callbackURL, originalRequest; + String targetHost, requestContent, forPlayerName, callbackURL, originalRequest; int targetPort, timeoutClock; boolean fastReturn; Set activeRequests; @@ -88,7 +88,7 @@ static class RunRequestThread extends Thread { public RunRequestThread(Socket connection, Set activeRequests) throws IOException, JSONException { String line = HttpReader.readAsServer(connection); System.out.println("On " + new Date() + ", client has requested: " + line); - + String response = null; if (line.equals("ping")) { response = generateSignedPing(); @@ -101,7 +101,7 @@ public RunRequestThread(Socket connection, Set activeRequests) throws IO } this.activeRequests = activeRequests; } - + JSONObject theJSON = new JSONObject(line); targetPort = theJSON.getInt("targetPort"); targetHost = theJSON.getString("targetHost"); @@ -114,7 +114,7 @@ public RunRequestThread(Socket connection, Set activeRequests) throws IO } else { fastReturn = true; } - + originalRequest = line; response = "okay"; } @@ -122,22 +122,22 @@ public RunRequestThread(Socket connection, Set activeRequests) throws IO HttpWriter.writeAsServer(connection, response); connection.close(); } - + @Override public void run() { - if (originalRequest != null) { + if (originalRequest != null) { synchronized (ongoingRequests) { ongoingRequests++; - } + } System.out.println("On " + new Date() + ", starting request. There are now " + ongoingRequests + " ongoing requests."); long startTime = System.currentTimeMillis(); - JSONObject responseJSON = new JSONObject(); + JSONObject responseJSON = new JSONObject(); try { responseJSON.put("originalRequest", originalRequest); try { - String response = HttpRequest.issueRequest(targetHost, targetPort, forPlayerName, requestContent, timeoutClock); + String response = HttpRequest.issueRequest(targetHost, targetPort, forPlayerName, requestContent, timeoutClock); responseJSON.put("response", response); - responseJSON.put("responseType", "OK"); + responseJSON.put("responseType", "OK"); } catch (SocketTimeoutException te) { responseJSON.put("responseType", "TO"); } catch (IOException ie) { @@ -172,7 +172,7 @@ public void run() { } } synchronized (ongoingRequests) { - ongoingRequests--; + ongoingRequests--; if (ongoingRequests == 0) { System.gc(); System.out.println("On " + new Date() + ", completed request. Garbage collecting since there are no ongoing requests."); @@ -182,18 +182,18 @@ public void run() { } synchronized (activeRequests) { activeRequests.remove(originalRequest); - } + } } } } - + static class TiltyardRegistration extends Thread { @Override public void run() { // Send a registration ping to Tiltyard every five minutes. while (true) { try { - RemoteResourceLoader.postRawWithTimeout(registrationURL, generateSignedPing(), 2500); + RemoteResourceLoader.postRawWithTimeout(registrationURL, generateSignedPing(), 2500); } catch (Exception e) { e.printStackTrace(); } @@ -205,8 +205,8 @@ public void run() { } } } - - public static void main(String[] args) { + + public static void main(String[] args) { ServerSocket listener = null; try { listener = new ServerSocket(SERVER_PORT); @@ -219,10 +219,10 @@ public static void main(String[] args) { if (theBackendKeys == null) { System.err.println("Could not load cryptographic keys for signing request responses."); return; - } + } new TiltyardRegistration().start(); } - + Set activeRequests = new HashSet(); while (true) { try { @@ -232,6 +232,6 @@ public static void main(String[] args) { } catch (Exception e) { System.err.println(e); } - } + } } } \ No newline at end of file diff --git a/src/org/ggp/base/apps/tiltyard/TiltyardRequestFarm_Test.java b/src/org/ggp/base/apps/tiltyard/TiltyardRequestFarm_Test.java index 260b3da5e..fbc032c3c 100644 --- a/src/org/ggp/base/apps/tiltyard/TiltyardRequestFarm_Test.java +++ b/src/org/ggp/base/apps/tiltyard/TiltyardRequestFarm_Test.java @@ -16,7 +16,7 @@ public class TiltyardRequestFarm_Test extends TestCase { public void setUp() { new RequestFarmLoopThread().start(); } - + public void testThroughput() { new ResponderLoopThread(2000).start(); new ReceiverLoopThread("OK").start(); @@ -29,28 +29,28 @@ public void testConnectionError() { new ReceiverLoopThread("CE").start(); runTestingLoop(); } - + public void testTimeout() { new ResponderLoopThread(4000).start(); new ReceiverLoopThread("TO").start(); runTestingLoop(); } - */ - + */ + static long doMath(long a) { return a/2+3; } - + // Connections are run asynchronously in their own threads. class ResponderThread extends Thread { private Socket conn; private int sleepTime; - + public ResponderThread(Socket connection, int sleepTime) { conn = connection; this.sleepTime = sleepTime; } - + @Override public void run() { try { @@ -65,17 +65,17 @@ public void run() { } Integer nSuccesses = new Integer(0); - + // Connections are run asynchronously in their own threads. class ReceiverThread extends Thread { private Socket conn; private String response; - + public ReceiverThread(Socket connection, String expectedResponse) { conn = connection; response = expectedResponse; } - + @Override public void run() { try { @@ -91,19 +91,19 @@ public void run() { } synchronized (nSuccesses) { nSuccesses++; - } + } } catch (Exception e) { e.printStackTrace(); } } } - + class ResponderLoopThread extends Thread { private int sleepTime; public ResponderLoopThread(int sleepTime) { this.sleepTime = sleepTime; } - + @Override public void run() { try { @@ -121,13 +121,13 @@ public void run() { } } } - + class ReceiverLoopThread extends Thread { private String response; public ReceiverLoopThread(String expectResponse) { response = expectResponse; } - + @Override public void run() { try { @@ -140,12 +140,12 @@ public void run() { System.err.println(e); } } - } catch (Exception e) { + } catch (Exception e) { e.printStackTrace(); } } } - + class RequestFarmLoopThread extends Thread { @Override public void run() { @@ -157,7 +157,7 @@ public void run() { } } } - + public void runTestingLoop() { try { Random r = new Random(); @@ -167,7 +167,7 @@ public void runTestingLoop() { theRequest.put("timeoutClock", 3000); theRequest.put("callbackURL", "http://127.0.0.1:12346"); theRequest.put("forPlayerName", ""); - + int nRequests = 0; while (true) { theRequest.put("requestContent", "" + r.nextLong()); @@ -185,6 +185,6 @@ public void runTestingLoop() { } } catch (Exception e) { e.printStackTrace(); - } + } } } \ No newline at end of file diff --git a/src/org/ggp/base/apps/utilities/GameServerRunner.java b/src/org/ggp/base/apps/utilities/GameServerRunner.java index 724ce5b80..bb0a2c7f7 100644 --- a/src/org/ggp/base/apps/utilities/GameServerRunner.java +++ b/src/org/ggp/base/apps/utilities/GameServerRunner.java @@ -19,7 +19,7 @@ /** * GameServerRunner is a utility program that lets you start up a match * directly from the command line. It takes the following arguments: - * + * * args[0] = tournament name, for storing results * args[1] = game key, for loading the game * args[2] = start clock, in seconds @@ -27,7 +27,7 @@ * args[4,5,6] = host, port, name for player 1 * args[7,8,9] = host, port, name for player 2 * etc... - * + * * @author Evan Cox * @author Sam Schreiber */ @@ -39,7 +39,7 @@ public static void main(String[] args) throws IOException, SymbolFormatException String tourneyName = args[0]; String gameKey = args[1]; Game game = GameRepository.getDefaultRepository().getGame(gameKey); - int startClock = Integer.valueOf(args[2]); + int startClock = Integer.valueOf(args[2]); int playClock = Integer.valueOf(args[3]); if ((args.length - 4) % 3 != 0) { throw new RuntimeException("Invalid number of player arguments of the form host/port/name."); @@ -62,12 +62,12 @@ public static void main(String[] args) throws IOException, SymbolFormatException } Match match = new Match(matchName, -1, startClock, playClock, game); match.setPlayerNamesFromHost(playerNames); - + // Actually run the match, using the desired configuration. GameServer server = new GameServer(match, hostNames, portNumbers); server.run(); server.join(); - + // Open up the directory for this tournament. // Create a "scores" file if none exists. File f = new File(tourneyName); @@ -76,18 +76,18 @@ public static void main(String[] args) throws IOException, SymbolFormatException f = new File(tourneyName + "/scores"); f.createNewFile(); } - + // Open up the XML file for this match, and save the match there. f = new File(tourneyName + "/" + matchName + ".xml"); - if (f.exists()) f.delete(); + if (f.exists()) f.delete(); BufferedWriter bw = new BufferedWriter(new FileWriter(f)); bw.write(match.toXML()); bw.flush(); bw.close(); - + // Open up the JSON file for this match, and save the match there. f = new File(tourneyName + "/" + matchName + ".json"); - if (f.exists()) f.delete(); + if (f.exists()) f.delete(); bw = new BufferedWriter(new FileWriter(f)); bw.write(match.toJSON()); bw.flush(); diff --git a/src/org/ggp/base/apps/utilities/SimpleGameSim.java b/src/org/ggp/base/apps/utilities/SimpleGameSim.java index 52fa918a4..a89c67cc3 100644 --- a/src/org/ggp/base/apps/utilities/SimpleGameSim.java +++ b/src/org/ggp/base/apps/utilities/SimpleGameSim.java @@ -30,18 +30,18 @@ * given game, and see which propositions become true/false in each state as * the game is played. This can be used to understand how a game runs, or to * debug issues in the state machine implementation. - * + * * It can also hide the step counter / control proposition, though this is * done in a very naive way, by just looking for (step ?x) and (control ?x) * propositions. None the less, it's still useful to have. - * + * * @author Sam Schreiber */ public class SimpleGameSim { public static final boolean hideStepCounter = true; public static final boolean hideControlProposition = true; public static final boolean showCurrentState = false; - + public static void main(String[] args) throws InterruptedException { final Game theGame = GameRepository.getDefaultRepository().getGame("nineBoardTicTacToe"); final Match theMatch = new Match("simpleGameSim." + Match.getRandomString(5), -1, 0, 0, theGame); @@ -57,7 +57,7 @@ public static void main(String[] args) throws InterruptedException { } catch (JSONException e) { System.err.println("Could not load sample cryptograhic keys: " + e); } - + // Set up fake players to pretend to play the game List fakeHosts = new ArrayList(); List fakePorts = new ArrayList(); @@ -71,10 +71,10 @@ public static void main(String[] args) throws InterruptedException { for (int i = 0; i < fakeHosts.size(); i++) { theServer.makePlayerPlayRandomly(i); } - + // TODO: Allow a custom state machine to be plugged into the GameServer so that we can - // simulate games using this tool with custom state machines, to verify they're sane. - + // simulate games using this tool with custom state machines, to verify they're sane. + final Set oldContents = new HashSet(); final int[] nState = new int[1]; theServer.addObserver(new Observer() { @@ -93,7 +93,7 @@ public void observe(Event event) { } for(GdlSentence oldSentence : oldContents) { if(hideStepCounter && oldSentence.toString().contains("step")) continue; - if(hideControlProposition && oldSentence.toString().contains("control")) continue; + if(hideControlProposition && oldSentence.toString().contains("control")) continue; if(!newContents.contains(oldSentence)) { System.out.print("-" + oldSentence + ", "); } @@ -101,7 +101,7 @@ public void observe(Event event) { System.out.println(); oldContents.clear(); oldContents.addAll(newContents); - + if(showCurrentState) System.out.println("State[" + nState[0] + "] Full: " + theCurrentState); nState[0]++; } else if (event instanceof ServerNewMovesEvent) { @@ -120,8 +120,8 @@ public void observe(Event event) { } } }); - + theServer.start(); theServer.join(); - } + } } \ No newline at end of file diff --git a/src/org/ggp/base/apps/validator/BatchValidator.java b/src/org/ggp/base/apps/validator/BatchValidator.java index b5fff1dfc..8bb025ba4 100644 --- a/src/org/ggp/base/apps/validator/BatchValidator.java +++ b/src/org/ggp/base/apps/validator/BatchValidator.java @@ -14,14 +14,14 @@ * BatchValidator does game validation on all of the games in a given game repository. * This allows you to quickly determine which games need to be repaired, given a large * existing game repository with games of varying quality. - * + * * @author schreib */ public final class BatchValidator { public static void main(String[] args) { - GameRepository repo = new CloudGameRepository("games.ggp.org/base"); + GameRepository repo = new CloudGameRepository("games.ggp.org/base"); for (String gameKey : repo.getGameKeys()) { if (gameKey.contains("amazons") || gameKey.contains("knightazons") || gameKey.contains("factoringImpossibleTurtleBrain") || gameKey.contains("quad") || gameKey.contains("blokbox") || gameKey.contains("othello")) continue; @@ -47,6 +47,6 @@ public static void main(String[] args) if (isValid) { System.out.println("Passed!"); } - } + } } } \ No newline at end of file diff --git a/src/org/ggp/base/apps/validator/OutcomePanel.java b/src/org/ggp/base/apps/validator/OutcomePanel.java index cd9e69faf..bf08e2e74 100644 --- a/src/org/ggp/base/apps/validator/OutcomePanel.java +++ b/src/org/ggp/base/apps/validator/OutcomePanel.java @@ -47,7 +47,7 @@ public boolean isCellEditable(int rowIndex, int colIndex) logTable.getColumnModel().getColumn(0).setMaxWidth(150); logTable.getColumnModel().getColumn(0).setPreferredWidth(500); progressBar.setMaximum(numValidators); - + this.add(new JScrollPane(logTable, ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED), new GridBagConstraints(0, 0, 1, 1, 1.0, 1.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(5, 5, 5, 5), 5, 5)); this.add(progressBar, new GridBagConstraints(0, 1, 1, 1, 1.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(5, 5, 5, 5), 5, 5)); } @@ -63,7 +63,7 @@ else if (event instanceof ValidatorFailureEvent) observeValidationFailureEvent((ValidatorFailureEvent) event); } } - + public static final String wrapLine(String line, int width) { StringBuilder wrappedLine = new StringBuilder(); while (line.length() > width) { diff --git a/src/org/ggp/base/apps/validator/Validator.java b/src/org/ggp/base/apps/validator/Validator.java index 6939dcb5c..aef250c4c 100644 --- a/src/org/ggp/base/apps/validator/Validator.java +++ b/src/org/ggp/base/apps/validator/Validator.java @@ -58,13 +58,13 @@ public void run() private Game theGame; private final JButton validateButton; - private final JTextField maxDepthTextField; + private final JTextField maxDepthTextField; private final JTextField simulationsTextField; private final JTextField millisToSimulateField; - private final JTabbedPane simulationsTabbedPane; + private final JTabbedPane simulationsTabbedPane; + + private final GameSelector gameSelector; - private final GameSelector gameSelector; - public Validator() { super(new GridBagLayout()); @@ -83,8 +83,8 @@ public Validator() simulationsTextField.setColumns(15); validateButton.setEnabled(false); - gameSelector = new GameSelector(); - + gameSelector = new GameSelector(); + int nRowCount = 0; JPanel sourcePanel = new JPanel(new GridBagLayout()); sourcePanel.setBorder(new TitledBorder("Source")); @@ -98,7 +98,7 @@ public Validator() sourcePanel.add(new JLabel("Simulations:"), new GridBagConstraints(0, nRowCount, 1, 1, 1.0, 0.0, GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 5, 5)); sourcePanel.add(simulationsTextField, new GridBagConstraints(1, nRowCount++, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(5, 5, 5, 5), 5, 5)); sourcePanel.add(new JLabel("Base Sim ms:"), new GridBagConstraints(0, nRowCount, 1, 1, 1.0, 0.0, GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 5, 5)); - sourcePanel.add(millisToSimulateField, new GridBagConstraints(1, nRowCount++, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(5, 5, 5, 5), 5, 5)); + sourcePanel.add(millisToSimulateField, new GridBagConstraints(1, nRowCount++, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(5, 5, 5, 5), 5, 5)); sourcePanel.add(validateButton, new GridBagConstraints(1, nRowCount++, 1, 1, 1.0, 1.0, GridBagConstraints.SOUTH, GridBagConstraints.HORIZONTAL, new Insets(5, 5, 5, 5), 0, 0)); JPanel simulationsPanel = new JPanel(new GridBagLayout()); @@ -107,18 +107,18 @@ public Validator() this.add(sourcePanel, new GridBagConstraints(0, 0, 1, 1, 0.0, 1.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(5, 5, 5, 5), 5, 5)); this.add(simulationsPanel, new GridBagConstraints(1, 0, 1, 1, 1.0, 1.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(5, 5, 5, 5), 5, 5)); - + gameSelector.getGameList().addActionListener(this); - gameSelector.repopulateGameList(); + gameSelector.repopulateGameList(); } @Override public void actionPerformed(ActionEvent e) { if (e.getSource() == gameSelector.getGameList()) { theGame = gameSelector.getSelectedGame(); - validateButton.setEnabled(theGame != null); - } - } + validateButton.setEnabled(theGame != null); + } + } private AbstractAction validateButtonMethod(final Validator validatorPanel) { @@ -129,13 +129,13 @@ public void actionPerformed(ActionEvent evt) try { int maxDepth = Integer.valueOf(maxDepthTextField.getText()); int simulations = Integer.valueOf(simulationsTextField.getText()); - int millisToSimulate = Integer.valueOf(millisToSimulateField.getText()); + int millisToSimulate = Integer.valueOf(millisToSimulateField.getText()); GameValidator[] theValidators = new GameValidator[] { new OPNFValidator(), new SimulationValidator(maxDepth, simulations), new BasesInputsValidator(millisToSimulate), - new StaticValidator(), + new StaticValidator(), }; OutcomePanel simulationPanel = new OutcomePanel(theValidators.length); for (GameValidator theValidator : theValidators) { @@ -143,12 +143,12 @@ public void actionPerformed(ActionEvent evt) validator.addObserver(simulationPanel); validator.start(); } - - validatorPanel.simulationsTabbedPane.addTab(theGame.getKey(), simulationPanel); + + validatorPanel.simulationsTabbedPane.addTab(theGame.getKey(), simulationPanel); } catch (Exception e) { // Do nothing. } } }; - } + } } diff --git a/src/org/ggp/base/apps/validator/event/ValidatorFailureEvent.java b/src/org/ggp/base/apps/validator/event/ValidatorFailureEvent.java index d6d943109..998a733ba 100644 --- a/src/org/ggp/base/apps/validator/event/ValidatorFailureEvent.java +++ b/src/org/ggp/base/apps/validator/event/ValidatorFailureEvent.java @@ -12,7 +12,7 @@ public ValidatorFailureEvent(String name, Exception exception) this.name = name; this.exception = exception; } - + public String getName() { return name; diff --git a/src/org/ggp/base/apps/validator/event/ValidatorSuccessEvent.java b/src/org/ggp/base/apps/validator/event/ValidatorSuccessEvent.java index 0bc5c8f75..8c4fc9416 100644 --- a/src/org/ggp/base/apps/validator/event/ValidatorSuccessEvent.java +++ b/src/org/ggp/base/apps/validator/event/ValidatorSuccessEvent.java @@ -10,7 +10,7 @@ public ValidatorSuccessEvent(String name) { this.name = name; } - + public String getName() { return name; diff --git a/src/org/ggp/base/player/GamePlayer.java b/src/org/ggp/base/player/GamePlayer.java index 1e2bd1b47..53355e6fc 100644 --- a/src/org/ggp/base/player/GamePlayer.java +++ b/src/org/ggp/base/player/GamePlayer.java @@ -32,7 +32,7 @@ public GamePlayer(int port, Gamer gamer) throws IOException { observers = new ArrayList(); listener = null; - + while(listener == null) { try { listener = new ServerSocket(port); @@ -40,9 +40,9 @@ public GamePlayer(int port, Gamer gamer) throws IOException listener = null; port++; System.err.println("Failed to start gamer on port: " + (port-1) + " trying port " + port); - } + } } - + this.port = port; this.gamer = gamer; } @@ -59,11 +59,11 @@ public void notifyObservers(Event event) observer.observe(event); } } - + public final int getGamerPort() { return port; } - + public final Gamer getGamer() { return gamer; } @@ -80,13 +80,13 @@ public void run() if (in.length() == 0) { throw new IOException("Empty message received."); } - + notifyObservers(new PlayerReceivedMessageEvent(in)); GamerLogger.log("GamePlayer", "[Received at " + System.currentTimeMillis() + "] " + in, GamerLogger.LOG_LEVEL_DATA_DUMP); Request request = new RequestFactory().create(gamer, in); String out = request.process(System.currentTimeMillis()); - + HttpWriter.writeAsServer(connection, out); connection.close(); notifyObservers(new PlayerSentMessageEvent(out)); @@ -108,16 +108,16 @@ public static void main(String[] args) System.err.println("Usage: GamePlayer "); System.exit(1); } - + try { GamePlayer player = new GamePlayer(Integer.valueOf(args[0]), new RandomGamer()); player.run(); } catch (NumberFormatException e) { - System.err.println("Illegal port number: " + args[0]); + System.err.println("Illegal port number: " + args[0]); e.printStackTrace(); System.exit(2); } catch (IOException e) { - System.err.println("IO Exception: " + e); + System.err.println("IO Exception: " + e); e.printStackTrace(); System.exit(3); } diff --git a/src/org/ggp/base/player/gamer/Gamer.java b/src/org/ggp/base/player/gamer/Gamer.java index 25141fd92..00f3226de 100644 --- a/src/org/ggp/base/player/gamer/Gamer.java +++ b/src/org/ggp/base/player/gamer/Gamer.java @@ -27,14 +27,14 @@ * design pattern. */ public abstract class Gamer implements Subject -{ +{ private Match match; private GdlConstant roleName; public Gamer() { observers = new ArrayList(); - + // When not playing a match, the variables 'match' // and 'roleName' should be NULL. This indicates that // the player is available for starting a new match. @@ -47,45 +47,45 @@ public Gamer() * and when you actually return from metaGame and selectMove. They are * stored here so they can be shared amongst all Gamers. */ public static final long PREFERRED_METAGAME_BUFFER = 3900; - public static final long PREFERRED_PLAY_BUFFER = 1900; - + public static final long PREFERRED_PLAY_BUFFER = 1900; + // ==== The Gaming Algorithms ==== public abstract void metaGame(long timeout) throws MetaGamingException; - + public abstract GdlTerm selectMove(long timeout) throws MoveSelectionException; - + /* Note that the match's goal values will not necessarily be known when * stop() is called, as we only know the final set of moves and haven't * interpreted them yet. To get the final goal values, process the final * moves of the game. */ public abstract void stop() throws StoppingException; // Cleanly stop playing the match - + public abstract void abort() throws AbortingException; // Abruptly stop playing the match public abstract void preview(Game g, long timeout) throws GamePreviewException; // Preview a game - + // ==== Gamer Profile and Configuration ==== public abstract String getName(); public String getSpecies() { return null; } - + public boolean isComputerPlayer() { return true; } - + public ConfigPanel getConfigPanel() { return new EmptyConfigPanel(); } - + public DetailPanel getDetailPanel() { return new EmptyDetailPanel(); } - // ==== Accessors ==== + // ==== Accessors ==== public final Match getMatch() { return match; } - + public final void setMatch(Match match) { this.match = match; } @@ -93,18 +93,18 @@ public final void setMatch(Match match) { public final GdlConstant getRoleName() { return roleName; } - + public final void setRoleName(GdlConstant roleName) { this.roleName = roleName; } - + // ==== Observer Stuff ==== private final List observers; public final void addObserver(Observer observer) { observers.add(observer); } - + public final void notifyObservers(Event event) { for (Observer observer : observers) { diff --git a/src/org/ggp/base/player/gamer/clojure/ClojureGamer.java b/src/org/ggp/base/player/gamer/clojure/ClojureGamer.java index 244feb4d6..2c5782665 100644 --- a/src/org/ggp/base/player/gamer/clojure/ClojureGamer.java +++ b/src/org/ggp/base/player/gamer/clojure/ClojureGamer.java @@ -20,7 +20,7 @@ * 1) Create a subclass of ClojureGamer that overrides getClojureGamerFile() and * getClojureGamerName() to indicate where the Clojure source code file is. * This is the Java stub that refers to the real Clojure gamer class. - * + * * 2) Create the Clojure source code file, in the /src_clj/ directory in the root * directory for this project. Make sure that the stub points to this class, * and that the Clojure class is a valid subclass of Gamer. @@ -28,7 +28,7 @@ * For examples where this has already been done, see @ClojureLegalGamerStub, * which is implemented in Clojure and hook into the Java framework using the * ClojureGamer stub. - * + * * @author Sam Schreiber */ public abstract class ClojureGamer extends Gamer @@ -36,8 +36,8 @@ public abstract class ClojureGamer extends Gamer Gamer theClojureGamer; protected abstract String getClojureGamerFile(); - protected abstract String getClojureGamerName(); - + protected abstract String getClojureGamerName(); + // Gamer stubs are lazily loaded because the Clojure interface takes // time to initialize, so we only want to load it when necessary, and // not for light-weight things like returning the player name. @@ -46,10 +46,10 @@ private void lazilyLoadGamerStub() { try { // Load the Clojure script -- as a side effect this initializes the runtime. RT.loadResourceScript(getClojureGamerFile() + ".clj"); - + // Get a reference to the gamer-generating function. Var gamerVar = RT.var("gamer_namespace", getClojureGamerName()); - + // Call it! theClojureGamer = (Gamer)gamerVar.invoke(); } catch(Exception e) { @@ -58,14 +58,14 @@ private void lazilyLoadGamerStub() { } } } - + // The following methods are overriden as 'final' because they should not // be changed in subclasses of this class. Subclasses of this class should // only implement getClojureGamerFile() and getClojureGamerName(), and then // implement the real methods in the actual Clojure gamer. Essentially, any // subclass of this class is a Java-implementation stub for the actual real // Clojure implementation. - + @Override public final void preview(Game game, long timeout) throws GamePreviewException { lazilyLoadGamerStub(); @@ -75,8 +75,8 @@ public final void preview(Game game, long timeout) throws GamePreviewException { GamerLogger.logError("GamePlayer", "Caught exception in Clojure stateMachineMetaGame:"); GamerLogger.logStackTrace("GamePlayer", e); } - } - + } + @Override public final void metaGame(long timeout) throws MetaGamingException { lazilyLoadGamerStub(); @@ -89,7 +89,7 @@ public final void metaGame(long timeout) throws MetaGamingException { GamerLogger.logStackTrace("GamePlayer", e); } } - + @Override public final GdlTerm selectMove(long timeout) throws MoveSelectionException { lazilyLoadGamerStub(); @@ -103,7 +103,7 @@ public final GdlTerm selectMove(long timeout) throws MoveSelectionException { return null; } } - + @Override public final void stop() { lazilyLoadGamerStub(); @@ -116,7 +116,7 @@ public final void stop() { GamerLogger.logStackTrace("GamePlayer", e); } } - + @Override public final void abort() { lazilyLoadGamerStub(); @@ -128,10 +128,10 @@ public final void abort() { GamerLogger.logError("GamePlayer", "Caught exception in Clojure stateMachineAbort:"); GamerLogger.logStackTrace("GamePlayer", e); } - } - + } + @Override public final String getName() { return getClojureGamerName(); - } + } } \ No newline at end of file diff --git a/src/org/ggp/base/player/gamer/clojure/ClojureGamer_Test.java b/src/org/ggp/base/player/gamer/clojure/ClojureGamer_Test.java index 6b4f8da07..4f0800296 100644 --- a/src/org/ggp/base/player/gamer/clojure/ClojureGamer_Test.java +++ b/src/org/ggp/base/player/gamer/clojure/ClojureGamer_Test.java @@ -11,10 +11,10 @@ /** * Unit tests for the ClojureGamer class, to verify that we can actually * instantiate a Clojure-based gamer and have it play moves in a game. - * + * * @author Sam */ -public class ClojureGamer_Test extends TestCase { +public class ClojureGamer_Test extends TestCase { public void testClojureGamer() { try { Gamer g = new SampleClojureGamerStub(); diff --git a/src/org/ggp/base/player/gamer/clojure/stubs/SampleClojureGamerStub.java b/src/org/ggp/base/player/gamer/clojure/stubs/SampleClojureGamerStub.java index 6fb60e040..a0ebd181a 100644 --- a/src/org/ggp/base/player/gamer/clojure/stubs/SampleClojureGamerStub.java +++ b/src/org/ggp/base/player/gamer/clojure/stubs/SampleClojureGamerStub.java @@ -6,7 +6,7 @@ * has been implemented in Clojure. This stub needs to exist so that the Clojure * code can interoperate with the rest of the Java framework (and applications * like Kiosk and PlayerPanel as a result). - * + * * @author Sam */ public final class SampleClojureGamerStub extends ClojureGamer diff --git a/src/org/ggp/base/player/gamer/event/GamerSelectedMoveEvent.java b/src/org/ggp/base/player/gamer/event/GamerSelectedMoveEvent.java index 78cb541ea..ada706d66 100644 --- a/src/org/ggp/base/player/gamer/event/GamerSelectedMoveEvent.java +++ b/src/org/ggp/base/player/gamer/event/GamerSelectedMoveEvent.java @@ -16,15 +16,15 @@ public GamerSelectedMoveEvent(List moves, Move selection, long time) { this.selection = selection; this.time = time; } - + public List getMoves() { return moves; } - + public Move getSelection() { return selection; } - + public long getTime() { return time; } diff --git a/src/org/ggp/base/player/gamer/exception/GamePreviewException.java b/src/org/ggp/base/player/gamer/exception/GamePreviewException.java index bbedeaf3b..0d361144e 100644 --- a/src/org/ggp/base/player/gamer/exception/GamePreviewException.java +++ b/src/org/ggp/base/player/gamer/exception/GamePreviewException.java @@ -6,7 +6,7 @@ public final class GamePreviewException extends Exception public GamePreviewException(Throwable cause) { super(cause); } - + @Override public String toString() { diff --git a/src/org/ggp/base/player/gamer/python/PythonGamer.java b/src/org/ggp/base/player/gamer/python/PythonGamer.java index d96996227..73030480b 100644 --- a/src/org/ggp/base/player/gamer/python/PythonGamer.java +++ b/src/org/ggp/base/player/gamer/python/PythonGamer.java @@ -16,27 +16,27 @@ /** * PythonGamer is a superclass that allows you to hook Python gamers into the * rest of the Java framework. In order to do this, do the following: - * + * * 1) Create a subclass of PythonGamer that overrides getPythonGamerName() and * getPythonGamerModule() to indicate where the Python source code file is. * This is the Java stub that refers to the real Python gamer class. - * + * * 2) Create the Python source code file, in the /src_py/ directory in the root * directory for this project. Make sure that the stub points to this class, * and that the Python class is a valid subclass of Gamer. - * + * * For examples where this has already been done, see @PythonRandomGamerStub, which * is implemented in Python and hooks into the Java framework using the PythonGamer stub. - * + * * @author Sam * @author evancox */ public abstract class PythonGamer extends Gamer { Gamer thePythonGamer; - + protected abstract String getPythonGamerName(); - protected abstract String getPythonGamerModule(); + protected abstract String getPythonGamerModule(); // Gamer stubs are lazily loaded because the Python interface takes // time to initialize, so we only want to load it when necessary, and @@ -56,14 +56,14 @@ private void lazilyLoadGamerStub() { } } } - + // The following methods are overriden as 'final' because they should not // be changed in subclasses of this class. Subclasses of this class should // only implement getPythonGamerName() and getPythonGamerModule(), and then // implement the real methods in the actual Python gamer. Essentially, any // subclass of this class is a Java-implementation stub for the actual real // Python implementation. - + @Override public final void preview(Game game, long timeout) throws GamePreviewException { lazilyLoadGamerStub(); @@ -73,8 +73,8 @@ public final void preview(Game game, long timeout) throws GamePreviewException { GamerLogger.logError("GamePlayer", "Caught exception in Python stateMachinePreview:"); GamerLogger.logStackTrace("GamePlayer", e); } - } - + } + @Override public final void metaGame(long timeout) throws MetaGamingException { lazilyLoadGamerStub(); @@ -87,7 +87,7 @@ public final void metaGame(long timeout) throws MetaGamingException { GamerLogger.logStackTrace("GamePlayer", e); } } - + @Override public final GdlTerm selectMove(long timeout) throws MoveSelectionException { lazilyLoadGamerStub(); @@ -101,7 +101,7 @@ public final GdlTerm selectMove(long timeout) throws MoveSelectionException { return null; } } - + @Override public final void stop() { lazilyLoadGamerStub(); @@ -114,7 +114,7 @@ public final void stop() { GamerLogger.logStackTrace("GamePlayer", e); } } - + @Override public final void abort() { lazilyLoadGamerStub(); @@ -126,10 +126,10 @@ public final void abort() { GamerLogger.logError("GamePlayer", "Caught exception in Python stateMachineAbort:"); GamerLogger.logStackTrace("GamePlayer", e); } - } - + } + @Override public final String getName() { return getPythonGamerName(); - } + } } \ No newline at end of file diff --git a/src/org/ggp/base/player/gamer/python/PythonGamer_Test.java b/src/org/ggp/base/player/gamer/python/PythonGamer_Test.java index 47bbfbc2b..2c8fb2018 100644 --- a/src/org/ggp/base/player/gamer/python/PythonGamer_Test.java +++ b/src/org/ggp/base/player/gamer/python/PythonGamer_Test.java @@ -11,10 +11,10 @@ /** * Unit tests for the PythonGamer class, to verify that we can actually * instantiate a Python-based gamer and have it play moves in a game. - * + * * @author Sam */ -public class PythonGamer_Test extends TestCase { +public class PythonGamer_Test extends TestCase { public void testPythonGamer() { try { Gamer g = new SamplePythonGamerStub(); diff --git a/src/org/ggp/base/player/gamer/python/stubs/SamplePythonGamerStub.java b/src/org/ggp/base/player/gamer/python/stubs/SamplePythonGamerStub.java index 96419dcb8..640f6d48d 100644 --- a/src/org/ggp/base/player/gamer/python/stubs/SamplePythonGamerStub.java +++ b/src/org/ggp/base/player/gamer/python/stubs/SamplePythonGamerStub.java @@ -6,7 +6,7 @@ * has been implemented in Python. This stub needs to exist so that the Python * code can interoperate with the rest of the Java framework (and applications * like Kiosk and PlayerPanel as a result). - * + * * @author Sam */ public final class SamplePythonGamerStub extends PythonGamer diff --git a/src/org/ggp/base/player/gamer/statemachine/human/HumanGamer.java b/src/org/ggp/base/player/gamer/statemachine/human/HumanGamer.java index 3be980b67..b8364b273 100644 --- a/src/org/ggp/base/player/gamer/statemachine/human/HumanGamer.java +++ b/src/org/ggp/base/player/gamer/statemachine/human/HumanGamer.java @@ -30,7 +30,7 @@ public final class HumanGamer extends StateMachineGamer public String getName() { return "Human"; } - + /** * Selects the default move as the first legal move, and then waits * while the Human sets their move. This is done via the HumanDetailPanel. @@ -50,46 +50,46 @@ public synchronized Move stateMachineSelectMove(long timeout) throws TransitionD } return move; - } + } private Move move; public void setMove(Move move) { this.move = move; } - + @Override public DetailPanel getDetailPanel() { return new HumanDetailPanel(); - } + } @Override public void preview(Game g, long timeout) throws GamePreviewException { // Human gamer does no game previewing. - } - + } + @Override public void stateMachineMetaGame(long timeout) throws TransitionDefinitionException, MoveDefinitionException, GoalDefinitionException { // Human gamer does no metagaming at the beginning of the match. - } - + } + @Override public void stateMachineStop() { // Human gamer does no special cleanup when the match ends normally. } - + @Override public void stateMachineAbort() { // Human gamer does no special cleanup when the match ends abruptly. - } - + } + @Override public StateMachine getInitialStateMachine() { return new CachedStateMachine(new ProverStateMachine()); } - + @Override public boolean isComputerPlayer() { return false; - } + } } \ No newline at end of file diff --git a/src/org/ggp/base/player/gamer/statemachine/random/RandomGamer.java b/src/org/ggp/base/player/gamer/statemachine/random/RandomGamer.java index 27450e4c7..529480945 100644 --- a/src/org/ggp/base/player/gamer/statemachine/random/RandomGamer.java +++ b/src/org/ggp/base/player/gamer/statemachine/random/RandomGamer.java @@ -26,8 +26,8 @@ public final class RandomGamer extends StateMachineGamer @Override public String getName() { return "Random"; - } - + } + @Override public Move stateMachineSelectMove(long timeout) throws TransitionDefinitionException, MoveDefinitionException, GoalDefinitionException { @@ -41,28 +41,28 @@ public Move stateMachineSelectMove(long timeout) throws TransitionDefinitionExce notifyObservers(new GamerSelectedMoveEvent(moves, selection, stop - start)); return selection; } - + @Override public StateMachine getInitialStateMachine() { return new CachedStateMachine(new ProverStateMachine()); } - + @Override public void preview(Game g, long timeout) throws GamePreviewException { // Random gamer does no game previewing. - } - + } + @Override public void stateMachineMetaGame(long timeout) throws TransitionDefinitionException, MoveDefinitionException, GoalDefinitionException { // Random gamer does no metagaming at the beginning of the match. - } - + } + @Override public void stateMachineStop() { // Random gamer does no special cleanup when the match ends normally. } - + @Override public void stateMachineAbort() { // Random gamer does no special cleanup when the match ends abruptly. @@ -71,5 +71,5 @@ public void stateMachineAbort() { @Override public DetailPanel getDetailPanel() { return new SimpleDetailPanel(); - } + } } \ No newline at end of file diff --git a/src/org/ggp/base/player/gamer/statemachine/sample/SampleGamer.java b/src/org/ggp/base/player/gamer/statemachine/sample/SampleGamer.java index 683183906..514da1b64 100644 --- a/src/org/ggp/base/player/gamer/statemachine/sample/SampleGamer.java +++ b/src/org/ggp/base/player/gamer/statemachine/sample/SampleGamer.java @@ -17,7 +17,7 @@ * advanced functionality so the example gamers can be presented concisely. * This class implements 7 of the 8 core functions that need to be implemented * for any gamer. - * + * * If you want to quickly create a gamer of your own, extend this class and * add the last core function : public Move stateMachineSelectMove(long timeout) */ @@ -28,10 +28,10 @@ public abstract class SampleGamer extends StateMachineGamer public void stateMachineMetaGame(long timeout) throws TransitionDefinitionException, MoveDefinitionException, GoalDefinitionException { // Sample gamers do no metagaming at the beginning of the match. - } - - - + } + + + /** This will currently return "SampleGamer" * If you are working on : public abstract class MyGamer extends SampleGamer * Then this function would return "MyGamer" @@ -39,31 +39,31 @@ public void stateMachineMetaGame(long timeout) throws TransitionDefinitionExcept public String getName() { return getClass().getSimpleName(); } - + // This is the default State Machine public StateMachine getInitialStateMachine() { return new CachedStateMachine(new ProverStateMachine()); - } + } // This is the defaul Sample Panel public DetailPanel getDetailPanel() { return new SimpleDetailPanel(); - } - - - + } + + + @Override public void stateMachineStop() { // Sample gamers do no special cleanup when the match ends normally. } - + @Override public void stateMachineAbort() { // Sample gamers do no special cleanup when the match ends abruptly. } - + @Override public void preview(Game g, long timeout) throws GamePreviewException { // Sample gamers do no game previewing. - } + } } \ No newline at end of file diff --git a/src/org/ggp/base/player/gamer/statemachine/sample/SampleLegalGamer.java b/src/org/ggp/base/player/gamer/statemachine/sample/SampleLegalGamer.java index adbed24ad..e6d3e3b32 100644 --- a/src/org/ggp/base/player/gamer/statemachine/sample/SampleLegalGamer.java +++ b/src/org/ggp/base/player/gamer/statemachine/sample/SampleLegalGamer.java @@ -21,9 +21,9 @@ public final class SampleLegalGamer extends SampleGamer { /** * This function is called at the start of each round - * You are required to return the Move your player will play + * You are required to return the Move your player will play * before the timeout. - * + * */ public Move stateMachineSelectMove(long timeout) throws TransitionDefinitionException, MoveDefinitionException, GoalDefinitionException { @@ -31,13 +31,13 @@ public Move stateMachineSelectMove(long timeout) throws TransitionDefinitionExce long start = System.currentTimeMillis(); /** - * We put in memory the list of legal moves from the + * We put in memory the list of legal moves from the * current state. The goal of every stateMachineSelectMove() * is to return one of these moves. The choice of which * Move to play is the goal of GGP. */ List moves = getStateMachine().getLegalMoves(getCurrentState(), getRole()); - + // SampleLegalGamer is very simple : it picks the first legal move Move selection = moves.get(0); @@ -48,7 +48,7 @@ public Move stateMachineSelectMove(long timeout) throws TransitionDefinitionExce /** * These are functions used by other parts of the GGP codebase * You shouldn't worry about them, just make sure that you have - * moves, selection, stop and start defined in the same way as + * moves, selection, stop and start defined in the same way as * this example, and copy-paste these two lines in your player */ notifyObservers(new GamerSelectedMoveEvent(moves, selection, stop - start)); diff --git a/src/org/ggp/base/player/gamer/statemachine/sample/SampleMonteCarloGamer.java b/src/org/ggp/base/player/gamer/statemachine/sample/SampleMonteCarloGamer.java index 7e11a8437..cb446b0e0 100644 --- a/src/org/ggp/base/player/gamer/statemachine/sample/SampleMonteCarloGamer.java +++ b/src/org/ggp/base/player/gamer/statemachine/sample/SampleMonteCarloGamer.java @@ -15,12 +15,12 @@ * pure Monte Carlo approach towards picking moves, doing simulations and then * choosing the move that has the highest expected score. It should be slightly * more challenging than the RandomGamer, while still playing reasonably fast. - * + * * However, right now it isn't challenging at all. It's extremely mediocre, and * doesn't even block obvious one-move wins. This is partially due to the speed * of the default state machine (which is slow) and mostly due to the algorithm * assuming that the opponent plays completely randomly, which is inaccurate. - * + * * @author Sam Schreiber */ public final class SampleMonteCarloGamer extends SampleGamer @@ -34,24 +34,24 @@ public Move stateMachineSelectMove(long timeout) throws TransitionDefinitionExce StateMachine theMachine = getStateMachine(); long start = System.currentTimeMillis(); long finishBy = timeout - 1000; - + List moves = theMachine.getLegalMoves(getCurrentState(), getRole()); Move selection = moves.get(0); - if (moves.size() > 1) { + if (moves.size() > 1) { int[] moveTotalPoints = new int[moves.size()]; int[] moveTotalAttempts = new int[moves.size()]; - + // Perform depth charges for each candidate move, and keep track // of the total score and total attempts accumulated for each move. for (int i = 0; true; i = (i+1) % moves.size()) { if (System.currentTimeMillis() > finishBy) break; - + int theScore = performDepthChargeFromMove(getCurrentState(), moves.get(i)); moveTotalPoints[i] += theScore; moveTotalAttempts[i] += 1; } - + // Compute the expected score for each move. double[] moveExpectedPoints = new double[moves.size()]; for (int i = 0; i < moves.size(); i++) { @@ -75,9 +75,9 @@ public Move stateMachineSelectMove(long timeout) throws TransitionDefinitionExce notifyObservers(new GamerSelectedMoveEvent(moves, selection, stop - start)); return selection; } - + private int[] depth = new int[1]; - int performDepthChargeFromMove(MachineState theState, Move myMove) { + int performDepthChargeFromMove(MachineState theState, Move myMove) { StateMachine theMachine = getStateMachine(); try { MachineState finalState = theMachine.performDepthCharge(theMachine.getRandomNextState(theState, getRole(), myMove), depth); diff --git a/src/org/ggp/base/player/gamer/statemachine/sample/SampleNoopGamer.java b/src/org/ggp/base/player/gamer/statemachine/sample/SampleNoopGamer.java index 1afc92057..d09bca1c1 100644 --- a/src/org/ggp/base/player/gamer/statemachine/sample/SampleNoopGamer.java +++ b/src/org/ggp/base/player/gamer/statemachine/sample/SampleNoopGamer.java @@ -18,7 +18,7 @@ public final class SampleNoopGamer extends SampleGamer public Move stateMachineSelectMove(long timeout) throws TransitionDefinitionException, MoveDefinitionException, GoalDefinitionException { return new Move(GdlPool.getConstant("NOOP")); - } + } @Override public DetailPanel getDetailPanel() { diff --git a/src/org/ggp/base/player/gamer/statemachine/sample/SampleSearchLightGamer.java b/src/org/ggp/base/player/gamer/statemachine/sample/SampleSearchLightGamer.java index eb174ac83..4e5c669f9 100644 --- a/src/org/ggp/base/player/gamer/statemachine/sample/SampleSearchLightGamer.java +++ b/src/org/ggp/base/player/gamer/statemachine/sample/SampleSearchLightGamer.java @@ -25,19 +25,19 @@ * a possible one-move win. It will also spend up to two seconds looking for * one-move wins it can take. This makes it slightly more challenging than the * RandomGamer, while still playing reasonably fast. - * + * * Essentially, it has a one-move search-light that it shines out, allowing it * to avoid moves that are immediately terrible, and also choose moves that are * immediately excellent. - * + * * This approach implicitly assumes that it is playing an alternating-play game, * which is not always true. It will play simultaneous-action games less well. * It also assumes that it is playing a zero-sum game, where its opponent will * always force it to lose if given that option. - * + * * This player is fairly good at games like Tic-Tac-Toe, Knight Fight, and Connect Four. * This player is pretty terrible at most games. - * + * * @author Sam Schreiber */ public final class SampleSearchLightGamer extends StateMachineGamer @@ -52,10 +52,10 @@ public void stateMachineMetaGame(long timeout) throws TransitionDefinitionExcept } private Random theRandom = new Random(); - + /** - * Employs a simple sample "Search Light" algorithm. First selects a default legal move. - * It then iterates through all of the legal moves in random order, updating the current move selection + * Employs a simple sample "Search Light" algorithm. First selects a default legal move. + * It then iterates through all of the legal moves in random order, updating the current move selection * using the following criteria. *

      *
    1. If a move produces a 1 step victory (given a random joint action) select it
    2. @@ -70,10 +70,10 @@ public Move stateMachineSelectMove(long timeout) throws TransitionDefinitionExce StateMachine theMachine = getStateMachine(); long start = System.currentTimeMillis(); long finishBy = timeout - 1000; - + List moves = theMachine.getLegalMoves(getCurrentState(), getRole()); Move selection = (moves.get(new Random().nextInt(moves.size()))); - + // Shuffle the moves into a random order, so that when we find the first // move that doesn't give our opponent a forced win, we aren't always choosing // the first legal move over and over (which is visibly repetitive). @@ -83,7 +83,7 @@ public Move stateMachineSelectMove(long timeout) throws TransitionDefinitionExce movesInRandomOrder.add(aMove); moves.remove(aMove); } - + // Go through all of the legal moves in a random over, and consider each one. // For each move, we want to determine whether taking that move will give our // opponent a one-move win. We're also interested in whether taking that move @@ -98,11 +98,11 @@ public Move stateMachineSelectMove(long timeout) throws TransitionDefinitionExce for(Move moveUnderConsideration : movesInRandomOrder) { // Check to see if there's time to continue. if(System.currentTimeMillis() > finishBy) break; - + // If we've found a reasonable move, only spend at most two seconds trying // to find a winning move. if(System.currentTimeMillis() > start + 2000 && reasonableMoveFound) break; - + // Get the next state of the game, if we take the move we're considering. // Since it's our turn, in an alternating-play game the opponent will only // have one legal move, and so calling "getRandomJointMove" with our move @@ -111,7 +111,7 @@ public Move stateMachineSelectMove(long timeout) throws TransitionDefinitionExce // may have many moves, and so we will randomly pick one of our opponent's // possible actions and assume they do that. MachineState nextState = theMachine.getNextState(getCurrentState(), theMachine.getRandomJointMove(getCurrentState(), getRole(), moveUnderConsideration)); - + // Does the move under consideration end the game? If it does, do we win // or lose? If we lose, don't bother considering it. If we win, then we // definitely want to take this move. If its goal is better than our current @@ -122,22 +122,22 @@ public Move stateMachineSelectMove(long timeout) throws TransitionDefinitionExce } else if(theMachine.getGoal(nextState, getRole()) == 100) { selection = moveUnderConsideration; break; - } else { + } else { if (theMachine.getGoal(nextState, getRole()) > maxGoal) { selection = moveUnderConsideration; - maxGoal = theMachine.getGoal(nextState, getRole()); + maxGoal = theMachine.getGoal(nextState, getRole()); } continue; } } - + // Check whether any of the legal joint moves from this state lead to // a loss for us. Again, this only makes sense in the context of an alternating // play zero-sum game, in which this is the opponent's move and they are trying // to make us lose, and so if they are offered any move that will make us lose // they will take it. - boolean forcedLoss = false; + boolean forcedLoss = false; for(List jointMove : theMachine.getLegalJointMoves(nextState)) { MachineState nextNextState = theMachine.getNextState(nextState, jointMove); if(theMachine.isTerminal(nextNextState)) { @@ -146,14 +146,14 @@ public Move stateMachineSelectMove(long timeout) throws TransitionDefinitionExce break; } } - + // Check to see if there's time to continue. if(System.currentTimeMillis() > finishBy) { forcedLoss = true; break; } } - + // If we've verified that this move isn't going to lead us to a state where // our opponent can defeat us in one move, we should keep track of it. if(!forcedLoss) { @@ -188,14 +188,14 @@ public String getName() { public DetailPanel getDetailPanel() { return new SimpleDetailPanel(); } - + @Override public void preview(Game g, long timeout) throws GamePreviewException { // Do nothing. } - + @Override public void stateMachineAbort() { // Do nothing. - } + } } \ No newline at end of file diff --git a/src/org/ggp/base/player/proxy/ProxyGamePlayer.java b/src/org/ggp/base/player/proxy/ProxyGamePlayer.java index 7fd73e044..f537c7ae9 100644 --- a/src/org/ggp/base/player/proxy/ProxyGamePlayer.java +++ b/src/org/ggp/base/player/proxy/ProxyGamePlayer.java @@ -42,29 +42,29 @@ * class that is passed in as a parameter. It serves as a proxy between this * Gamer process and the GGP server: it ensures that legal moves are sent back * to the server on time, accepts and stores working moves, and so on. - * + * * This class is not necessary, unless you are interested in adding another * layer of bullet-proofing to your player in preparation for a tournament * or for running your player for long periods of time. - * + * * There are advantages and disadvantages to this approach. The advantages are: - * + * * 1. Even if the Gamer process stalls, for example due to garbage collection, * you will always send a legal move back to the server in time. - * + * * 2. You can send "working moves" to the proxy, so that if your Gamer process * stalls, you can send back your best-guess move from before the stall. - * + * * The disadvantage is very simple: - * + * * 1. If the proxy breaks, you can revert to playing extremely poorly * even though your real Gamer process is fully functional. - * + * * The advantages are very important, and so my response to the disadvantage * has been to shake as many bugs out of the proxy as I can. While the code is * fairly complex, this proxy has proven to be decently reliable in my testing. * So, that's progress. - * + * * @author Sam Schreiber */ public final class ProxyGamePlayer extends Thread implements Subject @@ -75,7 +75,7 @@ public final class ProxyGamePlayer extends Thread implements Subject private final List observers; private ClientManager theClientManager; private Gamer theDefaultGamer; - + private class ClientManager extends Thread { private Process theClientProcess; private Socket theClientConnection; @@ -87,10 +87,10 @@ private class ClientManager extends Thread { public volatile boolean pleaseStop = false; public volatile boolean expectStop = false; private Thread parentThread; - + public ClientManager(Thread parentThread) { this.parentThread = parentThread; - + String command = GamerConfiguration.getCommandForJava(); List processArgs = new ArrayList(); processArgs.add(command); @@ -103,50 +103,50 @@ public ClientManager(Thread parentThread) { processArgs.add(System.getProperty("java.class.path")); processArgs.add("org.ggp.base.player.proxy.ProxyGamePlayerClient"); processArgs.add(gamerName); - processArgs.add("" + clientListener.getLocalPort()); + processArgs.add("" + clientListener.getLocalPort()); if(GamerConfiguration.runningOnLinux()) { processArgs.add(0, "nice"); - } + } ProcessBuilder pb = new ProcessBuilder(processArgs); - - try { + + try { GamerLogger.log("Proxy", "[PROXY] Starting a new proxy client, using gamer " + gamerName + "."); - - theClientProcess = pb.start(); + + theClientProcess = pb.start(); outConnector = new StreamConnector(theClientProcess.getErrorStream(), System.err); errConnector = new StreamConnector(theClientProcess.getInputStream(), System.out); outConnector.start(); errConnector.start(); - + theClientConnection = clientListener.accept(); - + theOutput = new PrintStream(theClientConnection.getOutputStream()); theInput = new BufferedReader(new InputStreamReader(theClientConnection.getInputStream())); - + GamerLogger.log("Proxy", "[PROXY] Proxy client started."); } catch(IOException e) { GamerLogger.logStackTrace("Proxy", e); } } - + // TODO: remove this class if nothing is being sent over it private class StreamConnector extends Thread { private InputStream theInput; private PrintStream theOutput; - - public volatile boolean pleaseStop = false; - - public StreamConnector(InputStream theInput, PrintStream theOutput) { + + public volatile boolean pleaseStop = false; + + public StreamConnector(InputStream theInput, PrintStream theOutput) { this.theInput = theInput; this.theOutput = theOutput; } - + public boolean isPrintableChar( char c ) { if(!Character.isDefined(c)) return false; if(Character.isIdentifierIgnorable(c)) return false; return true; } - + public void run() { try { while(!pleaseStop) { @@ -166,30 +166,30 @@ public void run() { } } } - + public void sendMessage(ProxyMessage theMessage) { if(theOutput != null) { theMessage.writeTo(theOutput); GamerLogger.log("Proxy", "[PROXY] Wrote message to client: " + theMessage); } } - + public void run() { while(theInput != null) { try { - ProxyMessage in = ProxyMessage.readFrom(theInput); + ProxyMessage in = ProxyMessage.readFrom(theInput); if(pleaseStop) return; - + GamerLogger.log("Proxy", "[PROXY] Got message from client: " + in); if(in == null) continue; - + processClientResponse(in, parentThread); } catch(SocketException se) { if(expectStop) return; - + GamerLogger.logStackTrace("Proxy", se); GamerLogger.logError("Proxy", "Shutting down reader as consequence of socket exception. Presumably this is because the gamer client crashed."); break; @@ -200,19 +200,19 @@ public void run() { } } } - + public void closeClient() { try { outConnector.pleaseStop = true; errConnector.pleaseStop = true; - + theClientConnection.close(); theInput = null; theOutput = null; } catch (IOException e) { GamerLogger.logStackTrace("Proxy", e); } - + theClientProcess.destroy(); } } @@ -224,7 +224,7 @@ public ProxyGamePlayer(int port, Class gamer) throws IOExceptio // in the event that we don't get a message from the client, or if // we need to handle a simple request (START or STOP). theDefaultGamer = new RandomGamer(); - + observers = new ArrayList(); listener = null; while (listener == null) { @@ -234,10 +234,10 @@ public ProxyGamePlayer(int port, Class gamer) throws IOExceptio listener = null; port++; GamerLogger.logError("Proxy", "Failed to start gamer on port: "+(port-1)+" trying port "+port); - } + } } myPort = port; - + // Start up the socket for communicating with clients int clientPort = 17147; while(clientListener == null) { @@ -249,11 +249,11 @@ public ProxyGamePlayer(int port, Class gamer) throws IOExceptio } } GamerLogger.log("Proxy", "[PROXY] Opened client communication socket on port " + clientPort + "."); - + // Start up the first ProxyClient gamerName = gamer.getSimpleName(); } - + public int getGamerPort() { return myPort; } @@ -275,35 +275,35 @@ public void notifyObservers(Event event) private long currentMoveCode = 0L; private boolean receivedClientMove = false; private boolean needRestart = false; - + @Override public void run() - { + { GamerConfiguration.showConfiguration(); GamerLogger.setSpilloverLogfile("spilloverLog"); - + // Start up the client manager theClientManager = new ClientManager(Thread.currentThread()); theClientManager.start(); - + // Start up the input queue listener inputQueue = new ArrayBlockingQueue(100); inputConnectionQueue = new ArrayBlockingQueue(100); QueueListenerThread theListener = new QueueListenerThread(); theListener.start(); - + while (true) { try - { - // First, read a message from the server. + { + // First, read a message from the server. ProxyMessage nextMessage = inputQueue.take(); - Socket connection = inputConnectionQueue.take(); + Socket connection = inputConnectionQueue.take(); String in = nextMessage.theMessage; - long receptionTime = nextMessage.receptionTime; + long receptionTime = nextMessage.receptionTime; notifyObservers(new PlayerReceivedMessageEvent(in)); GamerLogger.log("Proxy", "[PROXY] Got incoming message:" + in); - + // Formulate a request, and see how the legal gamer responds. String legalProxiedResponse; Request request = new RequestFactory().create(theDefaultGamer, in); @@ -317,49 +317,49 @@ public void run() } latestProxiedResponse = legalProxiedResponse; GamerLogger.log("Proxy", "[PROXY] Selected fallback move:" + latestProxiedResponse); - + if (!(request instanceof InfoRequest)) { // Update the move codes and prepare to send the request on to the client. receivedClientMove = false; currentMoveCode = 1 + theRandomGenerator.nextLong(); if(request instanceof StopRequest || request instanceof AbortRequest) theClientManager.expectStop = true; - + // Send the request on to the client, along with the move code. ProxyMessage theMessage = new ProxyMessage(in, currentMoveCode, receptionTime); theClientManager.sendMessage(theMessage); if(!(request instanceof PlayRequest)) // If we're not asked for a move, just let currentMoveCode = 0L; // the default gamer handle it by switching move code. - + // Wait the appropriate amount of time for the request. proxyProcessRequest(request, receptionTime); } else { - receivedClientMove = true; + receivedClientMove = true; } - + // Get the latest response, and complain if it's the default response, or isn't a valid response. String out = latestProxiedResponse; if(!receivedClientMove && (request instanceof PlayRequest)) { GamerLogger.logError("Proxy", "[PROXY] Did not receive any move information from client for this turn; falling back to first legal move."); GamerLogger.logError("ExecutiveSummary", "Proxy did not receive any move information from client this turn: used first legal move."); } - + // Cycle the move codes again so that we will ignore any more responses // that the client sends along to us. currentMoveCode = 0L; - + // And finally write the latest response out to the server. - GamerLogger.log("Proxy", "[PROXY] Wrote outgoing message:" + out); + GamerLogger.log("Proxy", "[PROXY] Wrote outgoing message:" + out); HttpWriter.writeAsServer(connection, out); connection.close(); notifyObservers(new PlayerSentMessageEvent(out)); // Once everything is said and done, restart the client if we're // due for a restart (having finished playing a game). - if(needRestart) { + if(needRestart) { theClientManager.closeClient(); - theClientManager.pleaseStop = true; - + theClientManager.pleaseStop = true; + if(GamerConfiguration.runningOnLinux()) { // Clean up the working directory and terminate any orphan processes. Thread.sleep(500); @@ -371,10 +371,10 @@ public void run() } Thread.sleep(500); } - + theClientManager = new ClientManager(Thread.currentThread()); - theClientManager.start(); - + theClientManager.start(); + theDefaultGamer = new RandomGamer(); GdlPool.drainPool(); SymbolPool.drainPool(); @@ -382,20 +382,20 @@ public void run() long usedMemory = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory(); double usedMemoryInMegs = usedMemory / 1024.0 / 1024.0; GamerLogger.log("Proxy", "[PROXY] Before collection, using " + usedMemoryInMegs + "mb of memory as proxy."); - + // Okay, seriously garbage collect please. As it turns out, - // this takes some convincing; Java isn't usually eager to do it. + // this takes some convincing; Java isn't usually eager to do it. for(int i = 0; i < 10; i++) { System.gc(); Thread.sleep(100); } - + usedMemory = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory(); usedMemoryInMegs = usedMemory / 1024.0 / 1024.0; GamerLogger.log("Proxy", "[PROXY] After collection, using a non-transient " + usedMemoryInMegs + "mb of memory as proxy."); - + System.out.println("Cleaned up completed match, with a residual " + usedMemoryInMegs + "mb of memory as proxy."); - + needRestart = false; } } @@ -411,17 +411,17 @@ public void run() } } } - + public static final long METAGAME_BUFFER = Gamer.PREFERRED_METAGAME_BUFFER + 100; public static final long PLAY_BUFFER = Gamer.PREFERRED_PLAY_BUFFER + 100; - + private void proxyProcessRequest(Request theRequest, long receptionTime) { long startSleeping = System.currentTimeMillis(); long timeToFinish = receptionTime; long timeToSleep = 0L; - + try { - if(theRequest instanceof PlayRequest) { + if(theRequest instanceof PlayRequest) { if (theDefaultGamer.getMatch() != null) { // They have this long to play timeToFinish = receptionTime + theDefaultGamer.getMatch().getPlayClock() * 1000 - PLAY_BUFFER; @@ -436,7 +436,7 @@ private void proxyProcessRequest(Request theRequest, long receptionTime) { GamerLogger.startFileLogging(theDefaultGamer.getMatch(), theDefaultGamer.getRoleName().toString()); System.out.println("Started playing " + theDefaultGamer.getMatch().getMatchId() + "."); - + // They have this long to metagame timeToFinish = receptionTime + theDefaultGamer.getMatch().getStartClock() * 1000 - METAGAME_BUFFER; timeToSleep = timeToFinish - System.currentTimeMillis(); @@ -450,7 +450,7 @@ private void proxyProcessRequest(Request theRequest, long receptionTime) { // Rise and shine! GamerLogger.log("Proxy", "[PROXY] Got woken up by final move!"); } - + GamerLogger.log("Proxy", "[PROXY] Proxy slept for " + (System.currentTimeMillis() - startSleeping) + ", and woke up " + (System.currentTimeMillis() - timeToFinish) + "ms late (started " + (startSleeping - receptionTime) + "ms after receiving message)."); } @@ -458,19 +458,19 @@ private void proxyProcessRequest(Request theRequest, long receptionTime) { private void processClientResponse(ProxyMessage in, Thread toWakeUp) { String theirTag = in.theMessage.substring(0,5); String theirMessage = in.theMessage.substring(5); - + // Ignore their message unless it has an up-to-date move code. if(!(in.messageCode == currentMoveCode)) { if(currentMoveCode > 0) GamerLogger.logError("Proxy", "CODE MISMATCH: " + currentMoveCode + " vs " + in.messageCode); return; } - + if(theirTag.equals("WORK:")) { - latestProxiedResponse = theirMessage; + latestProxiedResponse = theirMessage; GamerLogger.log("Proxy", "[PROXY] Got latest working move: " + latestProxiedResponse); receivedClientMove = true; - } else if(theirTag.equals("DONE:")) { + } else if(theirTag.equals("DONE:")) { latestProxiedResponse = theirMessage; GamerLogger.log("Proxy", "[PROXY] Got a final move: " + latestProxiedResponse); receivedClientMove = true; @@ -478,21 +478,21 @@ private void processClientResponse(ProxyMessage in, Thread toWakeUp) { toWakeUp.interrupt(); } } - + private BlockingQueue inputQueue; private BlockingQueue inputConnectionQueue; private class QueueListenerThread extends Thread { public void run() { while(true) { try { - // First, read a message from the server. + // First, read a message from the server. Socket connection = listener.accept(); String in = HttpReader.readAsServer(connection).replace('\n', ' ').replace('\r', ' '); long receptionTime = System.currentTimeMillis(); if(inputQueue.remainingCapacity() > 0) { inputQueue.add(new ProxyMessage(in, 0L, receptionTime)); inputConnectionQueue.add(connection); - + GamerLogger.log("Proxy", "[PROXY QueueListener] Got incoming message from game server: " + in + ". Added to queue in position " + inputQueue.size() + "."); } else { GamerLogger.logError("Proxy", "[PROXY QueueListener] Got incoming message from game server: " + in + ". Could not add to queue, because queue is full!"); diff --git a/src/org/ggp/base/player/proxy/ProxyGamePlayerClient.java b/src/org/ggp/base/player/proxy/ProxyGamePlayerClient.java index ba01b6249..6b693a741 100644 --- a/src/org/ggp/base/player/proxy/ProxyGamePlayerClient.java +++ b/src/org/ggp/base/player/proxy/ProxyGamePlayerClient.java @@ -27,13 +27,13 @@ public final class ProxyGamePlayerClient extends Thread implements Subject, Observer { - private final Gamer gamer; + private final Gamer gamer; private final List observers; - + private Socket theConnection; private BufferedReader theInput; private PrintStream theOutput; - + /** * @param args * Command line arguments: @@ -42,12 +42,12 @@ public final class ProxyGamePlayerClient extends Thread implements Subject, Obse public static void main(String[] args) { GamerLogger.setSpilloverLogfile("spilloverLog"); GamerLogger.log("Proxy", "Starting the ProxyGamePlayerClient program."); - + if (!(args.length == 2)) { GamerLogger.logError("Proxy", "Usage is: \n\tProxyGamePlayerClient gamer port"); return; } - + int port = 9147; Gamer gamer = null; try { @@ -56,7 +56,7 @@ public static void main(String[] args) { GamerLogger.logError("Proxy", args[1]+" is not a valid port."); return; } - + List> gamers = Lists.newArrayList(ProjectSearcher.GAMERS.getConcreteClasses()); List gamerNames = new ArrayList(); if(gamerNames.size()!=gamers.size()) @@ -64,7 +64,7 @@ public static void main(String[] args) { for(Class c : gamers) gamerNames.add(c.getName().replaceAll("^.*\\.","")); } - + int idx = gamerNames.indexOf(args[0]); if (idx == -1) { GamerLogger.logError("Proxy", args[0] + " is not a subclass of gamer. Valid options are:"); @@ -72,30 +72,30 @@ public static void main(String[] args) { GamerLogger.logError("Proxy", "\t"+s); return; } - + try { gamer = (Gamer)(gamers.get(idx).newInstance()); } catch(Exception ex) { GamerLogger.logError("Proxy", "Cannot create instance of " + args[0]); return; - } - + } + try { ProxyGamePlayerClient theClient = new ProxyGamePlayerClient(port, gamer); theClient.start(); } catch (IOException e) { GamerLogger.logStackTrace("Proxy", e); - } - } - + } + } + public ProxyGamePlayerClient(int port, Gamer gamer) throws IOException { observers = new ArrayList(); - - theConnection = new Socket("127.0.0.1", port); + + theConnection = new Socket("127.0.0.1", port); theOutput = new PrintStream(theConnection.getOutputStream()); theInput = new BufferedReader(new InputStreamReader(theConnection.getInputStream())); - + this.gamer = gamer; gamer.addObserver(this); } @@ -114,7 +114,7 @@ public void notifyObservers(Event event) } private long theCode; - + @Override public void run() { @@ -137,12 +137,12 @@ public void run() GamerLogger.log("Proxy", "[ProxyClient] Got message: " + theMessage); } String out = request.process(receptionTime); - + ProxyMessage outMessage = new ProxyMessage("DONE:" + out, theCode, 0L); outMessage.writeTo(theOutput); GamerLogger.log("Proxy", "[ProxyClient] Sent message: " + outMessage); notifyObservers(new PlayerSentMessageEvent(out)); - + if(request instanceof StopRequest) { GamerLogger.log("Proxy", "[ProxyClient] Got stop request, shutting down."); System.exit(0); @@ -150,7 +150,7 @@ public void run() if(request instanceof AbortRequest) { GamerLogger.log("Proxy", "[ProxyClient] Got abort request, shutting down."); System.exit(0); - } + } } catch (Exception e) { @@ -158,16 +158,16 @@ public void run() notifyObservers(new PlayerDroppedPacketEvent()); } } - + GamerLogger.log("Proxy", "[ProxyClient] Got interrupted, shutting down."); } - + public void observe(Event event) { if(event instanceof WorkingResponseSelectedEvent) { WorkingResponseSelectedEvent theWorking = (WorkingResponseSelectedEvent)event; ProxyMessage theMessage = new ProxyMessage("WORK:" + theWorking.getWorkingResponse(), theCode, 0L); theMessage.writeTo(theOutput); GamerLogger.log("Proxy", "[ProxyClient] Sent message: " + theMessage); - } + } } } diff --git a/src/org/ggp/base/player/proxy/ProxyMessage.java b/src/org/ggp/base/player/proxy/ProxyMessage.java index 35c7004de..3c9a22830 100644 --- a/src/org/ggp/base/player/proxy/ProxyMessage.java +++ b/src/org/ggp/base/player/proxy/ProxyMessage.java @@ -10,22 +10,22 @@ public class ProxyMessage implements Serializable { private static final long serialVersionUID = 1237859L; - + public final long messageCode; public final long receptionTime; public final String theMessage; - + public ProxyMessage(String theMessage, long messageCode, long receptionTime) { this.theMessage = theMessage; this.messageCode = messageCode; this.receptionTime = receptionTime; } - + public String toString() { - return "ProxyMessage<" + messageCode + ", " + receptionTime + ">[\"" + theMessage + "\"]"; + return "ProxyMessage<" + messageCode + ", " + receptionTime + ">[\"" + theMessage + "\"]"; } - - public static ProxyMessage readFrom(BufferedReader theInput) throws SocketException { + + public static ProxyMessage readFrom(BufferedReader theInput) throws SocketException { try { long messageCode = Long.parseLong(theInput.readLine()); long receptionTime = Long.parseLong(theInput.readLine()); @@ -42,14 +42,14 @@ public static ProxyMessage readFrom(BufferedReader theInput) throws SocketExcept theInput.skip(Long.MAX_VALUE); } catch(SocketException se) { GamerLogger.log("Proxy", "[ProxyMessage Reader] Socket closed: stopping read operation."); - throw se; + throw se; } catch(Exception ie) { GamerLogger.logStackTrace("Proxy", ie); } return null; } } - + public void writeTo(PrintStream theOutput) { synchronized (theOutput) { theOutput.println(messageCode); diff --git a/src/org/ggp/base/player/proxy/WorkingResponseSelectedEvent.java b/src/org/ggp/base/player/proxy/WorkingResponseSelectedEvent.java index 48ebea7b3..d7072bd64 100644 --- a/src/org/ggp/base/player/proxy/WorkingResponseSelectedEvent.java +++ b/src/org/ggp/base/player/proxy/WorkingResponseSelectedEvent.java @@ -4,11 +4,11 @@ public class WorkingResponseSelectedEvent extends Event { private String theResponse; - + public WorkingResponseSelectedEvent(String theResponse) { this.theResponse = theResponse; } - + public String getWorkingResponse() { return theResponse; } diff --git a/src/org/ggp/base/player/request/factory/RequestFactory.java b/src/org/ggp/base/player/request/factory/RequestFactory.java index 38df70960..94715af47 100644 --- a/src/org/ggp/base/player/request/factory/RequestFactory.java +++ b/src/org/ggp/base/player/request/factory/RequestFactory.java @@ -136,8 +136,8 @@ private AbortRequest createAbort(Gamer gamer, SymbolList list) throws GdlFormatE String matchId = arg1.getValue(); return new AbortRequest(gamer, matchId); - } - + } + private InfoRequest createInfo(Gamer gamer, SymbolList list) throws GdlFormatException { if (list.size() != 1) @@ -146,8 +146,8 @@ private InfoRequest createInfo(Gamer gamer, SymbolList list) throws GdlFormatExc } return new InfoRequest(gamer); - } - + } + private PreviewRequest createPreview(Gamer gamer, SymbolList list) throws GdlFormatException { if (list.size() != 3) @@ -160,10 +160,10 @@ private PreviewRequest createPreview(Gamer gamer, SymbolList list) throws GdlFor String theRulesheet = arg1.toString(); int previewClock = Integer.valueOf(arg2.getValue()); - + Game theReceivedGame = Game.createEphemeralGame(theRulesheet); return new PreviewRequest(gamer, theReceivedGame, previewClock); - } + } private List parseMoves(Symbol symbol) throws GdlFormatException { diff --git a/src/org/ggp/base/player/request/grammar/AbortRequest.java b/src/org/ggp/base/player/request/grammar/AbortRequest.java index 4d30cae9c..12cd03b69 100644 --- a/src/org/ggp/base/player/request/grammar/AbortRequest.java +++ b/src/org/ggp/base/player/request/grammar/AbortRequest.java @@ -16,7 +16,7 @@ public AbortRequest(Gamer gamer, String matchId) this.gamer = gamer; this.matchId = matchId; } - + @Override public String getMatchId() { return matchId; @@ -27,7 +27,7 @@ public String process(long receptionTime) { // First, check to ensure that this abort request is for the match // we're currently playing. If we're not playing a match, or we're - // playing a different match, send back "busy". + // playing a different match, send back "busy". if (gamer.getMatch() == null || !gamer.getMatch().getMatchId().equals(matchId)) { GamerLogger.logError("GamePlayer", "Got abort message not intended for current game: ignoring."); @@ -43,12 +43,12 @@ public String process(long receptionTime) } catch (AbortingException e) { GamerLogger.logStackTrace("GamePlayer", e); } - + // Once the match has ended, set 'roleName' and 'match' // to NULL to indicate that we're ready to begin a new match. gamer.setRoleName(null); gamer.setMatch(null); - + return "aborted"; } diff --git a/src/org/ggp/base/player/request/grammar/InfoRequest.java b/src/org/ggp/base/player/request/grammar/InfoRequest.java index f120d5926..57b3928e5 100644 --- a/src/org/ggp/base/player/request/grammar/InfoRequest.java +++ b/src/org/ggp/base/player/request/grammar/InfoRequest.java @@ -11,12 +11,12 @@ public InfoRequest(Gamer gamer) { this.gamer = gamer; } - + @Override public String getMatchId() { return null; } - + @Override public String process(long receptionTime) { @@ -26,7 +26,7 @@ public String process(long receptionTime) info.setSpecies(gamer.getSpecies()); return info.toSymbol().toString(); } - + @Override public String toString() { diff --git a/src/org/ggp/base/player/request/grammar/PlayRequest.java b/src/org/ggp/base/player/request/grammar/PlayRequest.java index ae7bb56c3..18edaad89 100644 --- a/src/org/ggp/base/player/request/grammar/PlayRequest.java +++ b/src/org/ggp/base/player/request/grammar/PlayRequest.java @@ -27,7 +27,7 @@ public PlayRequest(Gamer gamer, String matchId, List moves) public String getMatchId() { return matchId; } - + @Override public String process(long receptionTime) { diff --git a/src/org/ggp/base/player/request/grammar/PreviewRequest.java b/src/org/ggp/base/player/request/grammar/PreviewRequest.java index 8933dcf05..54589f44f 100644 --- a/src/org/ggp/base/player/request/grammar/PreviewRequest.java +++ b/src/org/ggp/base/player/request/grammar/PreviewRequest.java @@ -17,12 +17,12 @@ public PreviewRequest(Gamer gamer, Game theGame, int previewClock) this.game = theGame; this.previewClock = previewClock; } - + @Override public String getMatchId() { return null; - } - + } + @Override public String process(long receptionTime) { @@ -33,13 +33,13 @@ public String process(long receptionTime) //gamer.notifyObservers(new GamerUnrecognizedMatchEvent(matchId)); return "busy"; } - + // Otherwise, if we're not busy, have the gamer start previewing. try { //gamer.notifyObservers(new PlayerTimeEvent(gamer.getMatch().getStartClock() * 1000)); gamer.preview(game, previewClock * 1000 + receptionTime); //gamer.metaGame(gamer.getMatch().getStartClock() * 1000 + receptionTime); - } catch (GamePreviewException e) { + } catch (GamePreviewException e) { GamerLogger.logStackTrace("GamePlayer", e); // Upon encountering an uncaught exception during previewing, diff --git a/src/org/ggp/base/player/request/grammar/Request.java b/src/org/ggp/base/player/request/grammar/Request.java index 006ebd3dc..be5025d1b 100644 --- a/src/org/ggp/base/player/request/grammar/Request.java +++ b/src/org/ggp/base/player/request/grammar/Request.java @@ -6,7 +6,7 @@ public abstract class Request public abstract String process(long receptionTime); public abstract String getMatchId(); - + @Override public abstract String toString(); diff --git a/src/org/ggp/base/player/request/grammar/StartRequest.java b/src/org/ggp/base/player/request/grammar/StartRequest.java index 07de118da..326cd5924 100644 --- a/src/org/ggp/base/player/request/grammar/StartRequest.java +++ b/src/org/ggp/base/player/request/grammar/StartRequest.java @@ -29,7 +29,7 @@ public StartRequest(Gamer gamer, String matchId, GdlConstant roleName, Game theG this.startClock = startClock; this.playClock = playClock; } - + @Override public String getMatchId() { return matchId; @@ -45,10 +45,10 @@ public String process(long receptionTime) gamer.notifyObservers(new GamerUnrecognizedMatchEvent(matchId)); return "busy"; } - + // Create the new match, and handle all of the associated logistics // in the gamer to indicate that we're starting a new match. - Match match = new Match(matchId, -1, startClock, playClock, game); + Match match = new Match(matchId, -1, startClock, playClock, game); gamer.setMatch(match); gamer.setRoleName(roleName); gamer.notifyObservers(new GamerNewMatchEvent(match, roleName)); @@ -57,7 +57,7 @@ public String process(long receptionTime) try { gamer.notifyObservers(new PlayerTimeEvent(gamer.getMatch().getStartClock() * 1000)); gamer.metaGame(gamer.getMatch().getStartClock() * 1000 + receptionTime); - } catch (MetaGamingException e) { + } catch (MetaGamingException e) { GamerLogger.logStackTrace("GamePlayer", e); // Upon encountering an uncaught exception during metagaming, diff --git a/src/org/ggp/base/player/request/grammar/StopRequest.java b/src/org/ggp/base/player/request/grammar/StopRequest.java index fbd5ce7f5..056a6d268 100644 --- a/src/org/ggp/base/player/request/grammar/StopRequest.java +++ b/src/org/ggp/base/player/request/grammar/StopRequest.java @@ -21,7 +21,7 @@ public StopRequest(Gamer gamer, String matchId, List moves) this.matchId = matchId; this.moves = moves; } - + @Override public String getMatchId() { return matchId; @@ -32,7 +32,7 @@ public String process(long receptionTime) { // First, check to ensure that this stop request is for the match // we're currently playing. If we're not playing a match, or we're - // playing a different match, send back "busy". + // playing a different match, send back "busy". if (gamer.getMatch() == null || !gamer.getMatch().getMatchId().equals(matchId)) { GamerLogger.logError("GamePlayer", "Got stop message not intended for current game: ignoring."); @@ -51,12 +51,12 @@ public String process(long receptionTime) } catch (StoppingException e) { GamerLogger.logStackTrace("GamePlayer", e); } - + // Once the match has ended, set 'roleName' and 'match' // to NULL to indicate that we're ready to begin a new match. gamer.setRoleName(null); gamer.setMatch(null); - + return "done"; } diff --git a/src/org/ggp/base/server/GameServer.java b/src/org/ggp/base/server/GameServer.java index 97e9283d9..e4aa5dc5d 100644 --- a/src/org/ggp/base/server/GameServer.java +++ b/src/org/ggp/base/server/GameServer.java @@ -42,60 +42,60 @@ public final class GameServer extends Thread implements Subject { private final Match match; - private final StateMachine stateMachine; - private MachineState currentState; + private final StateMachine stateMachine; + private MachineState currentState; - private final List hosts; + private final List hosts; private final List ports; private final Boolean[] playerGetsUnlimitedTime; private final Boolean[] playerPlaysRandomly; - - private final List observers; + + private final List observers; private List previousMoves; - + private Map mostRecentErrors; - + private String saveToFilename; private String spectatorServerURL; private String spectatorServerKey; private boolean forceUsingEntireClock; - + public GameServer(Match match, List hosts, List ports) { this.match = match; - + this.hosts = hosts; - this.ports = ports; - + this.ports = ports; + playerGetsUnlimitedTime = new Boolean[hosts.size()]; Arrays.fill(playerGetsUnlimitedTime, Boolean.FALSE); - + playerPlaysRandomly = new Boolean[hosts.size()]; - Arrays.fill(playerPlaysRandomly, Boolean.FALSE); + Arrays.fill(playerPlaysRandomly, Boolean.FALSE); stateMachine = new ProverStateMachine(); stateMachine.initialize(match.getGame().getRules()); currentState = stateMachine.getInitialState(); previousMoves = null; - - mostRecentErrors = new HashMap(); - + + mostRecentErrors = new HashMap(); + match.appendState(currentState.getContents()); - + observers = new ArrayList(); - + spectatorServerURL = null; forceUsingEntireClock = false; } - + public void startSavingToFilename(String theFilename) { saveToFilename = theFilename; } - + public String startPublishingToSpectatorServer(String theURL) { spectatorServerURL = theURL; return publishWhenNecessary(); } - + public void addObserver(Observer observer) { observers.add(observer); } @@ -108,29 +108,29 @@ public List getGoals() throws GoalDefinitionException { return goals; } - + public StateMachine getStateMachine() { - return stateMachine; + return stateMachine; } public void notifyObservers(Event event) { for (Observer observer : observers) { observer.observe(event); } - + // Add error events to mostRecentErrors for recording. if (event instanceof ServerIllegalMoveEvent) { ServerIllegalMoveEvent sEvent = (ServerIllegalMoveEvent)event; mostRecentErrors.put(sEvent.getRole(), "IL " + sEvent.getMove()); } else if (event instanceof ServerTimeoutEvent) { ServerTimeoutEvent sEvent = (ServerTimeoutEvent)event; - mostRecentErrors.put(sEvent.getRole(), "TO"); + mostRecentErrors.put(sEvent.getRole(), "TO"); } else if (event instanceof ServerConnectionErrorEvent) { ServerConnectionErrorEvent sEvent = (ServerConnectionErrorEvent)event; mostRecentErrors.put(sEvent.getRole(), "CE"); } } - + // Should be called after each move, to collect all of the errors // caused by players and write them into the match description. private void appendErrorsToMatchDescription() { @@ -144,7 +144,7 @@ private void appendErrorsToMatchDescription() { } } match.appendErrors(theErrors); - mostRecentErrors.clear(); + mostRecentErrors.clear(); } @Override @@ -153,9 +153,9 @@ public void run() { if (match.getPreviewClock() >= 0) { sendPreviewRequests(); } - - notifyObservers(new ServerNewMatchEvent(stateMachine.getRoles(), currentState)); - notifyObservers(new ServerTimeEvent(match.getStartClock() * 1000)); + + notifyObservers(new ServerNewMatchEvent(stateMachine.getRoles(), currentState)); + notifyObservers(new ServerTimeEvent(match.getStartClock() * 1000)); sendStartRequests(); appendErrorsToMatchDescription(); @@ -169,11 +169,11 @@ public void run() { notifyObservers(new ServerNewMovesEvent(previousMoves)); currentState = stateMachine.getNextState(currentState, previousMoves); - + match.appendMoves2(previousMoves); match.appendState(currentState.getContents()); appendErrorsToMatchDescription(); - + if (match.isAborted()) { return; } @@ -195,29 +195,29 @@ public void run() { e.printStackTrace(); } } - + public void abort() { try { match.markAborted(); interrupt(); sendAbortRequests(); saveWhenNecessary(); - publishWhenNecessary(); + publishWhenNecessary(); notifyObservers(new ServerAbortedMatchEvent()); notifyObservers(new ServerMatchUpdatedEvent(match, spectatorServerKey, saveToFilename)); } catch (Exception e) { e.printStackTrace(); } } - + private void saveWhenNecessary() { if (saveToFilename == null) { return; } - + try { File file = new File(saveToFilename); - if (!file.exists()) { + if (!file.exists()) { file.createNewFile(); } FileWriter fw = new FileWriter(file); @@ -234,7 +234,7 @@ private String publishWhenNecessary() { if (spectatorServerURL == null) { return null; } - + int nAttempt = 0; while (true) { try { @@ -249,7 +249,7 @@ private String publishWhenNecessary() { nAttempt++; } } - + public String getSpectatorServerKey() { return spectatorServerKey; } @@ -267,7 +267,7 @@ private synchronized List sendPlayRequests() throws InterruptedException, for (PlayRequestThread thread : threads) { thread.start(); } - + if (forceUsingEntireClock) { Thread.sleep(match.getPlayClock() * 1000); } @@ -293,12 +293,12 @@ private synchronized void sendPreviewRequests() throws InterruptedException { } if (forceUsingEntireClock) { Thread.sleep(match.getStartClock() * 1000); - } + } for (PreviewRequestThread thread : threads) { thread.join(); } - } - + } + private synchronized void sendStartRequests() throws InterruptedException { List threads = new ArrayList(hosts.size()); for (int i = 0; i < hosts.size(); i++) { @@ -311,7 +311,7 @@ private synchronized void sendStartRequests() throws InterruptedException { } if (forceUsingEntireClock) { Thread.sleep(match.getStartClock() * 1000); - } + } for (StartRequestThread thread : threads) { thread.join(); } @@ -331,7 +331,7 @@ private synchronized void sendStopRequests(List previousMoves) throws Inte thread.join(); } } - + private void sendAbortRequests() throws InterruptedException { List threads = new ArrayList(hosts.size()); for (int i = 0; i < hosts.size(); i++) { @@ -346,12 +346,12 @@ private void sendAbortRequests() throws InterruptedException { thread.join(); } interrupt(); - } - + } + public void givePlayerUnlimitedTime(int i) { playerGetsUnlimitedTime[i] = true; } - + public void makePlayerPlayRandomly(int i) { playerPlaysRandomly[i] = true; } @@ -362,14 +362,14 @@ public void makePlayerPlayRandomly(int i) { public void setForceUsingEntireClock() { forceUsingEntireClock = true; } - + public Match getMatch() { return match; } - + private String getPlayerNameFromMatchForRequest(int i) { if (match.getPlayerNamesFromHost() != null) { - return match.getPlayerNamesFromHost().get(i); + return match.getPlayerNamesFromHost().get(i); } else { return ""; } diff --git a/src/org/ggp/base/server/event/ServerMatchUpdatedEvent.java b/src/org/ggp/base/server/event/ServerMatchUpdatedEvent.java index 028490fbe..826d30729 100644 --- a/src/org/ggp/base/server/event/ServerMatchUpdatedEvent.java +++ b/src/org/ggp/base/server/event/ServerMatchUpdatedEvent.java @@ -20,11 +20,11 @@ public ServerMatchUpdatedEvent(Match match, String externalPublicationKey, Strin public Match getMatch() { return match; } - + public String getExternalFilename() { return externalFilename; } - + public String getExternalPublicationKey() { return externalPublicationKey; } diff --git a/src/org/ggp/base/server/event/ServerNewMatchEvent.java b/src/org/ggp/base/server/event/ServerNewMatchEvent.java index 0a5e5ae37..4338781b0 100644 --- a/src/org/ggp/base/server/event/ServerNewMatchEvent.java +++ b/src/org/ggp/base/server/event/ServerNewMatchEvent.java @@ -25,7 +25,7 @@ public List getRoles() { return roles; } - + public MachineState getInitialState() { return initialState; diff --git a/src/org/ggp/base/server/request/RequestBuilder.java b/src/org/ggp/base/server/request/RequestBuilder.java index 5fa9efa20..b93b72328 100644 --- a/src/org/ggp/base/server/request/RequestBuilder.java +++ b/src/org/ggp/base/server/request/RequestBuilder.java @@ -24,7 +24,7 @@ public static String getPlayRequest(String matchId, List moves, GdlScrambl } sb.append(") )"); - return sb.toString(); + return sb.toString(); } } @@ -41,7 +41,7 @@ public static String getStartRequest(String matchId, Role role, List descri return sb.toString(); } - + public static String getPreviewRequest(List description, int previewClock, GdlScrambler scrambler) { StringBuilder sb = new StringBuilder(); @@ -54,7 +54,7 @@ public static String getPreviewRequest(List description, int previewClock, sb.append(") " + previewClock + " )"); return sb.toString(); - } + } public static String getStopRequest(String matchId, List moves, GdlScrambler scrambler) { @@ -62,23 +62,23 @@ public static String getStopRequest(String matchId, List moves, GdlScrambl return "( STOP " + matchId + " NIL )"; } else { StringBuilder sb = new StringBuilder(); - + sb.append("( STOP " + matchId + " ("); for (Move move : moves) { sb.append(scrambler.scramble(move.getContents()) + " "); } sb.append(") )"); - + return sb.toString(); } } - + public static String getAbortRequest(String matchId) { return "( ABORT " + matchId + " )"; } - + public static String getInfoRequest() { return "( INFO )"; diff --git a/src/org/ggp/base/server/threads/PlayRequestThread.java b/src/org/ggp/base/server/threads/PlayRequestThread.java index a03640df5..a57692bc3 100644 --- a/src/org/ggp/base/server/threads/PlayRequestThread.java +++ b/src/org/ggp/base/server/threads/PlayRequestThread.java @@ -21,7 +21,7 @@ public class PlayRequestThread extends RequestThread private final List legalMoves; private final Match match; private final Role role; - + private Move move; public PlayRequestThread(GameServer gameServer, Match match, List previousMoves, List legalMoves, Role role, String host, int port, String playerName, boolean unlimitedTime) @@ -34,12 +34,12 @@ public PlayRequestThread(GameServer gameServer, Match match, List previous move = legalMoves.get(new Random().nextInt(legalMoves.size())); } - + public Move getMove() { return move; } - + @Override protected void handleResponse(String response) { try { diff --git a/src/org/ggp/base/server/threads/PreviewRequestThread.java b/src/org/ggp/base/server/threads/PreviewRequestThread.java index d390be738..fda417456 100644 --- a/src/org/ggp/base/server/threads/PreviewRequestThread.java +++ b/src/org/ggp/base/server/threads/PreviewRequestThread.java @@ -12,7 +12,7 @@ public PreviewRequestThread(GameServer gameServer, Match match, Role role, Strin { super(gameServer, role, host, port, playerName, match.getPreviewClock() * 1000, RequestBuilder.getPreviewRequest(match.getGame().getRules(), match.getPreviewClock(), match.getGdlScrambler())); } - + @Override protected void handleResponse(String response) { ; diff --git a/src/org/ggp/base/server/threads/RequestThread.java b/src/org/ggp/base/server/threads/RequestThread.java index 64e33a9e4..5ca6f0db0 100644 --- a/src/org/ggp/base/server/threads/RequestThread.java +++ b/src/org/ggp/base/server/threads/RequestThread.java @@ -18,8 +18,8 @@ * with that host, a timeout, a game server to report connection issues to, * et cetera. This framework does the usual setup and try-catch responding so * that the concrete RequestThread subclasses can focus on request-specific - * business logic. - * + * business logic. + * * @author schreib */ public abstract class RequestThread extends Thread @@ -31,7 +31,7 @@ public abstract class RequestThread extends Thread private final int timeout; private final Role role; private final String request; - + public RequestThread(GameServer gameServer, Role role, String host, int port, String playerName, int timeout, String request) { this.gameServer = gameServer; @@ -44,12 +44,12 @@ public RequestThread(GameServer gameServer, Role role, String host, int port, St } protected abstract void handleResponse(String response); - + @Override public void run() { try { - String response = HttpRequest.issueRequest(host, port, playerName, request, timeout); + String response = HttpRequest.issueRequest(host, port, playerName, request, timeout); handleResponse(response); } catch (SocketTimeoutException e) { gameServer.notifyObservers(new ServerTimeoutEvent(role)); diff --git a/src/org/ggp/base/server/threads/StartRequestThread.java b/src/org/ggp/base/server/threads/StartRequestThread.java index 2b82de027..d58377265 100644 --- a/src/org/ggp/base/server/threads/StartRequestThread.java +++ b/src/org/ggp/base/server/threads/StartRequestThread.java @@ -12,7 +12,7 @@ public StartRequestThread(GameServer gameServer, Match match, Role role, String { super(gameServer, role, host, port, playerName, match.getStartClock() * 1000, RequestBuilder.getStartRequest(match.getMatchId(), role, match.getGame().getRules(), match.getStartClock(), match.getPlayClock(), match.getGdlScrambler())); } - + @Override protected void handleResponse(String response) { ; diff --git a/src/org/ggp/base/test/NoTabsInRulesheetsTest.java b/src/org/ggp/base/test/NoTabsInRulesheetsTest.java index c99fe7cfa..8550728c4 100644 --- a/src/org/ggp/base/test/NoTabsInRulesheetsTest.java +++ b/src/org/ggp/base/test/NoTabsInRulesheetsTest.java @@ -17,35 +17,35 @@ public class NoTabsInRulesheetsTest extends Assert { public void testNoTabsInRulesheets() { File testGamesFolder = new File("games", "test"); assertTrue(testGamesFolder.isDirectory()); - + for (File gameFile : testGamesFolder.listFiles(new KifFileFilter())) { String fileContents = FileUtils.readFileAsString(gameFile); assertFalse("The game "+gameFile+" contains tabs. Run the main method in NoTabsInRulesheetsTest to fix this.", fileContents.contains("\t")); } } - + // Modify the test games to use spaces instead of tabs. public static void main(String[] args) throws Exception { File testGamesFolder = new File("games", "test"); assertTrue(testGamesFolder.isDirectory()); - + for (File gameFile : testGamesFolder.listFiles(new KifFileFilter())) { String fileContents = FileUtils.readFileAsString(gameFile); String newContents = fileContents.replaceAll("\t", " "); //four spaces overwriteFileWithString(gameFile, newContents); } } - + static void overwriteFileWithString(File file, String newContents) throws IOException { BufferedWriter writer = new BufferedWriter(new FileWriter(file)); writer.append(newContents); writer.close(); } - + static class KifFileFilter implements FileFilter { @Override public boolean accept(File pathname) { return pathname.getName().endsWith(".kif"); } - } + } } diff --git a/src/org/ggp/base/test/ProverStateMachineTests.java b/src/org/ggp/base/test/ProverStateMachineTests.java index 5ef6d95e4..df04d3a07 100644 --- a/src/org/ggp/base/test/ProverStateMachineTests.java +++ b/src/org/ggp/base/test/ProverStateMachineTests.java @@ -141,7 +141,7 @@ public void testCase5B() throws Exception { state = sm.getNextState(state, Collections.singletonList(move("draw 1 1 1 2"))); assertTrue(sm.isTerminal(state)); } - + @Test public void testCase5C() throws Exception { List desc = new TestGameRepository().getGame("test_case_5c").getRules(); @@ -156,7 +156,7 @@ public void testCase5C() throws Exception { assertEquals(100, sm.getGoal(state, you)); assertEquals(Collections.singletonList(100), sm.getGoals(state)); } - + protected Move move(String description) { String[] parts = description.split(" "); GdlConstant head = GdlPool.getConstant(parts[0]); diff --git a/src/org/ggp/base/util/configuration/GamerConfiguration.java b/src/org/ggp/base/util/configuration/GamerConfiguration.java index 190597986..7a532e3ec 100644 --- a/src/org/ggp/base/util/configuration/GamerConfiguration.java +++ b/src/org/ggp/base/util/configuration/GamerConfiguration.java @@ -2,23 +2,23 @@ * GamerConfiguration handles machine/OS-specific details, so that these * details don't end up hard-coded into the gamer itself. Currently, these * details include: - * + * * > Locations of the "java" and "javac" binaries, independent of OS. - * + * * > Amounts of RAM to allocate to the gamer when running in Proxy mode, * based on the name of the system it's running on. - * + * * Machine-specific profiles are stored in an optional "gamerProfiles" file, * which has the following format: - * + * * (system name) (allocated RAM in MB) (proper name) - * + * * When the program begins, GamerConfiguration will automatically determine * which profile is applicable, and which operating system is running. From * then on, it can be called upon to provide information. If you want to add * a default profile, add an entry with (system name) equal to "*", and when * none of the earlier profiles match, that profile will be used. - * + * * @author Sam Schreiber */ @@ -34,11 +34,11 @@ public class GamerConfiguration { private static String strProfileName; private static int nMemoryForGamer; // in MB private static int nOperatingSystem; - + private static final int OS_WINDOWS = 1; private static final int OS_MACOS = 2; private static final int OS_LINUX = 3; - + public static void showConfiguration() { String osType = "Unknown"; if(runningOnLinux()) osType = "Linux"; @@ -46,25 +46,25 @@ public static void showConfiguration() { if(runningOnWindows()) osType = "Windows"; System.out.println(String.format("Configured according to the %s Profile, running on %s which is a variety of %s, allocating %d MB of memory to the gaming process.", strProfileName, strSystemOS, osType, nMemoryForGamer)); } - + private static String getComputerName() { try { return InetAddress.getLocalHost().getHostName().toLowerCase(); } catch (Exception e) { return null; - } + } } - + static { strProfileName = getComputerName(); - + boolean foundProfile = false; try { String line; BufferedReader in = new BufferedReader(new FileReader("src/org/ggp/base/util/configuration/gamerProfiles")); while((line = in.readLine()) != null) { if(line.length() == 0) continue; - if(line.charAt(0) == '#') continue; + if(line.charAt(0) == '#') continue; String[] splitLine = line.split("\\s+"); if(splitLine[0].equals(strProfileName)) { nMemoryForGamer = Integer.parseInt(splitLine[1]); @@ -84,12 +84,12 @@ private static String getComputerName() { } catch (Exception e) { e.printStackTrace(); } - + if(!foundProfile) { nMemoryForGamer = 1000; strProfileName = "Default"; } - + strSystemOS = System.getProperty("os.name"); if(strSystemOS.contains("Linux")) { nOperatingSystem = OS_LINUX; @@ -101,7 +101,7 @@ private static String getComputerName() { ; } } - + // OS-neutral accessors public static String getCommandForJava() { @@ -110,8 +110,8 @@ public static String getCommandForJava() { } else { return "java"; } - } - + } + public static String getCommandForJavac() { if(nOperatingSystem == OS_MACOS) { return "/System/Library/Frameworks/JavaVM.framework/Versions/1.6.0/Commands/javac"; @@ -119,13 +119,13 @@ public static String getCommandForJavac() { return "javac"; } } - + // Accessors - + public static boolean runningOnLinux () { return nOperatingSystem == OS_LINUX; } - + public static boolean runningOnMacOS () { return nOperatingSystem == OS_MACOS; } @@ -133,19 +133,19 @@ public static boolean runningOnMacOS () { public static boolean runningOnWindows () { return nOperatingSystem == OS_WINDOWS; } - + public static String getOperatingSystemName() { return strSystemOS; } - + public static String getProfileName() { return strProfileName; } - + public static int getMemoryForGamer() { return nMemoryForGamer; - } - + } + public static void main(String args[]) { System.out.println("Computer name: " + getComputerName()); GamerConfiguration.showConfiguration(); diff --git a/src/org/ggp/base/util/configuration/ProjectConfiguration.java b/src/org/ggp/base/util/configuration/ProjectConfiguration.java index 5b31e6672..72c1f296e 100644 --- a/src/org/ggp/base/util/configuration/ProjectConfiguration.java +++ b/src/org/ggp/base/util/configuration/ProjectConfiguration.java @@ -12,6 +12,6 @@ public class ProjectConfiguration { /* Game rulesheet repository information */ private static final String gamesRootDirectoryPath = "games"; - + public static final File gameImagesDirectory = new File(new File(gamesRootDirectoryPath, "resources"), "images"); } \ No newline at end of file diff --git a/src/org/ggp/base/util/crypto/BaseCryptography.java b/src/org/ggp/base/util/crypto/BaseCryptography.java index e1057a3ef..1dff84782 100644 --- a/src/org/ggp/base/util/crypto/BaseCryptography.java +++ b/src/org/ggp/base/util/crypto/BaseCryptography.java @@ -23,7 +23,7 @@ public static void main(String args[]) { EncodedKeyPair k = generateKeys(); System.out.println("{\"PK\":\"" + k.thePublicKey + "\", \"SK\":\"" + k.thePrivateKey + "\"}"); } - + public static EncodedKeyPair generateKeys() { try { // Generate a 2048-bit RSA key pair @@ -31,17 +31,17 @@ public static EncodedKeyPair generateKeys() { keyGen.initialize(2048); KeyPair keypair = keyGen.genKeyPair(); PrivateKey privateKey = keypair.getPrivate(); - PublicKey publicKey = keypair.getPublic(); + PublicKey publicKey = keypair.getPublic(); return new EncodedKeyPair(publicKey, privateKey); } catch (NoSuchAlgorithmException e) { return null; } } - + public static String signData(String thePrivateKey, String theData) { PrivateKey theSK = decodePrivateKey(thePrivateKey); if (theSK == null) return null; - + try { Signature sig = Signature.getInstance("SHA1WithRSA"); sig.initSign(theSK); @@ -54,7 +54,7 @@ public static String signData(String thePrivateKey, String theData) { } return null; } - + public static boolean verifySignature(String thePublicKey, String theSignature, String theData) throws SignatureException, NoSuchAlgorithmException, InvalidKeyException, UnsupportedEncodingException { PublicKey thePK = decodePublicKey(thePublicKey); if (thePK == null) throw new SignatureException("Could not reconstruct public key."); @@ -72,7 +72,7 @@ public static boolean verifySignature(String thePublicKey, String theSignature, public static class EncodedKeyPair { public final String thePublicKey; public final String thePrivateKey; - + public EncodedKeyPair(PublicKey thePK, PrivateKey theSK) { thePublicKey = encodeKey(thePK); thePrivateKey = encodeKey(theSK); @@ -82,8 +82,8 @@ public EncodedKeyPair(String theKeyJSON) throws JSONException { thePublicKey = theJSON.getString("PK"); thePrivateKey = theJSON.getString("SK"); } - } - + } + /* Functions for encoding and decoding public and private keys */ private static String encodeKey(PublicKey thePK) { return theCryptographyPrefix + encodeBytes(thePK.getEncoded()); @@ -97,7 +97,7 @@ private static String encodeSignature(byte[] theSignatureBytes) { private static PublicKey decodePublicKey(String thePK) { if (!thePK.startsWith(theCryptographyPrefix)) return null; thePK = thePK.replaceFirst(theCryptographyPrefix, ""); - + try { KeyFactory kf = KeyFactory.getInstance("RSA"); return kf.generatePublic(new X509EncodedKeySpec(decodeBytes(thePK))); @@ -110,7 +110,7 @@ private static PublicKey decodePublicKey(String thePK) { private static PrivateKey decodePrivateKey(String theSK) { if (!theSK.startsWith(theCryptographyPrefix)) return null; theSK = theSK.replaceFirst(theCryptographyPrefix, ""); - + try { KeyFactory kf = KeyFactory.getInstance("RSA"); return kf.generatePrivate(new PKCS8EncodedKeySpec(decodeBytes(theSK))); @@ -122,18 +122,18 @@ private static PrivateKey decodePrivateKey(String theSK) { } private static byte[] decodeSignature(String theSig) { if (!theSig.startsWith(theCryptographyPrefix)) return null; - theSig = theSig.replaceFirst(theCryptographyPrefix, ""); - + theSig = theSig.replaceFirst(theCryptographyPrefix, ""); + return decodeBytes(theSig); } - + static final String theCryptographyPrefix = "0"; - + /* Functions for encoding/decoding arrays of bytes */ private static String encodeBytes(byte[] theBytes) { return new String(Base64Coder.encode(theBytes)); } private static byte[] decodeBytes(String theString) { return Base64Coder.decode(theString); - } + } } \ No newline at end of file diff --git a/src/org/ggp/base/util/crypto/CanonicalJSON.java b/src/org/ggp/base/util/crypto/CanonicalJSON.java index 9dc7cf90f..01ca738bf 100644 --- a/src/org/ggp/base/util/crypto/CanonicalJSON.java +++ b/src/org/ggp/base/util/crypto/CanonicalJSON.java @@ -30,9 +30,9 @@ static String getCanonicalForm(String x, CanonicalizationStrategy s) { return getCanonicalForm(new JSONObject(x), s); } catch (JSONException e) { return null; - } + } } - + /* Main function to generate canonical strings for JSON objects */ static String getCanonicalForm(JSONObject x, CanonicalizationStrategy s) { if (s == CanonicalizationStrategy.SIMPLE) { @@ -41,21 +41,21 @@ static String getCanonicalForm(JSONObject x, CanonicalizationStrategy s) { throw new RuntimeException("Canonicalization strategy not recognized."); } } - + /* This should be identical to the standard code to render the JSON object, * except it forces the keys for maps to be listed in sorted order. */ static String renderSimpleCanonicalJSON(Object x) { try { if (x instanceof JSONObject) { JSONObject theObject = (JSONObject)x; - + // Sort the keys TreeSet t = new TreeSet(); Iterator i = theObject.keys(); while (i.hasNext()) t.add(i.next().toString()); Iterator keys = t.iterator(); - - StringBuffer sb = new StringBuffer("{"); + + StringBuffer sb = new StringBuffer("{"); while (keys.hasNext()) { if (sb.length() > 1) { sb.append(','); @@ -116,6 +116,6 @@ static String renderSimpleCanonicalJSON(Object x) { } } catch (Exception e) { return null; - } + } } } \ No newline at end of file diff --git a/src/org/ggp/base/util/crypto/SignableJSON.java b/src/org/ggp/base/util/crypto/SignableJSON.java index 963cb1755..d73c72f28 100644 --- a/src/org/ggp/base/util/crypto/SignableJSON.java +++ b/src/org/ggp/base/util/crypto/SignableJSON.java @@ -15,33 +15,33 @@ public class SignableJSON { // we can change this prefix to indicate that while still maintaining // backwards compatibility. static final String theCanonicalizationPrefix = "A"; - + public static void signJSON(JSONObject theJSON, String thePK, String theSK) throws JSONException { if (theJSON.has("matchHostPK") || theJSON.has("matchHostSignature")) throw new RuntimeException("Already signed JSON! Cannot sign again."); - + theJSON.put("matchHostPK", thePK); - String theSignature = BaseCryptography.signData(theSK, CanonicalJSON.getCanonicalForm(theJSON, CanonicalizationStrategy.SIMPLE)); + String theSignature = BaseCryptography.signData(theSK, CanonicalJSON.getCanonicalForm(theJSON, CanonicalizationStrategy.SIMPLE)); theJSON.put("matchHostSignature", theCanonicalizationPrefix + theSignature); } - + public static boolean isSignedJSON(JSONObject theJSON) throws JSONException { if (theJSON.has("matchHostPK") && theJSON.has("matchHostSignature")) return true; return false; } - + public static boolean verifySignedJSON(JSONObject theJSON) throws JSONException { if (!theJSON.has("matchHostPK") || !theJSON.has("matchHostSignature")) throw new RuntimeException("JSON not signed! Cannot verify."); - + String thePK = theJSON.getString("matchHostPK"); - + String theSignature = theJSON.getString("matchHostSignature"); if (!theSignature.startsWith(theCanonicalizationPrefix)) return false; theSignature = theSignature.replaceFirst(theCanonicalizationPrefix, ""); - + JSONObject tempObject = new JSONObject(theJSON.toString()); tempObject.remove("matchHostSignature"); try { diff --git a/src/org/ggp/base/util/crypto/Test_BaseCryptography.java b/src/org/ggp/base/util/crypto/Test_BaseCryptography.java index c8ebafbfa..721bd82b9 100644 --- a/src/org/ggp/base/util/crypto/Test_BaseCryptography.java +++ b/src/org/ggp/base/util/crypto/Test_BaseCryptography.java @@ -8,7 +8,7 @@ * Unit tests for the BaseCryptography class, which implements * a wrapper for the use of asymmetric public/private key cryptography * for use in GGP. - * + * * @author Sam */ public class Test_BaseCryptography extends TestCase { @@ -18,10 +18,10 @@ public void testSimpleCryptography() throws Exception { EncodedKeyPair theKeys = BaseCryptography.generateKeys(); String theSK = theKeys.thePrivateKey; String thePK = theKeys.thePublicKey; - + String theData = "Hello world!"; - String theSignature = BaseCryptography.signData(theSK, theData); + String theSignature = BaseCryptography.signData(theSK, theData); assertTrue(BaseCryptography.verifySignature(thePK, theSignature, theData)); } - + } \ No newline at end of file diff --git a/src/org/ggp/base/util/crypto/Test_CanonicalJSON.java b/src/org/ggp/base/util/crypto/Test_CanonicalJSON.java index 85583343c..820680260 100644 --- a/src/org/ggp/base/util/crypto/Test_CanonicalJSON.java +++ b/src/org/ggp/base/util/crypto/Test_CanonicalJSON.java @@ -8,20 +8,20 @@ * Unit tests for the CanonicalJSON class, which provides a * standard way for GGP systems to canonicalize JSON objects. * This is an important step in signing JSON objects. - * + * * @author Sam */ public class Test_CanonicalJSON extends TestCase { public void testSimpleCanonicalization() { CanonicalizationStrategy theStrategy = CanonicalizationStrategy.SIMPLE; - + String a = CanonicalJSON.getCanonicalForm("{1:2,2:3,3:{2:5,c:4,7:9,a:6}}", theStrategy); assertEquals(a, CanonicalJSON.getCanonicalForm("{2:3,3:{c:4,7:9,2:5,a:6},1:2}", theStrategy)); assertEquals(a, CanonicalJSON.getCanonicalForm("{3:{c:4,7:9,2:5,a:6},2:3,1:2}", theStrategy)); assertEquals(a, CanonicalJSON.getCanonicalForm("{3:{7:9,c:4,2:5,a:6},1:2,2:3}", theStrategy)); assertEquals(a, CanonicalJSON.getCanonicalForm("{2:3,3:{c:4,7:9,a:6,2:5},1:2}", theStrategy)); assertEquals(a, "{\"1\":2,\"2\":3,\"3\":{\"2\":5,\"7\":9,\"a\":6,\"c\":4}}"); - + String b = CanonicalJSON.getCanonicalForm("{'abc':3, \"def\":4, ghi:5}", theStrategy); assertEquals(b, CanonicalJSON.getCanonicalForm("{'def':4, abc:3, \"ghi\":5}", theStrategy)); assertEquals(b, CanonicalJSON.getCanonicalForm("{\"def\":4, ghi:5, 'abc':3}", theStrategy)); diff --git a/src/org/ggp/base/util/crypto/Test_SignableJSON.java b/src/org/ggp/base/util/crypto/Test_SignableJSON.java index 9bc677488..7d5966537 100644 --- a/src/org/ggp/base/util/crypto/Test_SignableJSON.java +++ b/src/org/ggp/base/util/crypto/Test_SignableJSON.java @@ -10,23 +10,23 @@ * Unit tests for the SignableJSON class, which provides an easy way * for code to sign JSON objects using PK/SK pairs, and check whether * a particular object has been signed. - * + * * @author Sam */ public class Test_SignableJSON extends TestCase { public void testSimpleSigning() throws JSONException { EncodedKeyPair p = BaseCryptography.generateKeys(); - + JSONObject x = new JSONObject("{3:{7:9,c:4,2:5,a:6},1:2,2:3,moves:14,states:21,alpha:'beta'}"); assertFalse(SignableJSON.isSignedJSON(x)); SignableJSON.signJSON(x, p.thePublicKey, p.thePrivateKey); assertTrue(SignableJSON.isSignedJSON(x)); assertTrue(SignableJSON.verifySignedJSON(x)); - + JSONObject x2 = new JSONObject(x.toString().replace(",", ", ").replace("{", "{ ").replace("}", "} ")); assertTrue(SignableJSON.isSignedJSON(x2)); assertTrue(SignableJSON.verifySignedJSON(x2)); - + JSONObject x3 = new JSONObject("{1:2,2:3,3:4}"); assertFalse(SignableJSON.isSignedJSON(x3)); } diff --git a/src/org/ggp/base/util/files/FileUtils.java b/src/org/ggp/base/util/files/FileUtils.java index 53ae47c7f..083431a36 100644 --- a/src/org/ggp/base/util/files/FileUtils.java +++ b/src/org/ggp/base/util/files/FileUtils.java @@ -7,7 +7,7 @@ import java.io.IOException; public class FileUtils { - /** + /** * @param filePath the name of the file to open. */ public static String readFileAsString(File file) { diff --git a/src/org/ggp/base/util/game/CloudGameRepository.java b/src/org/ggp/base/util/game/CloudGameRepository.java index 4bf0f845c..81e3fd2f6 100644 --- a/src/org/ggp/base/util/game/CloudGameRepository.java +++ b/src/org/ggp/base/util/game/CloudGameRepository.java @@ -21,7 +21,7 @@ * repository servers on the web, while continuing to work while the user is * offline through aggressive caching based on the immutability + versioning * scheme provided by the repository servers. - * + * * Essentially, each game has a version number stored in the game metadata * file. Game resources are immutable until this version number changes, at * which point the game needs to be reloaded. Version numbers are passed along @@ -31,31 +31,31 @@ * to worry about our offline cache becoming stale/invalid. However, to stay up * to date with the latest bugfixes, etc, we aggressively refresh the cache any * time we can connect to the repository server, as a matter of policy. - * + * * Cached games are stored locally, in a directory managed by this class. These * files are compressed, to decrease their footprint on the local disk. GGP Base - * has its SVN rules set up so that these caches are ignored by SVN. - * + * has its SVN rules set up so that these caches are ignored by SVN. + * * @author Sam */ public final class CloudGameRepository extends GameRepository { private final String theRepoURL; private final File theCacheDirectory; private static boolean needsRefresh = true; - + public CloudGameRepository(String theURL) { theRepoURL = RemoteGameRepository.properlyFormatURL(theURL); - + // Generate a unique hash of the repository URL, to use as the // local directory for files for the offline cache. StringBuilder theCacheHash = new StringBuilder(); try { byte[] bytesOfMessage = theRepoURL.getBytes("UTF-8"); MessageDigest md = MessageDigest.getInstance("MD5"); - byte[] theDigest = md.digest(bytesOfMessage); + byte[] theDigest = md.digest(bytesOfMessage); for(int i = 0; i < theDigest.length; i++) { theCacheHash.append(Math.abs(theDigest[i])); - } + } } catch(Exception e) { theCacheHash = null; } @@ -65,15 +65,15 @@ public CloudGameRepository(String theURL) { theCacheDirectory = new File(theCachesDirectory, "repoHash" + theCacheHash); if (theCacheDirectory.exists()) { // For existing caches, only force a full refresh at most once per day - needsRefresh = (System.currentTimeMillis() - theCacheDirectory.lastModified()) > 86400000; - } else { + needsRefresh = (System.currentTimeMillis() - theCacheDirectory.lastModified()) > 86400000; + } else { theCacheDirectory.mkdir(); needsRefresh = true; } if (needsRefresh) { Thread refreshThread = new RefreshCacheThread(theRepoURL); - refreshThread.start(); + refreshThread.start(); // Update the game cache asynchronously if there are already games. // Otherwise, force a blocking update. if (theCacheDirectory.listFiles().length == 0) { @@ -87,7 +87,7 @@ public CloudGameRepository(String theURL) { needsRefresh = false; } } - + protected Set getUncachedGameKeys() { Set theKeys = new HashSet(); for(File game : theCacheDirectory.listFiles()) { @@ -95,7 +95,7 @@ protected Set getUncachedGameKeys() { } return theKeys; } - + protected Game getUncachedGame(String theKey) { Game cachedGame = loadGameFromCache(theKey); if (cachedGame != null) { @@ -106,17 +106,17 @@ protected Game getUncachedGame(String theKey) { } // ================================================================ - + // Games are cached asynchronously in their own threads. class RefreshCacheForGameThread extends Thread { RemoteGameRepository theRepository; String theKey; - + public RefreshCacheForGameThread(RemoteGameRepository a, String b) { theRepository = a; theKey = b; } - + @Override public void run() { try { @@ -142,16 +142,16 @@ public void run() { } } } - + class RefreshCacheThread extends Thread { String theRepoURL; - + public RefreshCacheThread(String theRepoURL) { this.theRepoURL = theRepoURL; } - + @Override - public void run() { + public void run() { try { // Sleep for the first two seconds after which the cache is loaded, // so that we don't interfere with the user interface startup. @@ -164,14 +164,14 @@ public void run() { RemoteGameRepository remoteRepository = new RemoteGameRepository(theRepoURL); System.out.println("Updating the game cache..."); - long beginTime = System.currentTimeMillis(); + long beginTime = System.currentTimeMillis(); // Since games are immutable, we can guarantee that the games listed // by the repository server includes the games in the local cache, so // we can be happy just updating/refreshing the listed games. Set theGameKeys = remoteRepository.getGameKeys(); if (theGameKeys == null) return; - + // If the server offers a single combined metadata file, download that // and use it to avoid checking games that haven't gotten new versions. JSONObject bundledMetadata = remoteRepository.getBundledMetadata(); @@ -181,7 +181,7 @@ public void run() { try { Game myGameVersion = loadGameFromCache(theKey); if (myGameVersion == null) - continue; + continue; String remoteGameURL = remoteRepository.getGameURL(theKey); int remoteVersion = bundledMetadata.getJSONObject(theKey).getInt("version"); @@ -195,7 +195,7 @@ public void run() { } } catch (Exception e) { continue; - } + } } theGameKeys.removeAll(unchangedKeys); } @@ -219,15 +219,15 @@ public void run() { } long endTime = System.currentTimeMillis(); - System.out.println("Updating the game cache took: " + (endTime - beginTime) + "ms."); + System.out.println("Updating the game cache took: " + (endTime - beginTime) + "ms."); } - } - - // ================================================================ + } + + // ================================================================ private synchronized void saveGameToCache(String theKey, Game theGame) { if (theGame == null) return; - + File theGameFile = new File(theCacheDirectory, theKey + ".zip"); try { theGameFile.createNewFile(); @@ -240,12 +240,12 @@ private synchronized void saveGameToCache(String theKey, Game theGame) { gOut.close(); fOut.close(); } catch (Exception e) { - e.printStackTrace(); + e.printStackTrace(); } } - + private synchronized Game loadGameFromCache(String theKey) { - File theGameFile = new File(theCacheDirectory, theKey + ".zip"); + File theGameFile = new File(theCacheDirectory, theKey + ".zip"); String theLine = null; try { FileInputStream fIn = new FileInputStream(theGameFile); @@ -260,11 +260,11 @@ private synchronized Game loadGameFromCache(String theKey) { } catch (Exception e) { ; } - + if (theLine == null) return null; return Game.loadFromJSON(theLine); } - + private synchronized long getCacheEntryAge(String theKey) { File theGameFile = new File(theCacheDirectory, theKey + ".zip"); if (theGameFile.exists()) { @@ -274,7 +274,7 @@ private synchronized long getCacheEntryAge(String theKey) { } // ================================================================ - + public static void main(String[] args) { GameRepository theRepository = new CloudGameRepository("games.ggp.org/base"); @@ -282,10 +282,10 @@ public static void main(String[] args) { Map theGames = new HashMap(); for(String gameKey : theRepository.getGameKeys()) { - theGames.put(gameKey, theRepository.getGame(gameKey)); + theGames.put(gameKey, theRepository.getGame(gameKey)); } System.out.println("Games: " + theGames.size()); - + long endTime = System.currentTimeMillis(); System.out.println("Time: " + (endTime - beginTime) + "ms."); } diff --git a/src/org/ggp/base/util/game/Game.java b/src/org/ggp/base/util/game/Game.java index 8907d92ed..dd61e7c83 100644 --- a/src/org/ggp/base/util/game/Game.java +++ b/src/org/ggp/base/util/game/Game.java @@ -17,21 +17,21 @@ * like Chess or Connect Four. This information includes the game's rules and * stylesheet, and maybe a human-readable description, and also any available * metadata, like the game's name and its associated game repository URL. - * + * * Games do not necessarily have all of these fields. Games loaded from local * storage will not have a repository URL, and probably will be missing other * metadata as well. Games sent over the wire from a game server rather than * loaded from a repository are called "ephemeral" games, and contain only * their rulesheet; they have no metadata, and do not even have unique keys. - * + * * Aside from ephemeral games, all games have a key that is unique within their * containing repository (either local storage or a remote repository). Games * can be indexed internally using this key. Whenever possible, the user should * be shown the game's name (if available) rather than the internal key, since * the game's name is more readable/informative than the key. - * + * * (e.g. A game with the name "Three-Player Free-For-All" but the key "3pffa".) - * + * * NOTE: Games are different from matches. Games represent the actual game * being played, whereas matches are particular instances in which players * played through the game. For example, you might have a Game object that @@ -43,20 +43,20 @@ * when everything happened, how the match was configured, and so on. There * can be many Match objects all associated with a single Game object, just * as there can be many matches played of a particular game. - * + * * NOTE: Games operate only on "processed" rulesheets, which have been stripped * of comments and are properly formatted as SymbolLists. Rulesheets which have * not been processed in this fashion will break the Game object. This processing * can be done by calling "Game.preprocessRulesheet" on the raw rulesheet. Note * that rules transmitted over the network are always processed. - * + * * @author Sam */ public final class Game { private final String theKey; private final String theName; - private final String theDescription; + private final String theDescription; private final String theRepositoryURL; private final String theStylesheet; private final String theRulesheet; @@ -93,11 +93,11 @@ public String getDescription() { public String getStylesheet() { return theStylesheet; } - + public String getRulesheet() { return theRulesheet; } - + /** * Pre-process a rulesheet into the standard form. This involves stripping * comments and adding opening and closing parens so that the rulesheet is @@ -105,7 +105,7 @@ public String getRulesheet() { * the local disk or a repository server. This is always done to rulesheets * before they're stored in Game objects or sent over the network as part * of a START request. - * + * * @param raw rulesheet * @return processed rulesheet */ @@ -121,10 +121,10 @@ public static String preprocessRulesheet(String rawRulesheet) { rulesheetBuilder.append(" "); } String processedRulesheet = rulesheetBuilder.toString(); - + // Add opening and closing parens for parsing as symbol list. processedRulesheet = "( " + processedRulesheet + " )"; - + return processedRulesheet; } @@ -137,7 +137,7 @@ public static String preprocessRulesheet(String rawRulesheet) { * state machine is initialized -- as a result it's actually better to only parse * the rules when they're needed rather than parsing them for every game when the * game repository is created. - * + * * @return */ public List getRules() { @@ -155,9 +155,9 @@ public List getRules() { } catch (SymbolFormatException e) { e.printStackTrace(); return null; - } + } } - + public String serializeToJSON() { try { JSONObject theGameObject = new JSONObject(); @@ -167,28 +167,28 @@ public String serializeToJSON() { theGameObject.put("theRepositoryURL", getRepositoryURL()); theGameObject.put("theStylesheet", getStylesheet()); theGameObject.put("theRulesheet", getRulesheet()); - + return theGameObject.toString(); } catch(Exception e) { e.printStackTrace(); return null; } } - + public static Game loadFromJSON(String theSerializedGame) { try { JSONObject theGameObject = new JSONObject(theSerializedGame); - + String theKey = null; try { theKey = theGameObject.getString("theKey"); } catch (Exception e) {} - + String theName = null; try { theName = theGameObject.getString("theName"); } catch (Exception e) {} - + String theDescription = null; try { theDescription = theGameObject.getString("theDescription"); @@ -198,7 +198,7 @@ public static Game loadFromJSON(String theSerializedGame) { try { theRepositoryURL = theGameObject.getString("theRepositoryURL"); } catch (Exception e) {} - + String theStylesheet = null; try { theStylesheet = theGameObject.getString("theStylesheet"); @@ -208,11 +208,11 @@ public static Game loadFromJSON(String theSerializedGame) { try { theRulesheet = theGameObject.getString("theRulesheet"); } catch (Exception e) {} - + return new Game(theKey, theName, theDescription, theRepositoryURL, theStylesheet, theRulesheet); } catch(Exception e) { e.printStackTrace(); return null; - } + } } } \ No newline at end of file diff --git a/src/org/ggp/base/util/game/GameRepository.java b/src/org/ggp/base/util/game/GameRepository.java index 74a5919d9..abc74223e 100644 --- a/src/org/ggp/base/util/game/GameRepository.java +++ b/src/org/ggp/base/util/game/GameRepository.java @@ -8,18 +8,18 @@ * Game repositories contain games, and provide two main services: you can * query a repository to get a list of available games (by key), and given * a key, you can look up the associated Game object. - * + * * All queries to a game repository are cached, and the caching is handled * in this abstract base class. Concrete subclasses will implement the actual * behavior required for fetching games from the underlying repositories. - * + * * @author Sam */ public abstract class GameRepository { public static GameRepository getDefaultRepository() { return new CloudGameRepository("games.ggp.org/base"); } - + public Game getGame(String theKey) { if (!theGames.containsKey(theKey)) { Game theGame = getUncachedGame(theKey); @@ -36,12 +36,12 @@ public Set getGameKeys() { } return theGameKeys; } - + // Abstract methods, for implementation classes. protected abstract Game getUncachedGame(String theKey); protected abstract Set getUncachedGameKeys(); - + // Cached values, lazily filled. private Set theGameKeys; - private Map theGames = new HashMap(); + private Map theGames = new HashMap(); } \ No newline at end of file diff --git a/src/org/ggp/base/util/game/LocalGameRepository.java b/src/org/ggp/base/util/game/LocalGameRepository.java index e636b685f..994a45229 100644 --- a/src/org/ggp/base/util/game/LocalGameRepository.java +++ b/src/org/ggp/base/util/game/LocalGameRepository.java @@ -26,16 +26,16 @@ * web-based GGP.org infrastructure, this starts a simple HTTP server that * provides access to the local game resources, and then uses the standard * RemoteGameRepository interface to read from that server. - * + * * @author Sam */ public final class LocalGameRepository extends GameRepository { private static final int REPO_SERVER_PORT = 9140; private static HttpServer theLocalRepoServer = null; private static String theLocalRepoURL = "http://127.0.0.1:" + REPO_SERVER_PORT; - + private static RemoteGameRepository theRealRepo; - + public LocalGameRepository() { if (theLocalRepoServer == null) { try { @@ -47,17 +47,17 @@ public LocalGameRepository() { throw new RuntimeException(e); } } - + theRealRepo = new RemoteGameRepository(theLocalRepoURL); } - + public void cleanUp() { if (theLocalRepoServer != null) { theLocalRepoServer.stop(0); } } - + @Override protected Game getUncachedGame(String theKey) { return theRealRepo.getGame(theKey); @@ -67,9 +67,9 @@ protected Game getUncachedGame(String theKey) { protected Set getUncachedGameKeys() { return theRealRepo.getGameKeys(); } - + // ======================== - + class LocalRepoServer implements HttpHandler { public void handle(HttpExchange t) throws IOException { String theURI = t.getRequestURI().toString(); @@ -77,7 +77,7 @@ public void handle(HttpExchange t) throws IOException { if (response == null) { t.sendResponseHeaders(404, 0); OutputStream os = t.getResponseBody(); - os.close(); + os.close(); } else { t.sendResponseHeaders(200, response.length); OutputStream os = t.getResponseBody(); @@ -85,11 +85,11 @@ public void handle(HttpExchange t) throws IOException { os.close(); } } - } - + } + static class BaseRepository { - public static final String repositoryRootDirectory = theLocalRepoURL; - + public static final String repositoryRootDirectory = theLocalRepoURL; + public static boolean shouldIgnoreFile(String fileName) { if (fileName.startsWith(".")) return true; if (fileName.contains(" ")) return true; @@ -102,7 +102,7 @@ public static byte[] getResponseBytesForURI(String reqURI) throws IOException { if (!reqURI.startsWith("/games/")) { return getBytesForFile(new File("games" + reqURI)); } - + // Provide a listing of all of the metadata files for all of // the games, on request. if (reqURI.equals("/games/metadata")) { @@ -117,25 +117,25 @@ public static byte[] getResponseBytesForURI(String reqURI) throws IOException { } return theGameMetaMap.toString().getBytes(); } - + // Accessing the folder containing a game should show the game's // associated metadata (which includes the contents of the folder). if(reqURI.endsWith("/") && reqURI.length() > 9) { reqURI += "METADATA"; } - + // Extract out the version number String thePrefix = reqURI.substring(0, reqURI.lastIndexOf("/")); String theSuffix = reqURI.substring(reqURI.lastIndexOf("/")+1); Integer theExplicitVersion = null; try { String vPart = thePrefix.substring(thePrefix.lastIndexOf("/v")+2); - theExplicitVersion = Integer.parseInt(vPart); + theExplicitVersion = Integer.parseInt(vPart); thePrefix = thePrefix.substring(0, thePrefix.lastIndexOf("/v")); } catch (Exception e) { ; } - + // Sanity check: raise an exception if the parsing didn't work. if (theExplicitVersion == null) { if (!reqURI.equals(thePrefix + "/" + theSuffix)) { @@ -150,7 +150,7 @@ public static byte[] getResponseBytesForURI(String reqURI) throws IOException { // When no version number is explicitly specified, assume that we want the // latest version, whatever that is. Also, make sure the game version being // requested actually exists (i.e. is between 0 and the max version). - int nMaxVersion = getMaxVersionForDirectory(new File("games", thePrefix)); + int nMaxVersion = getMaxVersionForDirectory(new File("games", thePrefix)); Integer theFetchedVersion = theExplicitVersion; if (theFetchedVersion == null) theFetchedVersion = nMaxVersion; if (theFetchedVersion < 0 || theFetchedVersion > nMaxVersion) return null; @@ -167,14 +167,14 @@ public static byte[] getResponseBytesForURI(String reqURI) throws IOException { } return null; } - + // When the user requests a particular version, the metadata should always be for that version. // When the user requests the latest version, the metadata should always indicate the most recent version. public static byte[] adjustMetadataJSON(String reqURI, byte[] theMetaBytes, Integer nExplicitVersion, int nMaxVersion) throws IOException { try { JSONObject theMetaJSON = new JSONObject(new String(theMetaBytes)); if (nExplicitVersion == null) { - theMetaJSON.put("version", nMaxVersion); + theMetaJSON.put("version", nMaxVersion); } else { theMetaJSON.put("version", nExplicitVersion); } @@ -184,13 +184,13 @@ public static byte[] adjustMetadataJSON(String reqURI, byte[] theMetaBytes, Inte } catch (JSONException je) { throw new IOException(je); } - } - + } + private static int getMaxVersionForDirectory(File theDir) { if (!theDir.exists() || !theDir.isDirectory()) { return -1; } - + int maxVersion = 0; String[] children = theDir.list(); for (String s : children) { @@ -204,7 +204,7 @@ private static int getMaxVersionForDirectory(File theDir) { } return maxVersion; } - + private static byte[] getBytesForVersionedFile(String thePrefix, int theVersion, String theSuffix) { if (theVersion == 0) { return getBytesForFile(new File("games", thePrefix + "/" + theSuffix)); @@ -212,7 +212,7 @@ private static byte[] getBytesForVersionedFile(String thePrefix, int theVersion, return getBytesForFile(new File("games", thePrefix + "/v" + theVersion + "/" + theSuffix)); } } - + private static byte[] getBytesForFile(File theFile) { try { if (!theFile.exists()) { @@ -233,12 +233,12 @@ private static byte[] getBytesForFile(File theFile) { return null; } } - + private static String transformXSL(String theContent) { - // Special case override for XSLT + // Special case override for XSLT return "]>\n\n" + theContent; } - + private static String transformJS(String theContent) throws IOException { // Horrible hack; fix this later. Right now this is used to // let games share a common board user interface, but this should @@ -269,9 +269,9 @@ private static String readDirectory(File theDirectory) throws IOException { response.append("]"); return response.toString(); } - + public static String readFile(File rootFile) throws IOException { - // Show contents of the file. + // Show contents of the file. FileReader fr = new FileReader(rootFile); BufferedReader br = new BufferedReader(fr); try { @@ -286,29 +286,29 @@ public static String readFile(File rootFile) throws IOException { br.close(); } } - + private static byte[] readBinaryFile(File rootFile) throws IOException { InputStream in = new FileInputStream(rootFile); ByteArrayOutputStream out = new ByteArrayOutputStream(); - + // Transfer bytes from in to out byte[] buf = new byte[1024]; while (in.read(buf) > 0) { out.write(buf); } in.close(); - + return out.toByteArray(); } } - + static class MetadataCompleter { /** * Complete fields in the metadata procedurally, based on the game rulesheet. * This is used to fill in the number of roles, and create a list containing * the names of all of the roles. Applications which read the game metadata * can use these without also having to process the rulesheet. - * + * * @param theMetaJSON * @param theRulesheet * @throws JSONException @@ -317,6 +317,6 @@ public static void completeMetadataFromRulesheet(JSONObject theMetaJSON, String List theRoles = Role.computeRoles(Game.createEphemeralGame(Game.preprocessRulesheet(theRulesheet)).getRules()); theMetaJSON.put("roleNames", theRoles); theMetaJSON.put("numRoles", theRoles.size()); - } + } } } \ No newline at end of file diff --git a/src/org/ggp/base/util/game/RemoteGameRepository.java b/src/org/ggp/base/util/game/RemoteGameRepository.java index 7c1d1c174..f0189ef7b 100644 --- a/src/org/ggp/base/util/game/RemoteGameRepository.java +++ b/src/org/ggp/base/util/game/RemoteGameRepository.java @@ -13,20 +13,20 @@ /** * Remote game repositories provide access to game resources stored on game * repository servers on the web. These require a network connection to work. - * + * * @author Sam */ public final class RemoteGameRepository extends GameRepository { private final String theRepoURL; - + public RemoteGameRepository(String theURL) { theRepoURL = properlyFormatURL(theURL); } - + protected Set getUncachedGameKeys() { Set theGameKeys = new HashSet(); - try { - JSONArray theArray = RemoteResourceLoader.loadJSONArray(theRepoURL + "/games/"); + try { + JSONArray theArray = RemoteResourceLoader.loadJSONArray(theRepoURL + "/games/"); for(int i = 0; i < theArray.length(); i++) { theGameKeys.add(theArray.getString(i)); } @@ -35,11 +35,11 @@ protected Set getUncachedGameKeys() { } return theGameKeys; } - + protected Game getUncachedGame(String theKey) { return loadSingleGame(getGameURL(theKey)); } - + public static Game loadSingleGame(String theGameURL) { String[] theSplitURL = theGameURL.split("/"); String theKey = theSplitURL[theSplitURL.length-1]; @@ -49,13 +49,13 @@ public static Game loadSingleGame(String theGameURL) { return loadSingleGameFromMetadata(theKey, theGameURL, theMetadata); } catch (JSONException e) { e.printStackTrace(); - return null; + return null; } catch (IOException e) { e.printStackTrace(); return null; } } - + protected static Game loadSingleGameFromMetadata(String theKey, String theGameURL, JSONObject theMetadata) { // Ensure that the game URL has a version. try { @@ -67,20 +67,20 @@ protected static Game loadSingleGameFromMetadata(String theKey, String theGameUR e.printStackTrace(); return null; } - + String theName = null; try { theName = theMetadata.getString("gameName"); } catch(JSONException e) {} - - String theDescription = getGameResourceFromMetadata(theGameURL, theMetadata, "description"); + + String theDescription = getGameResourceFromMetadata(theGameURL, theMetadata, "description"); String theStylesheet = getGameResourceFromMetadata(theGameURL, theMetadata, "stylesheet"); String theRulesheet = Game.preprocessRulesheet(getGameResourceFromMetadata(theGameURL, theMetadata, "rulesheet")); - + if (theRulesheet == null || theRulesheet.isEmpty()) return null; - return new Game(theKey, theName, theDescription, theGameURL, theStylesheet, theRulesheet); + return new Game(theKey, theName, theDescription, theGameURL, theStylesheet, theRulesheet); } - + JSONObject getBundledMetadata() { try { return RemoteResourceLoader.loadJSON(theRepoURL + "/games/metadata"); @@ -90,16 +90,16 @@ JSONObject getBundledMetadata() { return null; } } - + // ============================================================================================ protected String getGameURL(String theGameKey) { return theRepoURL + "/games/" + theGameKey + "/"; } - + protected static String addVersionToGameURL(String theGameURL, int theVersion) { return theGameURL + "v" + theVersion + "/"; } - + protected static boolean isVersioned(String theGameURL, int theVersion) { return theGameURL.endsWith("/v" + theVersion + "/"); } @@ -107,7 +107,7 @@ protected static boolean isVersioned(String theGameURL, int theVersion) { protected static JSONObject getGameMetadataFromRepository(String theGameURL) throws JSONException, IOException { return RemoteResourceLoader.loadJSON(theGameURL); } - + protected static String getGameResourceFromMetadata(String theGameURL, JSONObject theMetadata, String theResource) { try { String theResourceFile = theMetadata.getString(theResource); @@ -115,8 +115,8 @@ protected static String getGameResourceFromMetadata(String theGameURL, JSONObjec } catch (Exception e) { return null; } - } - + } + static String properlyFormatURL(String theURL) { if (!theURL.startsWith("http://")) theURL = "http://" + theURL; diff --git a/src/org/ggp/base/util/game/TestGameRepository.java b/src/org/ggp/base/util/game/TestGameRepository.java index 593162734..05062fc09 100644 --- a/src/org/ggp/base/util/game/TestGameRepository.java +++ b/src/org/ggp/base/util/game/TestGameRepository.java @@ -10,7 +10,7 @@ /** * Test game repository that provides rulesheet-only access to games with no * associated metadata or other resources, to be used only for unit tests. - * + * * @author Sam */ public final class TestGameRepository extends GameRepository { @@ -22,12 +22,12 @@ protected Set getUncachedGameKeys() { } return theKeys; } - + protected Game getUncachedGame(String theKey) { try { return Game.createEphemeralGame(Game.preprocessRulesheet(FileUtils.readFileAsString(new File("games/test/" + theKey + ".kif")))); } catch (Exception e) { throw new RuntimeException(e); - } + } } } \ No newline at end of file diff --git a/src/org/ggp/base/util/gdl/GdlUtils.java b/src/org/ggp/base/util/gdl/GdlUtils.java index 2decc78dd..5940169cf 100644 --- a/src/org/ggp/base/util/gdl/GdlUtils.java +++ b/src/org/ggp/base/util/gdl/GdlUtils.java @@ -24,7 +24,7 @@ public class GdlUtils { - //TODO (AL): Check if we can switch over to just having this return a set. + //TODO (AL): Check if we can switch over to just having this return a set. public static List getVariables(Gdl gdl) { final List variablesList = new ArrayList(); final Set variables = new HashSet(); @@ -77,7 +77,7 @@ public static List getTupleFromSentence( GdlSentence sentence) { if(sentence instanceof GdlProposition) return Collections.emptyList(); - + //A simple crawl through the sentence. List tuple = new ArrayList(); try { @@ -106,7 +106,7 @@ public static List getTupleFromGroundSentence( GdlSentence sentence) { if(sentence instanceof GdlProposition) return Collections.emptyList(); - + //A simple crawl through the sentence. List tuple = new ArrayList(); try { @@ -130,7 +130,7 @@ private static void addBodyToGroundTuple(List body, List t } } } - + public static Map getAssignmentMakingLeftIntoRight( GdlSentence left, GdlSentence right) { Map assignment = new HashMap(); @@ -169,7 +169,7 @@ private static boolean fillAssignmentBody( return false; } assignment.put((GdlVariable)leftTerm, (GdlConstant)rightTerm); - } + } } else if(leftTerm instanceof GdlFunction) { if(!(rightTerm instanceof GdlFunction)) return false; diff --git a/src/org/ggp/base/util/gdl/GdlValidator.java b/src/org/ggp/base/util/gdl/GdlValidator.java index 3701a8cb8..4707a46b4 100644 --- a/src/org/ggp/base/util/gdl/GdlValidator.java +++ b/src/org/ggp/base/util/gdl/GdlValidator.java @@ -26,7 +26,7 @@ public final class GdlValidator * Note that as implemented, this method is incomplete: it only verifies a * subset of the correctness properties of well-formed Gdl. A more thorough * implementation is advisable. - * + * * @param symbol * The Symbol to validate. * @return True if the Symbol passes validation; false otherwise. @@ -54,7 +54,7 @@ else if ( containsOr(symbol) ) /** * A recursive method that checks whether a Symbol contains SymbolList that * does not begin with a SymbolAtom. - * + * * @param symbol * The Symbol to validate. * @return True if the Symbol passes validation; false otherwise. @@ -89,7 +89,7 @@ private boolean containsAnonymousList(Symbol symbol) /** * A recursive method that checks whether a Symbol contains the deprecated * 'or' keyword. - * + * * @param symbol * The Symbol to validate. * @return True if the Symbol passes validation; false otherwise. diff --git a/src/org/ggp/base/util/gdl/GdlVisitor.java b/src/org/ggp/base/util/gdl/GdlVisitor.java index bc5fbee77..0a6217e91 100644 --- a/src/org/ggp/base/util/gdl/GdlVisitor.java +++ b/src/org/ggp/base/util/gdl/GdlVisitor.java @@ -18,10 +18,10 @@ * A visitor for Gdl objects. The GdlVisitors class has methods for going * through a Gdl object or collection thereof and applying the visitor methods * to all relevant Gdl objects. - * + * * This visitor uses the adapter design pattern, providing empty implementations * of each method so subclasses need only implement the relevant methods. - * + * * @author Alex Landau */ public abstract class GdlVisitor { diff --git a/src/org/ggp/base/util/gdl/GdlVisitors.java b/src/org/ggp/base/util/gdl/GdlVisitors.java index b4cfbe5ba..9fad77221 100644 --- a/src/org/ggp/base/util/gdl/GdlVisitors.java +++ b/src/org/ggp/base/util/gdl/GdlVisitors.java @@ -23,7 +23,7 @@ public class GdlVisitors { * with the given GdlVisitor. For example, when called on a GdlRule, * the visitor's visitConstant function is called once for every * constant anywhere in the head or body of the rule. - * + * * @author Alex Landau */ public static void visitAll(Gdl gdl, GdlVisitor visitor) { diff --git a/src/org/ggp/base/util/gdl/grammar/GdlFunction.java b/src/org/ggp/base/util/gdl/grammar/GdlFunction.java index 97639fd8b..3ddd98b1d 100644 --- a/src/org/ggp/base/util/gdl/grammar/GdlFunction.java +++ b/src/org/ggp/base/util/gdl/grammar/GdlFunction.java @@ -44,7 +44,7 @@ public GdlConstant getName() { return name; } - + public List getBody() { return body; diff --git a/src/org/ggp/base/util/gdl/grammar/GdlRelation.java b/src/org/ggp/base/util/gdl/grammar/GdlRelation.java index 1c397f103..17144566b 100644 --- a/src/org/ggp/base/util/gdl/grammar/GdlRelation.java +++ b/src/org/ggp/base/util/gdl/grammar/GdlRelation.java @@ -79,7 +79,7 @@ public GdlTerm toTerm() { return GdlPool.getFunction(name, body); } - + @Override public List getBody() { diff --git a/src/org/ggp/base/util/gdl/grammar/GdlRule.java b/src/org/ggp/base/util/gdl/grammar/GdlRule.java index c2efab3ac..957142b8a 100644 --- a/src/org/ggp/base/util/gdl/grammar/GdlRule.java +++ b/src/org/ggp/base/util/gdl/grammar/GdlRule.java @@ -44,7 +44,7 @@ public GdlSentence getHead() { return head; } - + public List getBody() { return body; diff --git a/src/org/ggp/base/util/gdl/grammar/GdlSentence.java b/src/org/ggp/base/util/gdl/grammar/GdlSentence.java index 44843eb5f..678594ea1 100644 --- a/src/org/ggp/base/util/gdl/grammar/GdlSentence.java +++ b/src/org/ggp/base/util/gdl/grammar/GdlSentence.java @@ -19,7 +19,7 @@ public abstract class GdlSentence extends GdlLiteral public abstract String toString(); public abstract GdlTerm toTerm(); - + public abstract List getBody(); } diff --git a/src/org/ggp/base/util/gdl/model/DependencyGraphsTest.java b/src/org/ggp/base/util/gdl/model/DependencyGraphsTest.java index 8dbbd49f7..e8849e04f 100644 --- a/src/org/ggp/base/util/gdl/model/DependencyGraphsTest.java +++ b/src/org/ggp/base/util/gdl/model/DependencyGraphsTest.java @@ -13,7 +13,7 @@ public class DependencyGraphsTest { public void testSafeToposort() throws Exception { Set allElements = Sets.newHashSet(1, 2, 3, 4, 5, 6, 7, 8); Multimap graph = HashMultimap.create(); - + graph.put(2, 1); graph.put(3, 2); graph.put(4, 2); @@ -25,7 +25,7 @@ public void testSafeToposort() throws Exception { graph.put(6, 7); graph.put(7, 8); graph.put(8, 3); - + System.out.println(DependencyGraphs.toposortSafe(allElements, graph)); } } diff --git a/src/org/ggp/base/util/gdl/model/GameFlow.java b/src/org/ggp/base/util/gdl/model/GameFlow.java index 04540d133..b04a1ac70 100644 --- a/src/org/ggp/base/util/gdl/model/GameFlow.java +++ b/src/org/ggp/base/util/gdl/model/GameFlow.java @@ -38,14 +38,14 @@ * GameFlow describes the behavior of the sentences in sentence forms that depend * on which turn it is, but not on the actions of the player (past or present). * These include step counters and control markers. - * + * * @author Alex Landau */ public class GameFlow { private static final GdlConstant INIT = GdlPool.getConstant("init"); private static final GdlConstant TRUE = GdlPool.getConstant("true"); private static final GdlConstant NEXT = GdlPool.getConstant("next"); - + private int turnAfterLast; //We end with a loop private List> sentencesTrueByTurn = new ArrayList>(); //The non-constant ones private Set formsControlledByFlow; @@ -56,7 +56,7 @@ public GameFlow(List description) throws InterruptedException { description = GdlCleaner.run(description); description = DeORer.run(description); description = VariableConstrainer.replaceFunctionValuedVariables(description); - + //First we use a sentence model to get the relevant sentence forms SentenceDomainModel model = SentenceDomainModelFactory.createWithCartesianDomains(description); formsControlledByFlow = new HashSet(); @@ -80,7 +80,7 @@ private void solveTurns(SentenceDomainModel model) throws InterruptedException { for(SentenceForm form : constantForms) { functionInfoMap.put(form, FunctionInfoImpl.create(form, constantChecker)); } - + //First we set the "true" values, then we get the forms controlled by the flow... //Use "init" values Set trueFlowSentences = new HashSet(); @@ -95,7 +95,7 @@ private void solveTurns(SentenceDomainModel model) throws InterruptedException { //Go through ordering, adding to trueFlowSentences addSentenceForms(ordering, trueFlowSentences, model, functionInfoMap); sentencesTrueByTurn.add(trueFlowSentences); - + outer : while(true) { //Now we use the "next" values from the previous turn Set sentencesPreviouslyTrue = trueFlowSentences; @@ -121,7 +121,7 @@ private void solveTurns(SentenceDomainModel model) throws InterruptedException { sentencesTrueByTurn.add(trueFlowSentences); } } - + @SuppressWarnings("unchecked") private void addSentenceForms(List ordering, Set trueFlowSentences, @@ -143,11 +143,11 @@ private void addSentenceForms(List ordering, while(asnItr.hasNext()) { Map assignment = asnItr.next(); boolean isGoodAssignment = true; - + GdlSentence transformedHead = CommonTransforms.replaceVariables(head, assignment); if(trueFlowSentences.contains(transformedHead)) asnItr.changeOneInNext(varsInHead, assignment); - + //Go through the conjuncts for(GdlLiteral literal : rule.getBody()) { if(literal instanceof GdlSentence) { @@ -171,7 +171,7 @@ private void addSentenceForms(List ordering, GdlSentence internal = (GdlSentence) ((GdlNot) literal).getBody(); GdlSentence transformed = CommonTransforms.replaceVariables(internal, assignment); SentenceForm conjForm = model.getSentenceForm(transformed); - + if(constantForms.contains(conjForm)) { if(constantChecker.isTrueConstant(transformed)) { isGoodAssignment = false; @@ -184,11 +184,11 @@ private void addSentenceForms(List ordering, asnItr.changeOneInNext(GdlUtils.getVariables(literal), assignment); } } - + } //Nothing else needs attention, really } - + //We've gone through all the conjuncts and are at the //end of the rule if(isGoodAssignment) { @@ -256,15 +256,15 @@ public Set getTurnsConjunctsArePossible(List body) { relevantLiterals.add(literal); } } - + //If none are related to the game flow, then that's it. It can //happen on any turn. //if(relevantLiterals.isEmpty()) //return getCompleteTurnSet(); Set turnsPossible = new HashSet(getCompleteTurnSet()); - + //For each of the relevant literals, we need to see if there are assignments - //such that + //such that for(GdlLiteral literal : relevantLiterals) { List turns = new ArrayList(); if(literal instanceof GdlSentence) { diff --git a/src/org/ggp/base/util/gdl/model/GameFlowTester.java b/src/org/ggp/base/util/gdl/model/GameFlowTester.java index fa5b0599a..aba72439a 100644 --- a/src/org/ggp/base/util/gdl/model/GameFlowTester.java +++ b/src/org/ggp/base/util/gdl/model/GameFlowTester.java @@ -7,7 +7,7 @@ public class GameFlowTester { //This doesn't really "test" the game flow so much as let us //examine it to evaluate it. public static void main(String[] args) throws InterruptedException { - String gameName = "tictactoe"; + String gameName = "tictactoe"; Game theGame = GameRepository.getDefaultRepository().getGame(gameName); GameFlow flow = new GameFlow(theGame.getRules()); diff --git a/src/org/ggp/base/util/gdl/scrambler/GdlRenderer.java b/src/org/ggp/base/util/gdl/scrambler/GdlRenderer.java index fe087dce4..74c76d0f7 100644 --- a/src/org/ggp/base/util/gdl/scrambler/GdlRenderer.java +++ b/src/org/ggp/base/util/gdl/scrambler/GdlRenderer.java @@ -19,13 +19,13 @@ * in the way you'd expect. It can be subclassed to override particular parts * of the rendering scheme; for example, to render GdlConstants scrambled via * a mapping. - * + * * TODO(schreib): Would it ever make sense for this to replace the regular * toString methods in the Gdl objects? - * + * * TODO(schreib): What is the relationship between this and the GdlVisitor * framework that Alex put together? Can they be combined? - * + * * @author Sam Schreiber */ public class GdlRenderer { diff --git a/src/org/ggp/base/util/gdl/scrambler/GdlRenderer_Test.java b/src/org/ggp/base/util/gdl/scrambler/GdlRenderer_Test.java index b4cb7c1d1..de793f865 100644 --- a/src/org/ggp/base/util/gdl/scrambler/GdlRenderer_Test.java +++ b/src/org/ggp/base/util/gdl/scrambler/GdlRenderer_Test.java @@ -9,10 +9,10 @@ /** * Unit tests for the GdlRenderer class, which provides a way * to render Gdl objects as Strings. - * + * * @author Sam */ -public class GdlRenderer_Test extends TestCase { +public class GdlRenderer_Test extends TestCase { /** * One important property for GdlRenderer is that it should generate * an identical rendering as if you had called the toString() method diff --git a/src/org/ggp/base/util/gdl/scrambler/GdlScrambler.java b/src/org/ggp/base/util/gdl/scrambler/GdlScrambler.java index 937999cf2..3cb423dd2 100644 --- a/src/org/ggp/base/util/gdl/scrambler/GdlScrambler.java +++ b/src/org/ggp/base/util/gdl/scrambler/GdlScrambler.java @@ -4,7 +4,7 @@ import org.ggp.base.util.gdl.grammar.Gdl; import org.ggp.base.util.symbol.factory.exceptions.SymbolFormatException; -public interface GdlScrambler { +public interface GdlScrambler { public String scramble(Gdl x); public Gdl unscramble(String x) throws SymbolFormatException, GdlFormatException; public boolean scrambles(); diff --git a/src/org/ggp/base/util/gdl/scrambler/GdlScrambler_Test.java b/src/org/ggp/base/util/gdl/scrambler/GdlScrambler_Test.java index 0b7fb1810..87a87abad 100644 --- a/src/org/ggp/base/util/gdl/scrambler/GdlScrambler_Test.java +++ b/src/org/ggp/base/util/gdl/scrambler/GdlScrambler_Test.java @@ -18,7 +18,7 @@ * Unit tests for the GdlScrambler class, which provides a way * to scramble and unscramble Gdl objects without changing the * underlying physics of the games they represent. - * + * * @author Sam */ public class GdlScrambler_Test extends TestCase { @@ -29,8 +29,8 @@ public class GdlScrambler_Test extends TestCase { */ public void testNoOpScrambler() throws GdlFormatException, SymbolFormatException { runScramblerTest(new NoOpGdlScrambler()); - } - + } + /** * When scrambling is enabled, the "MappingGdlScrambler" is used. This class * systematically replaces all of the constant and variable names in the Gdl @@ -40,7 +40,7 @@ public void testNoOpScrambler() throws GdlFormatException, SymbolFormatException public void testMappingScrambler() throws GdlFormatException, SymbolFormatException { runScramblerTest(new MappingGdlScrambler(new Random())); } - + /** * Furthermore, the mapping scrambler can be initialized with a Random object, * which can be used to ensure deterministic, reproducible scrambling. This can @@ -72,12 +72,12 @@ public void testMappingScramblerConsistency() { } assertEquals(aScrambledRules.toString(), bScrambledRules.toString()); assertEquals(aScrambledRules.toString(), dScrambledRules.toString()); - assertEquals(aScrambledRules.toString(), eScrambledRules.toString()); + assertEquals(aScrambledRules.toString(), eScrambledRules.toString()); assertFalse(aScrambledRules.toString().equals(cScrambledRules.toString())); assertEquals(cScrambledRules.toString(), fScrambledRules.toString()); } - } - + } + private void runScramblerTest(GdlScrambler scrambler) throws SymbolFormatException, GdlFormatException { GameRepository repo = GameRepository.getDefaultRepository(); for (String gameKey : repo.getGameKeys()) { @@ -99,9 +99,9 @@ private void runScramblerTest(GdlScrambler scrambler) throws SymbolFormatExcepti // One important property for any scrambler is that the original // and the unscrambled Gdl must be the same. This guarantees that // the server can correctly unscramble responses from the players. - assertEquals(gameKey, renderedRule, renderedUnscrambledRule); + assertEquals(gameKey, renderedRule, renderedUnscrambledRule); } - + // An important property for any scrambler is that the scrambled rules // have the same physics as the regular rules. For example, the number // of roles in each game should be the same, and the number of facts @@ -112,7 +112,7 @@ private void runScramblerTest(GdlScrambler scrambler) throws SymbolFormatExcepti ProverStateMachine pNormal = new ProverStateMachine(); ProverStateMachine pScrambled = new ProverStateMachine(); pNormal.initialize(game.getRules()); - pScrambled.initialize(theScrambledRules); + pScrambled.initialize(theScrambledRules); assertEquals(gameKey, pNormal.getRoles().size(), pScrambled.getRoles().size()); assertEquals(gameKey, pNormal.getInitialState().getContents().size(), pScrambled.getInitialState().getContents().size()); } diff --git a/src/org/ggp/base/util/gdl/scrambler/MappingGdlScrambler.java b/src/org/ggp/base/util/gdl/scrambler/MappingGdlScrambler.java index 6a65b022b..8e0614cc8 100644 --- a/src/org/ggp/base/util/gdl/scrambler/MappingGdlScrambler.java +++ b/src/org/ggp/base/util/gdl/scrambler/MappingGdlScrambler.java @@ -14,19 +14,19 @@ import org.ggp.base.util.gdl.grammar.GdlVariable; import org.ggp.base.util.symbol.factory.exceptions.SymbolFormatException; -public class MappingGdlScrambler implements GdlScrambler { - private Map scrambleMapping; - private Map unscrambleMapping; +public class MappingGdlScrambler implements GdlScrambler { + private Map scrambleMapping; + private Map unscrambleMapping; private Random random; - + private int scrambledPrefix; private Stack scrambledTokens; - + public MappingGdlScrambler(Random theRandom) { random = theRandom; scrambleMapping = new HashMap(); unscrambleMapping = new HashMap(); - + scrambledPrefix = 0; scrambledTokens = new Stack(); for (String word : WordList.words) { @@ -34,7 +34,7 @@ public MappingGdlScrambler(Random theRandom) { } Collections.shuffle(scrambledTokens, random); } - + private class ScramblingRenderer extends GdlRenderer { @Override protected String renderConstant(GdlConstant constant) { @@ -43,7 +43,7 @@ protected String renderConstant(GdlConstant constant) { @Override protected String renderVariable(GdlVariable variable) { return scrambleWord(variable.toString()); - } + } } private class UnscramblingRenderer extends GdlRenderer { @Override @@ -53,24 +53,24 @@ protected String renderConstant(GdlConstant constant) { @Override protected String renderVariable(GdlVariable variable) { return unscrambleWord(variable.toString()); - } - } - + } + } + @Override public String scramble(Gdl x) { return new ScramblingRenderer().renderGdl(x); } - + @Override public Gdl unscramble(String x) throws SymbolFormatException, GdlFormatException { return GdlFactory.create(new UnscramblingRenderer().renderGdl(GdlFactory.create(x))); } - + @Override public boolean scrambles() { return true; } - + private String scrambleWord(String realWord) { if (!shouldMap(realWord)) { return realWord; @@ -85,7 +85,7 @@ private String scrambleWord(String realWord) { } return scrambleMapping.get(realWord); } - + private String unscrambleWord(String fakeWord) { if (!shouldMap(fakeWord)) { return fakeWord; @@ -107,7 +107,7 @@ private String getRandomWord() { } return scrambledTokens.pop(); } - + private static boolean shouldMap(String token) { if (GdlPool.KEYWORDS.contains(token.toLowerCase())) { return false; diff --git a/src/org/ggp/base/util/gdl/transforms/CondensationIsolator.java b/src/org/ggp/base/util/gdl/transforms/CondensationIsolator.java index 9e36caf58..391e79cad 100644 --- a/src/org/ggp/base/util/gdl/transforms/CondensationIsolator.java +++ b/src/org/ggp/base/util/gdl/transforms/CondensationIsolator.java @@ -95,7 +95,7 @@ public static List run(List description) throws InterruptedException { description = GdlCleaner.run(description); description = DeORer.run(description); description = VariableConstrainer.replaceFunctionValuedVariables(description); - + //How do we define a condensation, and what needs to be true in it? //Definition: A condensation set is a set of conjuncts of a //sentence. diff --git a/src/org/ggp/base/util/gdl/transforms/DeORer.java b/src/org/ggp/base/util/gdl/transforms/DeORer.java index a8ef6238c..7d8e10d38 100644 --- a/src/org/ggp/base/util/gdl/transforms/DeORer.java +++ b/src/org/ggp/base/util/gdl/transforms/DeORer.java @@ -21,11 +21,11 @@ * As a GDL transformer, this class takes in a GDL description of a game, * transforms it in some way, and outputs a new GDL descriptions of a game * which is functionally equivalent to the original game. - * + * * DeORer removes OR rules from the GDL. Technically, these rules shouldn't * be in the GDL in the first place, but it's very straightforward to remove * them, so we do that so that we can handle GDL descriptions that use OR. - * + * * @author Ethan Dreyfuss */ public class DeORer { @@ -48,7 +48,7 @@ public static List run(List description) } return newDesc; } - + private static List> deOr(List rhs) { List> wrapped = new ArrayList>(); wrapped.add(rhs); @@ -68,11 +68,11 @@ private static List> deOr2(List> rhsList) { if(!expandedSomething) { List expandedList = expandFirstOr(lit); - + if(expandedList.size() > 1) { for(Gdl replacement : expandedList) - { + { List newRhs = new ArrayList(rhs); if(!(replacement instanceof GdlLiteral)) throw new RuntimeException("Top level return value is different type of gdl."); GdlLiteral newLit = (GdlLiteral)replacement; @@ -80,10 +80,10 @@ private static List> deOr2(List> rhsList) { rval.add(newRhs); } expandedSomething = true; - break; + break; } } - + i++; } if(!expandedSomething) //If I didn't find anything to expand @@ -91,10 +91,10 @@ private static List> deOr2(List> rhsList) { } else rval.add(rhs); //If I've already expanded this function call - + } - - if(!expandedSomething) + + if(!expandedSomething) return rhsList; else return deOr2(rval); @@ -129,7 +129,7 @@ else if(gdl instanceof GdlOr) rval = new ArrayList(); for(int i=0; i run(List description) throws InterruptedException { SentenceFormModel model = SentenceFormModelFactory.create(description); GdlConstant NEXT = GdlPool.getConstant("next"); - + List nextFormsToReplace = new ArrayList(); //Find the update rules for each "true" statement for(SentenceForm nextForm : model.getSentenceForms()) { @@ -74,7 +74,7 @@ public static List run(List description) throws InterruptedException { } } } - + List newDescription = new ArrayList(description); //Now, replace the next forms for(SentenceForm nextForm : nextFormsToReplace) { diff --git a/src/org/ggp/base/util/gdl/transforms/TransformTester.java b/src/org/ggp/base/util/gdl/transforms/TransformTester.java index 4630ac63a..163c359d7 100644 --- a/src/org/ggp/base/util/gdl/transforms/TransformTester.java +++ b/src/org/ggp/base/util/gdl/transforms/TransformTester.java @@ -9,33 +9,33 @@ /** - * + * * @author Sam Schreiber * */ public class TransformTester { public static void main(String args[]) throws InterruptedException { - + final boolean showDiffs = false; final ProverStateMachine theReference = new ProverStateMachine(); - final ProverStateMachine theMachine = new ProverStateMachine(); - + final ProverStateMachine theMachine = new ProverStateMachine(); + GameRepository theRepository = GameRepository.getDefaultRepository(); for(String gameKey : theRepository.getGameKeys()) { if(gameKey.contains("laikLee")) continue; List description = theRepository.getGame(gameKey).getRules(); List newDescription = description; - + // Choose the transformation(s) to test here description = DeORer.run(description); newDescription = VariableConstrainer.replaceFunctionValuedVariables(description); - + if(description.hashCode() != newDescription.hashCode()) { theReference.initialize(description); theMachine.initialize(newDescription); System.out.println("Detected activation in game " + gameKey + ". Checking consistency: "); StateMachineVerifier.checkMachineConsistency(theReference, theMachine, 10000); - + if(showDiffs) { for(Gdl x : newDescription) { if(!description.contains(x)) @@ -47,6 +47,6 @@ public static void main(String args[]) throws InterruptedException { } } } - } - } + } + } } diff --git a/src/org/ggp/base/util/gdl/transforms/standalone/StandaloneDeORer.java b/src/org/ggp/base/util/gdl/transforms/standalone/StandaloneDeORer.java index 2ba8e1cb6..548443ffa 100644 --- a/src/org/ggp/base/util/gdl/transforms/standalone/StandaloneDeORer.java +++ b/src/org/ggp/base/util/gdl/transforms/standalone/StandaloneDeORer.java @@ -18,10 +18,10 @@ * The standalone version of DeORer can be run as its own program. It * takes a .kif file as input and generates a new .kif file with the * modified output. The new filename is (original name)_DEORED.kif. - * + * * The new file is not intended to be particularly legible; it is * intended mainly for use by other programs. - * + * * @author Alex Landau * */ @@ -35,28 +35,28 @@ public static void main(String[] args) { System.out.println("Please enter the path of a .kif file as an argument."); return; } - + String filename = args[0]; Game theGame = Game.createEphemeralGame(Game.preprocessRulesheet(FileUtils.readFileAsString(new File(filename)))); if (theGame.getRules() == null || theGame.getRules().size() == 0) { System.err.println("Problem reading the file " + filename + " or parsing the GDL."); return; } - + try { new StaticValidator().checkValidity(theGame); } catch (ValidatorException e) { System.err.println("GDL validation error: " + e.toString()); return; } - + List transformedDescription = DeORer.run(theGame.getRules()); String newFilename = filename.substring(0, filename.lastIndexOf(".kif")) + "_DEORED.kif"; - + try { BufferedWriter out = new BufferedWriter(new FileWriter(new File(newFilename))); - + for(Gdl gdl : transformedDescription) { out.write(gdl.toString()); out.newLine(); diff --git a/src/org/ggp/base/util/gdl/transforms/standalone/StandaloneVariableConstrainer.java b/src/org/ggp/base/util/gdl/transforms/standalone/StandaloneVariableConstrainer.java index e9b09c83c..f33f583e3 100644 --- a/src/org/ggp/base/util/gdl/transforms/standalone/StandaloneVariableConstrainer.java +++ b/src/org/ggp/base/util/gdl/transforms/standalone/StandaloneVariableConstrainer.java @@ -18,10 +18,10 @@ * The standalone version of VariableConstrainer can be run as its own * program. It takes a .kif file as input and generates a new .kif file * with the modified output. The new filename is (original name)_VARCONST.kif. - * + * * The new file is not intended to be particularly legible; it is * intended mainly for use by other programs. - * + * * @author Alex Landau * */ @@ -32,28 +32,28 @@ public static void main(String[] args) throws InterruptedException { System.out.println("Please enter the path of a .kif file as an argument."); return; } - + String filename = args[0]; Game theGame = Game.createEphemeralGame(Game.preprocessRulesheet(FileUtils.readFileAsString(new File(filename)))); if (theGame.getRules() == null || theGame.getRules().size() == 0) { System.err.println("Problem reading the file " + filename + " or parsing the GDL."); return; } - + try { new StaticValidator().checkValidity(theGame); } catch (ValidatorException e) { System.err.println("GDL validation error: " + e.toString()); return; } - + List transformedDescription = VariableConstrainer.replaceFunctionValuedVariables(theGame.getRules()); String newFilename = filename.substring(0, filename.lastIndexOf(".kif")) + "_VARCONST.kif"; - + try { BufferedWriter out = new BufferedWriter(new FileWriter(new File(newFilename))); - + for(Gdl gdl : transformedDescription) { out.write(gdl.toString()); out.newLine(); diff --git a/src/org/ggp/base/util/http/HttpReader.java b/src/org/ggp/base/util/http/HttpReader.java index c55e2acdf..1dc106cc8 100644 --- a/src/org/ggp/base/util/http/HttpReader.java +++ b/src/org/ggp/base/util/http/HttpReader.java @@ -10,23 +10,23 @@ public final class HttpReader { // Wrapper methods to support socket timeouts for reading requests/responses. - + public static String readAsClient(Socket socket, int timeout) throws IOException, SocketTimeoutException { socket.setSoTimeout(timeout); return readAsClient(socket); } - + public static String readAsServer(Socket socket, int timeout) throws IOException, SocketTimeoutException { socket.setSoTimeout(timeout); return readAsServer(socket); } - + // Implementations of reading HTTP responses (readAsClient) and // HTTP requests (readAsServer) for the purpose of communicating // with other general game playing systems. - + public static String readAsClient(Socket socket) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream())); @@ -58,16 +58,16 @@ public static String readAsServer(Socket socket) throws IOException throw new IOException("Drop this message at the network layer."); } else { HttpWriter.writeAsServer(socket, ""); - throw new IOException("Unexpected request type: " + requestLine); + throw new IOException("Unexpected request type: " + requestLine); } - + return message; } - + private static String readContentFromPOST(BufferedReader br) throws IOException { String line; int theContentLength = -1; - StringBuilder theContent = new StringBuilder(); + StringBuilder theContent = new StringBuilder(); while ((line = br.readLine()) != null) { if (line.toLowerCase().startsWith("content-length:")) { try { diff --git a/src/org/ggp/base/util/http/HttpRequest.java b/src/org/ggp/base/util/http/HttpRequest.java index 6d1201405..47959f8f3 100644 --- a/src/org/ggp/base/util/http/HttpRequest.java +++ b/src/org/ggp/base/util/http/HttpRequest.java @@ -9,14 +9,14 @@ * HttpRequest is a helper class that encapsulates all of the code necessary * for a match host to issue a long-lived HTTP request to a player, wait for * the response, and return it. This is a key part of the GGP gaming protocol. - * + * * @author schreib */ public final class HttpRequest { public static String issueRequest(String targetHost, int targetPort, String forPlayerName, String requestContent, int timeoutClock) throws IOException { Socket socket = new Socket(); - InetAddress theHost = InetAddress.getByName(targetHost); + InetAddress theHost = InetAddress.getByName(targetHost); socket.connect(new InetSocketAddress(theHost.getHostAddress(), targetPort), 5000); HttpWriter.writeAsClient(socket, theHost.getHostName(), requestContent, forPlayerName); String response = (timeoutClock < 0) ? HttpReader.readAsClient(socket) : HttpReader.readAsClient(socket, timeoutClock); diff --git a/src/org/ggp/base/util/http/HttpWriter.java b/src/org/ggp/base/util/http/HttpWriter.java index 28e0f4c68..837cf9841 100644 --- a/src/org/ggp/base/util/http/HttpWriter.java +++ b/src/org/ggp/base/util/http/HttpWriter.java @@ -10,7 +10,7 @@ public final class HttpWriter public static void writeAsClientGET(Socket socket, String hostField, String data, String playerName) throws IOException { PrintWriter pw = new PrintWriter(socket.getOutputStream()); - + pw.println("GET /" + URLEncoder.encode(data, "UTF-8") + " HTTP/1.0"); pw.println("Accept: text/delim"); pw.println("Host: " + hostField); @@ -18,10 +18,10 @@ public static void writeAsClientGET(Socket socket, String hostField, String data pw.println("Receiver: "+playerName); pw.println(); pw.println(); - + pw.flush(); } - + public static void writeAsClient(Socket socket, String hostField, String data, String playerName) throws IOException { PrintWriter pw = new PrintWriter(socket.getOutputStream()); @@ -35,7 +35,7 @@ public static void writeAsClient(Socket socket, String hostField, String data, S pw.println("Content-Length: " + data.length()); pw.println(); pw.print(data); - + pw.flush(); } diff --git a/src/org/ggp/base/util/http/Test_Http.java b/src/org/ggp/base/util/http/Test_Http.java index 40981def9..ff4802196 100644 --- a/src/org/ggp/base/util/http/Test_Http.java +++ b/src/org/ggp/base/util/http/Test_Http.java @@ -13,8 +13,8 @@ /** * Unit tests for the HttpReader/HttpWriter pair, which are the way that * game players and game servers communicate. Please update these tests - * as needed when bugs are discovered, to prevent regressions. - * + * as needed when bugs are discovered, to prevent regressions. + * * @author Sam */ public class Test_Http extends TestCase { @@ -22,18 +22,18 @@ public void testSimpleEcho() throws IOException { SocketPair testPair = new SocketPair(); doSimpleEchoCheck(testPair, "Hello World", "SamplePlayer"); } - + public void testPathologicalEchos() throws IOException { SocketPair testPair = new SocketPair(); doSimpleEchoCheck(testPair, "", ""); - doSimpleEchoCheck(testPair, "", "SamplePlayer"); + doSimpleEchoCheck(testPair, "", "SamplePlayer"); doSimpleEchoCheck(testPair, "123 456 ^&!*! // 2198725 !@#$%^&*() DATA", "SamplePlayer"); doSimpleEchoCheck(testPair, "abcdefgijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ", "SamplePlayer"); doSimpleEchoCheck(testPair, "Test String", ""); doSimpleEchoCheck(testPair, "Test String", "!@#$%^&*()1234567890"); - doSimpleEchoCheck(testPair, "Test String", "abcdefgijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"); + doSimpleEchoCheck(testPair, "Test String", "abcdefgijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"); } - + public void testGenericPOSTs() throws IOException { SocketPair testPair = new SocketPair(); doClientEchoCheckOverPOST(testPair, "", ""); @@ -41,7 +41,7 @@ public void testGenericPOSTs() throws IOException { doClientEchoCheckOverPOST(testPair, "Test String", "Accept: text/delim\nSender: GAMESERVER"); doClientEchoCheckOverPOST(testPair, "1234567890abcdefgijklmnopqrstuvwxyz!@#$%^&*()1234567890", ""); } - + public void testGenericGETs() throws IOException { SocketPair testPair = new SocketPair(); doClientEchoCheckOverGET(testPair, "", ""); @@ -49,37 +49,37 @@ public void testGenericGETs() throws IOException { doClientEchoCheckOverGET(testPair, "Test String", "Accept: text/delim\nSender: GAMESERVER"); doClientEchoCheckOverGET(testPair, "1234567890abcdefgijklmnopqrstuvwxyz!@#$%^&*()1234567890", ""); } - + // Helper functions for running specific checks. - + private void doSimpleEchoCheck(SocketPair p, String data, String playerName) throws IOException { HttpWriter.writeAsClient(p.client, "", data, playerName); String readData = HttpReader.readAsServer(p.server); assertEquals(readData.toUpperCase(), data.toUpperCase()); - + HttpWriter.writeAsServer(p.server, data); readData = HttpReader.readAsClient(p.client); assertEquals(readData.toUpperCase(), data.toUpperCase()); } - + private void doClientEchoCheckOverPOST(SocketPair p, String data, String headers) throws IOException { writeClientPostHTTP(p.client, headers, data); String readData = HttpReader.readAsServer(p.server); assertEquals(readData.toUpperCase(), data.toUpperCase()); } - + private void doClientEchoCheckOverGET(SocketPair p, String data, String headers) throws IOException { writeClientGetHTTP(p.client, headers, data); String readData = HttpReader.readAsServer(p.server); assertEquals(readData.toUpperCase(), data.toUpperCase()); - } - + } + // Helper functions for testing different types of HTTP interactions. - + private void writeClientPostHTTP(Socket writeOutTo, String headers, String data) throws IOException { BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(writeOutTo.getOutputStream())); PrintWriter pw = new PrintWriter(bw); - + pw.println("POST / HTTP/1.0"); if(headers.length() > 0) pw.println(headers); pw.println("Content-length: " + data.length()); @@ -87,25 +87,25 @@ private void writeClientPostHTTP(Socket writeOutTo, String headers, String data) pw.println(data); pw.flush(); } - + private void writeClientGetHTTP(Socket writeOutTo, String headers, String data) throws IOException { BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(writeOutTo.getOutputStream())); PrintWriter pw = new PrintWriter(bw); - + pw.println("GET /" + URLEncoder.encode(data, "UTF-8") + " HTTP/1.0"); if(headers.length() > 0) pw.println(headers); pw.println("Content-length: 0"); pw.println(); pw.println(); pw.flush(); - } - + } + // Utility class to create a pair of client/server sockets // on the local machine that are connected to each other. private class SocketPair { public Socket client; public Socket server; - + public SocketPair() { // Create a server socket on the first available port. int defaultTestingPort = 13174; @@ -118,7 +118,7 @@ public SocketPair() { defaultTestingPort++; } } while(ss == null); - + try { client = new Socket("127.0.0.1", defaultTestingPort); server = ss.accept(); @@ -126,9 +126,9 @@ public SocketPair() { fail("Could not establish connection: " + e); e.printStackTrace(); } - + assertNotNull(client); - assertNotNull(server); + assertNotNull(server); } - } + } } \ No newline at end of file diff --git a/src/org/ggp/base/util/loader/RemoteResourceLoader.java b/src/org/ggp/base/util/loader/RemoteResourceLoader.java index fa4bb5a48..3871c6dc7 100644 --- a/src/org/ggp/base/util/loader/RemoteResourceLoader.java +++ b/src/org/ggp/base/util/loader/RemoteResourceLoader.java @@ -14,7 +14,7 @@ /** * RemoteResourceLoader loads remotely-stored resources. It can load resources * as raw strings, JSON objects, or JSON arrays. - * + * * @author Sam */ public class RemoteResourceLoader { @@ -24,14 +24,14 @@ public static JSONObject loadJSON(String theURL) throws JSONException, IOExcepti public static JSONObject loadJSON(String theURL, int nMaxAttempts) throws JSONException, IOException { return new JSONObject(loadRaw(theURL, nMaxAttempts)); } - + public static JSONArray loadJSONArray(String theURL) throws JSONException, IOException { return loadJSONArray(theURL, 1); } public static JSONArray loadJSONArray(String theURL, int nMaxAttempts) throws JSONException, IOException { return new JSONArray(loadRaw(theURL, nMaxAttempts)); } - + public static String loadRaw(String theURL) throws IOException { return loadRaw(theURL, 1); } @@ -39,13 +39,13 @@ public static String loadRaw(String theURL, int nMaxAttempts) throws IOException int nAttempt = 0; while(true) { nAttempt++; - try { + try { URL url = new URL(theURL); URLConnection urlConnection = url.openConnection(); urlConnection.setUseCaches(false); urlConnection.setDefaultUseCaches(false); - urlConnection.addRequestProperty("Cache-Control", "no-cache,max-age=0"); - urlConnection.addRequestProperty("Pragma", "no-cache"); + urlConnection.addRequestProperty("Cache-Control", "no-cache,max-age=0"); + urlConnection.addRequestProperty("Pragma", "no-cache"); if (urlConnection.getContentLength() == 0) throw new IOException("Could not load URL: " + theURL); StringBuilder theRawData = new StringBuilder(); @@ -72,7 +72,7 @@ public static String postRawWithTimeout(String theURL, String toPost, int nTimeo OutputStreamWriter out = new OutputStreamWriter(urlConnection.getOutputStream()); out.write(toPost); out.close(); - + BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream())); StringBuilder decodedString = new StringBuilder(); String decodedLine; diff --git a/src/org/ggp/base/util/logging/GamerLogger.java b/src/org/ggp/base/util/logging/GamerLogger.java index f58010721..a964c72d6 100644 --- a/src/org/ggp/base/util/logging/GamerLogger.java +++ b/src/org/ggp/base/util/logging/GamerLogger.java @@ -20,9 +20,9 @@ * Logs are written to directories on a per-game basis. Each logfile represents * a single logical component of the game playing program, identified whenever * the logger is called. - * + * * TODO: More details about specific use examples. - * + * * @author Sam Schreiber */ public class GamerLogger { @@ -33,37 +33,37 @@ public static void emitToConsole(String s) { System.out.print(s); } } - + public static void stopFileLogging() { log("Logger", "Stopped logging to files at: " + new Date()); log("Logger", "LOG SEALED"); writeLogsToFile = false; } - + public static void setSpilloverLogfile(String spilloverFilename) { spilloverLogfile = spilloverFilename; } - + public static void startFileLogging(Match m, String roleName) { writeLogsToFile = true; myDirectory = "logs/" + m.getMatchId() + "-" + roleName; - + new File(myDirectory).mkdirs(); - + log("Logger", "Started logging to files at: " + new Date()); log("Logger", "Game rules: " + m.getGame().getRules()); log("Logger", "Start clock: " + m.getStartClock()); - log("Logger", "Play clock: " + m.getPlayClock()); + log("Logger", "Play clock: " + m.getPlayClock()); } - + public static void setFileToDisplay(String toFile) { filesToDisplay.add(toFile); } - + public static void setMinimumLevelToDisplay(int nLevel) { minLevelToDisplay = nLevel; } - + public static void setSuppressLoggerOutput(boolean bSuppress) { suppressLoggerOutput = bSuppress; } @@ -72,45 +72,45 @@ public static void setSuppressLoggerOutput(boolean bSuppress) { public static final int LOG_LEVEL_ORDINARY = 3; public static final int LOG_LEVEL_IMPORTANT = 6; public static final int LOG_LEVEL_CRITICAL = 9; - + public static void logError(String toFile, String message) { logEntry(System.err, toFile, message, LOG_LEVEL_CRITICAL); if(writeLogsToFile) { logEntry(System.err, "Errors", "(in " + toFile + ") " + message, LOG_LEVEL_CRITICAL); } } - + public static void log(String toFile, String message) { log(toFile, message, LOG_LEVEL_ORDINARY); } - + public static void log(String toFile, String message, int nLevel) { logEntry(System.out, toFile, message, nLevel); - } - + } + public static void logStackTrace(String toFile, Exception ex) { StringWriter s = new StringWriter(); ex.printStackTrace(new PrintWriter(s)); logError(toFile, s.toString()); } - + public static void logStackTrace(String toFile, Error ex) { StringWriter s = new StringWriter(); ex.printStackTrace(new PrintWriter(s)); logError(toFile, s.toString()); - } - - // Private Implementation + } + + // Private Implementation private static boolean writeLogsToFile = false; - + private static final Random theRandom = new Random(); private static final Set filesToSkip = new HashSet(); private static final long maximumLogfileSize = 25 * 1024 * 1024; - + private static void logEntry(PrintStream ordinaryOutput, String toFile, String message, int logLevel) { if(suppressLoggerOutput) return; - + // When we're not writing to a particular directory, and we're not spilling over into // a general logfile, write directly to the standard output unless it is really unimportant. if(!writeLogsToFile && spilloverLogfile == null) { @@ -119,15 +119,15 @@ private static void logEntry(PrintStream ordinaryOutput, String toFile, String m } return; } - + try { String logMessage = logFormat(logLevel, ordinaryOutput == System.err, message); - + // If we are also displaying this file, write it to the standard output. if(filesToDisplay.contains(toFile) || logLevel >= minLevelToDisplay) { ordinaryOutput.println("[" + toFile + "] " + message); } - + // When constructing filename, if we are not writing to a particular directory, // go directly to the spillover file if one exists. String myFilename = myDirectory + "/" + toFile; @@ -147,28 +147,28 @@ private static void logEntry(PrintStream ordinaryOutput, String toFile, String m logLevel = 9; logMessage = logFormat(logLevel, ordinaryOutput == System.err, "File too long; stopping all writes to this file."); } - } - + } + // Finally, write the log message to the file. BufferedWriter out = new BufferedWriter(new FileWriter(myFilename, true)); out.write(logMessage); out.close(); } catch (IOException e) { e.printStackTrace(); - } - } - + } + } + private static String logFormat(int logLevel, boolean isError, String message) { - String logMessage = "LOG " + System.currentTimeMillis() + " [L" + logLevel + "]: " + (isError ? " " : "") + message; + String logMessage = "LOG " + System.currentTimeMillis() + " [L" + logLevel + "]: " + (isError ? " " : "") + message; if(logMessage.charAt(logMessage.length() - 1) != '\n') { logMessage += '\n'; // All log lines must end with a newline. } return logMessage; } - - private static String myDirectory; + + private static String myDirectory; private static HashSet filesToDisplay = new HashSet(); private static int minLevelToDisplay = Integer.MAX_VALUE; private static boolean suppressLoggerOutput; - private static String spilloverLogfile; + private static String spilloverLogfile; } \ No newline at end of file diff --git a/src/org/ggp/base/util/logging/LogSummaryGenerator.java b/src/org/ggp/base/util/logging/LogSummaryGenerator.java index b6c6f97e0..ac032c840 100644 --- a/src/org/ggp/base/util/logging/LogSummaryGenerator.java +++ b/src/org/ggp/base/util/logging/LogSummaryGenerator.java @@ -20,8 +20,8 @@ public boolean accept(File dir, String name) { } else { return getSummaryFromLogsDirectory(logsDirectory + "/" + theMatchingMatches[0]); } - return null; + return null; } - + public abstract String getSummaryFromLogsDirectory(String theLogsDirectory); } \ No newline at end of file diff --git a/src/org/ggp/base/util/match/Match.java b/src/org/ggp/base/util/match/Match.java index 48717ba81..cc3ea5bc7 100644 --- a/src/org/ggp/base/util/match/Match.java +++ b/src/org/ggp/base/util/match/Match.java @@ -38,7 +38,7 @@ * lists what move each player made at each step through the match. This * also includes other relevant metadata about the match, including some * unique identifiers, configuration information, and so on. - * + * * NOTE: Match objects created by a player, representing state read from * a server, are not completely filled out. For example, they only get an * ephemeral Game object, which has a rulesheet but no key or metadata. @@ -46,7 +46,7 @@ * information on what states have been observed, because (somehow) they * are representing games without using state machines. In general, these * player-created Match objects shouldn't be sent out into the ecosystem. - * + * * @author Sam */ public final class Match @@ -67,11 +67,11 @@ public final class Match private boolean isAborted; private final List goalValues; private final int numRoles; - + private EncodedKeyPair theCryptographicKeys; private List thePlayerNamesFromHost; private List isPlayerHuman; - + private GdlScrambler theGdlScrambler = new NoOpGdlScrambler(); public Match(String matchId, int previewClock, int startClock, int playClock, Game theGame) @@ -81,23 +81,23 @@ public Match(String matchId, int previewClock, int startClock, int playClock, Ga this.startClock = startClock; this.playClock = playClock; this.theGame = theGame; - + this.startTime = new Date(); this.randomToken = getRandomString(32); this.spectatorAuthToken = getRandomString(12); this.isCompleted = false; this.isAborted = false; - + this.numRoles = Role.computeRoles(theGame.getRules()).size(); - + this.moveHistory = new ArrayList>(); this.stateHistory = new ArrayList>(); this.stateTimeHistory = new ArrayList(); this.errorHistory = new ArrayList>(); - + this.goalValues = new ArrayList(); } - + public Match(String theJSON, Game theGame, String authToken) throws JSONException, SymbolFormatException, GdlFormatException { JSONObject theMatchObject = new JSONObject(theJSON); @@ -112,13 +112,13 @@ public Match(String theJSON, Game theGame, String authToken) throws JSONExceptio } else { this.theGame = theGame; } - + if (theMatchObject.has("previewClock")) { this.previewClock = theMatchObject.getInt("previewClock"); } else { this.previewClock = -1; } - + this.startTime = new Date(theMatchObject.getLong("startTime")); this.randomToken = theMatchObject.getString("randomToken"); this.spectatorAuthToken = authToken; @@ -130,12 +130,12 @@ public Match(String theJSON, Game theGame, String authToken) throws JSONExceptio } this.numRoles = Role.computeRoles(this.theGame.getRules()).size(); - + this.moveHistory = new ArrayList>(); this.stateHistory = new ArrayList>(); this.stateTimeHistory = new ArrayList(); this.errorHistory = new ArrayList>(); - + JSONArray theMoves = theMatchObject.getJSONArray("moves"); for (int i = 0; i < theMoves.length(); i++) { List theMove = new ArrayList(); @@ -155,7 +155,7 @@ public Match(String theJSON, Game theGame, String authToken) throws JSONExceptio } stateHistory.add(theState); } - JSONArray theStateTimes = theMatchObject.getJSONArray("stateTimes"); + JSONArray theStateTimes = theMatchObject.getJSONArray("stateTimes"); for (int i = 0; i < theStateTimes.length(); i++) { this.stateTimeHistory.add(new Date(theStateTimes.getLong(i))); } @@ -171,18 +171,18 @@ public Match(String theJSON, Game theGame, String authToken) throws JSONExceptio errorHistory.add(theMoveErrors); } } - + this.goalValues = new ArrayList(); try { JSONArray theGoalValues = theMatchObject.getJSONArray("goalValues"); - for (int i = 0; i < theGoalValues.length(); i++) { + for (int i = 0; i < theGoalValues.length(); i++) { this.goalValues.add(theGoalValues.getInt(i)); } } catch (JSONException e) {} - + // TODO: Add a way to recover cryptographic public keys and signatures. // Or, perhaps loading a match into memory for editing should strip those? - + if (theMatchObject.has("playerNamesFromHost")) { thePlayerNamesFromHost = new ArrayList(); JSONArray thePlayerNames = theMatchObject.getJSONArray("playerNamesFromHost"); @@ -195,36 +195,36 @@ public Match(String theJSON, Game theGame, String authToken) throws JSONExceptio JSONArray isPlayerHumanArray = theMatchObject.getJSONArray("isPlayerHuman"); for (int i = 0; i < isPlayerHumanArray.length(); i++) { isPlayerHuman.add(isPlayerHumanArray.getBoolean(i)); - } + } } } - + /* Mutators */ - + public void setCryptographicKeys(EncodedKeyPair k) { this.theCryptographicKeys = k; } - + public void enableScrambling() { theGdlScrambler = new MappingGdlScrambler(new Random(startTime.getTime())); for (Gdl rule : theGame.getRules()) { theGdlScrambler.scramble(rule); } } - + public void setPlayerNamesFromHost(List thePlayerNames) { this.thePlayerNamesFromHost = thePlayerNames; } - + public List getPlayerNamesFromHost() { return thePlayerNamesFromHost; } - + public void setWhichPlayersAreHuman(List isPlayerHuman) { this.isPlayerHuman = isPlayerHuman; } - public void appendMoves(List moves) { + public void appendMoves(List moves) { moveHistory.add(moves); } @@ -236,14 +236,14 @@ public void appendMoves2(List moves) { for(Move m : moves) { theMoves.add(m.getContents()); } - appendMoves(theMoves); + appendMoves(theMoves); } - + public void appendState(Set state) { stateHistory.add(state); stateTimeHistory.add(new Date()); } - + public void appendErrors(List errors) { errorHistory.add(errors); } @@ -254,21 +254,21 @@ public void appendNoErrors() { theNoErrors.add(""); } errorHistory.add(theNoErrors); - } - + } + public void markCompleted(List theGoalValues) { this.isCompleted = true; if (theGoalValues != null) { this.goalValues.addAll(theGoalValues); } } - + public void markAborted() { this.isAborted = true; } /* Complex accessors */ - + public String toJSON() { JSONObject theJSON = new JSONObject(); @@ -301,13 +301,13 @@ public String toJSON() { } catch (JSONException e) { return null; } - + if (theCryptographicKeys != null) { try { SignableJSON.signJSON(theJSON, theCryptographicKeys.thePublicKey, theCryptographicKeys.thePrivateKey); if (!SignableJSON.isSignedJSON(theJSON)) { throw new Exception("Could not recognize signed match: " + theJSON); - } + } if (!SignableJSON.verifySignedJSON(theJSON)) { throw new Exception("Could not verify signed match: " + theJSON); } @@ -317,7 +317,7 @@ public String toJSON() { theJSON.remove("matchHostSignature"); } } - + return theJSON.toString(); } @@ -344,13 +344,13 @@ public String toXML() { } } theXML.append(""); - + return theXML.toString(); } catch (JSONException je) { return null; } } - + public List getMostRecentMoves() { if (moveHistory.size() == 0) return null; @@ -360,31 +360,31 @@ public List getMostRecentMoves() { public Set getMostRecentState() { if (stateHistory.size() == 0) return null; - return stateHistory.get(stateHistory.size()-1); + return stateHistory.get(stateHistory.size()-1); } - + public String getGameRepositoryURL() { return getGame().getRepositoryURL(); } - + public String toString() { return toJSON(); - } - + } + /* Simple accessors */ public String getMatchId() { return matchId; } - + public String getRandomToken() { return randomToken; } - + public String getSpectatorAuthToken() { return spectatorAuthToken; } - + public Game getGame() { return theGame; } @@ -392,19 +392,19 @@ public Game getGame() { public List> getMoveHistory() { return moveHistory; } - + public List> getStateHistory() { return stateHistory; } - + public List getStateTimeHistory() { return stateTimeHistory; } - + public List> getErrorHistory() { return errorHistory; } - + public int getPreviewClock() { return previewClock; } @@ -416,11 +416,11 @@ public int getPlayClock() { public int getStartClock() { return startClock; } - + public Date getStartTime() { return startTime; } - + public boolean isCompleted() { return isCompleted; } @@ -432,13 +432,13 @@ public boolean isAborted() { public List getGoalValues() { return goalValues; } - + public GdlScrambler getGdlScrambler() { return theGdlScrambler; } - + /* Static methods */ - + public static final String getRandomString(int nLength) { Random theGenerator = new Random(); String theString = ""; @@ -450,24 +450,24 @@ public static final String getRandomString(int nLength) { } return theString; } - + /* JSON rendering methods */ - + private static final String renderArrayAsJSON(List theList, boolean useQuotes) { String s = "["; for (int i = 0; i < theList.size(); i++) { Object o = theList.get(i); // AppEngine-specific, not needed yet: if (o instanceof Text) o = ((Text)o).getValue(); if (o instanceof Date) o = ((Date)o).getTime(); - + if (useQuotes) s += "\""; s += o.toString(); if (useQuotes) s += "\""; - + if (i < theList.size() - 1) s += ", "; } - return s + "]"; + return s + "]"; } private static final List renderStateHistory(List> stateHistory) { @@ -483,16 +483,16 @@ private static final List renderMoveHistory(List> moveHist for (List aMove : moveHistory) { renderedMoves.add(renderArrayAsJSON(aMove, true)); } - return renderedMoves; + return renderedMoves; } - + private static final List renderErrorHistory(List> errorHistory) { List renderedErrors = new ArrayList(); for (List anError : errorHistory) { renderedErrors.add(renderArrayAsJSON(anError, true)); } - return renderedErrors; - } + return renderedErrors; + } private static final String renderStateAsSymbolList(Set theState) { // Strip out the TRUE proposition, since those are implied for states. @@ -503,13 +503,13 @@ private static final String renderStateAsSymbolList(Set theState) { } return s + ")"; } - + /* XML Rendering methods -- these are horribly inefficient and are included only for legacy/standards compatibility */ - + private static final String renderLeafXML(String tagName, Object value) { return "<" + tagName + ">" + value.toString() + ""; } - + private static final String renderMoveHistoryXML(List> moveHistory) { StringBuilder theXML = new StringBuilder(); theXML.append(""); @@ -523,7 +523,7 @@ private static final String renderMoveHistoryXML(List> moveHistory theXML.append(""); return theXML.toString(); } - + private static final String renderErrorHistoryXML(List> errorHistory) { StringBuilder theXML = new StringBuilder(); theXML.append(""); @@ -537,7 +537,7 @@ private static final String renderErrorHistoryXML(List> errorHistor theXML.append(""); return theXML.toString(); } - + private static final String renderStateHistoryXML(List> stateHistory) { StringBuilder theXML = new StringBuilder(); theXML.append(""); @@ -547,7 +547,7 @@ private static final String renderStateHistoryXML(List> stateHi theXML.append(""); return theXML.toString(); } - + public static final String renderStateXML(Set state) { StringBuilder theXML = new StringBuilder(); theXML.append(""); @@ -557,7 +557,7 @@ public static final String renderStateXML(Set state) { theXML.append(""); return theXML.toString(); } - + private static final String renderArrayXML(String tag, JSONArray arr) throws JSONException { StringBuilder theXML = new StringBuilder(); for (int i = 0; i < arr.length(); i++) { @@ -565,7 +565,7 @@ private static final String renderArrayXML(String tag, JSONArray arr) throws JSO } return theXML.toString(); } - + private static final String renderGdlToXML(Gdl gdl) { String rval = ""; if(gdl instanceof GdlConstant) { @@ -601,5 +601,5 @@ private static final String renderGdlToXML(Gdl gdl) { System.err.println("gdlToXML Error: could not handle "+gdl.toString()); return null; } - } + } } \ No newline at end of file diff --git a/src/org/ggp/base/util/match/MatchPublisher.java b/src/org/ggp/base/util/match/MatchPublisher.java index 1aa7dd1f4..494d03c2c 100644 --- a/src/org/ggp/base/util/match/MatchPublisher.java +++ b/src/org/ggp/base/util/match/MatchPublisher.java @@ -48,12 +48,12 @@ public static String performPOST(String theURL, String theAuth, String theData) static class MatchPublisherThread extends Thread { private Match theMatch; private String spectatorURL; - + public MatchPublisherThread(String spectatorURL, Match theMatch) { this.theMatch = theMatch; this.spectatorURL = spectatorURL; } - + @Override public void run() { try { @@ -61,9 +61,9 @@ public void run() { } catch (IOException e) { e.printStackTrace(); } - } + } } - + public static void publishToSpectatorServerAsync(String spectatorURL, Match theMatch) throws IOException { MatchPublisherThread theThread = new MatchPublisherThread(spectatorURL, theMatch); theThread.start(); diff --git a/src/org/ggp/base/util/presence/InfoResponse.java b/src/org/ggp/base/util/presence/InfoResponse.java index 3b83109b9..58b62c940 100644 --- a/src/org/ggp/base/util/presence/InfoResponse.java +++ b/src/org/ggp/base/util/presence/InfoResponse.java @@ -14,7 +14,7 @@ * Wherein we poorly reinvent JSON, so that we can keep INFO responses * consistent with the Symbol-based KIF format that the other GGP protocol * messages are in. - * + * * @author schreib */ @@ -22,37 +22,37 @@ public class InfoResponse { private String name; private String status; private String species; - + public InfoResponse() { ; } - + public void setName(String name) { this.name = name; } - + public void setStatus(String status) { this.status = status; } - + public void setSpecies(String species) { this.species = species; } - + public String getName() { return name; } - + public String getStatus() { return status; } - + public String getSpecies() { return species; } - + public InfoResponse(Symbol symbol) { - if (symbol instanceof SymbolList) { + if (symbol instanceof SymbolList) { SymbolList pairs = (SymbolList)symbol; for (int i = 0; i < pairs.size(); i++) { Symbol pairSymbol = pairs.get(i); @@ -77,7 +77,7 @@ public InfoResponse(Symbol symbol) { status = ((SymbolAtom) symbol).getValue(); } } - + public static InfoResponse create(String original) { try { return new InfoResponse(SymbolFactory.create(original)); @@ -91,8 +91,8 @@ private Symbol getKeyValueSymbol(String key, String value) { Symbol valueSymbol = SymbolPool.getAtom(value); return SymbolPool.getList(new Symbol[] {keySymbol, valueSymbol} ); } - - public Symbol toSymbol() { + + public Symbol toSymbol() { List infoList = new ArrayList(); if (name != null) { infoList.add(getKeyValueSymbol("name", name)); diff --git a/src/org/ggp/base/util/presence/PlayerPresence.java b/src/org/ggp/base/util/presence/PlayerPresence.java index e51dc6016..6c880a048 100644 --- a/src/org/ggp/base/util/presence/PlayerPresence.java +++ b/src/org/ggp/base/util/presence/PlayerPresence.java @@ -11,7 +11,7 @@ public class PlayerPresence { private String name; private String status; private long statusTime; - + PlayerPresence(String host, int port) { this.host = host; this.port = port; @@ -19,7 +19,7 @@ public class PlayerPresence { this.status = null; this.statusTime = 0; } - + public void updateInfo() { InfoResponse info; try { @@ -36,23 +36,23 @@ public void updateInfo() { statusTime = System.currentTimeMillis(); } } - + public synchronized String getName() { return name; - } - + } + public synchronized String getStatus() { return status; } - + public synchronized long getStatusAge() { return System.currentTimeMillis() - statusTime; } - + public String getHost() { return host; } - + public int getPort() { return port; } diff --git a/src/org/ggp/base/util/presence/PlayerPresenceManager.java b/src/org/ggp/base/util/presence/PlayerPresenceManager.java index 775b19cd0..d6af81c99 100644 --- a/src/org/ggp/base/util/presence/PlayerPresenceManager.java +++ b/src/org/ggp/base/util/presence/PlayerPresenceManager.java @@ -24,17 +24,17 @@ public class PlayerPresenceManager implements Subject { private Map monitoredPlayers; - + public class PlayerPresenceChanged extends Event {} public class PlayerPresenceAdded extends Event {} public class PlayerPresenceRemoved extends Event {} - + public static boolean isDifferent(String a, String b) { if (a == null && b == null) return false; if (a == null && b != null) return true; return !a.equals(b); - } - + } + public static final int INFO_PING_PERIOD_IN_SECONDS = 1; class PresenceMonitor extends Thread { public void run() { @@ -47,10 +47,10 @@ public void run() { Set keys = new HashSet(monitoredPlayers.keySet()); for (String key : keys) { PlayerPresence presence = monitoredPlayers.get(key); - if (presence == null) continue; + if (presence == null) continue; if (presence.getStatusAge() > INFO_PING_PERIOD_IN_SECONDS*1000) { String old_name = presence.getName(); - String old_status = presence.getStatus(); + String old_status = presence.getStatus(); presence.updateInfo(); String new_name = presence.getName(); String new_status = presence.getStatus(); @@ -62,16 +62,16 @@ public void run() { } } } - } + } } - + public PlayerPresenceManager() { monitoredPlayers = new HashMap(); loadPlayersJSON(); if (monitoredPlayers.size() == 0) { try { // When starting from a blank slate, add some initial players to the - // monitoring list just so that it's clear how it works. + // monitoring list just so that it's clear how it works. addPlayer("127.0.0.1:9147"); addPlayer("127.0.0.1:9148"); } catch (InvalidHostportException e) { @@ -80,10 +80,10 @@ public PlayerPresenceManager() { } new PresenceMonitor().start(); } - + @SuppressWarnings("serial") public class InvalidHostportException extends Exception {} - + private PlayerPresence addPlayerSilently(String hostport) throws InvalidHostportException { try { if (!monitoredPlayers.containsKey(hostport)) { @@ -100,25 +100,25 @@ private PlayerPresence addPlayerSilently(String hostport) throws InvalidHostport } catch (NumberFormatException e) { throw new InvalidHostportException(); } - } - + } + public PlayerPresence addPlayer(String hostport) throws InvalidHostportException { PlayerPresence presence = addPlayerSilently(hostport); notifyObservers(new PlayerPresenceAdded()); savePlayersJSON(); return presence; } - + public void removePlayer(String hostport) { monitoredPlayers.remove(hostport); notifyObservers(new PlayerPresenceRemoved()); savePlayersJSON(); } - + public PlayerPresence getPresence(String hostport) { return monitoredPlayers.get(hostport); } - + public Set getSortedPlayerNames() { return new TreeSet(monitoredPlayers.keySet()); } @@ -135,14 +135,14 @@ public void notifyObservers(Event event) { observer.observe(event); } } - + private static final String playerListFilename = ".ggpserver-playerlist.json"; private void savePlayersJSON() { try { JSONObject playerListJSON = new JSONObject(); playerListJSON.put("hostports", monitoredPlayers.keySet()); File file = new File(System.getProperty("user.home"), playerListFilename); - if (!file.exists()) { + if (!file.exists()) { file.createNewFile(); } FileWriter fw = new FileWriter(file); diff --git a/src/org/ggp/base/util/presence/Test_InfoResponse.java b/src/org/ggp/base/util/presence/Test_InfoResponse.java index e92fe4de9..2fb05d1bc 100644 --- a/src/org/ggp/base/util/presence/Test_InfoResponse.java +++ b/src/org/ggp/base/util/presence/Test_InfoResponse.java @@ -6,7 +6,7 @@ * Unit tests for the BaseCryptography class, which implements * a wrapper for the use of asymmetric public/private key cryptography * for use in GGP. - * + * * @author Sam */ public class Test_InfoResponse extends TestCase { @@ -18,14 +18,14 @@ public void testFormingInfoResponse() { response.setStatus("available"); assertEquals(response.toSymbol().toString(), "( ( name PlayerName ) ( status available ) )"); } - + public void testParsingInfoResponse() { String input = "( ( name PlayerName ) ( status available ) )"; InfoResponse response = InfoResponse.create(input); assertEquals(response.getName(), "PlayerName"); assertEquals(response.getStatus(), "available"); } - + public void testParsingInfoResponseWithExtras() { String input = "( whatsup ( name PlayerName ) ( ( foo bar ) baz ) ( status available ) zzq )"; InfoResponse response = InfoResponse.create(input); @@ -39,28 +39,28 @@ public void testParsingInfoResponseWithNoStatus() { assertEquals(response.getName(), "PlayerName"); assertEquals(response.getStatus(), null); } - + public void testParsingInfoResponseWithNoInfo() { String input = "( )"; InfoResponse response = InfoResponse.create(input); assertEquals(response.getName(), null); assertEquals(response.getStatus(), null); } - + public void testParsingBadlyFormedInfoResponse() { String input = "("; InfoResponse response = InfoResponse.create(input); assertEquals(response.getName(), null); assertEquals(response.getStatus(), null); } - + public void testParsingStatusOnlyInfoResponse() { String input = "busy"; InfoResponse response = InfoResponse.create(input); assertEquals(response.getName(), null); assertEquals(response.getStatus(), "busy"); } - + public void testParsingInfoResponseLegacyJSON() { String input = "{\"name\":\"PlayerName\",\"status\":\"available\"}"; InfoResponse response = InfoResponse.create(input); diff --git a/src/org/ggp/base/util/propnet/architecture/Component.java b/src/org/ggp/base/util/propnet/architecture/Component.java index 4c3c6807b..c9bb36ced 100644 --- a/src/org/ggp/base/util/propnet/architecture/Component.java +++ b/src/org/ggp/base/util/propnet/architecture/Component.java @@ -12,7 +12,7 @@ public abstract class Component implements Serializable { - + private static final long serialVersionUID = 352524175700224447L; /** The inputs to the component. */ private final Set inputs; @@ -30,7 +30,7 @@ public Component() /** * Adds a new input. - * + * * @param input * A new input. */ @@ -38,22 +38,22 @@ public void addInput(Component input) { inputs.add(input); } - + public void removeInput(Component input) { inputs.remove(input); } - + public void removeOutput(Component output) { outputs.remove(output); } - + public void removeAllInputs() { inputs.clear(); } - + public void removeAllOutputs() { outputs.clear(); @@ -61,7 +61,7 @@ public void removeAllOutputs() /** * Adds a new output. - * + * * @param output * A new output. */ @@ -72,41 +72,41 @@ public void addOutput(Component output) /** * Getter method. - * + * * @return The inputs to the component. */ public Set getInputs() { return inputs; } - + /** * A convenience method, to get a single input. * To be used only when the component is known to have * exactly one input. - * + * * @return The single input to the component. */ public Component getSingleInput() { assert inputs.size() == 1; return inputs.iterator().next(); - } - + } + /** * Getter method. - * + * * @return The outputs of the component. */ public Set getOutputs() { return outputs; } - + /** * A convenience method, to get a single output. * To be used only when the component is known to have * exactly one output. - * + * * @return The single output to the component. */ public Component getSingleOutput() { @@ -116,14 +116,14 @@ public Component getSingleOutput() { /** * Returns the value of the Component. - * + * * @return The value of the Component. */ public abstract boolean getValue(); /** * Returns a representation of the Component in .dot format. - * + * * @see java.lang.Object#toString() */ @Override @@ -131,7 +131,7 @@ public Component getSingleOutput() { /** * Returns a configurable representation of the Component in .dot format. - * + * * @param shape * The value to use as the shape attribute. * @param fillcolor diff --git a/src/org/ggp/base/util/propnet/architecture/PropNet.java b/src/org/ggp/base/util/propnet/architecture/PropNet.java index f275b1916..517d8fce0 100644 --- a/src/org/ggp/base/util/propnet/architecture/PropNet.java +++ b/src/org/ggp/base/util/propnet/architecture/PropNet.java @@ -26,7 +26,7 @@ /** * The PropNet class is designed to represent Propositional Networks. - * + * * A propositional network (also known as a "propnet") is a way of representing * a game as a logic circuit. States of the game are represented by assignments * of TRUE or FALSE to "base" propositions, each of which represents a single @@ -36,12 +36,12 @@ * to TRUE to indicate that the fact is true in the current state of the game. * Likewise, the base corresponding to the fact (cell 1 1 o) would be false, * because in that state of the game there isn't an 'o' in the cell (1,1). - * + * * A state of the game is uniquely determined by the assignment of truth values * to the base propositions in the propositional network. Every assignment of * truth values to base propositions corresponds to exactly one unique state of * the game. - * + * * Given the values of the base propositions, you can use the connections in * the network (AND gates, OR gates, NOT gates) to determine the truth values * of other propositions. For example, you can determine whether the terminal @@ -50,19 +50,19 @@ * also determine the value of the goal propositions, which represent facts * like (goal xplayer 100). If that proposition is true, then that fact is true * in this state of the game, which means that xplayer has 100 points. - * + * * You can also use a propositional network to determine the next state of the * game, given the current state and the moves for each player. First, you set * the input propositions which correspond to each move to TRUE. Once that has * been done, you can determine the truth value of the transitions. Each base * proposition has a "transition" component going into it. This transition has * the truth value that its base will take on in the next state of the game. - * + * * For further information about propositional networks, see: - * + * * "Decomposition of Games for Efficient Reasoning" by Eric Schkufza. * "Factoring General Games using Propositional Automata" by Evan Cox et al. - * + * * @author Sam Schreiber */ @@ -70,34 +70,34 @@ public final class PropNet { /** References to every component in the PropNet. */ private final Set components; - + /** References to every Proposition in the PropNet. */ private final Set propositions; - + /** References to every BaseProposition in the PropNet, indexed by name. */ private final Map basePropositions; - + /** References to every InputProposition in the PropNet, indexed by name. */ private final Map inputPropositions; - + /** References to every LegalProposition in the PropNet, indexed by role. */ private final Map> legalPropositions; - + /** References to every GoalProposition in the PropNet, indexed by role. */ private final Map> goalPropositions; - + /** A reference to the single, unique, InitProposition. */ private final Proposition initProposition; - + /** A reference to the single, unique, TerminalProposition. */ private final Proposition terminalProposition; - + /** A helper mapping between input/legal propositions. */ private final Map legalInputMap; - + /** A helper list of all of the roles. */ private final List roles; - + public void addComponent(Component c) { components.add(c); @@ -107,13 +107,13 @@ public void addComponent(Component c) /** * Creates a new PropNet from a list of Components, along with indices over * those components. - * + * * @param components * A list of Components. */ public PropNet(List roles, Set components) { - + this.roles = roles; this.components = components; this.propositions = recordPropositions(); @@ -125,12 +125,12 @@ public PropNet(List roles, Set components) this.terminalProposition = recordTerminalProposition(); this.legalInputMap = makeLegalInputMap(); } - + public List getRoles() { return roles; } - + public Map getLegalInputMap() { return legalInputMap; @@ -158,10 +158,10 @@ private Map makeLegalInputMap() { } return legalInputMap; } - + /** * Getter method. - * + * * @return References to every BaseProposition in the PropNet, indexed by * name. */ @@ -172,7 +172,7 @@ public Map getBasePropositions() /** * Getter method. - * + * * @return References to every Component in the PropNet. */ public Set getComponents() @@ -182,7 +182,7 @@ public Set getComponents() /** * Getter method. - * + * * @return References to every GoalProposition in the PropNet, indexed by * player name. */ @@ -193,7 +193,7 @@ public Map> getGoalPropositions() /** * Getter method. A reference to the single, unique, InitProposition. - * + * * @return */ public Proposition getInitProposition() @@ -203,7 +203,7 @@ public Proposition getInitProposition() /** * Getter method. - * + * * @return References to every InputProposition in the PropNet, indexed by * name. */ @@ -214,7 +214,7 @@ public Map getInputPropositions() /** * Getter method. - * + * * @return References to every LegalProposition in the PropNet, indexed by * player name. */ @@ -225,7 +225,7 @@ public Map> getLegalPropositions() /** * Getter method. - * + * * @return References to every Proposition in the PropNet. */ public Set getPropositions() @@ -235,7 +235,7 @@ public Set getPropositions() /** * Getter method. - * + * * @return A reference to the single, unique, TerminalProposition. */ public Proposition getTerminalProposition() @@ -245,7 +245,7 @@ public Proposition getTerminalProposition() /** * Returns a representation of the PropNet in .dot format. - * + * * @see java.lang.Object#toString() */ @Override @@ -266,7 +266,7 @@ public String toString() /** * Outputs the propnet in .dot format to a particular file. * This can be viewed with tools like Graphviz and ZGRViewer. - * + * * @param filename the name of the file to output to */ public void renderToFile(String filename) { @@ -284,11 +284,11 @@ public void renderToFile(String filename) { /** * Builds an index over the BasePropositions in the PropNet. - * + * * This is done by going over every single-input proposition in the network, * and seeing whether or not its input is a transition, which would mean that * by definition the proposition is a base proposition. - * + * * @return An index over the BasePropositions in the PropNet. */ private Map recordBasePropositions() @@ -298,7 +298,7 @@ private Map recordBasePropositions() // Skip all propositions without exactly one input. if (proposition.getInputs().size() != 1) continue; - + Component component = proposition.getSingleInput(); if (component instanceof Transition) { basePropositions.put(proposition.getName(), proposition); @@ -310,12 +310,12 @@ private Map recordBasePropositions() /** * Builds an index over the GoalPropositions in the PropNet. - * + * * This is done by going over every function proposition in the network * where the name of the function is "goal", and extracting the name of the * role associated with that goal proposition, and then using those role * names as keys that map to the goal propositions in the index. - * + * * @return An index over the GoalPropositions in the PropNet. */ private Map> recordGoalPropositions() @@ -326,11 +326,11 @@ private Map> recordGoalPropositions() // Skip all propositions that aren't GdlRelations. if (!(proposition.getName() instanceof GdlRelation)) continue; - + GdlRelation relation = (GdlRelation) proposition.getName(); if (!relation.getName().getValue().equals("goal")) continue; - + Role theRole = new Role((GdlConstant) relation.get(0)); if (!goalPropositions.containsKey(theRole)) { goalPropositions.put(theRole, new HashSet()); @@ -343,7 +343,7 @@ private Map> recordGoalPropositions() /** * Returns a reference to the single, unique, InitProposition. - * + * * @return A reference to the single, unique, InitProposition. */ private Proposition recordInitProposition() @@ -353,7 +353,7 @@ private Proposition recordInitProposition() // Skip all propositions that aren't GdlPropositions. if (!(proposition.getName() instanceof GdlProposition)) continue; - + GdlConstant constant = ((GdlProposition) proposition.getName()).getName(); if (constant.getValue().toUpperCase().equals("INIT")) { return proposition; @@ -364,7 +364,7 @@ private Proposition recordInitProposition() /** * Builds an index over the InputPropositions in the PropNet. - * + * * @return An index over the InputPropositions in the PropNet. */ private Map recordInputPropositions() @@ -375,7 +375,7 @@ private Map recordInputPropositions() // Skip all propositions that aren't GdlFunctions. if (!(proposition.getName() instanceof GdlRelation)) continue; - + GdlRelation relation = (GdlRelation) proposition.getName(); if (relation.getName().getValue().equals("does")) { inputPropositions.put(proposition.getName(), proposition); @@ -387,7 +387,7 @@ private Map recordInputPropositions() /** * Builds an index over the LegalPropositions in the PropNet. - * + * * @return An index over the LegalPropositions in the PropNet. */ private Map> recordLegalPropositions() @@ -398,7 +398,7 @@ private Map> recordLegalPropositions() // Skip all propositions that aren't GdlRelations. if (!(proposition.getName() instanceof GdlRelation)) continue; - + GdlRelation relation = (GdlRelation) proposition.getName(); if (relation.getName().getValue().equals("legal")) { GdlConstant name = (GdlConstant) relation.get(0); @@ -406,7 +406,7 @@ private Map> recordLegalPropositions() if (!legalPropositions.containsKey(r)) { legalPropositions.put(r, new HashSet()); } - legalPropositions.get(r).add(proposition); + legalPropositions.get(r).add(proposition); } } @@ -415,7 +415,7 @@ private Map> recordLegalPropositions() /** * Builds an index over the Propositions in the PropNet. - * + * * @return An index over Propositions in the PropNet. */ private Set recordPropositions() @@ -432,7 +432,7 @@ private Set recordPropositions() /** * Records a reference to the single, unique, TerminalProposition. - * + * * @return A reference to the single, unqiue, TerminalProposition. */ private Proposition recordTerminalProposition() @@ -450,8 +450,8 @@ private Proposition recordTerminalProposition() } return null; - } - + } + public int getSize() { return components.size(); } @@ -464,7 +464,7 @@ public int getNumAnds() { } return andCount; } - + public int getNumOrs() { int orCount = 0; for(Component c : components) { @@ -473,7 +473,7 @@ public int getNumOrs() { } return orCount; } - + public int getNumNots() { int notCount = 0; for(Component c : components) { @@ -497,12 +497,12 @@ public int getNumLinks() { * that this method only be used in an optimization period between * the propnet's creation and its initial use, during which it * should only be accessed by a single thread. - * + * * The INIT and terminal components cannot be removed. */ public void removeComponent(Component c) { - - + + //Go through all the collections it could appear in if(c instanceof Proposition) { Proposition p = (Proposition) c; @@ -528,7 +528,7 @@ public void removeComponent(Component c) { Proposition partner = legalInputMap.get(p); if(partner != null) { legalInputMap.remove(partner); - legalInputMap.remove(p); + legalInputMap.remove(p); } } } diff --git a/src/org/ggp/base/util/propnet/architecture/components/And.java b/src/org/ggp/base/util/propnet/architecture/components/And.java index b0f0d7531..dbdbb663e 100644 --- a/src/org/ggp/base/util/propnet/architecture/components/And.java +++ b/src/org/ggp/base/util/propnet/architecture/components/And.java @@ -10,7 +10,7 @@ public final class And extends Component { /** * Returns true if and only if every input to the and is true. - * + * * @see org.ggp.base.util.propnet.architecture.Component#getValue() */ @Override diff --git a/src/org/ggp/base/util/propnet/architecture/components/Constant.java b/src/org/ggp/base/util/propnet/architecture/components/Constant.java index 0715b465d..092482054 100644 --- a/src/org/ggp/base/util/propnet/architecture/components/Constant.java +++ b/src/org/ggp/base/util/propnet/architecture/components/Constant.java @@ -13,7 +13,7 @@ public final class Constant extends Component /** * Creates a new Constant with value value. - * + * * @param value * The value of the Constant. */ @@ -24,7 +24,7 @@ public Constant(boolean value) /** * Returns the value that the constant was initialized to. - * + * * @see org.ggp.base.util.propnet.architecture.Component#getValue() */ @Override diff --git a/src/org/ggp/base/util/propnet/architecture/components/Not.java b/src/org/ggp/base/util/propnet/architecture/components/Not.java index c61b3dea3..4ee1e3778 100644 --- a/src/org/ggp/base/util/propnet/architecture/components/Not.java +++ b/src/org/ggp/base/util/propnet/architecture/components/Not.java @@ -10,7 +10,7 @@ public final class Not extends Component { /** * Returns the inverse of the input to the not. - * + * * @see org.ggp.base.util.propnet.architecture.Component#getValue() */ @Override diff --git a/src/org/ggp/base/util/propnet/architecture/components/Or.java b/src/org/ggp/base/util/propnet/architecture/components/Or.java index de203ab45..d5be07847 100644 --- a/src/org/ggp/base/util/propnet/architecture/components/Or.java +++ b/src/org/ggp/base/util/propnet/architecture/components/Or.java @@ -10,7 +10,7 @@ public final class Or extends Component { /** * Returns true if and only if at least one of the inputs to the or is true. - * + * * @see org.ggp.base.util.propnet.architecture.Component#getValue() */ @Override diff --git a/src/org/ggp/base/util/propnet/architecture/components/Proposition.java b/src/org/ggp/base/util/propnet/architecture/components/Proposition.java index f1173dda3..72c6f6928 100644 --- a/src/org/ggp/base/util/propnet/architecture/components/Proposition.java +++ b/src/org/ggp/base/util/propnet/architecture/components/Proposition.java @@ -16,7 +16,7 @@ public final class Proposition extends Component /** * Creates a new Proposition with name name. - * + * * @param name * The name of the Proposition. */ @@ -28,30 +28,30 @@ public Proposition(GdlSentence name) /** * Getter method. - * + * * @return The name of the Proposition. */ public GdlSentence getName() { return name; } - + /** * Setter method. - * + * * This should only be rarely used; the name of a proposition * is usually constant over its entire lifetime. - * + * * @return The name of the Proposition. */ public void setName(GdlSentence newName) { name = newName; - } + } /** * Returns the current value of the Proposition. - * + * * @see org.ggp.base.util.propnet.architecture.Component#getValue() */ @Override @@ -62,7 +62,7 @@ public boolean getValue() /** * Setter method. - * + * * @param value * The new value of the Proposition. */ diff --git a/src/org/ggp/base/util/propnet/architecture/components/Transition.java b/src/org/ggp/base/util/propnet/architecture/components/Transition.java index 371b043a8..2cb7e0443 100644 --- a/src/org/ggp/base/util/propnet/architecture/components/Transition.java +++ b/src/org/ggp/base/util/propnet/architecture/components/Transition.java @@ -10,7 +10,7 @@ public final class Transition extends Component { /** * Returns the value of the input to the transition. - * + * * @see org.ggp.base.util.propnet.architecture.Component#getValue() */ @Override diff --git a/src/org/ggp/base/util/propnet/factory/OptimizingPropNetFactory.java b/src/org/ggp/base/util/propnet/factory/OptimizingPropNetFactory.java index dc6a9694e..91d10ad3f 100644 --- a/src/org/ggp/base/util/propnet/factory/OptimizingPropNetFactory.java +++ b/src/org/ggp/base/util/propnet/factory/OptimizingPropNetFactory.java @@ -66,7 +66,7 @@ * classes of rules that have poor performance and replace them with equivalent * rules that have better performance, with performance measured by the size of * the propnet.) - * + * * Known issues: * - Does not work on games with many advanced forms of recursion. These include: * - Anything that breaks the SentenceModel @@ -89,7 +89,7 @@ * CondensationIsolator could solve these problems. A stopgap alternative is to * try both settings and use the smaller propnet (or the first to be created, * if multithreading). - * + * */ public class OptimizingPropNetFactory { static final private GdlConstant LEGAL = GdlPool.getConstant("legal"); @@ -125,9 +125,9 @@ public static PropNet create(List description, boolean verbose) throws Inte description = VariableConstrainer.replaceFunctionValuedVariables(description); description = Relationizer.run(description); - description = CondensationIsolator.run(description); - - + description = CondensationIsolator.run(description); + + if(verbose) for(Gdl gdl : description) System.out.println(gdl); @@ -277,7 +277,7 @@ private static void removeUselessBasePropositions( * to the outputs of the PropNetFactory. This is for consistency and for * backwards compatibility with respect to state machines designed for the * old propnet factory. Feel free to remove this for your player. - * + * * @param componentSet */ private static void normalizePropositions(Set componentSet) { diff --git a/src/org/ggp/base/util/propnet/factory/PropNetFactory.java b/src/org/ggp/base/util/propnet/factory/PropNetFactory.java index 3590c784e..0b4e06dac 100644 --- a/src/org/ggp/base/util/propnet/factory/PropNetFactory.java +++ b/src/org/ggp/base/util/propnet/factory/PropNetFactory.java @@ -23,7 +23,7 @@ public final class PropNetFactory *
    3. Flattens the game description to remove variables.
    4. *
    5. Converts the flattened description into an equivalent PropNet.
    6. *
    - * + * * @param description * A game description. * @return An equivalent PropNet. diff --git a/src/org/ggp/base/util/propnet/factory/annotater/PropNetAnnotater.java b/src/org/ggp/base/util/propnet/factory/annotater/PropNetAnnotater.java index 2c101de64..051dafcb6 100644 --- a/src/org/ggp/base/util/propnet/factory/annotater/PropNetAnnotater.java +++ b/src/org/ggp/base/util/propnet/factory/annotater/PropNetAnnotater.java @@ -31,7 +31,7 @@ * Annotater generates ( base ?x ) annotations that explicitly specify the * domains of the propositions in a game. This only works on some relatively * simple games, unfortunately. - * + * * @author Ethan Dreyfuss */ public class PropNetAnnotater { @@ -40,34 +40,34 @@ public class PropNetAnnotater { private Set baseRelations = new HashSet(); private Set universe = new HashSet(); private GdlFunction universalDom = null; - + private class Domain { public Domain(Location loc) {this.loc = loc;} public Set values = new HashSet(); public Set> functionRefs = new HashSet>(); public Location loc; - + @Override public String toString() { return "Name: "+loc.name+" index: "+loc.idx+"\nvalues: "+values+"\nfunctionRefs: "+functionRefs; } } - + private class Location { public GdlConstant name; public Integer idx; - + public Location() {} - + @SuppressWarnings("unused") public Location(Location other) { name = other.name; idx = other.idx; } - + @Override public boolean equals(Object other) { @@ -76,7 +76,7 @@ public boolean equals(Object other) Location rhs = (Location)other; return idx==rhs.idx && name.toString().equals(rhs.name.toString()); } - + @Override public int hashCode() { @@ -85,21 +85,21 @@ public int hashCode() int val = bigInt.bitCount()+bigInt.intValue(); return val+idx; } - + @Override public String toString() { return name.toString()+"("+idx+")"; } } - + HashMap domains = new HashMap(); - + public PropNetAnnotater(List description) { this.description = description; } - + public List getAnnotations() { //Find universe and initial domains @@ -108,32 +108,32 @@ public List getAnnotations() processGdl(gdl, null); processDomain(gdl); } - + //Compute the actual domains of everything updateDomains(); - + //printDomains(); //printDomainRefs(); - + //Compute function corresponding to universal set for insertion in baseprops List body = new ArrayList(); body.addAll(universe); universalDom = GdlPool.getFunction(GdlPool.getConstant("thing"), body); - + //Find next/init things and use them to instantiate base props for(Gdl gdl : description) { findAndInstantiateBaseProps(gdl); } - + baseRelations = mergeBaseRelations(baseRelations); - + //Return the results List rval = new ArrayList(); rval.addAll(baseRelations); return rval; } - + private Set mergeBaseRelations(Set rels) { HashMap>> merges = new HashMap>>(); for(GdlRelation rel : rels) @@ -143,10 +143,10 @@ private Set mergeBaseRelations(Set rels) { merges.put(name, new ArrayList>()); List> merge = merges.get(name); addRelToMerge(rel, merge); - } - + } + Set rval = new HashSet(); - + GdlConstant valConst = GdlPool.getConstant("val"); for(GdlConstant c : merges.keySet()) { @@ -162,10 +162,10 @@ private Set mergeBaseRelations(Set rels) { GdlRelation toAdd = GdlPool.getRelation(baseConstant, body); rval.add(toAdd); } - + return rval; } - + private class SortTerms implements Comparator { public int compare(GdlTerm arg0, GdlTerm arg1) { @@ -173,36 +173,36 @@ public int compare(GdlTerm arg0, GdlTerm arg1) { GdlConstant a2 = (GdlConstant)arg1; String s1 = a1.toString(); String s2 = a2.toString(); - + int num1 = -1; int num2 = -1; - + try {num1 = Integer.parseInt(s1);} catch(Exception ex) {} try {num2 = Integer.parseInt(s2);} catch(Exception ex) {} - + if(num1 == -1 && num2 == -1) return Collator.getInstance().compare(s1, s2); - + if(num1 == -1) return 1; - + if(num2 == -1) return -1; - + return num1-num2; - } + } } private void addRelToMerge(GdlRelation rel, List> merge) { for(int i=1; i()); - + GdlFunction f = (GdlFunction)t; Set dom = merge.get(i-1); for(GdlTerm t2 : f.getBody()) @@ -225,7 +225,7 @@ void printDomains() System.out.println("\t\t"+val); } } - + void printDomainRefs() { System.out.println("Domains refs: "); @@ -242,7 +242,7 @@ void printDomainRefs() } } } - + void processGdl(Gdl gdl, GdlConstant parent) { if(gdl instanceof GdlRelation) @@ -269,7 +269,7 @@ else if(gdl instanceof GdlFunction) { GdlFunction func = (GdlFunction)gdl; for(Gdl gdl2 : func.getBody()) - processGdl(gdl2, func.getName()); + processGdl(gdl2, func.getName()); } else if(gdl instanceof GdlDistinct) { @@ -297,9 +297,9 @@ else if(gdl instanceof GdlVariable) //IGNORE } } - + private GdlConstant baseConstant = GdlPool.getConstant("base"); - + private void findAndInstantiateBaseProps(Gdl gdl) { if(gdl instanceof GdlRelation) @@ -318,7 +318,7 @@ private void findAndInstantiateBaseProps(Gdl gdl) GdlRelation toAdd = GdlPool.getRelation(baseConstant, body); baseRelations.add(toAdd); System.err.println("Weird init of constant"); - } + } else if(template instanceof GdlVariable) { System.err.println("Weird init of constant"); @@ -362,7 +362,7 @@ else if(gdl instanceof GdlRule) } } } - + private void instantiateBaseProps(GdlSentence template) { List body = new ArrayList(); @@ -376,7 +376,7 @@ private void instantiateBaseProps(GdlSentence template) domBody.add(arg); GdlFunction dom = GdlPool.getFunction(GdlPool.getConstant("val"), domBody); body.add(dom); - } + } else if(arg instanceof GdlVariable) { List domBody = new ArrayList(); @@ -398,7 +398,7 @@ else if(arg instanceof GdlFunction) GdlRelation toAdd = GdlPool.getRelation(baseConstant, body); baseRelations.add(toAdd); } - + void processDomain(Gdl gdl) { if(gdl instanceof GdlRelation) @@ -417,11 +417,11 @@ else if(gdl instanceof GdlRule) if(head instanceof GdlRelation) { GdlRelation rel = (GdlRelation)head; - + int i=0; for(GdlTerm term : rel.getBody()) { - addDomain2(term, rel.getName(), i, rule.getBody()); + addDomain2(term, rel.getName(), i, rule.getBody()); i++; } } @@ -434,9 +434,9 @@ else if(head instanceof GdlProposition) throw new RuntimeException("Don't know how to deal with this."); } } - - - + + + void addDomain2(GdlTerm term, GdlConstant name, int idx, List RHS) { Location loc = new Location(); @@ -470,25 +470,25 @@ else if(term instanceof GdlVariable) private Set findAllInstancesOf(GdlVariable var, List RHS) { Set rval = new HashSet(); - + for(GdlLiteral literal : RHS) { rval.addAll(findAllInstancesOf(var,literal)); } - + return rval; } private Set findAllInstancesOf(GdlVariable var, GdlLiteral literal) { return findAllInstancesOf(var,literal,null); } - + private Set findAllInstancesOf(GdlVariable var, Gdl gdl, Location loc) { if(!domains.containsKey(loc)) domains.put(loc, new Domain(loc)); - + Set rval = new HashSet(); - + if(gdl instanceof GdlRelation) { GdlRelation relation = (GdlRelation) gdl; @@ -551,7 +551,7 @@ else if(gdl instanceof GdlRule) { throw new RuntimeException("Shouldn't nest rules."); } - + return rval; } @@ -567,7 +567,7 @@ void addDomain(GdlRelation relation) i++; } } - + void addDomain(GdlTerm term, Location loc) { if(!domains.containsKey(loc)) @@ -595,7 +595,7 @@ else if(term instanceof GdlVariable) throw new RuntimeException("Uh oh, unbound variable which I don't know how to deal with."); } } - + void updateDomains() { boolean changedSomething = true; @@ -605,7 +605,7 @@ void updateDomains() for(Domain d : domains.values()) { int before = d.values.size(); - + for(Set intSet : d.functionRefs) { Set domain = null; @@ -619,10 +619,10 @@ void updateDomains() domain.retainAll(d2.values); } } - if(domain!=null) + if(domain!=null) d.values.addAll(domain); } - + if(d.loc != null) { String name = d.loc.name.toString(); @@ -647,18 +647,18 @@ else if(name.equals("true")) d.values.addAll(otherDom.values); } } - + if(d.values.size()!=before) changedSomething = true; } } } - + private void instantiateBasePropsWithRHS(GdlSentence template, List RHS) { instantiateBaseProps(template); } - + public List getAugmentedDescription() { List rval = new ArrayList(); @@ -666,7 +666,7 @@ public List getAugmentedDescription() { boolean notBase = true; if(gdl instanceof GdlRelation) - { + { GdlRelation rel = (GdlRelation)gdl; if(rel.getName().toString().equals("base")) notBase = false; @@ -677,13 +677,13 @@ public List getAugmentedDescription() rval.addAll(getAnnotations()); return rval; } - + /** * @param args */ public static void main(String[] args) { List description = GameRepository.getDefaultRepository().getGame("conn4").getRules();; - + PropNetAnnotater aa = new PropNetAnnotater(description); System.out.println("Annotations for connect four are: \n"+aa.getAnnotations()); } diff --git a/src/org/ggp/base/util/propnet/factory/converter/PropNetConverter.java b/src/org/ggp/base/util/propnet/factory/converter/PropNetConverter.java index 056baa3fe..dcfc85d89 100644 --- a/src/org/ggp/base/util/propnet/factory/converter/PropNetConverter.java +++ b/src/org/ggp/base/util/propnet/factory/converter/PropNetConverter.java @@ -47,7 +47,7 @@ public final class PropNetConverter *
  • Adds or gates to Propositions with more than one input.
  • *
  • Adds inputs that are implicitly specified by description.
  • * - * + * * @param description * A game description. * @return An equivalent PropNet. @@ -71,7 +71,7 @@ public PropNet convert(List roles, List description) fixDisjunctions(); addMissingInputs(); - + return new PropNet(roles, components); } @@ -104,7 +104,7 @@ private void addMissingInputs() /** * Converts a literal to equivalent PropNet Components and returns a * reference to the last of those components. - * + * * @param literal * The literal to convert to equivalent PropNet Components. * @return The last of those components. @@ -156,7 +156,7 @@ else if ( literal instanceof GdlNot ) /** * Converts a sentence to equivalent PropNet Components and returns the * first of those components. - * + * * @param sentence * The sentence to convert to equivalent PropNet Components. * @return The first of those Components. @@ -193,7 +193,7 @@ private Proposition convertHead(GdlSentence sentence) * convertHead() method on the head, and the * convertConjunct method on every literal in the body and * joining the results by an and gate. - * + * * @param rule * The rule to convert. */ @@ -216,7 +216,7 @@ private void convertRule(GdlRule rule) /** * Converts a sentence to equivalent PropNet Components. - * + * * @param sentence * The sentence to convert to equivalent PropNet Components. */ @@ -299,7 +299,7 @@ private void fixDisjunctions() /** * Returns a Proposition with name term, creating one if none * already exists. - * + * * @param sentence * The name of the Proposition. * @return A Proposition with name term. diff --git a/src/org/ggp/base/util/propnet/factory/flattener/PropNetAnnotatedFlattener.java b/src/org/ggp/base/util/propnet/factory/flattener/PropNetAnnotatedFlattener.java index dd6e86c0e..12e0315b6 100644 --- a/src/org/ggp/base/util/propnet/factory/flattener/PropNetAnnotatedFlattener.java +++ b/src/org/ggp/base/util/propnet/factory/flattener/PropNetAnnotatedFlattener.java @@ -28,15 +28,15 @@ * PropNetAnnotatedFlattener is an implementation of a GDL flattener that needs * the rules to contain ( base ?x ) propositions that explicitly specify domains * for all of the base propositions. - * + * * This flattener should work on all sizes of games, but requires these explicit * annotations to be present in the game description; it cannot infer them. - * + * * A separate PropNetAnnotater class is able to generate these annotations. * Sadly, it can only annotate relatively simple games. If there are no base * propositions in a game description, PropNetAnnotatedFlattener will call * the annotater in an attempt to generate annotations. - * + * * To use this class: * PropNetAnnotatedFlattener AF = new PropNetAnnotatedFlattener(description); * List flatDescription = AF.flatten(); @@ -48,7 +48,7 @@ public final class PropNetAnnotatedFlattener private Map> instantiations; /** An archive of the rules in a game description, indexed by head name. */ private Map> templates; - + /** * Construct a BasicPropNetFlattener for a given game. */ @@ -66,20 +66,20 @@ public PropNetAnnotatedFlattener(List description) { *
  • Creates every instantiation of each rule in the description and * records the result.
  • * - * + * * @param description * A game description. * @return An equivalent description, without variables. */ public List flatten() - { + { description = DeORer.run(description); if (noAnnotations()) { GamerLogger.log("StateMachine", "Could not find 'base' annotations. Attempting to generate them..."); description = new PropNetAnnotater(description).getAugmentedDescription(); GamerLogger.log("StateMachine", "Annotations generated."); } - + templates = recordTemplates(description); instantiations = initializeInstantiations(description); @@ -91,16 +91,16 @@ public List flatten() return flatDescription; } - + public boolean noAnnotations() { for ( Gdl gdl : description ) { - if ( ! (gdl instanceof GdlSentence) ) continue; + if ( ! (gdl instanceof GdlSentence) ) continue; GdlSentence sentence = (GdlSentence) gdl; - + if (sentence.getName().getValue().equals("base")) return false; } - + return true; } @@ -110,7 +110,7 @@ public boolean noAnnotations() { * (base name (arg1 a11 a12 ... a1n) ... (argn an1 an2 ... ann)) * the method will return every possible combination of rules with name * name and args arg1 through argn. - * + * * @param base * A base rule. * @param index @@ -146,7 +146,7 @@ private void expandTrue(GdlSentence base, int index, LinkedList working * constant, building one first if necessary. Rules with heads * named legal are generated by looking up the instantiation for * rules with heads named does and renaming the results. - * + * * @param constant * The name of the head of the rule to instantiate. * @return A list of instantiations. @@ -185,7 +185,7 @@ private List getInstantiations(GdlConstant constant) * Creates an archive of rule instantiations from a game description, * initialized with true rules, built using the reserved * base keyword. - * + * * @param description * A game description. * @return An archive of rule instantiations, indexed by head name. @@ -227,7 +227,7 @@ private Map> initializeInstantiations(List descr * Instantiations are generated by created every possible combination of * instantiations to the literals in the body of the rule so long as those * instantiations do not conflict with each other. - * + * * @param template * The rule to instantiate. * @param index @@ -271,7 +271,7 @@ private void instantiate(GdlRule template, int index, Substitution theta, Setbase keyword. - * + * * @param description * A game description. * @return An archive of rules, indexed by head name. diff --git a/src/org/ggp/base/util/propnet/factory/flattener/PropNetFlattener.java b/src/org/ggp/base/util/propnet/factory/flattener/PropNetFlattener.java index 7d2990c88..37aefad49 100644 --- a/src/org/ggp/base/util/propnet/factory/flattener/PropNetFlattener.java +++ b/src/org/ggp/base/util/propnet/factory/flattener/PropNetFlattener.java @@ -30,7 +30,7 @@ * PropNetFlattener is an implementation of a GDL flattener using fixed-point * analysis of the rules. This flattener works on many small and medium-sized * games, but can fail on very large games. - * + * * To use this class: * PropNetFlattener PF = new PropNetFlattener(description); * List flatDescription = PF.flatten(); @@ -42,27 +42,27 @@ public class PropNetFlattener { private List description; - + private class Assignment extends ArrayList { - private static final long serialVersionUID = 1L; + private static final long serialVersionUID = 1L; } - + private class Assignments extends HashSet { - private static final long serialVersionUID = 1L; + private static final long serialVersionUID = 1L; } - + private class Index extends HashMap { - private static final long serialVersionUID = 1L; + private static final long serialVersionUID = 1L; } - + private class Condition { public Condition(GdlTerm template) - { + { this.template = getConstantAndVariableList(template); key = findGenericForm(template); updateDom(); } - + public void updateDom() { if(!domains.containsKey(key)) @@ -70,34 +70,34 @@ public void updateDom() else dom = domains.get(key); } - + public List template; public Domain dom; GdlTerm key; - + @Override public String toString() { return template.toString(); } } - + private class RuleReference { public List productionTemplate; //The template from the rule head, contains only variables and constants public List conditions = new ArrayList(); //the conditions (right hand side of the rule) public Gdl originalRule; - + public RuleReference(GdlRule originalRule) { this.originalRule = originalRule; } - + @Override public String toString() { return "\n\tProduction: "+(productionTemplate!=null ? productionTemplate.toString() : "null")+" conditions: "+(conditions!=null ? conditions.toString() : "null"); } - + @Override public boolean equals(Object other) { @@ -106,24 +106,24 @@ public boolean equals(Object other) RuleReference rhs = (RuleReference)other; return rhs.productionTemplate==this.productionTemplate && rhs.conditions.equals(this.conditions); } - + @Override public int hashCode() { return productionTemplate.hashCode()+conditions.hashCode(); } } - + private class Domain { public Domain(GdlTerm name, GdlTerm name2) {this.name = name; this.name2 = name2;} - + public Assignments assignments = new Assignments(); - public List indices = new ArrayList(); + public List indices = new ArrayList(); public Set ruleRefs = new HashSet(); - + @SuppressWarnings("unused") public GdlTerm name, name2; - + @Override public String toString() { @@ -142,7 +142,7 @@ public void buildIndices() { { if(c.dom == null) c.updateDom(); - + if(c.dom != null) newConditions.add(c); } @@ -150,15 +150,15 @@ public void buildIndices() { ruleRef.conditions = newConditions; } } - + public void addAssignmentToIndex(Assignment assignment) { for(int i=0; i domains = new HashMap(); - + private List extraRefs = new ArrayList(); - + public PropNetFlattener(List description) { this.description = description; } - + public List flatten() { //Find universe and initial domains @@ -185,22 +185,22 @@ public List flatten() { initializeDomains(gdl); } - + for(Domain d : domains.values()) d.buildIndices(); - + //Compute the actual domains of everything updateDomains(); - + //printDomains(); //printDomainRefs(); - + return getAllInstantiations(); } private List getAllInstantiations() { List rval = new ArrayList(); - + for(Gdl gdl : description) { if(gdl instanceof GdlRelation) @@ -209,17 +209,17 @@ private List getAllInstantiations() { String name = relation.getName().toString(); if(name.equals("base")) continue; - + rval.add(GdlPool.getRule(relation)); } } - + for(Domain d : domains.values()) { for(RuleReference r : d.ruleRefs) { Set> varInstantiations = findSatisfyingInstantiations(r); - + for(Map varInstantiation : varInstantiations){ if(varInstantiation.containsValue(null)) throw new RuntimeException("Shouldn't instantiate anything to null."); @@ -229,8 +229,8 @@ private List getAllInstantiations() { } } } - - + + for(RuleReference ruleRef : extraRefs) { List newConditions = new ArrayList(); @@ -238,7 +238,7 @@ private List getAllInstantiations() { { if(c.dom == null) c.updateDom(); - + if(c.dom != null) newConditions.add(c); } @@ -248,7 +248,7 @@ private List getAllInstantiations() { for(RuleReference r : extraRefs) { Set> varInstantiations = findSatisfyingInstantiations(r); - + for(Map varInstantiation : varInstantiations){ if(varInstantiation.containsValue(null)) throw new RuntimeException("Shouldn't instantiate anything to null."); @@ -257,24 +257,24 @@ private List getAllInstantiations() { if(rval.get(rval.size()-1).toString().contains("null")) throw new RuntimeException("Shouldn't instantiate anything to null."); } - + if(varInstantiations.size() == 0) rval.add(getInstantiation(r.originalRule, new HashMap())); } - + return rval; } - + private GdlRule getInstantiation(Gdl gdl, Map varInstantiation) { Gdl instant = getInstantiationAux(gdl, varInstantiation); - return (GdlRule)instant; + return (GdlRule)instant; } - + private Gdl getInstantiationAux(Gdl gdl, Map varInstantiation) { if(gdl instanceof GdlRelation) { GdlRelation relation = (GdlRelation) gdl; - + List body = new ArrayList(); for(int i=0; i body = new ArrayList(); for(int i=0; i body = new ArrayList(); for(int i=0; i productionTemplate = getConstantAndVariableList(term); - + List> newRHSs = deOr(rule.getBody()); for(List RHS : newRHSs) { @@ -393,7 +393,7 @@ else if(gdl instanceof GdlRule) } dom.ruleRefs.add(ruleRef); } - + } else { @@ -414,8 +414,8 @@ else if(gdl instanceof GdlRule) } } } - } - + } + private Assignment getConstantList(GdlTerm term) { Assignment rval = new Assignment(); if(term instanceof GdlConstant) @@ -425,14 +425,14 @@ private Assignment getConstantList(GdlTerm term) { } else if(term instanceof GdlVariable) throw new RuntimeException("Called getConstantList on something containing a variable."); - + GdlFunction func = (GdlFunction)term; for(GdlTerm t : func.getBody()) rval.addAll(getConstantList(t)); - + return rval; } - + private List getConstantAndVariableList(GdlTerm term) { List rval = new ArrayList(); if(term instanceof GdlConstant) @@ -445,11 +445,11 @@ else if(term instanceof GdlVariable) rval.add(term); return rval; } - + GdlFunction func = (GdlFunction)term; for(GdlTerm t : func.getBody()) rval.addAll(getConstantAndVariableList(t)); - + return rval; } @@ -463,7 +463,7 @@ private GdlTerm findGenericForm(GdlTerm term) { return fillerVar; else if(term instanceof GdlVariable) return fillerVar; - + GdlFunction func = (GdlFunction)term; List newBody = new ArrayList(); for(GdlTerm t : func.getBody()) @@ -497,11 +497,11 @@ private List> deOr2(List> rhsList) { if(!expandedSomething) { List expandedList = expandFirstOr(lit); - + if(expandedList.size() > 1) { for(Gdl replacement : expandedList) - { + { List newRhs = new ArrayList(rhs); if(!(replacement instanceof GdlLiteral)) throw new RuntimeException("Top level return value is different type of gdl."); GdlLiteral newLit = (GdlLiteral)replacement; @@ -509,10 +509,10 @@ private List> deOr2(List> rhsList) { rval.add(newRhs); } expandedSomething = true; - break; + break; } } - + i++; } if(!expandedSomething) //If I didn't find anything to expand @@ -520,10 +520,10 @@ private List> deOr2(List> rhsList) { } else rval.add(rhs); //If I've already expanded this function call - + } - - if(!expandedSomething) + + if(!expandedSomething) return rhsList; else return deOr2(rval); @@ -558,7 +558,7 @@ else if(gdl instanceof GdlOr) rval = new ArrayList(); for(int i=0; i> instantiations = findSatisfyingInstantiations(ruleRef); for(Map instantiation : instantiations) { @@ -647,7 +647,7 @@ void updateDomains() { GdlVariable var = (GdlVariable)t; a.add(instantiation.get(var)); - } + } } if(!d.assignments.contains(a)) { @@ -671,7 +671,7 @@ void updateDomains() //There's a variable and we didn't find an instantiation isVar = true; break; - } + } } if(!isVar && !d.assignments.contains(a)) { @@ -689,26 +689,26 @@ void updateDomains() } } - - private Set> findSatisfyingInstantiations(RuleReference ruleRef) + + private Set> findSatisfyingInstantiations(RuleReference ruleRef) { Map emptyInstantiation = new HashMap(); - + return findSatisfyingInstantiations(ruleRef.conditions, 0, emptyInstantiation); } //Coolest method in this whole thing, does the real work of the JOIN stuff private Set> findSatisfyingInstantiations( List conditions, int idx, - Map instantiation) + Map instantiation) { Set> rval = new HashSet>(); if(idx==conditions.size()) { rval.add(instantiation); return rval; - } - + } + Condition cond = conditions.get(idx); Domain dom = cond.dom; Assignments assignments = null; @@ -724,7 +724,7 @@ private Set> findSatisfyingInstantiations( } else if(t instanceof GdlConstant) c = (GdlConstant)t; - + if(c != null) { if(assignments == null) @@ -754,7 +754,7 @@ else if(t instanceof GdlConstant) { assignments = dom.assignments; } - + for(Assignment a : assignments) { Map newInstantiation = new HashMap(instantiation); @@ -770,7 +770,7 @@ else if(t instanceof GdlConstant) } rval.addAll(findSatisfyingInstantiations(conditions, idx+1, newInstantiation)); } - + return rval; } @@ -779,17 +779,17 @@ else if(t instanceof GdlConstant) */ public static void main(String[] args) { List description = GameRepository.getDefaultRepository().getGame("conn4").getRules(); - + PropNetFlattener flattener = new PropNetFlattener(description); List flattened = flattener.flatten(); System.out.println("Flattened description for connect four contains: \n" + flattened.size() + "\n\n"); - + List strings = new ArrayList(); for(GdlRule rule : flattened) strings.add(rule.toString()); Collections.sort(strings); - + for(String s : strings) - System.out.println(s); + System.out.println(s); } } \ No newline at end of file diff --git a/src/org/ggp/base/util/prover/aima/substituter/Substituter.java b/src/org/ggp/base/util/prover/aima/substituter/Substituter.java index 6c991960d..813d9aa69 100644 --- a/src/org/ggp/base/util/prover/aima/substituter/Substituter.java +++ b/src/org/ggp/base/util/prover/aima/substituter/Substituter.java @@ -31,7 +31,7 @@ public static GdlSentence substitute(GdlSentence sentence, Substitution theta) { return substituteSentence(sentence, theta); } - + public static GdlRule substitute(GdlRule rule, Substitution theta) { return substituteRule(rule, theta); diff --git a/src/org/ggp/base/util/prover/aima/substitution/Substitution.java b/src/org/ggp/base/util/prover/aima/substitution/Substitution.java index a4a5d6352..f98235333 100644 --- a/src/org/ggp/base/util/prover/aima/substitution/Substitution.java +++ b/src/org/ggp/base/util/prover/aima/substitution/Substitution.java @@ -59,10 +59,10 @@ public void put(GdlVariable variable, GdlTerm term) { contents.put(variable, term); } - + /** * Creates an identical substitution. - * + * * @return A new, identical substitution. */ public Substitution copy() diff --git a/src/org/ggp/base/util/prover/aima/unifier/Unifier.java b/src/org/ggp/base/util/prover/aima/unifier/Unifier.java index 6571682d5..0f39de5ed 100644 --- a/src/org/ggp/base/util/prover/aima/unifier/Unifier.java +++ b/src/org/ggp/base/util/prover/aima/unifier/Unifier.java @@ -49,10 +49,10 @@ else if ((x instanceof GdlFunction) && (y instanceof GdlFunction)) if (! unifyTerm(xFunction.getName(), yFunction.getName(), theta)) return false; - + for (int i = 0; i < xFunction.arity(); i++) { - if (! unifyTerm(xFunction.get(i), yFunction.get(i), theta)) + if (! unifyTerm(xFunction.get(i), yFunction.get(i), theta)) return false; } } @@ -60,7 +60,7 @@ else if ((x instanceof GdlFunction) && (y instanceof GdlFunction)) { return false; } - + return true; } diff --git a/src/org/ggp/base/util/reflection/ProjectSearcher.java b/src/org/ggp/base/util/reflection/ProjectSearcher.java index 52a5b3c55..7b1cc0466 100644 --- a/src/org/ggp/base/util/reflection/ProjectSearcher.java +++ b/src/org/ggp/base/util/reflection/ProjectSearcher.java @@ -21,7 +21,7 @@ public static void main(String[] args) public static final LoadedClasses GAMERS = new LoadedClasses(Gamer.class); public static final LoadedClasses GAME_CANVASES = new LoadedClasses(GameCanvas.class); - + public static final ImmutableSet> getAllClassesThatAre(Class klass) { return new LoadedClasses(klass).getConcreteClasses(); } diff --git a/src/org/ggp/base/util/statemachine/FailsafeStateMachine.java b/src/org/ggp/base/util/statemachine/FailsafeStateMachine.java index aeced70b5..06e6e7fcf 100644 --- a/src/org/ggp/base/util/statemachine/FailsafeStateMachine.java +++ b/src/org/ggp/base/util/statemachine/FailsafeStateMachine.java @@ -20,18 +20,18 @@ * fall back to a regular prover if the state machine fails. It's not totally * clear that this is helpful, but it's an additional layer of bullet-proofing * in case anything goes wrong. - * + * * @author Sam Schreiber */ public class FailsafeStateMachine extends StateMachine -{ +{ private StateMachine theBackingMachine = null; private List gameDescription; - + public FailsafeStateMachine (StateMachine theInitialMachine) { theBackingMachine = theInitialMachine; - } - + } + @Override public String getName() { if(theBackingMachine != null) { @@ -39,23 +39,23 @@ public String getName() { } return "Failsafe(null)"; } - + @Override public synchronized void initialize(List description) { this.gameDescription = description; - + if(attemptLoadingInitialMachine()) return; GamerLogger.logError("StateMachine", "Failsafe Machine: failed to load initial state machine. Falling back..."); if(attemptLoadingProverMachine()) return; - + GamerLogger.logError("StateMachine", "Failsafe Machine: catastrophic failure to load *any* state machine. Cannot recover."); GamerLogger.logError("StateMachine", "Failsafe Machine: cannot recover from current state. Shutting down."); - theBackingMachine = null; + theBackingMachine = null; } - + private void failGracefully(Exception e1, Error e2) { if(e1 != null) GamerLogger.logStackTrace("StateMachine", e1); if(e2 != null) GamerLogger.logStackTrace("StateMachine", e2); @@ -64,13 +64,13 @@ private void failGracefully(Exception e1, Error e2) { if(theBackingMachine.getClass() != ProverStateMachine.class) { GamerLogger.logError("StateMachine", "Failsafe Machine: online failure for " + theBackingMachine.getClass() + ". Attempting to restart with a standard prover."); if(attemptLoadingProverMachine()) - return; + return; } - + theBackingMachine = null; - GamerLogger.logError("StateMachine", "Failsafe Machine: online failure for regular prover. Cannot recover."); + GamerLogger.logError("StateMachine", "Failsafe Machine: online failure for regular prover. Cannot recover."); } - + private boolean attemptLoadingInitialMachine() { try { theBackingMachine.initialize(gameDescription); @@ -80,7 +80,7 @@ private boolean attemptLoadingInitialMachine() { } catch(ThreadDeath d) { throw d; } catch(Error e2) { - } + } return false; } @@ -89,23 +89,23 @@ private boolean attemptLoadingProverMachine() { StateMachine theStateMachine = new ProverStateMachine(); theStateMachine.initialize(gameDescription); theBackingMachine = theStateMachine; - GamerLogger.log("StateMachine", "Failsafe Machine: successfully loaded traditional prover."); + GamerLogger.log("StateMachine", "Failsafe Machine: successfully loaded traditional prover."); return true; } catch(Exception e1) { } catch(ThreadDeath d) { throw d; } catch(OutOfMemoryError e) { - throw e; + throw e; } catch(Error e2) { - } + } return false; - } - + } + @Override public int getGoal(MachineState state, Role role) throws GoalDefinitionException { if(theBackingMachine == null) return 0; - + try { return theBackingMachine.getGoal(state, role); } catch(GoalDefinitionException ge) { @@ -113,13 +113,13 @@ public int getGoal(MachineState state, Role role) throws GoalDefinitionException } catch(Exception e) { failGracefully(e, null); } catch(ThreadDeath d) { - throw d; + throw d; } catch(OutOfMemoryError e) { - throw e; + throw e; } catch(Error e) { - failGracefully(null, e); + failGracefully(null, e); } - + return getGoal(state, role); } @@ -127,19 +127,19 @@ public int getGoal(MachineState state, Role role) throws GoalDefinitionException public MachineState getInitialState() { if(theBackingMachine == null) return null; - + try { return theBackingMachine.getInitialState(); } catch(Exception e) { failGracefully(e, null); } catch(ThreadDeath d) { - throw d; + throw d; } catch(OutOfMemoryError e) { - throw e; + throw e; } catch(Error e) { - failGracefully(null, e); + failGracefully(null, e); } - + return getInitialState(); } @@ -147,7 +147,7 @@ public MachineState getInitialState() { public List getLegalMoves(MachineState state, Role role) throws MoveDefinitionException { if(theBackingMachine == null) return null; - + try { return theBackingMachine.getLegalMoves(state, role); } catch(MoveDefinitionException me) { @@ -157,19 +157,19 @@ public List getLegalMoves(MachineState state, Role role) throws MoveDefini } catch(OutOfMemoryError e) { throw e; } catch(ThreadDeath d) { - throw d; + throw d; } catch(Error e) { - failGracefully(null, e); + failGracefully(null, e); } - + return getLegalMoves(state, role); } - + @Override public Move getRandomMove(MachineState state, Role role) throws MoveDefinitionException { if(theBackingMachine == null) return null; - + try { return theBackingMachine.getRandomMove(state, role); } catch(MoveDefinitionException me) { @@ -179,19 +179,19 @@ public Move getRandomMove(MachineState state, Role role) throws MoveDefinitionEx } catch(OutOfMemoryError e) { throw e; } catch(ThreadDeath d) { - throw d; + throw d; } catch(Error e) { - failGracefully(null, e); + failGracefully(null, e); } - + return getRandomMove(state, role); - } + } @Override public MachineState getMachineStateFromSentenceList(Set sentenceList) { if(theBackingMachine == null) return null; - + try { return theBackingMachine.getMachineStateFromSentenceList(sentenceList); } catch(Exception e) { @@ -201,9 +201,9 @@ public MachineState getMachineStateFromSentenceList(Set sentenceLis } catch(OutOfMemoryError e) { throw e; } catch(Error e) { - failGracefully(null, e); + failGracefully(null, e); } - + return getMachineStateFromSentenceList(sentenceList); } @@ -211,7 +211,7 @@ public MachineState getMachineStateFromSentenceList(Set sentenceLis public Move getMoveFromTerm(GdlTerm term) { if(theBackingMachine == null) return null; - + try { return theBackingMachine.getMoveFromTerm(term); } catch(Exception e) { @@ -219,11 +219,11 @@ public Move getMoveFromTerm(GdlTerm term) { } catch(ThreadDeath d) { throw d; } catch(OutOfMemoryError e) { - throw e; + throw e; } catch(Error e) { - failGracefully(null, e); + failGracefully(null, e); } - + return getMoveFromTerm(term); } @@ -231,7 +231,7 @@ public Move getMoveFromTerm(GdlTerm term) { public MachineState getNextState(MachineState state, List moves) throws TransitionDefinitionException { if(theBackingMachine == null) return null; - + try { return theBackingMachine.getNextState(state, moves); } catch(TransitionDefinitionException te) { @@ -241,19 +241,19 @@ public MachineState getNextState(MachineState state, List moves) throws Tr } catch(ThreadDeath d) { throw d; } catch(OutOfMemoryError e) { - throw e; + throw e; } catch(Error e) { - failGracefully(null, e); + failGracefully(null, e); } - + return getNextState(state, moves); } - + @Override public MachineState getNextStateDestructively(MachineState state, List moves) throws TransitionDefinitionException { if(theBackingMachine == null) return null; - + try { return theBackingMachine.getNextStateDestructively(state, moves); } catch(TransitionDefinitionException te) { @@ -263,19 +263,19 @@ public MachineState getNextStateDestructively(MachineState state, List mov } catch(ThreadDeath d) { throw d; } catch(OutOfMemoryError e) { - throw e; + throw e; } catch(Error e) { - failGracefully(null, e); + failGracefully(null, e); } - + return getNextStateDestructively(state, moves); - } + } @Override public Role getRoleFromConstant(GdlConstant constant) { if(theBackingMachine == null) return null; - + try { return theBackingMachine.getRoleFromConstant(constant); } catch(Exception e) { @@ -283,19 +283,19 @@ public Role getRoleFromConstant(GdlConstant constant) { } catch(ThreadDeath d) { throw d; } catch(OutOfMemoryError e) { - throw e; + throw e; } catch(Error e) { - failGracefully(null, e); + failGracefully(null, e); } - + return getRoleFromConstant(constant); } - + @Override public List getRoles() { if(theBackingMachine == null) return null; - + try { return theBackingMachine.getRoles(); } catch(Exception e) { @@ -303,19 +303,19 @@ public List getRoles() { } catch(ThreadDeath d) { throw d; } catch(OutOfMemoryError e) { - throw e; + throw e; } catch(Error e) { - failGracefully(null, e); + failGracefully(null, e); } - + return getRoles(); - } + } @Override public boolean isTerminal(MachineState state) { if(theBackingMachine == null) return false; - + try { return theBackingMachine.isTerminal(state); } catch(Exception e) { @@ -325,17 +325,17 @@ public boolean isTerminal(MachineState state) { } catch(OutOfMemoryError e) { throw e; } catch(Error e) { - failGracefully(null, e); + failGracefully(null, e); } - + return isTerminal(state); } - + @Override public MachineState performDepthCharge(MachineState state, int[] theDepth) throws TransitionDefinitionException, MoveDefinitionException { if(theBackingMachine == null) return null; - + try { return theBackingMachine.performDepthCharge(state, theDepth); } catch (TransitionDefinitionException te) { @@ -349,17 +349,17 @@ public MachineState performDepthCharge(MachineState state, int[] theDepth) throw } catch(OutOfMemoryError e) { throw e; } catch(Error e) { - failGracefully(null, e); + failGracefully(null, e); } - + return performDepthCharge(state, theDepth); } - + @Override public void getAverageDiscountedScoresFromRepeatedDepthCharges(MachineState state, double[] avgScores, double[] avgDepth, double discountFactor, int repetitions) throws TransitionDefinitionException, MoveDefinitionException, GoalDefinitionException { if(theBackingMachine == null) return; - + try { theBackingMachine.getAverageDiscountedScoresFromRepeatedDepthCharges(state, avgScores, avgDepth, discountFactor, repetitions); return; @@ -376,17 +376,17 @@ public void getAverageDiscountedScoresFromRepeatedDepthCharges(MachineState stat } catch(OutOfMemoryError e) { throw e; } catch(Error e) { - failGracefully(null, e); + failGracefully(null, e); } - + getAverageDiscountedScoresFromRepeatedDepthCharges(state, avgScores, avgDepth, discountFactor, repetitions); } - + @Override public void updateRoot(MachineState theState) { if(theBackingMachine == null) return; - + try { theBackingMachine.updateRoot(theState); return; @@ -395,11 +395,11 @@ public void updateRoot(MachineState theState) { } catch(ThreadDeath d) { throw d; } catch(OutOfMemoryError e) { - throw e; + throw e; } catch(Error e) { - failGracefully(null, e); + failGracefully(null, e); } - + updateRoot(theState); } diff --git a/src/org/ggp/base/util/statemachine/MachineState.java b/src/org/ggp/base/util/statemachine/MachineState.java index d854315cb..0a0620c1f 100644 --- a/src/org/ggp/base/util/statemachine/MachineState.java +++ b/src/org/ggp/base/util/statemachine/MachineState.java @@ -8,7 +8,7 @@ public class MachineState { public MachineState() { this.contents = null; } - + /** * Starts with a simple implementation of a MachineState. StateMachines that * want to do more advanced things can subclass this implementation, but for @@ -29,7 +29,7 @@ public Set getContents() { return contents; } - + public MachineState clone() { return new MachineState(new HashSet(contents)); } @@ -47,7 +47,7 @@ public String toString() return "(MachineState with null contents)"; else return contents.toString(); - } + } public boolean equals(Object o) { diff --git a/src/org/ggp/base/util/statemachine/cache/CachedStateMachine.java b/src/org/ggp/base/util/statemachine/cache/CachedStateMachine.java index 690c70e4b..7a6fc22cf 100644 --- a/src/org/ggp/base/util/statemachine/cache/CachedStateMachine.java +++ b/src/org/ggp/base/util/statemachine/cache/CachedStateMachine.java @@ -16,7 +16,7 @@ public final class CachedStateMachine extends StateMachine { private final StateMachine backingStateMachine; - private final TtlCache ttlCache; + private final TtlCache ttlCache; private final class Entry { @@ -109,7 +109,7 @@ public boolean isTerminal(MachineState state) return entry.terminal; } } - + @Override public void doPerMoveWork() { @@ -123,7 +123,7 @@ public void prune() @Override public void initialize(List description) { - backingStateMachine.initialize(description); + backingStateMachine.initialize(description); } @Override @@ -134,7 +134,7 @@ public List getRoles() { @Override public MachineState getInitialState() { - // TODO(schreib): Should this be cached as well? + // TODO(schreib): Should this be cached as well? return backingStateMachine.getInitialState(); } } \ No newline at end of file diff --git a/src/org/ggp/base/util/statemachine/cache/TtlCache.java b/src/org/ggp/base/util/statemachine/cache/TtlCache.java index e02f127e4..cb7d666d2 100644 --- a/src/org/ggp/base/util/statemachine/cache/TtlCache.java +++ b/src/org/ggp/base/util/statemachine/cache/TtlCache.java @@ -17,7 +17,7 @@ * method prune() is called, the TTL of all of the pairs in the * map is decremented, and pairs whose TTL has reached zero are * removed. - * + * * While this class implements the Map interface, keep in mind * that it only decrements the TTL of an entry when that entry * is accessed directly. @@ -42,7 +42,7 @@ public Entry(V value, int ttl) public boolean equals(Object o) { if (o instanceof TtlCache.Entry) { return ((Entry)o).value.equals(value); - } + } return false; } } @@ -66,7 +66,7 @@ public synchronized V get(Object key) Entry entry = contents.get(key); if (entry == null) return null; - + // Reset the TTL when a value is accessed directly. entry.ttl = ttl; return entry.value; @@ -135,7 +135,7 @@ public synchronized Collection values() { theValues.add(e.value); return theValues; } - + private class entrySetMapEntry implements Map.Entry { private K key; private V value; @@ -144,16 +144,16 @@ private class entrySetMapEntry implements Map.Entry { key = k; value = v; } - + public K getKey() { return key; } public V getValue() { return value; } public V setValue(V value) { return (this.value = value); } } - + public synchronized Set> entrySet() { Set> theEntries = new HashSet>(); for (Map.Entry e : contents.entrySet()) theEntries.add(new entrySetMapEntry(e.getKey(), e.getValue().value)); return theEntries; - } + } } \ No newline at end of file diff --git a/src/org/ggp/base/util/statemachine/implementation/propnet/SamplePropNetStateMachine.java b/src/org/ggp/base/util/statemachine/implementation/propnet/SamplePropNetStateMachine.java index 71b01445d..81f9999e0 100644 --- a/src/org/ggp/base/util/statemachine/implementation/propnet/SamplePropNetStateMachine.java +++ b/src/org/ggp/base/util/statemachine/implementation/propnet/SamplePropNetStateMachine.java @@ -33,7 +33,7 @@ public class SamplePropNetStateMachine extends StateMachine { private List ordering; /** The player roles */ private List roles; - + /** * Initializes the PropNetStateMachine. You should compute the topological * ordering here. Additionally you may compute the initial state here, at @@ -44,8 +44,8 @@ public void initialize(List description) { propNet = PropNetFactory.create(description); roles = propNet.getRoles(); ordering = getOrdering(); - } - + } + /** * Computes if the state is terminal. Should return the value * of the terminal proposition for the state. @@ -55,13 +55,13 @@ public boolean isTerminal(MachineState state) { // TODO: Compute whether the MachineState is terminal. return false; } - + /** * Computes the goal for a role in the current state. * Should return the value of the goal proposition that * is true for that role. If there is not exactly one goal * proposition true for that role, then you should throw a - * GoalDefinitionException because the goal is ill-defined. + * GoalDefinitionException because the goal is ill-defined. */ @Override public int getGoal(MachineState state, Role role) @@ -69,7 +69,7 @@ public int getGoal(MachineState state, Role role) // TODO: Compute the goal for role in state. return -1; } - + /** * Returns the initial state. The initial state can be computed * by only setting the truth value of the INIT proposition to true, @@ -80,7 +80,7 @@ public MachineState getInitialState() { // TODO: Compute the initial state. return null; } - + /** * Computes the legal moves for role in state. */ @@ -90,7 +90,7 @@ public List getLegalMoves(MachineState state, Role role) // TODO: Compute legal moves. return null; } - + /** * Computes the next state given state and the list of moves. */ @@ -100,37 +100,37 @@ public MachineState getNextState(MachineState state, List moves) // TODO: Compute the next state. return null; } - + /** * This should compute the topological ordering of propositions. * Each component is either a proposition, logical gate, or transition. * Logical gates and transitions only have propositions as inputs. - * + * * The base propositions and input propositions should always be exempt * from this ordering. - * + * * The base propositions values are set from the MachineState that * operations are performed on and the input propositions are set from * the Moves that operations are performed on as well (if any). - * + * * @return The order in which the truth values of propositions need to be set. */ public List getOrdering() { // List to contain the topological ordering. List order = new LinkedList(); - + // All of the components in the PropNet List components = new ArrayList(propNet.getComponents()); - + // All of the propositions in the PropNet. List propositions = new ArrayList(propNet.getPropositions()); - - // TODO: Compute the topological ordering. - + + // TODO: Compute the topological ordering. + return order; } - + /* Already implemented for you */ @Override public List getRoles() { @@ -138,15 +138,15 @@ public List getRoles() { } /* Helper methods */ - + /** * The Input propositions are indexed by (does ?player ?action). - * + * * This translates a list of Moves (backed by a sentence that is simply ?action) * into GdlSentences that can be used to get Propositions from inputPropositions. - * and accordingly set their values etc. This is a naive implementation when coupled with + * and accordingly set their values etc. This is a naive implementation when coupled with * setting input values, feel free to change this for a more efficient implementation. - * + * * @param moves * @return */ @@ -154,7 +154,7 @@ private List toDoes(List moves) { List doeses = new ArrayList(moves.size()); Map roleIndices = getRoleIndices(); - + for (int i = 0; i < roles.size(); i++) { int index = roleIndices.get(roles.get(i)); @@ -162,7 +162,7 @@ private List toDoes(List moves) } return doeses; } - + /** * Takes in a Legal Proposition and returns the appropriate corresponding Move * @param p @@ -172,25 +172,25 @@ public static Move getMoveFromProposition(Proposition p) { return new Move(p.getName().get(1)); } - + /** * Helper method for parsing the value of a goal proposition * @param goalProposition * @return the integer value of the goal proposition - */ + */ private int getGoalValue(Proposition goalProposition) { GdlRelation relation = (GdlRelation) goalProposition.getName(); GdlConstant constant = (GdlConstant) relation.get(1); return Integer.parseInt(constant.toString()); } - + /** * A Naive implementation that computes a PropNetMachineState * from the true BasePropositions. This is correct but slower than more advanced implementations * You need not use this method! * @return PropNetMachineState - */ + */ public MachineState getStateFromBase() { Set contents = new HashSet(); diff --git a/src/org/ggp/base/util/statemachine/verifier/StateMachineVerifier.java b/src/org/ggp/base/util/statemachine/verifier/StateMachineVerifier.java index e3f9ee8a9..98c830561 100644 --- a/src/org/ggp/base/util/statemachine/verifier/StateMachineVerifier.java +++ b/src/org/ggp/base/util/statemachine/verifier/StateMachineVerifier.java @@ -19,12 +19,12 @@ public static boolean checkMachineConsistency(StateMachine theReference, StateMa List theMachines = new ArrayList(); theMachines.add(theReference); theMachines.add(theSubject); - + GamerLogger.emitToConsole("Consistency checking: ["); int nRound = 0; while(true) { nRound++; - + GamerLogger.emitToConsole("."); MachineState[] theCurrentStates = new MachineState[theMachines.size()]; for(int i = 0; i < theMachines.size(); i++) { @@ -32,14 +32,14 @@ public static boolean checkMachineConsistency(StateMachine theReference, StateMa theCurrentStates[i] = theMachines.get(i).getInitialState(); } catch(Exception e) { GamerLogger.log("StateMachine", "Machine #" + i + " failed to generate an initial state!"); - return false; + return false; } } while(!theMachines.get(0).isTerminal(theCurrentStates[0])) { if(System.currentTimeMillis() > startTime + timeToSpend) - break; - + break; + // Do per-state consistency checks for(int i = 1; i < theMachines.size(); i++) { for(Role theRole : theMachines.get(0).getRoles()) { @@ -66,7 +66,7 @@ public static boolean checkMachineConsistency(StateMachine theReference, StateMa } catch(Exception e) { GamerLogger.logStackTrace("StateMachine", e); } - } + } } catch(Exception e) { GamerLogger.logStackTrace("StateMachine", e); } @@ -74,7 +74,7 @@ public static boolean checkMachineConsistency(StateMachine theReference, StateMa if(System.currentTimeMillis() > startTime + timeToSpend) break; - + // Do final consistency checks for(int i = 1; i < theMachines.size(); i++) { if(!theMachines.get(i).isTerminal(theCurrentStates[i])) { @@ -95,7 +95,7 @@ public static boolean checkMachineConsistency(StateMachine theReference, StateMa } } catch(Exception e) { GamerLogger.log("StateMachine", "Inconsistency between machine #" + i + " and ProverStateMachine over goal-ness of state " + theCurrentStates[0] + " vs " + theCurrentStates[i]); - return false; + return false; } } } diff --git a/src/org/ggp/base/util/symbol/factory/SymbolFactory.java b/src/org/ggp/base/util/symbol/factory/SymbolFactory.java index d85bffede..a97826322 100644 --- a/src/org/ggp/base/util/symbol/factory/SymbolFactory.java +++ b/src/org/ggp/base/util/symbol/factory/SymbolFactory.java @@ -25,10 +25,10 @@ public static Symbol create(String string) throws SymbolFormatException { throw new SymbolFormatException(string); } - } + } /* Private, implementation-specific methods below here */ - + private static Symbol convert(LinkedList tokens) { if (tokens.getFirst().equals("(")) diff --git a/src/org/ggp/base/util/symbol/grammar/SymbolPool.java b/src/org/ggp/base/util/symbol/grammar/SymbolPool.java index a0708d730..3b253aaab 100644 --- a/src/org/ggp/base/util/symbol/grammar/SymbolPool.java +++ b/src/org/ggp/base/util/symbol/grammar/SymbolPool.java @@ -14,11 +14,11 @@ public final class SymbolPool /** * If the pool does not have a mapping for the given key, adds a mapping from key to value * to the pool. - * + * * Note that even if you've checked to make sure that the pool doesn't contain the key, * you still shouldn't assume that this method actually inserts the given value, since * this class is accessed by multiple threads simultaneously. - * + * * @return the value mapped to by key in the pool */ private static V addToPool(K key, V value, ConcurrentMap pool) { @@ -28,13 +28,13 @@ private static V addToPool(K key, V value, ConcurrentMap pool) { else return prevValue; } - + public static SymbolAtom getAtom(String value) { SymbolAtom ret = atomPool.get(value); if(ret == null) ret = addToPool(value, new SymbolAtom(value), atomPool); - + return ret; } @@ -43,7 +43,7 @@ public static SymbolList getList(List contents) SymbolList ret = listPool.get(contents); if(ret == null) ret = addToPool(contents, new SymbolList(contents), listPool); - + return ret; } diff --git a/src/org/ggp/base/util/ui/CloseableTabs.java b/src/org/ggp/base/util/ui/CloseableTabs.java index 949139cd8..8199ec103 100644 --- a/src/org/ggp/base/util/ui/CloseableTabs.java +++ b/src/org/ggp/base/util/ui/CloseableTabs.java @@ -17,19 +17,19 @@ public class CloseableTabs { private final static int CLOSE_ICON_SIZE = 8; - + public static void addClosableTab(JTabbedPane tabPane, JComponent tabContent, String tabName, AbstractAction closeAction) { JPanel tabTopPanel = new JPanel(new GridBagLayout()); tabTopPanel.setOpaque(false); - - JButton btnClose = new JButton(); + + JButton btnClose = new JButton(); BufferedImage img = new BufferedImage(CLOSE_ICON_SIZE, CLOSE_ICON_SIZE, BufferedImage.TYPE_4BYTE_ABGR); - Graphics g = img.getGraphics(); + Graphics g = img.getGraphics(); g.setColor(Color.BLACK); g.drawLine(0, CLOSE_ICON_SIZE-1, CLOSE_ICON_SIZE-1, 0); g.drawLine(0, 0, CLOSE_ICON_SIZE-1, CLOSE_ICON_SIZE-1); btnClose.setIcon(new ImageIcon(img)); - btnClose.addActionListener(closeAction); + btnClose.addActionListener(closeAction); tabTopPanel.add(new JLabel(tabName), new GridBagConstraints(0, 0, 1, 1, 1.0, 1.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0)); tabTopPanel.add(btnClose, new GridBagConstraints(1, 0, 1, 1, 1.0, 1.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 4, 0, 0), 0, 0)); diff --git a/src/org/ggp/base/util/ui/ConsolePanel.java b/src/org/ggp/base/util/ui/ConsolePanel.java index 6efcc85b8..8e6f8e892 100644 --- a/src/org/ggp/base/util/ui/ConsolePanel.java +++ b/src/org/ggp/base/util/ui/ConsolePanel.java @@ -16,24 +16,24 @@ * ConsolePanel implements a light-weight panel that shows all of the * messages being send to stdout and stderr. This can be useful in a graphical * application that also needs to alert the user about warnings that occur in - * lower-level components, like the network communication stack. + * lower-level components, like the network communication stack. */ @SuppressWarnings("serial") public class ConsolePanel extends JPanel { public ConsolePanel() { super(new BorderLayout()); - + // Create an output console. outputConsole = new JTextArea(); outputConsole.setEditable(false); - outputConsole.setForeground(new Color(125, 0, 0)); + outputConsole.setForeground(new Color(125, 0, 0)); outputConsole.setText("(Console output will be displayed here.)\n\n"); JScrollPane outputConsolePane = new JScrollPane(outputConsole); - + setBorder(new TitledBorder("Java Console:")); - add(outputConsolePane, BorderLayout.CENTER); + add(outputConsolePane, BorderLayout.CENTER); validate(); - + // Send the standard out and standard error streams // to this panel, instead. OutputStream out = new OutputStream() { @@ -48,9 +48,9 @@ public void write(byte[] b) throws IOException { } }; System.setOut(new PrintStream(out, true)); - System.setErr(new PrintStream(out, true)); + System.setErr(new PrintStream(out, true)); } - + private final JTextArea outputConsole; private void updateTextArea(final String text) { SwingUtilities.invokeLater(new Runnable() { diff --git a/src/org/ggp/base/util/ui/GameSelector.java b/src/org/ggp/base/util/ui/GameSelector.java index 285ca407b..cfb75a0ff 100644 --- a/src/org/ggp/base/util/ui/GameSelector.java +++ b/src/org/ggp/base/util/ui/GameSelector.java @@ -22,44 +22,44 @@ * is a little rough, and could use some polish, but it provides all * of the important functionality: you can load games both from local * storage and from game repositories on the web. - * + * * @author Sam Schreiber */ public class GameSelector implements ActionListener { JComboBox theGameList; JComboBox theRepositoryList; - + GameRepository theSelectedRepository; Map theCachedRepositories; class NamedItem { public final String theKey; public final String theName; - + public NamedItem(String theKey, String theName) { this.theKey = theKey; this.theName = theName; } - + public String toString() { return theName; } } - + public GameSelector() { theGameList = new JComboBox(); - theGameList.addActionListener(this); - + theGameList.addActionListener(this); + theRepositoryList = new JComboBox(); theRepositoryList.addActionListener(this); - theCachedRepositories = new HashMap(); + theCachedRepositories = new HashMap(); theRepositoryList.addItem("games.ggp.org/base"); theRepositoryList.addItem("games.ggp.org/dresden"); theRepositoryList.addItem("games.ggp.org/stanford"); theRepositoryList.addItem("Local Game Repository"); } - + @Override public void actionPerformed(ActionEvent e) { if (e.getSource() == theRepositoryList) { @@ -76,14 +76,14 @@ public void actionPerformed(ActionEvent e) { } repopulateGameList(); } - } - + } + public GameRepository getSelectedGameRepository() { return theSelectedRepository; } - - public void repopulateGameList() { - GameRepository theRepository = getSelectedGameRepository(); + + public void repopulateGameList() { + GameRepository theRepository = getSelectedGameRepository(); List theKeyList = new ArrayList(theRepository.getGameKeys()); Collections.sort(theKeyList); theGameList.removeAllItems(); @@ -101,15 +101,15 @@ public void repopulateGameList() { theGameList.addItem(new NamedItem(theKey, theName)); } } - + public JComboBox getRepositoryList() { return theRepositoryList; } - + public JComboBox getGameList() { return theGameList; } - + public Game getSelectedGame() { try { return getSelectedGameRepository().getGame(((NamedItem)theGameList.getSelectedItem()).theKey); diff --git a/src/org/ggp/base/util/ui/GameStateRenderer.java b/src/org/ggp/base/util/ui/GameStateRenderer.java index 7986abb71..bf1a5cc19 100644 --- a/src/org/ggp/base/util/ui/GameStateRenderer.java +++ b/src/org/ggp/base/util/ui/GameStateRenderer.java @@ -25,13 +25,13 @@ * that converts that XML match state into HTML. After rendering the match * state in HTML as a DOM, it renders that DOM into a BufferedImage which * can be displayed to the user. - * + * * TODO: This class is still pretty rough, and I suspect there's much room * for improvement. Furthermore, improving this class will yield immediate * visible benefits, in terms of better visualizations and such. For example, * when rendering games that don't take up the full 600x600 image, there's an * empty black space on the final image, which looks bad. That could be fixed. - * + * * @author Ethan Dreyfuss and Sam Schreiber */ public class GameStateRenderer { @@ -48,10 +48,10 @@ public static synchronized void renderImagefromGameXML(String gameXML, String XS String xhtml = getXHTMLfromGameXML(gameXML, XSL); xhtml = xhtml.replace("", ""); - + xhtml = xhtml.replace("", "
    "); xhtml = xhtml.replace("", "
    "); - + InputSource is = new InputSource(new BufferedReader(new StringReader(xhtml))); Document dom = XMLResource.load(is).getDocument(); @@ -64,7 +64,7 @@ public static synchronized void renderImagefromGameXML(String gameXML, String XS private static String getXHTMLfromGameXML(String gameXML, String XSL) { XSL = XSL.replace("]>", ""); XSL = XSL.replace("&ROOT;", "http://games.ggp.org/base").trim(); - + IOString game = new IOString(gameXML); IOString xslIOString = new IOString(XSL); IOString content = new IOString(""); @@ -78,7 +78,7 @@ private static String getXHTMLfromGameXML(String gameXML, String XSL) { } catch (Exception ex) { ex.printStackTrace(); } - + Tidy tidy = new Tidy(); tidy.setXHTML(true); tidy.setShowWarnings(false); @@ -86,7 +86,7 @@ private static String getXHTMLfromGameXML(String gameXML, String XSL) { tidy.setDropEmptyParas(false); IOString tidied = new IOString(""); - tidy.parse(content.getInputStream(), tidied.getOutputStream()); + tidy.parse(content.getInputStream(), tidied.getOutputStream()); return tidied.getString(); } @@ -99,7 +99,7 @@ public IOString(String s) { } public String getString() { return buf.toString(); - } + } public InputStream getInputStream() { return new IOString.IOStringInputStream(); diff --git a/src/org/ggp/base/util/ui/JLabelBold.java b/src/org/ggp/base/util/ui/JLabelBold.java index 93da899d9..fe438ba21 100644 --- a/src/org/ggp/base/util/ui/JLabelBold.java +++ b/src/org/ggp/base/util/ui/JLabelBold.java @@ -5,7 +5,7 @@ public class JLabelBold extends JLabel { private static final long serialVersionUID = 1L; - public JLabelBold(String text) { + public JLabelBold(String text) { super(text); setFont(new Font(getFont().getFamily(), Font.BOLD, getFont().getSize()+2)); } diff --git a/src/org/ggp/base/util/ui/NativeUI.java b/src/org/ggp/base/util/ui/NativeUI.java index 7992ae96c..f0a320b47 100644 --- a/src/org/ggp/base/util/ui/NativeUI.java +++ b/src/org/ggp/base/util/ui/NativeUI.java @@ -8,7 +8,7 @@ * system that it's running on. This is wrapped into its own separate class * because it's used in a number of different places (all of the graphical * applications) and it's useful to edit it centrally. - * + * * @author Sam Schreiber */ public class NativeUI { diff --git a/src/org/ggp/base/util/ui/PlayerSelector.java b/src/org/ggp/base/util/ui/PlayerSelector.java index 00a9904f7..7eb9ad4d2 100644 --- a/src/org/ggp/base/util/ui/PlayerSelector.java +++ b/src/org/ggp/base/util/ui/PlayerSelector.java @@ -20,11 +20,11 @@ public class PlayerSelector { private PlayerPresenceManager thePresenceManager; - + public PlayerSelector() { thePresenceManager = new PlayerPresenceManager(); } - + class PlayerPresenceLabel extends JLabel implements ListCellRenderer { private static final long serialVersionUID = 1L; private int maxLabelLength; @@ -35,7 +35,7 @@ public PlayerPresenceLabel(int maxLabelLength) { setVerticalAlignment(CENTER); this.maxLabelLength = maxLabelLength; } - + public Component getListCellRendererComponent( JList list, String value, @@ -50,15 +50,15 @@ public Component getListCellRendererComponent( setBackground(list.getBackground()); setForeground(list.getForeground()); } - + PlayerPresence presence = thePresenceManager.getPresence(value.toString()); String status = presence.getStatus(); if (status != null) status = status.toLowerCase(); - - int iconSize = 20; - + + int iconSize = 20; + BufferedImage img = new BufferedImage( iconSize, iconSize, BufferedImage.TYPE_INT_RGB ); - Graphics g = img.getGraphics(); + Graphics g = img.getGraphics(); g.setColor( getBackground() ); g.fillRect( 0, 0, iconSize, iconSize ); if (status == null) { @@ -72,9 +72,9 @@ public Component getListCellRendererComponent( } else { g.setColor(Color.MAGENTA); } - + g.fillOval( 3, 3, iconSize-6, iconSize-6 ); - + String textLabel = presence.getHost() + ":" + presence.getPort(); if (presence.getName() != null) { textLabel = presence.getName() + " (" + textLabel + ")"; @@ -82,14 +82,14 @@ public Component getListCellRendererComponent( if (textLabel.length() > maxLabelLength) { textLabel = textLabel.substring(0, maxLabelLength-3) + "..."; } - + setIcon(new ImageIcon(img)); setText(textLabel); - setFont(list.getFont()); + setFont(list.getFont()); return this; } } - + class PlayerSelectorBox extends JComboBox implements Observer { private static final long serialVersionUID = 1L; @@ -98,11 +98,11 @@ public PlayerSelectorBox() { setRenderer(new PlayerPresenceLabel(20)); addAllPlayerItems(); } - + private void addAllPlayerItems() { for (String name : thePresenceManager.getSortedPlayerNames()) { addItem(name); - } + } } @Override @@ -111,7 +111,7 @@ public void observe(Event event) { repaint(); revalidate(); } else if (event instanceof PlayerPresenceManager.PlayerPresenceAdded || - event instanceof PlayerPresenceManager.PlayerPresenceRemoved) { + event instanceof PlayerPresenceManager.PlayerPresenceRemoved) { Object currentlySelected = getSelectedItem(); removeAllItems(); addAllPlayerItems(); @@ -121,7 +121,7 @@ public void observe(Event event) { } } } - + class PlayerSelectorList extends JList implements Observer { private static final long serialVersionUID = 1L; @@ -131,7 +131,7 @@ public PlayerSelectorList() { setSelectionMode(ListSelectionModel.SINGLE_SELECTION); setAllPlayerItems(); } - + private void setAllPlayerItems() { setListData(thePresenceManager.getSortedPlayerNames().toArray(new String[0])); } @@ -140,7 +140,7 @@ private void setAllPlayerItems() { public void observe(Event event) { if (event instanceof PlayerPresenceManager.PlayerPresenceChanged) { repaint(); - revalidate(); + revalidate(); } else if (event instanceof PlayerPresenceManager.PlayerPresenceAdded || event instanceof PlayerPresenceManager.PlayerPresenceRemoved) { Object currentlySelected = getSelectedValue(); @@ -149,26 +149,26 @@ public void observe(Event event) { repaint(); revalidate(); } - } + } } - + public void addPlayer(String hostport) throws InvalidHostportException { thePresenceManager.addPlayer(hostport); } - + public void removePlayer(String hostport) { thePresenceManager.removePlayer(hostport); - } - + } + public PlayerPresence getPlayerPresence(String name) { return thePresenceManager.getPresence(name); } - + public JComboBox getPlayerSelectorBox() { return new PlayerSelectorBox(); } - + public JList getPlayerSelectorList() { return new PlayerSelectorList(); - } + } } \ No newline at end of file diff --git a/src/org/ggp/base/util/ui/PublishButton.java b/src/org/ggp/base/util/ui/PublishButton.java index 73400d800..fc72f9bad 100644 --- a/src/org/ggp/base/util/ui/PublishButton.java +++ b/src/org/ggp/base/util/ui/PublishButton.java @@ -12,13 +12,13 @@ @SuppressWarnings("serial") public class PublishButton extends JButton implements ActionListener { private GameServer theServer; - + public PublishButton(String theName) { super(theName); this.addActionListener(this); this.setEnabled(false); } - + public void setServer(GameServer theServer) { this.theServer = theServer; this.setEnabled(true); @@ -36,8 +36,8 @@ public void actionPerformed(ActionEvent e) { int nChoice = JOptionPane.showConfirmDialog(this, "Publishing successfully. Would you like to open the spectator view in a browser?", "Publishing Match Online", - JOptionPane.YES_NO_OPTION); - if (nChoice == JOptionPane.YES_OPTION) { + JOptionPane.YES_NO_OPTION); + if (nChoice == JOptionPane.YES_OPTION) { try { java.awt.Desktop.getDesktop().browse(java.net.URI.create(theURL)); } catch (Exception ee) { @@ -48,7 +48,7 @@ public void actionPerformed(ActionEvent e) { JOptionPane.showMessageDialog(this, "Unknown problem when publishing match.", "Publishing Match Online", - JOptionPane.ERROR_MESSAGE); + JOptionPane.ERROR_MESSAGE); } } else { JOptionPane.showMessageDialog(this,