diff --git a/.settings/org.eclipse.jdt.ui.prefs b/.settings/org.eclipse.jdt.ui.prefs
new file mode 100644
index 000000000..2b54565e9
--- /dev/null
+++ b/.settings/org.eclipse.jdt.ui.prefs
@@ -0,0 +1,56 @@
+#Thu Nov 14 14:53:34 PST 2013
+cleanup_settings_version=2
+eclipse.preferences.version=1
+editor_save_participant_org.eclipse.jdt.ui.postsavelistener.cleanup=true
+sp_cleanup.add_default_serial_version_id=true
+sp_cleanup.add_generated_serial_version_id=false
+sp_cleanup.add_missing_annotations=true
+sp_cleanup.add_missing_deprecated_annotations=true
+sp_cleanup.add_missing_methods=false
+sp_cleanup.add_missing_nls_tags=false
+sp_cleanup.add_missing_override_annotations=true
+sp_cleanup.add_missing_override_annotations_interface_methods=true
+sp_cleanup.add_serial_version_id=false
+sp_cleanup.always_use_blocks=true
+sp_cleanup.always_use_parentheses_in_expressions=false
+sp_cleanup.always_use_this_for_non_static_field_access=false
+sp_cleanup.always_use_this_for_non_static_method_access=false
+sp_cleanup.convert_to_enhanced_for_loop=false
+sp_cleanup.correct_indentation=false
+sp_cleanup.format_source_code=false
+sp_cleanup.format_source_code_changes_only=false
+sp_cleanup.make_local_variable_final=false
+sp_cleanup.make_parameters_final=false
+sp_cleanup.make_private_fields_final=true
+sp_cleanup.make_type_abstract_if_missing_method=false
+sp_cleanup.make_variable_declarations_final=false
+sp_cleanup.never_use_blocks=false
+sp_cleanup.never_use_parentheses_in_expressions=true
+sp_cleanup.on_save_use_additional_actions=true
+sp_cleanup.organize_imports=true
+sp_cleanup.qualify_static_field_accesses_with_declaring_class=false
+sp_cleanup.qualify_static_member_accesses_through_instances_with_declaring_class=true
+sp_cleanup.qualify_static_member_accesses_through_subtypes_with_declaring_class=true
+sp_cleanup.qualify_static_member_accesses_with_declaring_class=false
+sp_cleanup.qualify_static_method_accesses_with_declaring_class=false
+sp_cleanup.remove_private_constructors=true
+sp_cleanup.remove_trailing_whitespaces=true
+sp_cleanup.remove_trailing_whitespaces_all=true
+sp_cleanup.remove_trailing_whitespaces_ignore_empty=false
+sp_cleanup.remove_unnecessary_casts=false
+sp_cleanup.remove_unnecessary_nls_tags=false
+sp_cleanup.remove_unused_imports=true
+sp_cleanup.remove_unused_local_variables=false
+sp_cleanup.remove_unused_private_fields=true
+sp_cleanup.remove_unused_private_members=false
+sp_cleanup.remove_unused_private_methods=true
+sp_cleanup.remove_unused_private_types=true
+sp_cleanup.sort_members=false
+sp_cleanup.sort_members_all=false
+sp_cleanup.use_blocks=false
+sp_cleanup.use_blocks_only_for_return_and_throw=false
+sp_cleanup.use_parentheses_in_expressions=false
+sp_cleanup.use_this_for_non_static_field_access=false
+sp_cleanup.use_this_for_non_static_field_access_only_if_necessary=true
+sp_cleanup.use_this_for_non_static_method_access=false
+sp_cleanup.use_this_for_non_static_method_access_only_if_necessary=true
diff --git a/src/external/JSON/JSONArray.java b/src/external/JSON/JSONArray.java
index 3a0d49915..7e728989f 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.
@@ -808,7 +808,8 @@ public JSONObject toJSONObject(JSONArray names) throws JSONException {
* @return a printable, displayable, transmittable
* representation of the array.
*/
- public String toString() {
+ @Override
+ public String toString() {
try {
return '[' + join(",") + ']';
} catch (Exception e) {
diff --git a/src/external/JSON/JSONException.java b/src/external/JSON/JSONException.java
index 9b2055c79..a799ac5fa 100644
--- a/src/external/JSON/JSONException.java
+++ b/src/external/JSON/JSONException.java
@@ -22,7 +22,8 @@ public JSONException(Throwable cause) {
this.cause = cause;
}
- public Throwable getCause() {
+ @Override
+ public Throwable getCause() {
return this.cause;
}
}
diff --git a/src/external/JSON/JSONObject.java b/src/external/JSON/JSONObject.java
index f11ed5fa1..bc0afc607 100644
--- a/src/external/JSON/JSONObject.java
+++ b/src/external/JSON/JSONObject.java
@@ -27,8 +27,8 @@ of this software and associated documentation files (the "Software"), to deal
import java.io.IOException;
import java.io.Writer;
import java.lang.reflect.Field;
-import java.lang.reflect.Modifier;
import java.lang.reflect.Method;
+import java.lang.reflect.Modifier;
import java.util.Collection;
import java.util.Enumeration;
import java.util.HashMap;
@@ -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"}
.
*
@@ -103,7 +103,8 @@ private static final class Null {
* so the clone method returns itself.
* @return NULL.
*/
- protected final Object clone() {
+ @Override
+ protected final Object clone() {
return this;
}
@@ -113,7 +114,8 @@ protected final Object clone() {
* @return true if the object parameter is the JSONObject.NULL object
* or null.
*/
- public boolean equals(Object object) {
+ @Override
+ public boolean equals(Object object) {
return object == null || object == this;
}
@@ -121,7 +123,8 @@ public boolean equals(Object object) {
* Get the "null" string value.
* @return The string "null".
*/
- public String toString() {
+ @Override
+ public String toString() {
return "null";
}
}
@@ -156,7 +159,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 +235,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 +323,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 +354,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 +423,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 +501,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 +558,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 +642,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 +660,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 +735,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 +939,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 +959,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 +1140,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 , producing <\/,
- * allowing JSON text to be delivered in HTML. In JSON text, a string
+ * allowing JSON text to be delivered in HTML. In JSON text, a string
* cannot contain a control character or an unescaped quote or backslash.
* @param string A String
* @return A String correctly formatted for insertion in a JSON text.
@@ -1240,8 +1243,8 @@ public static Object stringToValue(String string) {
}
/*
- * If it might be a number, try converting it.
- * We support the non-standard 0x- convention.
+ * If it might be a number, try converting it.
+ * We support the non-standard 0x- convention.
* If a number cannot be produced, then the value will just
* be a string. Note that the 0x-, plus, and implied string
* conventions are non-standard. A JSON parser may accept
@@ -1258,7 +1261,7 @@ public static Object stringToValue(String string) {
}
}
try {
- if (string.indexOf('.') > -1 ||
+ if (string.indexOf('.') > -1 ||
string.indexOf('e') > -1 || string.indexOf('E') > -1) {
return Double.valueOf(string);
} else {
@@ -1329,7 +1332,8 @@ public JSONArray toJSONArray(JSONArray names) throws JSONException {
* with {
(left brace) and ending
* with }
(right brace) .
*/
- public String toString() {
+ @Override
+ public String toString() {
try {
Iterator> keys = keys();
StringBuffer sb = new StringBuffer("{");
@@ -1536,11 +1540,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 +1556,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 +1588,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..72c80693b 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.
@@ -438,8 +438,9 @@ public JSONException syntaxError(String message) {
*
* @return " at {index} [character {character} line {line}]"
*/
- public String toString() {
- return " at " + index + " [character " + this.character + " line " +
+ @Override
+ public String toString() {
+ 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..50e933451 100644
--- a/src/org/ggp/base/apps/kiosk/GameCanvas.java
+++ b/src/org/ggp/base/apps/kiosk/GameCanvas.java
@@ -27,44 +27,47 @@
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) {
+ @Override
+ 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){
+
+ @Override
+ public void mouseReleased(MouseEvent e){
lastClickX = -1;
- lastClickY = -1;
+ lastClickY = -1;
}
- });
-
+ });
+
addMouseMotionListener( new MouseMotionAdapter() {
- public void mouseDragged(MouseEvent e) {
+ @Override
+ public void mouseDragged(MouseEvent e) {
if(lastClickX == -1)
return;
@@ -72,34 +75,35 @@ 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){
+
+ @Override
+ 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 +111,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 +145,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 +186,7 @@ protected Set gameStateHasFactsMatching(String ptrn) {
}
return theMatches;
}
-
+
protected boolean gameStateHasLegalMove(String move) {
try {
List legalMoves = stateMachine.getLegalMoves(gameState, myRole);
@@ -190,12 +194,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 +219,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 +229,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 +260,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..54219bad4 100644
--- a/src/org/ggp/base/apps/kiosk/Kiosk.java
+++ b/src/org/ggp/base/apps/kiosk/Kiosk.java
@@ -13,6 +13,7 @@
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
+
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
@@ -26,7 +27,6 @@
import javax.swing.ListSelectionModel;
import javax.swing.border.TitledBorder;
-import com.google.common.collect.Lists;
import org.ggp.base.player.GamePlayer;
import org.ggp.base.player.gamer.Gamer;
import org.ggp.base.player.gamer.exception.AbortingException;
@@ -47,19 +47,21 @@
import org.ggp.base.util.ui.NativeUI;
import org.ggp.base.util.ui.PublishButton;
+import com.google.common.collect.Lists;
+
/**
* Kiosk is a program for running two-player human-vs-computer matches
* 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");
@@ -74,7 +76,8 @@ public static void main(String[] args)
NativeUI.setNativeUI();
final Kiosk serverPanel = new Kiosk();
javax.swing.SwingUtilities.invokeLater(new Runnable() {
- public void run() {
+ @Override
+ public void run() {
createAndShowGUI(serverPanel);
}
});
@@ -84,29 +87,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 extends GameCanvas> availableCanvas : theAvailableCanvasList) {
@@ -117,15 +120,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 +147,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 +175,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 +186,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 +199,24 @@ 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() {
+
+ @Override
+ public String toString() {
return gameName;
}
-
+
public GameCanvas getCanvas() {
try {
return (GameCanvas)theCanvasClass.newInstance();
@@ -228,17 +232,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 +263,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 +292,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 +300,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 +311,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 +364,7 @@ public void itemStateChanged(ItemEvent e) {
computerAddress.setVisible(false);
}
validate();
- }
+ }
}
@Override
@@ -370,10 +374,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..6243393dc 100644
--- a/src/org/ggp/base/apps/kiosk/games/BattleCanvas.java
+++ b/src/org/ggp/base/apps/kiosk/games/BattleCanvas.java
@@ -11,8 +11,10 @@
public class BattleCanvas extends GameCanvas_Chessboard {
private static final long serialVersionUID = 1L;
- public String getGameName() { return "Battle"; }
- protected String getGameKey() { return "battle"; }
+ @Override
+ public String getGameName() { return "Battle"; }
+ @Override
+ protected String getGameKey() { return "battle"; }
@Override
protected Set getLegalMovesForCell(int xCell, int yCell) {
@@ -20,7 +22,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 +34,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 +51,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..07c1d8546 100644
--- a/src/org/ggp/base/apps/kiosk/games/BiddingTicTacToeCanvas.java
+++ b/src/org/ggp/base/apps/kiosk/games/BiddingTicTacToeCanvas.java
@@ -12,14 +12,20 @@
public class BiddingTicTacToeCanvas extends GameCanvas_FancyGrid {
private static final long serialVersionUID = 1L;
- public String getGameName() { return "Tic-Tac-Toe (Bidding)"; }
- 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
+ public String getGameName() { return "Tic-Tac-Toe (Bidding)"; }
+ @Override
+ protected String getGameKey() { return "biddingTicTacToe"; }
+ @Override
+ protected int getGridHeight() { return 5; }
+ @Override
+ protected int getGridWidth() { return 7; }
+
+ @Override
+ protected boolean coordinatesStartAtOne() { return false; }
+ @Override
+ protected boolean useGridVisualization() { return false; }
+
@Override
protected Set getFactsAboutCell(int xCell, int yCell) {
if(onGrid(xCell, yCell)) {
@@ -43,7 +49,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 +57,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 +69,7 @@ protected void renderCellBackground(Graphics g, int xCell, int yCell) {
}
}
}
-
+
@Override
protected void renderCellContent(Graphics g, String theFact) {
String[] cellFacts = theFact.split(" ");
@@ -79,25 +85,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..4cff74d6d 100644
--- a/src/org/ggp/base/apps/kiosk/games/BlockerCanvas.java
+++ b/src/org/ggp/base/apps/kiosk/games/BlockerCanvas.java
@@ -11,29 +11,34 @@
public class BlockerCanvas extends GameCanvas_FancyGrid {
private static final long serialVersionUID = 1L;
- public String getGameName() { return "Blocker"; }
- protected String getGameKey() { return "blocker"; }
- protected int getGridHeight() { return 6; }
- protected int getGridWidth() { return 6; }
+ @Override
+ public String getGameName() { return "Blocker"; }
+ @Override
+ protected String getGameKey() { return "blocker"; }
+ @Override
+ protected int getGridHeight() { return 6; }
+ @Override
+ protected int getGridWidth() { return 6; }
- protected boolean coordinatesStartAtOne() { return false; }
+ @Override
+ 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 +58,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..323ee44ba 100644
--- a/src/org/ggp/base/apps/kiosk/games/BlokboxSimpleCanvas.java
+++ b/src/org/ggp/base/apps/kiosk/games/BlokboxSimpleCanvas.java
@@ -18,72 +18,76 @@
public class BlokboxSimpleCanvas extends GameCanvas_SimpleGrid {
private static final long serialVersionUID = 1L;
- public String getGameName() { return "Blokbox Simple"; }
- protected String getGameKey() { return "blokbox_simple"; }
-
+ @Override
+ public String getGameName() { return "Blokbox Simple"; }
+ @Override
+ 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 + " \\)");
}
// ========================================================================
- protected int getGridHeight() { return 20; }
- protected int getGridWidth() { return 20; }
-
+ @Override
+ protected int getGridHeight() { return 20; }
+ @Override
+ 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 +100,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 +121,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 +155,19 @@ 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) {
+ @Override
+ 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 +182,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 +204,36 @@ 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) {
+ @Override
+ public void updateGameState(MachineState gameState) {
factsCache.clear();
super.updateGameState(gameState);
}
-
- protected final void renderCell(Graphics g, int xCell, int yCell) {
+
+ @Override
+ 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() {
+ @Override
+ 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..73224ba24 100644
--- a/src/org/ggp/base/apps/kiosk/games/BreakthroughCanvas.java
+++ b/src/org/ggp/base/apps/kiosk/games/BreakthroughCanvas.java
@@ -11,38 +11,41 @@
public class BreakthroughCanvas extends GameCanvas_Chessboard {
private static final long serialVersionUID = 1L;
- public String getGameName() { return "Breakthrough"; }
- protected String getGameKey() { return "breakthrough"; }
+ @Override
+ public String getGameName() { return "Breakthrough"; }
+ @Override
+ protected String getGameKey() { return "breakthrough"; }
@Override
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) {
+
+ @Override
+ 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..5b219bedf 100644
--- a/src/org/ggp/base/apps/kiosk/games/BreakthroughHolesCanvas.java
+++ b/src/org/ggp/base/apps/kiosk/games/BreakthroughHolesCanvas.java
@@ -11,8 +11,10 @@
public class BreakthroughHolesCanvas extends GameCanvas_Chessboard {
private static final long serialVersionUID = 1L;
- public String getGameName() { return "Breakthrough (Holes)"; }
- protected String getGameKey() { return "breakthroughHoles"; }
+ @Override
+ public String getGameName() { return "Breakthrough (Holes)"; }
+ @Override
+ protected String getGameKey() { return "breakthroughHoles"; }
@Override
protected Set getFactsAboutCell(int xCell, int yCell) {
@@ -20,35 +22,36 @@ 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) {
+
+ @Override
+ 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..0d4d70906 100644
--- a/src/org/ggp/base/apps/kiosk/games/BreakthroughSmallCanvas.java
+++ b/src/org/ggp/base/apps/kiosk/games/BreakthroughSmallCanvas.java
@@ -11,41 +11,46 @@
public class BreakthroughSmallCanvas extends GameCanvas_Chessboard {
private static final long serialVersionUID = 1L;
- public String getGameName() { return "Breakthrough (Small)"; }
- protected String getGameKey() { return "breakthroughSmall"; }
+ @Override
+ public String getGameName() { return "Breakthrough (Small)"; }
+ @Override
+ protected String getGameKey() { return "breakthroughSmall"; }
+
+ @Override
+ protected int getGridHeight() { return 6; }
+ @Override
+ protected int getGridWidth() { return 6; }
- protected int getGridHeight() { 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) {
+
+ @Override
+ 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..7b91a46db 100644
--- a/src/org/ggp/base/apps/kiosk/games/CephalopodCanvas.java
+++ b/src/org/ggp/base/apps/kiosk/games/CephalopodCanvas.java
@@ -11,25 +11,29 @@
public class CephalopodCanvas extends GameCanvas_FancyGrid {
private static final long serialVersionUID = 1L;
- public String getGameName() { return "Cephalopod"; }
- protected String getGameKey() { return "cephalopodMicro"; }
- protected int getGridHeight() { return 3; }
- protected int getGridWidth() { return 3; }
-
+ @Override
+ public String getGameName() { return "Cephalopod"; }
+ @Override
+ protected String getGameKey() { return "cephalopodMicro"; }
+ @Override
+ protected int getGridHeight() { return 3; }
+ @Override
+ 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 +42,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 +54,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..c7323c399 100644
--- a/src/org/ggp/base/apps/kiosk/games/CheckersCanvas.java
+++ b/src/org/ggp/base/apps/kiosk/games/CheckersCanvas.java
@@ -9,20 +9,22 @@
public class CheckersCanvas extends GameCanvas_Chessboard {
- private static final long serialVersionUID = 1L;
-
- public String getGameName() { return "Checkers"; }
- protected String getGameKey() { return "checkers"; }
-
+ private static final long serialVersionUID = 1L;
+
+ @Override
+ public String getGameName() { return "Checkers"; }
+ @Override
+ 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 +38,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..771299b86 100644
--- a/src/org/ggp/base/apps/kiosk/games/CheckersSmallCanvas.java
+++ b/src/org/ggp/base/apps/kiosk/games/CheckersSmallCanvas.java
@@ -9,42 +9,46 @@
public class CheckersSmallCanvas extends GameCanvas_Chessboard {
- 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; }
+ private static final long serialVersionUID = 1L;
+
+ @Override
+ public String getGameName() { return "Checkers (Small)"; }
+ @Override
+ protected String getGameKey() { return "checkersSmall"; }
+
+ @Override
+ protected int getGridHeight() { return 8; }
+ @Override
+ 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 +60,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..cd0248cca 100644
--- a/src/org/ggp/base/apps/kiosk/games/CheckersTinyCanvas.java
+++ b/src/org/ggp/base/apps/kiosk/games/CheckersTinyCanvas.java
@@ -9,42 +9,46 @@
public class CheckersTinyCanvas extends GameCanvas_Chessboard {
- 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; }
+ private static final long serialVersionUID = 1L;
+
+ @Override
+ public String getGameName() { return "Checkers (Tiny)"; }
+ @Override
+ protected String getGameKey() { return "checkersTiny"; }
+
+ @Override
+ protected int getGridHeight() { return 8; }
+ @Override
+ 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 +60,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..729be5488 100644
--- a/src/org/ggp/base/apps/kiosk/games/ChessCanvas.java
+++ b/src/org/ggp/base/apps/kiosk/games/ChessCanvas.java
@@ -11,15 +11,17 @@
public class ChessCanvas extends GameCanvas_Chessboard {
private static final long serialVersionUID = 1L;
- public String getGameName() { return "Chess"; }
- protected String getGameKey() { return "chess"; }
+ @Override
+ public String getGameName() { return "Chess"; }
+ @Override
+ protected String getGameKey() { return "chess"; }
@Override
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 +35,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..8b501849f 100644
--- a/src/org/ggp/base/apps/kiosk/games/ChickenTicTacToeCanvas.java
+++ b/src/org/ggp/base/apps/kiosk/games/ChickenTicTacToeCanvas.java
@@ -11,26 +11,30 @@
// 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
+ public String getGameName() { return "Tic-Tac-Toe (Chicken)"; }
+ @Override
+ protected String getGameKey() { return "chickentictactoe"; }
+ @Override
+ protected int getGridHeight() { return 3; }
+ @Override
+ 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..dba069064 100644
--- a/src/org/ggp/base/apps/kiosk/games/ConnectFiveCanvas.java
+++ b/src/org/ggp/base/apps/kiosk/games/ConnectFiveCanvas.java
@@ -10,30 +10,32 @@
public class ConnectFiveCanvas extends GameCanvas_Chessboard {
public static final long serialVersionUID = 0x1;
-
- public String getGameName() { return "Connect Five"; }
- protected String getGameKey() { return "connect5"; }
-
+
+ @Override
+ public String getGameName() { return "Connect Five"; }
+ @Override
+ 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..f30879695 100644
--- a/src/org/ggp/base/apps/kiosk/games/ConnectFourCanvas.java
+++ b/src/org/ggp/base/apps/kiosk/games/ConnectFourCanvas.java
@@ -10,17 +10,21 @@
public class ConnectFourCanvas extends GameCanvas_SimpleGrid {
private static final long serialVersionUID = 1L;
- public String getGameName() { return "Connect Four"; }
- protected String getGameKey() { return "connectFour"; }
- protected int getGridHeight() { return 6; }
- protected int getGridWidth() { return 8; }
+ @Override
+ public String getGameName() { return "Connect Four"; }
+ @Override
+ protected String getGameKey() { return "connectFour"; }
+ @Override
+ protected int getGridHeight() { return 6; }
+ @Override
+ 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 +34,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 +56,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..f77c16dfc 100644
--- a/src/org/ggp/base/apps/kiosk/games/FFACanvas.java
+++ b/src/org/ggp/base/apps/kiosk/games/FFACanvas.java
@@ -11,41 +11,48 @@
public class FFACanvas extends GameCanvas_FancyGrid {
private static final long serialVersionUID = 1L;
- public String getGameName() { return "Free-For-All"; }
- protected String getGameKey() { return "2pffa"; }
- protected int getGridHeight() { return 7; }
- protected int getGridWidth() { return 7; }
-
- protected final boolean useGridVisualization() { return false; }
- protected final boolean coordinatesStartAtOne() { return true; }
-
- protected final void renderCellBackground(Graphics g, int xCell, int yCell) {
+ @Override
+ public String getGameName() { return "Free-For-All"; }
+ @Override
+ protected String getGameKey() { return "2pffa"; }
+ @Override
+ protected int getGridHeight() { return 7; }
+ @Override
+ protected int getGridWidth() { return 7; }
+
+ @Override
+ protected final boolean useGridVisualization() { return false; }
+ @Override
+ protected final boolean coordinatesStartAtOne() { return true; }
+
+ @Override
+ 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 +66,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 +87,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..5102571e3 100644
--- a/src/org/ggp/base/apps/kiosk/games/GoldenRectangleCanvas.java
+++ b/src/org/ggp/base/apps/kiosk/games/GoldenRectangleCanvas.java
@@ -10,17 +10,21 @@
public class GoldenRectangleCanvas extends GameCanvas_SimpleGrid {
private static final long serialVersionUID = 1L;
- public String getGameName() { return "Golden Rectangle"; }
- protected String getGameKey() { return "golden_rectangle"; }
- protected int getGridHeight() { return 8; }
- protected int getGridWidth() { return 7; }
+ @Override
+ public String getGameName() { return "Golden Rectangle"; }
+ @Override
+ protected String getGameKey() { return "golden_rectangle"; }
+ @Override
+ protected int getGridHeight() { return 8; }
+ @Override
+ 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 +36,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 +58,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..ed39a2cf0 100644
--- a/src/org/ggp/base/apps/kiosk/games/KnightFightCanvas.java
+++ b/src/org/ggp/base/apps/kiosk/games/KnightFightCanvas.java
@@ -11,16 +11,20 @@
public class KnightFightCanvas extends GameCanvas_Chessboard {
private static final long serialVersionUID = 1L;
- public String getGameName() { return "Knight Fight"; }
- protected String getGameKey() { return "knightfight"; }
- protected int getGridHeight() { return 10; }
- protected int getGridWidth() { return 10; }
+ @Override
+ public String getGameName() { return "Knight Fight"; }
+ @Override
+ protected String getGameKey() { return "knightfight"; }
+ @Override
+ protected int getGridHeight() { return 10; }
+ @Override
+ 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 + " (.*) \\)");
@@ -29,36 +33,37 @@ protected Set getLegalMovesForCell(int xCell, int yCell) {
return theMoves;
}
- protected void renderCellContent(Graphics g, String theFact) {
+ @Override
+ 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..0e92f0099 100644
--- a/src/org/ggp/base/apps/kiosk/games/KnightthroughCanvas.java
+++ b/src/org/ggp/base/apps/kiosk/games/KnightthroughCanvas.java
@@ -11,38 +11,41 @@
public class KnightthroughCanvas extends GameCanvas_Chessboard {
private static final long serialVersionUID = 1L;
- public String getGameName() { return "Knightthrough"; }
- protected String getGameKey() { return "knightthrough"; }
+ @Override
+ public String getGameName() { return "Knightthrough"; }
+ @Override
+ protected String getGameKey() { return "knightthrough"; }
@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) {
+
+ @Override
+ 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..a75534b1f 100644
--- a/src/org/ggp/base/apps/kiosk/games/NumberTicTacToeCanvas.java
+++ b/src/org/ggp/base/apps/kiosk/games/NumberTicTacToeCanvas.java
@@ -10,38 +10,42 @@
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
+ public String getGameName() { return "Tic-Tac-Toe (Numeric)"; }
+ @Override
+ protected String getGameKey() { return "numbertictactoe"; }
+ @Override
+ protected int getGridHeight() { return 3; }
+ @Override
+ 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..7b08c52c4 100644
--- a/src/org/ggp/base/apps/kiosk/games/PawnWhoppingCanvas.java
+++ b/src/org/ggp/base/apps/kiosk/games/PawnWhoppingCanvas.java
@@ -11,8 +11,10 @@
public class PawnWhoppingCanvas extends GameCanvas_Chessboard {
private static final long serialVersionUID = 1L;
- public String getGameName() { return "Pawn Whopping"; }
- protected String getGameKey() { return "pawnWhopping"; }
+ @Override
+ public String getGameName() { return "Pawn Whopping"; }
+ @Override
+ protected String getGameKey() { return "pawnWhopping"; }
@Override
protected Set getLegalMovesForCell(int xCell, int yCell) {
@@ -20,7 +22,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 +34,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..0fff5ab89 100644
--- a/src/org/ggp/base/apps/kiosk/games/PentagoCanvas.java
+++ b/src/org/ggp/base/apps/kiosk/games/PentagoCanvas.java
@@ -11,16 +11,20 @@
public class PentagoCanvas extends GameCanvas_FancyGrid {
private static final long serialVersionUID = 1L;
- public String getGameName() { return "Pentago"; }
- protected String getGameKey() { return "pentago"; }
- protected int getGridHeight() { return 6; }
- protected int getGridWidth() { return 6; }
-
+ @Override
+ public String getGameName() { return "Pentago"; }
+ @Override
+ protected String getGameKey() { return "pentago"; }
+ @Override
+ protected int getGridHeight() { return 6; }
+ @Override
+ 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 +48,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 +56,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..436bcbe74 100644
--- a/src/org/ggp/base/apps/kiosk/games/TTCC4Canvas.java
+++ b/src/org/ggp/base/apps/kiosk/games/TTCC4Canvas.java
@@ -11,56 +11,63 @@
public class TTCC4Canvas extends GameCanvas_FancyGrid {
private static final long serialVersionUID = 1L;
- public String getGameName() { return "TTCC4"; }
- protected String getGameKey() { return "ttcc4_2player"; }
- protected int getGridHeight() { return 7; }
- protected int getGridWidth() { return 7; }
-
- protected final boolean useGridVisualization() { return false; }
- protected final boolean coordinatesStartAtOne() { return true; }
-
- protected final void renderCellBackground(Graphics g, int xCell, int yCell) {
+ @Override
+ public String getGameName() { return "TTCC4"; }
+ @Override
+ protected String getGameKey() { return "ttcc4_2player"; }
+ @Override
+ protected int getGridHeight() { return 7; }
+ @Override
+ protected int getGridWidth() { return 7; }
+
+ @Override
+ protected final boolean useGridVisualization() { return false; }
+ @Override
+ protected final boolean coordinatesStartAtOne() { return true; }
+
+ @Override
+ 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 +75,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 +103,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 +129,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..ee5599289 100644
--- a/src/org/ggp/base/apps/kiosk/games/TTCC4SmallCanvas.java
+++ b/src/org/ggp/base/apps/kiosk/games/TTCC4SmallCanvas.java
@@ -11,50 +11,57 @@
public class TTCC4SmallCanvas extends GameCanvas_FancyGrid {
private static final long serialVersionUID = 1L;
- public String getGameName() { return "TTCC4 (Small)"; }
- protected String getGameKey() { return "ttcc4_2player_small"; }
- protected int getGridHeight() { return 5; }
- protected int getGridWidth() { return 5; }
-
- protected final boolean useGridVisualization() { return false; }
- protected final boolean coordinatesStartAtOne() { return true; }
-
- protected final void renderCellBackground(Graphics g, int xCell, int yCell) {
+ @Override
+ public String getGameName() { return "TTCC4 (Small)"; }
+ @Override
+ protected String getGameKey() { return "ttcc4_2player_small"; }
+ @Override
+ protected int getGridHeight() { return 5; }
+ @Override
+ protected int getGridWidth() { return 5; }
+
+ @Override
+ protected final boolean useGridVisualization() { return false; }
+ @Override
+ protected final boolean coordinatesStartAtOne() { return true; }
+
+ @Override
+ 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 +69,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 +97,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 +123,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..6e20314f0 100644
--- a/src/org/ggp/base/apps/kiosk/games/TTCCanvas.java
+++ b/src/org/ggp/base/apps/kiosk/games/TTCCanvas.java
@@ -11,43 +11,50 @@
public class TTCCanvas extends GameCanvas_FancyGrid {
private static final long serialVersionUID = 1L;
- public String getGameName() { return "Tic-Tac-Chess"; }
- protected String getGameKey() { return "2pttc"; }
- protected int getGridHeight() { return 7; }
- protected int getGridWidth() { return 7; }
-
- protected final boolean useGridVisualization() { return false; }
- protected final boolean coordinatesStartAtOne() { return true; }
-
- protected final void renderCellBackground(Graphics g, int xCell, int yCell) {
+ @Override
+ public String getGameName() { return "Tic-Tac-Chess"; }
+ @Override
+ protected String getGameKey() { return "2pttc"; }
+ @Override
+ protected int getGridHeight() { return 7; }
+ @Override
+ protected int getGridWidth() { return 7; }
+
+ @Override
+ protected final boolean useGridVisualization() { return false; }
+ @Override
+ protected final boolean coordinatesStartAtOne() { return true; }
+
+ @Override
+ 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 +66,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..48b9c5a24 100644
--- a/src/org/ggp/base/apps/kiosk/games/TTTxNineCanvas.java
+++ b/src/org/ggp/base/apps/kiosk/games/TTTxNineCanvas.java
@@ -11,24 +11,30 @@
public class TTTxNineCanvas extends GameCanvas_SimpleGrid {
private static final long serialVersionUID = 1L;
- public String getGameName() { return "Nine Board Tic Tac Toe"; }
- protected String getGameKey() { return "nineBoardTicTacToe"; }
- protected int getGridHeight() { return 9; }
- protected int getGridWidth() { return 9; }
+ @Override
+ public String getGameName() { return "Nine Board Tic Tac Toe"; }
+ @Override
+ protected String getGameKey() { return "nineBoardTicTacToe"; }
+ @Override
+ protected int getGridHeight() { return 9; }
+ @Override
+ protected int getGridWidth() { return 9; }
+
+ @Override
+ protected boolean coordinatesStartAtOne() { return false; }
- protected boolean coordinatesStartAtOne() { return false; }
-
private int xSelectedBoard = 0;
private int ySelectedBoard = 0;
private int xSelectedSpot = 0;
private int ySelectedSpot = 0;
- protected void handleClickOnCell(int xCell, int yCell, int xWithin, int yWithin) {
+ @Override
+ protected void handleClickOnCell(int xCell, int yCell, int xWithin, int yWithin) {
int xBoard = 1 + (xCell / 3);
int yBoard = 1 + (yCell / 3);
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 +52,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 +65,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 +114,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 +124,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 +143,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 +156,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..a466b63f9 100644
--- a/src/org/ggp/base/apps/kiosk/games/TicTacToeCanvas.java
+++ b/src/org/ggp/base/apps/kiosk/games/TicTacToeCanvas.java
@@ -11,34 +11,38 @@
/**
* 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
+ public String getGameName() { return "Tic-Tac-Toe"; }
+ @Override
+ protected String getGameKey() { return "ticTacToe"; }
+ @Override
+ protected int getGridHeight() { return 3; }
+ @Override
+ 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..ab34dd279 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,57 @@
/**
* 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() {
+
+ @Override
+ public String getGameName() {
return "Tic-Tac-Toe (Old Version)";
}
-
- protected String getGameKey() {
+
+ @Override
+ protected String getGameKey() {
return "ticTacToe";
- }
+ }
private Graphics mostRecentG;
- protected void paintGame(Graphics g) {
+ @Override
+ 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 +74,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 +99,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);
}
@@ -106,29 +109,31 @@ protected void paintGame(Graphics g) {
}
}
- protected void handleDragEvent(int dx, int dy) {
+ @Override
+ protected void handleDragEvent(int dx, int dy) {
;
}
private int xSelectedCell, ySelectedCell;
- protected void handleClickEvent(int x, int y) {
+ @Override
+ 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 +141,12 @@ protected void handleClickEvent(int x, int y) {
;
}
}
-
- public void clearMoveSelection() {
+
+ @Override
+ 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..9bc068987 100644
--- a/src/org/ggp/base/apps/kiosk/templates/GameCanvas_Chessboard.java
+++ b/src/org/ggp/base/apps/kiosk/templates/GameCanvas_Chessboard.java
@@ -9,31 +9,36 @@
* 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 {
private static final long serialVersionUID = 1L;
- protected int getGridHeight() { return 8; }
- protected int getGridWidth() { return 8; }
+ @Override
+ protected int getGridHeight() { return 8; }
+ @Override
+ protected int getGridWidth() { return 8; }
- protected final boolean useGridVisualization() { return true; }
- protected final boolean coordinatesStartAtOne() { return true; }
-
- protected final void renderCellBackground(Graphics g, int xCell, int yCell) {
+ @Override
+ protected final boolean useGridVisualization() { return true; }
+ @Override
+ protected final boolean coordinatesStartAtOne() { return true; }
+
+ @Override
+ 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..40e81d75c 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,31 +96,32 @@ 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) {
+ @Override
+ protected final void handleClickOnCell(int xCell, int yCell, int xWithin, int yWithin) {
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));
}
@@ -132,38 +133,41 @@ 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) {
+ @Override
+ public void updateGameState(MachineState gameState) {
factsCache.clear();
super.updateGameState(gameState);
}
-
- protected final void renderCell(Graphics g, int xCell, int yCell) {
+
+ @Override
+ 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() {
+ @Override
+ 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..ce2c23bbc 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,56 @@
* 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) {
+ @Override
+ 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 +68,30 @@ protected final void paintGame(Graphics g) {
renderCell(cellGraphics, x, y);
}
}
- }
+ }
}
- protected final void handleClickEvent(int x, int y) {
+ @Override
+ 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..42ed759f7 100644
--- a/src/org/ggp/base/apps/player/Player.java
+++ b/src/org/ggp/base/apps/player/Player.java
@@ -19,7 +19,6 @@
import javax.swing.JTextField;
import javax.swing.border.TitledBorder;
-import com.google.common.collect.Lists;
import org.ggp.base.apps.player.config.ConfigPanel;
import org.ggp.base.apps.player.detail.DetailPanel;
import org.ggp.base.apps.player.match.MatchPanel;
@@ -29,6 +28,8 @@
import org.ggp.base.util.reflection.ProjectSearcher;
import org.ggp.base.util.ui.NativeUI;
+import com.google.common.collect.Lists;
+
@SuppressWarnings("serial")
public final class Player extends JPanel
@@ -47,12 +48,13 @@ 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()
{
+ @Override
public void run()
{
createAndShowGUI(playerPanel);
@@ -66,9 +68,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()
@@ -118,6 +120,7 @@ private AbstractAction createButtonMethod()
return new AbstractAction("Create")
{
+ @Override
public void actionPerformed(ActionEvent evt)
{
try
@@ -143,7 +146,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 +155,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..b24b7c591 100644
--- a/src/org/ggp/base/apps/player/PlayerRunner.java
+++ b/src/org/ggp/base/apps/player/PlayerRunner.java
@@ -4,13 +4,14 @@
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
+
import org.ggp.base.player.GamePlayer;
import org.ggp.base.player.gamer.Gamer;
import org.ggp.base.util.reflection.ProjectSearcher;
/**
* This is a simple command line app for running players.
- *
+ *
* @author schreib
*/
public final class PlayerRunner
@@ -31,7 +32,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/DetailPanel.java b/src/org/ggp/base/apps/player/detail/DetailPanel.java
index 858f4bf3f..380b566bf 100644
--- a/src/org/ggp/base/apps/player/detail/DetailPanel.java
+++ b/src/org/ggp/base/apps/player/detail/DetailPanel.java
@@ -1,7 +1,9 @@
package org.ggp.base.apps.player.detail;
import java.awt.LayoutManager;
+
import javax.swing.JPanel;
+
import org.ggp.base.util.observer.Observer;
/**
diff --git a/src/org/ggp/base/apps/player/detail/EmptyDetailPanel.java b/src/org/ggp/base/apps/player/detail/EmptyDetailPanel.java
index d3b635c51..49ff68677 100644
--- a/src/org/ggp/base/apps/player/detail/EmptyDetailPanel.java
+++ b/src/org/ggp/base/apps/player/detail/EmptyDetailPanel.java
@@ -3,7 +3,9 @@
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
+
import javax.swing.JLabel;
+
import org.ggp.base.util.observer.Event;
/**
@@ -17,6 +19,7 @@ public EmptyDetailPanel() {
this.add(new JLabel("No details available."), new GridBagConstraints(0, 0, 1, 1, 1.0, 1.0, GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 5, 5));
}
+ @Override
public void observe(Event event) {
// Do nothing when notified about events
}
diff --git a/src/org/ggp/base/apps/player/detail/SimpleDetailPanel.java b/src/org/ggp/base/apps/player/detail/SimpleDetailPanel.java
index bbc6c488e..d28fc9e42 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 {
@@ -42,6 +42,7 @@ public boolean isCellEditable(int rowIndex, int colIndex) {
this.add(new JScrollPane(moveTable, 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));
}
+ @Override
public void observe(Event event) {
if (event instanceof GamerNewMatchEvent) {
observe((GamerNewMatchEvent) event);
diff --git a/src/org/ggp/base/apps/player/match/MatchPanel.java b/src/org/ggp/base/apps/player/match/MatchPanel.java
index e86579522..10ae8997d 100644
--- a/src/org/ggp/base/apps/player/match/MatchPanel.java
+++ b/src/org/ggp/base/apps/player/match/MatchPanel.java
@@ -48,6 +48,7 @@ public boolean isCellEditable(int rowIndex, int colIndex)
this.add(new JScrollPane(matchTable, 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));
}
+ @Override
public void observe(Event event)
{
if (event instanceof GamerCompletedMatchEvent)
diff --git a/src/org/ggp/base/apps/player/network/NetworkPanel.java b/src/org/ggp/base/apps/player/network/NetworkPanel.java
index 28a4a143d..a51d6b46c 100644
--- a/src/org/ggp/base/apps/player/network/NetworkPanel.java
+++ b/src/org/ggp/base/apps/player/network/NetworkPanel.java
@@ -44,6 +44,7 @@ public boolean isCellEditable(int rowIndex, int colIndex)
this.add(new JScrollPane(networkTable, 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));
}
+ @Override
public void observe(Event event)
{
if (event instanceof PlayerReceivedMessageEvent)
diff --git a/src/org/ggp/base/apps/server/Server.java b/src/org/ggp/base/apps/server/Server.java
index a8c55481b..29d9b04cc 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,28 +59,29 @@ 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()
{
+ @Override
public void run()
{
createAndShowGUI(serverPanel, "Game Server");
}
});
}
-
+
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 +92,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 +127,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 +146,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 +168,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 +209,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,11 +228,12 @@ public void actionPerformed(ActionEvent e) {
validate();
runButton.setEnabled(true);
- }
- }
+ }
+ }
private AbstractAction runButtonMethod() {
return new AbstractAction("Start a new match!") {
+ @Override
public void actionPerformed(ActionEvent evt) {
int startClock = (Integer)startClockSpinner.getValue();
int playClock = (Integer)playClockSpinner.getValue();
@@ -241,9 +243,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 {
@@ -259,19 +261,21 @@ public void actionPerformed(ActionEvent evt) {
private AbstractAction testPlayerButtonMethod() {
return new AbstractAction("Test") {
+ @Override
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") {
+ @Override
public void actionPerformed(ActionEvent evt) {
String hostport = JOptionPane.showInputDialog(null, "What is the new player's address?\nPlease use the format \"host:port\".", "Add a player", JOptionPane.QUESTION_MESSAGE, null, null, "127.0.0.1:9147").toString();
try {
@@ -282,9 +286,10 @@ public void actionPerformed(ActionEvent evt) {
}
};
}
-
+
private AbstractAction removePlayerButtonMethod() {
return new AbstractAction("Remove") {
+ @Override
public void actionPerformed(ActionEvent evt) {
if (playerSelectorList.getSelectedValue() != null) {
playerSelector.removePlayer(playerSelectorList.getSelectedValue().toString());
diff --git a/src/org/ggp/base/apps/server/error/ErrorPanel.java b/src/org/ggp/base/apps/server/error/ErrorPanel.java
index 8f128fb53..4c0852026 100644
--- a/src/org/ggp/base/apps/server/error/ErrorPanel.java
+++ b/src/org/ggp/base/apps/server/error/ErrorPanel.java
@@ -46,6 +46,7 @@ public boolean isCellEditable(int rowIndex, int colIndex)
this.add(new JScrollPane(errorTable, 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));
}
+ @Override
public void observe(Event event)
{
if (event instanceof ServerConnectionErrorEvent)
diff --git a/src/org/ggp/base/apps/server/history/HistoryPanel.java b/src/org/ggp/base/apps/server/history/HistoryPanel.java
index 1c7076b85..ab64b4cae 100644
--- a/src/org/ggp/base/apps/server/history/HistoryPanel.java
+++ b/src/org/ggp/base/apps/server/history/HistoryPanel.java
@@ -49,6 +49,7 @@ public boolean isCellEditable(int rowIndex, int colIndex)
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));
}
+ @Override
public void observe(Event event)
{
if (event instanceof ServerNewMatchEvent)
diff --git a/src/org/ggp/base/apps/server/leaderboard/LeaderboardPanel.java b/src/org/ggp/base/apps/server/leaderboard/LeaderboardPanel.java
index 169a59a2b..a442bf968 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
@@ -61,6 +61,7 @@ public Class> getColumnClass(int colIndex) {
leaderTable.getColumnModel().getColumn(2).setPreferredWidth(10);
sorter = new TableRowSorter(model);
sorter.setComparator(1, new Comparator() {
+ @Override
public int compare(Integer a, Integer b) {
return a-b;
}
@@ -72,14 +73,15 @@ public int compare(Integer a, Integer b) {
add(new JScrollPane(leaderTable, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED), BorderLayout.CENTER);
}
+ @Override
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 +105,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..449768d0d 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,32 +140,33 @@ 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") {
- public void actionPerformed(ActionEvent evt) {
+ @Override
+ public void actionPerformed(ActionEvent evt) {
for (int i = 0; i < matchesTabbedPane.getTabCount(); i++) {
if (tabToClose == matchesTabbedPane.getComponentAt(i)) {
matchesTabbedPane.remove(tabToClose);
@@ -173,9 +174,10 @@ public void actionPerformed(ActionEvent evt) {
}
}
};
- }
-
+ }
+
class SchedulingThread extends Thread {
+ @Override
public void run() {
while (true) {
try {
@@ -194,6 +196,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..1ebc37faa 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,14 +92,15 @@ 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") {
+ @Override
public void actionPerformed(ActionEvent evt) {
if (queueTable.getSelectedRow() >= 0) {
String matchId = queueTable.getModel().getValueAt(queueTable.getSelectedRow(), 0).toString();
@@ -114,9 +115,10 @@ public void actionPerformed(ActionEvent evt) {
}
};
}
-
+
private AbstractAction viewSavedMatchButtonMethod() {
return new AbstractAction("View Saved") {
+ @Override
public void actionPerformed(ActionEvent evt) {
if (queueTable.getSelectedRow() >= 0) {
String matchId = queueTable.getModel().getValueAt(queueTable.getSelectedRow(), 0).toString();
@@ -131,9 +133,10 @@ public void actionPerformed(ActionEvent evt) {
}
};
}
-
+
private AbstractAction removeMatchButtonMethod() {
return new AbstractAction("Cancel Match") {
+ @Override
public void actionPerformed(ActionEvent evt) {
if (queueTable.getSelectedRow() >= 0) {
String matchId = queueTable.getModel().getValueAt(queueTable.getSelectedRow(), 0).toString();
@@ -145,7 +148,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 +159,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 +190,21 @@ 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);
}
-
+
+ @Override
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 +214,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 +237,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 +253,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 +261,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..718c81710 100644
--- a/src/org/ggp/base/apps/server/states/StatesPanel.java
+++ b/src/org/ggp/base/apps/server/states/StatesPanel.java
@@ -20,13 +20,14 @@
@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;
+ @Override
public void observe(Event event) {
if (event instanceof ServerNewGameStateEvent)
{
@@ -47,7 +48,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 +61,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..9cab32535 100644
--- a/src/org/ggp/base/apps/server/visualization/VisualizationPanel.java
+++ b/src/org/ggp/base/apps/server/visualization/VisualizationPanel.java
@@ -39,11 +39,12 @@ 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));
}
private int stepCount = 1;
+ @Override
public void observe(Event event)
{
if (event instanceof ServerNewGameStateEvent) {
@@ -60,16 +61,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 +84,7 @@ public void run()
} catch(Exception ex) {
ex.printStackTrace();
}
-
+
if(newPanel != null) {
// Add the rendered panel as a new tab
synchronized(tabLock) {
@@ -94,7 +95,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 +111,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..2018f5c13 100644
--- a/src/org/ggp/base/apps/tiltyard/TiltyardRequestFarm.java
+++ b/src/org/ggp/base/apps/tiltyard/TiltyardRequestFarm.java
@@ -9,13 +9,13 @@
import java.util.HashSet;
import java.util.Set;
-import org.ggp.base.util.loader.RemoteResourceLoader;
-import org.ggp.base.util.crypto.SignableJSON;
import org.ggp.base.util.crypto.BaseCryptography.EncodedKeyPair;
+import org.ggp.base.util.crypto.SignableJSON;
import org.ggp.base.util.files.FileUtils;
import org.ggp.base.util.http.HttpReader;
import org.ggp.base.util.http.HttpRequest;
import org.ggp.base.util.http.HttpWriter;
+import org.ggp.base.util.loader.RemoteResourceLoader;
import external.JSON.JSONException;
import external.JSON.JSONObject;
@@ -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..964c9a0b3 100644
--- a/src/org/ggp/base/apps/tiltyard/TiltyardRequestFarm_Test.java
+++ b/src/org/ggp/base/apps/tiltyard/TiltyardRequestFarm_Test.java
@@ -4,19 +4,20 @@
import java.net.Socket;
import java.util.Random;
-import org.ggp.base.util.loader.RemoteResourceLoader;
+import junit.framework.TestCase;
+
import org.ggp.base.util.http.HttpReader;
import org.ggp.base.util.http.HttpWriter;
-
-import junit.framework.TestCase;
+import org.ggp.base.util.loader.RemoteResourceLoader;
import external.JSON.JSONObject;
public class TiltyardRequestFarm_Test extends TestCase {
+ @Override
public void setUp() {
new RequestFarmLoopThread().start();
}
-
+
public void testThroughput() {
new ResponderLoopThread(2000).start();
new ReceiverLoopThread("OK").start();
@@ -29,28 +30,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 +66,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 +92,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 +122,13 @@ public void run() {
}
}
}
-
+
class ReceiverLoopThread extends Thread {
private String response;
public ReceiverLoopThread(String expectResponse) {
response = expectResponse;
}
-
+
@Override
public void run() {
try {
@@ -140,12 +141,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 +158,7 @@ public void run() {
}
}
}
-
+
public void runTestingLoop() {
try {
Random r = new Random();
@@ -167,7 +168,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 +186,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..de3440142 100644
--- a/src/org/ggp/base/apps/utilities/SimpleGameSim.java
+++ b/src/org/ggp/base/apps/utilities/SimpleGameSim.java
@@ -10,8 +10,8 @@
import org.ggp.base.server.event.ServerCompletedMatchEvent;
import org.ggp.base.server.event.ServerNewGameStateEvent;
import org.ggp.base.server.event.ServerNewMovesEvent;
-import org.ggp.base.util.crypto.SignableJSON;
import org.ggp.base.util.crypto.BaseCryptography.EncodedKeyPair;
+import org.ggp.base.util.crypto.SignableJSON;
import org.ggp.base.util.files.FileUtils;
import org.ggp.base.util.game.Game;
import org.ggp.base.util.game.GameRepository;
@@ -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..8fc66fa27 100644
--- a/src/org/ggp/base/apps/validator/BatchValidator.java
+++ b/src/org/ggp/base/apps/validator/BatchValidator.java
@@ -4,24 +4,24 @@
import org.ggp.base.util.game.Game;
import org.ggp.base.util.game.GameRepository;
import org.ggp.base.validator.BasesInputsValidator;
+import org.ggp.base.validator.GameValidator;
import org.ggp.base.validator.OPNFValidator;
import org.ggp.base.validator.SimulationValidator;
import org.ggp.base.validator.StaticValidator;
-import org.ggp.base.validator.GameValidator;
import org.ggp.base.validator.ValidatorException;
/**
* 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..412050dbc 100644
--- a/src/org/ggp/base/apps/validator/OutcomePanel.java
+++ b/src/org/ggp/base/apps/validator/OutcomePanel.java
@@ -47,11 +47,12 @@ 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));
}
+ @Override
public void observe(Event event)
{
if (event instanceof ValidatorSuccessEvent)
@@ -63,7 +64,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..b769408b6 100644
--- a/src/org/ggp/base/apps/validator/Validator.java
+++ b/src/org/ggp/base/apps/validator/Validator.java
@@ -22,10 +22,10 @@
import org.ggp.base.util.ui.GameSelector;
import org.ggp.base.util.ui.NativeUI;
import org.ggp.base.validator.BasesInputsValidator;
+import org.ggp.base.validator.GameValidator;
import org.ggp.base.validator.OPNFValidator;
import org.ggp.base.validator.SimulationValidator;
import org.ggp.base.validator.StaticValidator;
-import org.ggp.base.validator.GameValidator;
@SuppressWarnings("serial")
public final class Validator extends JPanel implements ActionListener
@@ -49,6 +49,7 @@ public static void main(String[] args)
javax.swing.SwingUtilities.invokeLater(new Runnable()
{
+ @Override
public void run()
{
createAndShowGUI(validatorPanel);
@@ -58,13 +59,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 +84,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 +99,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,35 +108,36 @@ 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)
{
return new AbstractAction("Validate")
{
+ @Override
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 +145,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/ValidatorThread.java b/src/org/ggp/base/apps/validator/ValidatorThread.java
index 5b76dc872..da6d4f403 100644
--- a/src/org/ggp/base/apps/validator/ValidatorThread.java
+++ b/src/org/ggp/base/apps/validator/ValidatorThread.java
@@ -25,11 +25,13 @@ public ValidatorThread(Game theGame, GameValidator theValidator)
this.observers = new ArrayList();
}
+ @Override
public void addObserver(Observer observer)
{
observers.add(observer);
}
+ @Override
public void notifyObservers(Event event)
{
for (Observer observer : observers)
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..869a73f0e 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,18 +40,20 @@ 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;
}
+ @Override
public void addObserver(Observer observer)
{
observers.add(observer);
}
+ @Override
public void notifyObservers(Event event)
{
for (Observer observer : observers)
@@ -59,11 +61,11 @@ public void notifyObservers(Event event)
observer.observe(event);
}
}
-
+
public final int getGamerPort() {
return port;
}
-
+
public final Gamer getGamer() {
return gamer;
}
@@ -80,13 +82,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 +110,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..d66282823 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,20 @@ 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;
+ @Override
public final void addObserver(Observer observer)
{
observers.add(observer);
}
-
+
+ @Override
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..e8a7deda8 100644
--- a/src/org/ggp/base/player/gamer/clojure/ClojureGamer_Test.java
+++ b/src/org/ggp/base/player/gamer/clojure/ClojureGamer_Test.java
@@ -1,20 +1,20 @@
package org.ggp.base.player.gamer.clojure;
+import junit.framework.TestCase;
+
import org.ggp.base.player.gamer.Gamer;
import org.ggp.base.player.gamer.clojure.stubs.SampleClojureGamerStub;
import org.ggp.base.util.game.GameRepository;
import org.ggp.base.util.gdl.grammar.GdlPool;
import org.ggp.base.util.match.Match;
-import junit.framework.TestCase;
-
/**
* 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..d70e145c3 100644
--- a/src/org/ggp/base/player/gamer/clojure/stubs/SampleClojureGamerStub.java
+++ b/src/org/ggp/base/player/gamer/clojure/stubs/SampleClojureGamerStub.java
@@ -6,11 +6,13 @@
* 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
{
- protected String getClojureGamerFile() { return "sample_gamer"; }
- protected String getClojureGamerName() { return "SampleClojureGamer"; }
+ @Override
+ protected String getClojureGamerFile() { return "sample_gamer"; }
+ @Override
+ protected String getClojureGamerName() { return "SampleClojureGamer"; }
}
\ No newline at end of file
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..07d8ffe12 100644
--- a/src/org/ggp/base/player/gamer/python/PythonGamer_Test.java
+++ b/src/org/ggp/base/player/gamer/python/PythonGamer_Test.java
@@ -1,20 +1,20 @@
package org.ggp.base.player.gamer.python;
+import junit.framework.TestCase;
+
import org.ggp.base.player.gamer.Gamer;
import org.ggp.base.player.gamer.python.stubs.SamplePythonGamerStub;
import org.ggp.base.util.game.GameRepository;
import org.ggp.base.util.gdl.grammar.GdlPool;
import org.ggp.base.util.match.Match;
-import junit.framework.TestCase;
-
/**
* 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..194251a10 100644
--- a/src/org/ggp/base/player/gamer/python/stubs/SamplePythonGamerStub.java
+++ b/src/org/ggp/base/player/gamer/python/stubs/SamplePythonGamerStub.java
@@ -6,11 +6,13 @@
* 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
{
- protected String getPythonGamerModule() { return "sample_gamer"; }
- protected String getPythonGamerName() { return "SamplePythonGamer"; }
+ @Override
+ protected String getPythonGamerModule() { return "sample_gamer"; }
+ @Override
+ protected String getPythonGamerName() { return "SamplePythonGamer"; }
}
\ No newline at end of file
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/human/event/HumanNewMovesEvent.java b/src/org/ggp/base/player/gamer/statemachine/human/event/HumanNewMovesEvent.java
index c9a07e549..2525cc591 100644
--- a/src/org/ggp/base/player/gamer/statemachine/human/event/HumanNewMovesEvent.java
+++ b/src/org/ggp/base/player/gamer/statemachine/human/event/HumanNewMovesEvent.java
@@ -16,7 +16,8 @@ public final class HumanNewMovesEvent extends Event
public HumanNewMovesEvent(List moves, Move selection)
{
- Collections.sort(moves, new Comparator(){public int compare(Move o1, Move o2) {return o1.toString().compareTo(o2.toString());}});
+ Collections.sort(moves, new Comparator(){@Override
+ public int compare(Move o1, Move o2) {return o1.toString().compareTo(o2.toString());}});
this.moves = moves;
this.selection = selection;
}
diff --git a/src/org/ggp/base/player/gamer/statemachine/human/gui/HumanDetailPanel.java b/src/org/ggp/base/player/gamer/statemachine/human/gui/HumanDetailPanel.java
index 05fc1018a..08f3bbfa4 100644
--- a/src/org/ggp/base/player/gamer/statemachine/human/gui/HumanDetailPanel.java
+++ b/src/org/ggp/base/player/gamer/statemachine/human/gui/HumanDetailPanel.java
@@ -63,6 +63,7 @@ public boolean isCellEditable(int rowIndex, int colIndex)
this.add(timerBar, new GridBagConstraints(0, 2, 2, 1, 1.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(5, 5, 5, 5), 5, 5));
}
+ @Override
public void observe(Event event)
{
if (event instanceof HumanNewMovesEvent)
@@ -107,6 +108,7 @@ private AbstractAction selectButtonMethod()
return new AbstractAction("Select")
{
+ @Override
public void actionPerformed(ActionEvent evt)
{
int row = moveTable.getSelectedRow();
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..61b8c123c 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,42 +28,45 @@ 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"
*/
+ @Override
public String getName() {
return getClass().getSimpleName();
}
-
+
// This is the default State Machine
+ @Override
public StateMachine getInitialStateMachine() {
return new CachedStateMachine(new ProverStateMachine());
- }
+ }
// This is the defaul Sample Panel
+ @Override
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..3409ef6db 100644
--- a/src/org/ggp/base/player/gamer/statemachine/sample/SampleLegalGamer.java
+++ b/src/org/ggp/base/player/gamer/statemachine/sample/SampleLegalGamer.java
@@ -21,23 +21,24 @@ 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.
- *
+ *
*/
+ @Override
public Move stateMachineSelectMove(long timeout) throws TransitionDefinitionException, MoveDefinitionException, GoalDefinitionException
{
// We get the current start time
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 +49,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.
*
* If a move produces a 1 step victory (given a random joint action) select it
@@ -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..ed65ca1f8 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,51 +103,52 @@ 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() {
+
+ @Override
+ public void run() {
try {
while(!pleaseStop) {
int next = theInput.read();
@@ -166,30 +167,31 @@ 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() {
+
+ @Override
+ 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 +202,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 +226,7 @@ public ProxyGamePlayer(int port, Class extends Gamer> 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 +236,10 @@ public ProxyGamePlayer(int port, Class extends Gamer> 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,20 +251,22 @@ public ProxyGamePlayer(int port, Class extends Gamer> 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;
}
+ @Override
public void addObserver(Observer observer)
{
observers.add(observer);
}
+ @Override
public void notifyObservers(Event event)
{
for (Observer observer : observers)
@@ -275,35 +279,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 +321,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 +375,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 +386,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 +415,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 +440,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 +454,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 +462,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 +482,22 @@ private void processClientResponse(ProxyMessage in, Thread toWakeUp) {
toWakeUp.interrupt();
}
}
-
+
private BlockingQueue inputQueue;
private BlockingQueue inputConnectionQueue;
private class QueueListenerThread extends Thread {
- public void run() {
+ @Override
+ 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..70634b33d 100644
--- a/src/org/ggp/base/player/proxy/ProxyGamePlayerClient.java
+++ b/src/org/ggp/base/player/proxy/ProxyGamePlayerClient.java
@@ -8,7 +8,6 @@
import java.util.ArrayList;
import java.util.List;
-import com.google.common.collect.Lists;
import org.ggp.base.player.event.PlayerDroppedPacketEvent;
import org.ggp.base.player.event.PlayerReceivedMessageEvent;
import org.ggp.base.player.event.PlayerSentMessageEvent;
@@ -25,15 +24,17 @@
import org.ggp.base.util.observer.Subject;
import org.ggp.base.util.reflection.ProjectSearcher;
+import com.google.common.collect.Lists;
+
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 +43,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 +57,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 +65,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,39 +73,41 @@ 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);
}
+ @Override
public void addObserver(Observer observer)
{
observers.add(observer);
}
+ @Override
public void notifyObservers(Event event)
{
for (Observer observer : observers)
@@ -114,7 +117,7 @@ public void notifyObservers(Event event)
}
private long theCode;
-
+
@Override
public void run()
{
@@ -137,12 +140,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 +153,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 +161,17 @@ public void run()
notifyObservers(new PlayerDroppedPacketEvent());
}
}
-
+
GamerLogger.log("Proxy", "[ProxyClient] Got interrupted, shutting down.");
}
-
- public void observe(Event event) {
+
+ @Override
+ 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..0c14b369f 100644
--- a/src/org/ggp/base/player/proxy/ProxyMessage.java
+++ b/src/org/ggp/base/player/proxy/ProxyMessage.java
@@ -10,22 +10,23 @@
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 + "\"]";
+
+ @Override
+ public String toString() {
+ 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 +43,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..9542d99f2 100644
--- a/src/org/ggp/base/player/request/factory/RequestFactory.java
+++ b/src/org/ggp/base/player/request/factory/RequestFactory.java
@@ -6,9 +6,9 @@
import org.ggp.base.player.gamer.Gamer;
import org.ggp.base.player.request.factory.exceptions.RequestFormatException;
import org.ggp.base.player.request.grammar.AbortRequest;
-import org.ggp.base.player.request.grammar.PreviewRequest;
import org.ggp.base.player.request.grammar.InfoRequest;
import org.ggp.base.player.request.grammar.PlayRequest;
+import org.ggp.base.player.request.grammar.PreviewRequest;
import org.ggp.base.player.request.grammar.Request;
import org.ggp.base.player.request.grammar.StartRequest;
import org.ggp.base.player.request.grammar.StopRequest;
@@ -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..8c709e0d7 100644
--- a/src/org/ggp/base/server/GameServer.java
+++ b/src/org/ggp/base/server/GameServer.java
@@ -21,8 +21,8 @@
import org.ggp.base.server.event.ServerTimeEvent;
import org.ggp.base.server.event.ServerTimeoutEvent;
import org.ggp.base.server.threads.AbortRequestThread;
-import org.ggp.base.server.threads.PreviewRequestThread;
import org.ggp.base.server.threads.PlayRequestThread;
+import org.ggp.base.server.threads.PreviewRequestThread;
import org.ggp.base.server.threads.RandomPlayRequestThread;
import org.ggp.base.server.threads.StartRequestThread;
import org.ggp.base.server.threads.StopRequestThread;
@@ -42,61 +42,62 @@
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) {
+
+ @Override
+ public void addObserver(Observer observer) {
observers.add(observer);
}
@@ -108,29 +109,30 @@ public List getGoals() throws GoalDefinitionException {
return goals;
}
-
+
public StateMachine getStateMachine() {
- return stateMachine;
+ return stateMachine;
}
- public void notifyObservers(Event event) {
+ @Override
+ 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 +146,7 @@ private void appendErrorsToMatchDescription() {
}
}
match.appendErrors(theErrors);
- mostRecentErrors.clear();
+ mostRecentErrors.clear();
}
@Override
@@ -153,9 +155,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 +171,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 +197,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 +236,7 @@ private String publishWhenNecessary() {
if (spectatorServerURL == null) {
return null;
}
-
+
int nAttempt = 0;
while (true) {
try {
@@ -249,7 +251,7 @@ private String publishWhenNecessary() {
nAttempt++;
}
}
-
+
public String getSpectatorServerKey() {
return spectatorServerKey;
}
@@ -267,7 +269,7 @@ private synchronized List sendPlayRequests() throws InterruptedException,
for (PlayRequestThread thread : threads) {
thread.start();
}
-
+
if (forceUsingEntireClock) {
Thread.sleep(match.getPlayClock() * 1000);
}
@@ -293,12 +295,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 +313,7 @@ private synchronized void sendStartRequests() throws InterruptedException {
}
if (forceUsingEntireClock) {
Thread.sleep(match.getStartClock() * 1000);
- }
+ }
for (StartRequestThread thread : threads) {
thread.join();
}
@@ -331,7 +333,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 +348,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 +364,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..270b3dbff 100644
--- a/src/org/ggp/base/util/crypto/Test_BaseCryptography.java
+++ b/src/org/ggp/base/util/crypto/Test_BaseCryptography.java
@@ -1,14 +1,14 @@
package org.ggp.base.util.crypto;
-import org.ggp.base.util.crypto.BaseCryptography.EncodedKeyPair;
-
import junit.framework.TestCase;
+import org.ggp.base.util.crypto.BaseCryptography.EncodedKeyPair;
+
/**
* 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..4191afd10 100644
--- a/src/org/ggp/base/util/crypto/Test_CanonicalJSON.java
+++ b/src/org/ggp/base/util/crypto/Test_CanonicalJSON.java
@@ -1,27 +1,27 @@
package org.ggp.base.util.crypto;
-import org.ggp.base.util.crypto.CanonicalJSON.CanonicalizationStrategy;
-
import junit.framework.TestCase;
+import org.ggp.base.util.crypto.CanonicalJSON.CanonicalizationStrategy;
+
/**
* 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..60f9b0ebe 100644
--- a/src/org/ggp/base/util/crypto/Test_SignableJSON.java
+++ b/src/org/ggp/base/util/crypto/Test_SignableJSON.java
@@ -1,32 +1,33 @@
package org.ggp.base.util.crypto;
+import junit.framework.TestCase;
+
import org.ggp.base.util.crypto.BaseCryptography.EncodedKeyPair;
import external.JSON.JSONException;
import external.JSON.JSONObject;
-import junit.framework.TestCase;
/**
* 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..4d7c94de1 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,16 +87,18 @@ public CloudGameRepository(String theURL) {
needsRefresh = false;
}
}
-
- protected Set getUncachedGameKeys() {
+
+ @Override
+ protected Set getUncachedGameKeys() {
Set theKeys = new HashSet();
for(File game : theCacheDirectory.listFiles()) {
theKeys.add(game.getName().replace(".zip", ""));
}
return theKeys;
}
-
- protected Game getUncachedGame(String theKey) {
+
+ @Override
+ protected Game getUncachedGame(String theKey) {
Game cachedGame = loadGameFromCache(theKey);
if (cachedGame != null) {
return cachedGame;
@@ -106,17 +108,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 +144,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 +166,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 +183,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 +197,7 @@ public void run() {
}
} catch (Exception e) {
continue;
- }
+ }
}
theGameKeys.removeAll(unchangedKeys);
}
@@ -219,15 +221,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 +242,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 +262,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 +276,7 @@ private synchronized long getCacheEntryAge(String theKey) {
}
// ================================================================
-
+
public static void main(String[] args) {
GameRepository theRepository = new CloudGameRepository("games.ggp.org/base");
@@ -282,10 +284,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