repo
stringlengths 1
191
⌀ | file
stringlengths 23
351
| code
stringlengths 0
5.32M
| file_length
int64 0
5.32M
| avg_line_length
float64 0
2.9k
| max_line_length
int64 0
288k
| extension_type
stringclasses 1
value |
---|---|---|---|---|---|---|
Ludii | Ludii-master/Common/src/graphics/svg/element/style/StrokeLineJoin.java | package graphics.svg.element.style;
import java.awt.Color;
import java.awt.Graphics2D;
import graphics.svg.element.Element;
//-----------------------------------------------------------------------------
/**
* SVG line join property.
* @author cambolbro
*/
public class StrokeLineJoin extends Style
{
// Format: stroke-linejoin="round"
private final String lineJoin = "miter";
//-------------------------------------------------------------------------
public StrokeLineJoin()
{
super("stroke-linejoin");
}
//-------------------------------------------------------------------------
public String lineJoin()
{
return lineJoin;
}
//-------------------------------------------------------------------------
@Override
public Element newOne()
{
return new StrokeLineJoin();
}
//-------------------------------------------------------------------------
@Override
public boolean load(final String expr)
{
final boolean okay = true;
// ...
return okay;
}
@Override
public Element newInstance()
{
return null;
}
@Override
public void render
(
Graphics2D g2d, double x0, double y0, Color footprintColour,
Color fillColour, Color strokeColour
)
{
// ...
}
@Override
public void setBounds()
{
// ...
}
//-------------------------------------------------------------------------
}
| 1,363 | 16.05 | 79 | java |
Ludii | Ludii-master/Common/src/graphics/svg/element/style/StrokeOpacity.java | package graphics.svg.element.style;
import java.awt.Color;
import java.awt.Graphics2D;
import graphics.svg.element.Element;
//-----------------------------------------------------------------------------
/**
* SVG stroke opacity property.
* @author cambolbro
*/
public class StrokeOpacity extends Style
{
// Format: stroke-opacity=".5"
private final double opacity = 1;
//-------------------------------------------------------------------------
public StrokeOpacity()
{
super("stroke-opacity");
}
//-------------------------------------------------------------------------
public double opacity()
{
return opacity;
}
//-------------------------------------------------------------------------
@Override
public Element newOne()
{
return new StrokeOpacity();
}
//-------------------------------------------------------------------------
@Override
public boolean load(final String expr)
{
final boolean okay = true;
// ...
return okay;
}
@Override
public Element newInstance()
{
return null;
}
@Override
public void render
(
Graphics2D g2d, double x0, double y0, Color footprintColour,
Color fillColour, Color strokeColour
)
{
// ...
}
@Override
public void setBounds()
{
// ...
}
//-------------------------------------------------------------------------
}
| 1,348 | 16.075949 | 79 | java |
Ludii | Ludii-master/Common/src/graphics/svg/element/style/StrokeWidth.java | package graphics.svg.element.style;
import java.awt.Color;
import java.awt.Graphics2D;
import graphics.svg.element.Element;
//-----------------------------------------------------------------------------
/**
* SVG stroke width property.
* @author cambolbro
*/
public class StrokeWidth extends Style
{
// Format: stroke-width="1"
private final double width = 1;
//-------------------------------------------------------------------------
public StrokeWidth()
{
super("stroke-width");
}
//-------------------------------------------------------------------------
public double width()
{
return width;
}
//-------------------------------------------------------------------------
@Override
public Element newOne()
{
return new StrokeWidth();
}
//-------------------------------------------------------------------------
@Override
public boolean load(final String expr)
{
final boolean okay = true;
// ...
return okay;
}
@Override
public Element newInstance()
{
return null;
}
@Override
public void render
(
Graphics2D g2d, double x0, double y0, Color footprintColour,
Color fillColour, Color strokeColour
)
{
// ...
}
@Override
public void setBounds()
{
// ...
}
//-------------------------------------------------------------------------
}
| 1,335 | 15.493827 | 79 | java |
Ludii | Ludii-master/Common/src/graphics/svg/element/style/Style.java | package graphics.svg.element.style;
import graphics.svg.element.BaseElement;
import graphics.svg.element.Element;
//-----------------------------------------------------------------------------
/**
* Base class for SVG paint elements.
* @author cambolbro
*/
public abstract class Style extends BaseElement
{
//-------------------------------------------------------------------------
public Style(final String label)
{
super(label);
}
//-------------------------------------------------------------------------
/**
* Load this element's painting properties.
* @return Whether expression is in the right format and data was loaded.
*/
@Override
public boolean load(final String expr)
{
final boolean okay = true;
// ...
return okay;
}
//-------------------------------------------------------------------------
@Override
public Element newOne()
{
return new StrokeDashArray();
}
}
| 931 | 18.829787 | 79 | java |
Ludii | Ludii-master/Common/src/graphics/svg/element/text/Text.java | package graphics.svg.element.text;
import java.awt.Color;
import java.awt.Graphics2D;
import graphics.svg.element.BaseElement;
import graphics.svg.element.Element;
//-----------------------------------------------------------------------------
/**
* SVG text elements. How handled yet -- added for completeness.
* @author cambolbro
*/
public class Text extends BaseElement
{
//-------------------------------------------------------------------------
public Text()
{
super("Text");
}
//-------------------------------------------------------------------------
@Override
public Element newInstance()
{
return new Text();
}
//-------------------------------------------------------------------------
@Override
public boolean load(final String expr)
{
try
{
throw new Exception("SVG text loading not implemented yet.");
}
catch (final Exception e)
{
System.out.println(e);
}
return false;
}
//-------------------------------------------------------------------------
@Override
public void setBounds()
{
System.out.println("Text.setBounds() not implemented yet.");
}
//-------------------------------------------------------------------------
@Override
public void render
(
final Graphics2D g2d, final double x0, final double y0,
final Color footprintColour, final Color fillColour, final Color strokeColour
)
{
// ...
}
@Override
public Element newOne()
{
return new Text();
}
//-------------------------------------------------------------------------
}
| 1,539 | 18.74359 | 79 | java |
Ludii | Ludii-master/Common/src/main/AliasesData.java | package main;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Contains data on aliases for games, loaded from Player/res/help/Aliases.txt.
* This file is not under version control, but can be generated by running
* Player/player/utils/GenerateAliasesFile.java
*
* @author Dennis Soemers
*/
public class AliasesData
{
//-------------------------------------------------------------------------
/** Path where we expect our data to be generated */
private static final String RESOURCE_PATH = "/help/Aliases.txt";
/** We'll only load once, and then just cache here */
private static AliasesData data = null;
//-------------------------------------------------------------------------
/** Mapping from full game paths to lists of aliases */
private final Map<String, List<String>> gameAliases = new HashMap<String, List<String>>();
//-------------------------------------------------------------------------
/**
* Constructor
*/
private AliasesData()
{
// Do not instantiate: use static loadData() method instead
}
//-------------------------------------------------------------------------
/**
* @param gamePath Full game path (starting with /lud/ and ending with .lud)
* @return List of aliases for the game (or null if no known aliases)
*/
public List<String> aliasesForGame(final String gamePath)
{
return gameAliases.get(gamePath);
}
//-------------------------------------------------------------------------
/**
* @param gameNameInput Full game name.
* @return List of aliases for the game (or null if no known aliases)
*/
public List<String> aliasesForGameName(final String gameNameInput)
{
for (final Map.Entry<String, List<String>> entry : gameAliases.entrySet())
{
final String[] pathSplit = entry.getKey().split("/");
String gameName = pathSplit[pathSplit.length-1];
gameName = gameName.substring(0,gameName.length()-4);
if (gameName.toLowerCase().equals(gameNameInput))
{
return gameAliases.get(entry.getKey());
}
}
return gameAliases.get(gameNameInput);
}
//-------------------------------------------------------------------------
/**
* @return Aliases data
*/
public static AliasesData loadData()
{
if (data == null)
{
data = new AliasesData();
try (final InputStream resource = AliasesData.class.getResourceAsStream(RESOURCE_PATH))
{
if (resource != null)
{
try
(
final InputStreamReader isr = new InputStreamReader(resource, "UTF-8");
final BufferedReader rdr = new BufferedReader(isr)
)
{
String currGame = null;
String line;
while ((line = rdr.readLine()) != null)
{
if (line.startsWith("/lud/") && line.endsWith(".lud"))
{
currGame = line;
}
else
{
if (!data.gameAliases.containsKey(currGame))
data.gameAliases.put(currGame, new ArrayList<String>());
data.gameAliases.get(currGame).add(line);
}
}
}
}
}
catch (final IOException e)
{
e.printStackTrace();
}
}
return data;
}
//-------------------------------------------------------------------------
}
| 3,402 | 25.176923 | 91 | java |
Ludii | Ludii-master/Common/src/main/ClickInfo.java | package main;
//
///**
// * A class that is used for storing all necessary information about a user's click
// *
// * @author Matthew Stephenson
// */
public class ClickInfo
{
// private int site = -1;
// private int level = 0;
// private int graphElementType = 0;
//
// /**
// * Constructor.
// *
// * @param site
// * @param level
// * @param graphElementType
// */
//
// public ClickInfo(int site, int level, int graphElementType)
// {
// this.site = site;
// this.level = level;
// this.graphElementType = graphElementType;
// }
//
// public ClickInfo(){}
//
// public int site()
// {
// return site;
// }
// public int level()
// {
// return level;
// }
// public int graphElementType()
// {
// return graphElementType;
// }
//
// public void setSite(Integer[] i)
// {
// site = i[0].intValue();
// level = i[1].intValue();
// }
//
// public void setSite(int i)
// {
// site = i;
// }
//
// public void setGraphElementType(int i)
// {
// graphElementType = i;
// }
//
// public boolean equals(ClickInfo c)
// {
// return (this.site == c.site && this.level == c.level && this.graphElementType == c.graphElementType);
// }
}
| 1,153 | 16.753846 | 105 | java |
Ludii | Ludii-master/Common/src/main/CommandLineArgParse.java | package main;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Class for parsing of command line arguments.
*
* Functionality loosely based on the argparse module of Python 3.
*
* @author Dennis Soemers
*/
public final class CommandLineArgParse
{
//-------------------------------------------------------------------------
/**
* Types of options we may have
*
* @author Dennis Soemers
*/
public enum OptionTypes
{
/** Boolean option */
Boolean,
/** Int option */
Int,
/** Float option */
Float,
/** Double option */
Double,
/** String option */
String
}
//-------------------------------------------------------------------------
/** Whether or not arguments are case sensitive. True by default */
protected final boolean caseSensitive;
/** Description of the program for which we're parsing arguments */
protected final String description;
/** Nameless options (values must be provided by user in fixed order) */
protected final List<ArgOption> namelessOptions = new ArrayList<ArgOption>();
/** Named options (these may be provided by user in any order) */
protected final Map<String, ArgOption> namedOptions = new HashMap<String, ArgOption>();
/** List of named options that are required (nameless options are always required) */
protected final List<ArgOption> requiredNamedOptions = new ArrayList<ArgOption>();
/** All options, precisely in the order in which they were provided. */
protected final List<ArgOption> allOptions = new ArrayList<ArgOption>();
/** List containing user-provided values for nameless args (populated by parseArguments() call) */
protected final List<Object> providedNamelessValues = new ArrayList<Object>();
/** Map containing all user-provided values (populated by parseArguments() call) */
protected final Map<String, Object> providedValues = new HashMap<String, Object>();
//-------------------------------------------------------------------------
/**
* Constructor
*/
public CommandLineArgParse()
{
this(true);
}
/**
* Constructor
* @param caseSensitive
*/
public CommandLineArgParse(final boolean caseSensitive)
{
this(caseSensitive, null);
}
/**
* Constructor
* @param caseSensitive
* @param description
*/
public CommandLineArgParse(final boolean caseSensitive, final String description)
{
this.caseSensitive = caseSensitive;
this.description = description;
}
//-------------------------------------------------------------------------
/**
* Adds the given option
* @param argOption
*/
public void addOption(final ArgOption argOption)
{
// some error checking
if (argOption.names != null)
{
for (String name : argOption.names)
{
if (!caseSensitive)
name = name.toLowerCase();
if (name.equals("-h") || name.equals("--help"))
{
System.err.println
(
"Not adding option! Cannot use arg name: " + name +
". This is reserved for help message."
);
return;
}
}
}
else
{
if (argOption.expectsList())
{
System.err.println("Multi-valued nameless arguments are not currently supported!");
return;
}
if (!namedOptions.isEmpty())
{
System.err.println("Adding nameless options after named options is not currently supported!");
return;
}
}
if
(
argOption.numValsStr != null &&
!argOption.numValsStr.equals("+") &&
!argOption.numValsStr.equals("*")
)
{
System.err.println("Not adding option! Invalid numVals specified: " + argOption.numValsStr);
return;
}
// try to automatically determine type if not specified
if (argOption.type == null)
{
if (argOption.defaultVal != null)
{
if (argOption.defaultVal instanceof Boolean)
argOption.type = OptionTypes.Boolean;
else if (argOption.defaultVal instanceof Integer)
argOption.type = OptionTypes.Int;
else if (argOption.defaultVal instanceof Float)
argOption.type = OptionTypes.Float;
else if (argOption.defaultVal instanceof Double)
argOption.type = OptionTypes.Double;
else
argOption.type = OptionTypes.String;
}
else
{
if (argOption.expectsList())
{
// probably not a boolean flag, let's default to strings
argOption.type = OptionTypes.String;
}
else if (argOption.numVals == 1)
{
// also probably not a boolean flag
argOption.type = OptionTypes.String;
}
else
{
// expects 0 args, so likely a boolean flag
argOption.type = OptionTypes.Boolean;
}
}
}
// only allow boolean args to have non-list 0 values
if
(
argOption.type != OptionTypes.Boolean &&
argOption.numValsStr == null &&
argOption.numVals == 0
)
{
System.err.println("Not adding option! Cannot accept 0 values for non-boolean option.");
return;
}
// set a default value of false for booleans with no default set yet
if (argOption.type == OptionTypes.Boolean && argOption.defaultVal == null)
argOption.defaultVal = Boolean.FALSE;
//System.out.println("adding option: " + argOption);
// add option to all the relevant lists/maps
allOptions.add(argOption);
// make sure default value is legal
if (argOption.defaultVal != null && argOption.legalVals != null)
{
boolean found = false;
for (final Object legalVal : argOption.legalVals)
{
if (legalVal.equals(argOption.defaultVal))
{
found = true;
break;
}
}
if (!found)
{
System.err.println
(
"Error: default value " + argOption.defaultVal +
" is not legal. Legal values = " + Arrays.toString(argOption.legalVals)
);
return;
}
}
if (argOption.names == null)
{
namelessOptions.add(argOption);
}
else
{
for (String name : argOption.names)
{
if (!caseSensitive)
name = name.toLowerCase();
if (namedOptions.containsKey(name))
System.err.println("Error: Duplicate name:" + name);
namedOptions.put(name, argOption);
}
if (argOption.required)
requiredNamedOptions.add(argOption);
}
}
/**
* Parses the given arguments.
* @param args
* @return True if arguments were parsed successfully, false otherwise.
* Will also return false if the user requested help through "-h" or "--help"
* (because that typically means we'd want to stop running the program).
*/
public boolean parseArguments(final String[] args)
{
String currentToken = null;
int nextNamelessOption = 0;
ArgOption currentOption = null;
String currentOptionName = null;
List<Object> currentValues = null;
try
{
for (int i = 0; i < args.length; /**/)
{
currentToken = args[i];
final String token = caseSensitive ? currentToken : currentToken.toLowerCase();
if (token.equals("-h") || token.equals("--help"))
{
printHelp(System.out);
return false;
}
if (nextNamelessOption < namelessOptions.size())
{
// we should be starting with a new nameless option
if (!finishArgOption(currentOption, currentOptionName, currentValues))
return false;
if (namedOptions.containsKey(token))
{
System.err.println
(
"Error: found name \"" + currentToken + "\" while expecting more nameless options."
);
return false;
}
currentOption = namelessOptions.get(nextNamelessOption);
currentOptionName = "NAMELESS_" + nextNamelessOption;
currentValues = new ArrayList<Object>(1);
currentValues.add(tokenToVal(token, currentOption.type));
++nextNamelessOption;
}
else if (namedOptions.containsKey(token))
{
// looks like we're starting with a new named option
if (!finishArgOption(currentOption, currentOptionName, currentValues))
return false;
currentOption = namedOptions.get(token);
currentOptionName = currentToken;
currentValues = new ArrayList<Object>();
}
else
{
// add this token as a value
currentValues.add(tokenToVal(token, currentOption.type));
}
++i;
}
// also make sure to finish handling the very last option
if (!finishArgOption(currentOption, currentOptionName, currentValues))
return false;
}
catch (final Exception e)
{
System.err.println("Parsing args failed on token \"" + currentToken + "\" with exception:");
e.printStackTrace();
System.err.println();
printHelp(System.err);
System.err.println();
return false;
}
// let's make sure we have values for all the required options
if (providedNamelessValues.size() < namelessOptions.size())
{
System.err.println("Missing value for nameless option " + providedNamelessValues.size());
return false;
}
for (final ArgOption option : requiredNamedOptions)
{
final String key = caseSensitive ? option.names[0] : option.names[0].toLowerCase();
if (!providedValues.containsKey(key))
{
System.err.println("Missing value for required option: " + option.names[0]);
return false;
}
}
return true;
}
//-------------------------------------------------------------------------
/**
* @param i
* @return The value for the i'th positional (nameless) argument
*/
public Object getValue(final int i)
{
return providedNamelessValues.get(i);
}
/**
* @param i
* @return The value for the i'th positional (nameless) argument as boolean
*/
public boolean getValueBool(final int i)
{
return ((Boolean) providedNamelessValues.get(i)).booleanValue();
}
/**
* @param i
* @return The value for the i'th positional (nameless) argument as int
*/
public int getValueInt(final int i)
{
return ((Integer) providedNamelessValues.get(i)).intValue();
}
/**
* @param i
* @return The value for the i'th positional (nameless) argument as float
*/
public float getValueFloat(final int i)
{
return ((Float) providedNamelessValues.get(i)).floatValue();
}
/**
* @param i
* @return The value for the i'th positional (nameless) argument as double
*/
public double getValueDouble(final int i)
{
return ((Double) providedNamelessValues.get(i)).doubleValue();
}
/**
* @param i
* @return The value for the i'th positional (nameless) argument as String
*/
public String getValueString(final int i)
{
return (String) providedNamelessValues.get(i);
}
/**
* @param name Name of the option for which to get value
* @return The value for the argument with given name (may return default value)
*/
public Object getValue(final String name)
{
String key = name;
if (!caseSensitive)
key = key.toLowerCase();
return providedValues.getOrDefault(key, namedOptions.get(key).defaultVal);
}
/**
* @param name Name of the option for which to get value
* @return The value for the argument with given name (may return default value) as boolean
*/
public boolean getValueBool(final String name)
{
return ((Boolean) getValue(name)).booleanValue();
}
/**
* @param name Name of the option for which to get value
* @return The value for the argument with given name (may return default value) as int
*/
public int getValueInt(final String name)
{
return ((Integer) getValue(name)).intValue();
}
/**
* @param name Name of the option for which to get value
* @return The value for the argument with given name (may return default value) as float
*/
public float getValueFloat(final String name)
{
return ((Float) getValue(name)).floatValue();
}
/**
* @param name Name of the option for which to get value
* @return The value for the argument with given name (may return default value) as double
*/
public double getValueDouble(final String name)
{
return ((Double) getValue(name)).doubleValue();
}
/**
* @param name Name of the option for which to get value
* @return The value for the argument with given name (may return default value) as String
*/
public String getValueString(final String name)
{
return (String) getValue(name);
}
//-------------------------------------------------------------------------
/**
* Print help message to given output stream
* @param out
*/
public void printHelp(final PrintStream out)
{
if (description != null)
out.print(description);
else
out.print("No program description.");
out.println();
out.println();
if (!namelessOptions.isEmpty())
{
out.println("Positional arguments:");
for (final ArgOption option : namelessOptions)
{
printOptionLine(option, out);
}
out.println();
}
out.println("Required named arguments:");
for (int i = 0; i < allOptions.size(); ++i)
{
final ArgOption option = allOptions.get(i);
// skip nameless options, already had those
if (option.names != null)
{
if (option.required)
{
printOptionLine(option, out);
}
}
}
out.println();
out.println("Optional named arguments:");
out.println(" -h, --help Show this help message.");
for (int i = 0; i < allOptions.size(); ++i)
{
final ArgOption option = allOptions.get(i);
// skip nameless options, already had those
if (option.names != null)
{
if (!option.required)
{
printOptionLine(option, out);
}
}
}
}
/**
* Prints a help line for the given option
* @param option
* @param out
*/
private static void printOptionLine(final ArgOption option, final PrintStream out)
{
final StringBuilder sb = new StringBuilder();
if (option.names == null)
{
if (option.legalVals != null)
{
sb.append(" {");
for (int i = 0; i < option.legalVals.length; ++i)
{
if (i > 0)
sb.append(",");
sb.append(option.legalVals[i]);
}
sb.append("}");
}
else
{
sb.append(" " + option.type.toString().toUpperCase());
}
}
else
{
sb.append(" ");
for (int i = 0; i < option.names.length; ++i)
{
sb.append(option.names[i]);
if (i + 1 < option.names.length)
sb.append(", ");
}
String metaVar = option.names[0].toUpperCase();
while (metaVar.startsWith("-"))
{
metaVar = metaVar.substring(1);
}
metaVar = metaVar.replaceAll("-", "_");
if (option.numValsStr == null)
{
if (option.numVals > 0)
{
if (option.numVals == 1)
{
sb.append(" " + metaVar);
}
else
{
for (int i = 1; i <= option.numVals; ++i)
{
sb.append(" " + metaVar + "_" + i);
}
}
}
}
else if (option.numValsStr.equals("+"))
{
sb.append(" " + metaVar + "_1");
sb.append(" [ " + metaVar + "_* ... ]");
}
else if (option.numValsStr.equals("*"))
{
sb.append(" [ " + metaVar + "_* ... ]");
}
}
if (sb.length() >= 65)
{
sb.append("\t");
}
else
{
while (sb.length() < 65)
{
sb.append(" ");
}
}
sb.append(option.help);
out.println(sb.toString());
}
//-------------------------------------------------------------------------
/**
* Finish handling the arg option we're currently processing
* @param currentOption
* @param currentOptionName
* @param currentValues
* @return True if everything is fine, false if there's a problem
*/
private boolean finishArgOption
(
final ArgOption currentOption,
final String currentOptionName,
final List<Object> currentValues
)
{
if (currentOption != null)
{
// first check if our current option has as many values as it needs
if (currentOption.numValsStr == null)
{
if (currentValues.size() != currentOption.numVals)
{
System.err.println
(
"Error: " + currentOptionName + " requires " + currentOption.numVals +
" values, but received " + currentValues.size() + " values."
);
return false;
}
}
else if (currentOption.numValsStr.equals("+"))
{
if (currentValues.size() == 0)
{
System.err.println
(
"Error: " + currentOptionName + " requires more than 0" +
" values, but only received 0 values."
);
return false;
}
}
// make sure all provided values are legal
if (currentOption.legalVals != null)
{
for (final Object val : currentValues)
{
boolean found = false;
for (final Object legalVal : currentOption.legalVals)
{
if (val.equals(legalVal))
{
found = true;
break;
}
}
if (!found)
{
System.err.println
(
"Error: " + val + " is an illegal value."
+ " Legal values = " + Arrays.toString(currentOption.legalVals)
);
return false;
}
}
}
if (currentOption.names == null)
{
if (currentOption.expectsList())
{
// just put the list as value
providedNamelessValues.add(currentValues);
}
else if (currentValues.size() == 0 && currentOption.type == OptionTypes.Boolean)
{
// boolean flag without any values, simply means "set to true"
providedNamelessValues.add(Boolean.TRUE);
}
else
{
// extract element from list (should be just a single element)
providedNamelessValues.add(currentValues.get(0));
}
}
else
{
for (String name : currentOption.names)
{
if (!caseSensitive)
name = name.toLowerCase();
if (currentOption.expectsList())
{
// just put the list as value
providedValues.put(name, currentValues);
}
else if (currentValues.size() == 0 && currentOption.type == OptionTypes.Boolean)
{
// boolean flag without any values, simply means "set to true"
providedValues.put(name, Boolean.TRUE);
}
else
{
// extract element from list (should be just a single element)
providedValues.put(name, currentValues.get(0));
}
}
}
}
return true;
}
private static Object tokenToVal(final String token, final OptionTypes type)
{
if (type == OptionTypes.Boolean)
return Boolean.parseBoolean(token);
else if (type == OptionTypes.Double)
return Double.parseDouble(token);
else if (type == OptionTypes.Float)
return Float.parseFloat(token);
else if (type == OptionTypes.Int)
return Integer.parseInt(token);
else
return token;
}
//-------------------------------------------------------------------------
/**
* Class for options that we may have.
*
* @author Dennis Soemers
*/
public final static class ArgOption
{
//---------------------------------------------------------------------
/** List of names/flags for this option */
protected String[] names = null;
/**
* Option type.
*
* If the type is not specified, we will try to intelligently determine
* the type based on any specified default values. If there is no
* specified default value either, we'll assume boolean by default,
* or String if the number of values has been specified to be greater
* than 0.
*/
protected OptionTypes type = null;
/** Expected number of values we expect to be supplied */
protected int numVals = 0;
/**
* String description of expected number of values. Can be:
* - null, meaning we just look at the numVals int
* - "*", meaning we allow any number >= 0
* - "+", meaning we allow any number > 0
*/
protected String numValsStr = null;
/**
* Default value to be returned if no value supplied.
* Only used for args that are not nameless, and not required.
*/
protected Object defaultVal = null;
/**
* If true, the parser will fail if no value is provided by the user.
* False by default.
*/
protected boolean required = false;
/** If not null, only objects in this array will be legal */
protected Object[] legalVals = null;
/** Description for this option in help message */
protected String help = "";
//---------------------------------------------------------------------
/**
* Constructor
*/
public ArgOption()
{
// do nothing
}
//---------------------------------------------------------------------
/**
* Set names/flags that can be used for this arg option
* @param optionNames
* @return Arg option with names.
*/
public ArgOption withNames(final String... optionNames)
{
this.names = optionNames;
return this;
}
/**
* Set type for this arg option
* @param optionType
* @return Arg option with type.
*/
public ArgOption withType(final OptionTypes optionType)
{
this.type = optionType;
return this;
}
/**
* Set the expected number of values for this arg option
* @param optionNumVals
* @return Arg option with values.
*/
public ArgOption withNumVals(final int optionNumVals)
{
this.numVals = optionNumVals;
return this;
}
/**
* Set the expected number of values for this arg option
* @param optionNumValsStr
* Use "*" for anything >= 0, or "+" for anything > 0
* @return Arg option with values.
*/
public ArgOption withNumVals(final String optionNumValsStr)
{
if (StringRoutines.isInteger(optionNumValsStr))
return withNumVals(Integer.parseInt(optionNumValsStr));
this.numValsStr = optionNumValsStr;
return this;
}
/**
* Set the default value for this arg option
* @param optionDefaultVal
* @return Arg option with default.
*/
public ArgOption withDefault(final Object optionDefaultVal)
{
this.defaultVal = optionDefaultVal;
return this;
}
/**
* Mark this arg option as required
* @return Arg option with required set.
*/
public ArgOption setRequired()
{
return setRequired(true);
}
/**
* Set whether this arg option is required
* @param required
* @return Arg option with required set.
*/
public ArgOption setRequired(final boolean required)
{
this.required = required;
return this;
}
/**
* Set restricted list of legal values
* @param optionLegalVals
* @return Arg option with legal values.
*/
public ArgOption withLegalVals(final Object... optionLegalVals)
{
this.legalVals = optionLegalVals;
return this;
}
/**
* Set the description for help message of this arg option
* @param optionHelp
* @return Arg option with help.
*/
public ArgOption help(final String optionHelp)
{
this.help = optionHelp;
return this;
}
//---------------------------------------------------------------------
/**
* @return Whether we expect a list of values (rather than a single value)
*/
protected boolean expectsList()
{
if (numValsStr != null)
return true;
return (numVals > 1);
}
//---------------------------------------------------------------------
@Override
public String toString()
{
final StringBuilder sb = new StringBuilder();
sb.append("[ArgOption: ");
if (names != null)
{
for (int i = 0; i < names.length; ++i)
{
sb.append(names[i]);
if (i + 1 < names.length)
sb.append(", ");
}
}
sb.append(" type=" + type);
if (numValsStr != null)
sb.append(" numVals=" + numValsStr);
else
sb.append(" numVals=" + numVals);
if (defaultVal != null)
sb.append(" default=" + defaultVal);
if (required)
sb.append(" required");
if (legalVals != null)
{
sb.append(" legalVals=" + Arrays.toString(legalVals));
}
if (help.length() > 0)
sb.append("\t\t" + help);
sb.append("]");
return sb.toString();
}
//---------------------------------------------------------------------
}
//-------------------------------------------------------------------------
}
| 23,850 | 23.091919 | 106 | java |
Ludii | Ludii-master/Common/src/main/Constants.java | package main;
/**
* Global constants.
*
* @author cambolbro and Eric.Piette
*/
public final class Constants
{
//-------------------------------------------------------------------------
// Admin
/** Version number of the Ludii's grammar/ludeme-based language. */
public static final String LUDEME_VERSION = "1.3.11";
/** Date last modified. */
public static final String DATE = "15/05/2023";
/** lud-path for default game to load (on initial launch, when prefs/trial loading fails, etc.) */
public static final String DEFAULT_GAME_PATH = "/lud/board/war/replacement/eliminate/all/Surakarta.lud";
//-------------------------------------------------------------------------
// Limits
/** Maximum score. */
public static final int MAX_SCORE = 1000000000;
/** Minimum score. *
public static final int MIN_SCORE = -1000000000;
/** The maximum number of iterations allowed in a loop inside an eval method. */
public static final int MAX_NUM_ITERATION = 10000;
/** Maximum number of players. */
public static final int MAX_PLAYERS = 16;
/** Maximum number of consecutive player turns (for purposes of hash codes, not a strict limit). */
public static final int MAX_CONSECUTIVES_TURNS = 16;
/** Highest possible team id. */
public static final int MAX_PLAYER_TEAM = MAX_PLAYERS;
/** Default value for components, if not specified. */
public static final int DEFAULT_PIECE_VALUE = 1;
/** Highest possible number of rules phases in a game. */
public static final int MAX_PHASES = 16;
/** Maximum distance a piece can travel. */
public static final int MAX_DISTANCE = 1000;
/** The max number of pits on a dominoes. */
public static final int MAX_PITS_DOMINOES = 16;
/** The max number of sides of a tile component. */
public static final int MAX_SIDES_TILE = 16;
/** The max number of faces for a die. */
public static final int MAX_FACE_DIE = 100;
/** The maximum value of a piece. */
public static final int MAX_VALUE_PIECE = 1024;
/** Minimum image size. */
public static final int MIN_IMAGE_SIZE = 2;
/** Default limit on number of turns (to be multiplied by number of players) per trial. */
public static final int DEFAULT_TURN_LIMIT = 1250;
/** Default limit on number of moves per trial. */
public static final int DEFAULT_MOVES_LIMIT = 10000;
/** Max Stack Height. */
public static final int MAX_STACK_HEIGHT = 32;
/** Maximum number of cell colours. */
public static final int MAX_CELL_COLOURS = 6;
//-------------------------------------------------------------------------
// Public Constants (in the grammar)
/** Off-board marker. */
public static final int OFF = -1;
/** End-track marker. */
public static final int END = -2;
/** Value for a variable not defined. */
public static final int UNDEFINED = -1;
/** A large number that's unlikely to occur in a game. */
public static final int INFINITY = 1000000000;
//-------------------------------------------------------------------------
// Internal constants (for internal use)
/** Signifies no owner or no user. */
public static final int NOBODY = 0;
/** Signifies no piece. */
public static final int NO_PIECE = 0;
/** Empty cell indicator for testing blocked connections. */
public static final int UNUSED = -4;
/** Highest absolute value of public constant. */
public static final int CONSTANT_RANGE = 4;
public static final double EPSILON = 1E-5;
//-------------------------------------------------------------------------
// Default values
/** Default number of players we use if Players argument is null in Game. */
public static final int DEFAULT_NUM_PLAYERS = 2;
/** The integer corresponding to the default rotation of a site. */
public static final int DEFAULT_ROTATION = 0;
/** The integer corresponding to the default piece value of a site. */
public static final int DEFAULT_VALUE = 0;
/** The integer corresponding to the default state of a site. */
public static final int DEFAULT_STATE = 0;
/** The integer corresponding to the ground level. */
public static final int GROUND_LEVEL = 0;
/** Size of default board for boardless games on hex tiling. */
public static final int SIZE_HEX_BOARDLESS = 21;
/** Size of default board for boardless games. */
public static final int SIZE_BOARDLESS = 41;
//-------------------------------------------------------------------------
// Emergency game descriptions
public static String FAIL_SAFE_GAME_DESCRIPTION =
"(game \"Tic-Tac-Toe\" \n" +
" (players 2) \n" +
" (equipment { \n" +
" (board (square 3)) \n" +
" (piece \"Disc\" P1) \n" +
" (piece \"Cross\" P2) \n" +
" }) \n" +
" (rules \n" +
" (play (move Add (to (sites Empty))))\n" +
" (end (if (is Line 3) (result Mover Win)))\n" +
" )\n" +
")";
public static String BASIC_GAME_DESCRIPTION =
"(game \"Name\" \n" +
" (players 2) \n" +
" (equipment { \n" +
" (board (square 3)) \n" +
" (piece \"Ball\" Each) \n" +
" }) \n" +
" (rules \n" +
" (play (move Add (to (sites Empty))))\n" +
" (end (if (no Moves Next) (result Mover Win)))\n" +
" )\n" +
")";
//-------------------------------------------------------------------------
}
| 5,339 | 30.785714 | 105 | java |
Ludii | Ludii-master/Common/src/main/DaemonThreadFactory.java | package main;
import java.util.concurrent.ThreadFactory;
/**
* Thread factory that produces daemon threads
*
* @author Dennis Soemers
*/
public class DaemonThreadFactory implements ThreadFactory
{
//-------------------------------------------------------------------------
/** Singleton */
public final static ThreadFactory INSTANCE = new DaemonThreadFactory();
//-------------------------------------------------------------------------
/**
* Constructor (private, singleton)
*/
private DaemonThreadFactory()
{
// Do nothing
}
//-------------------------------------------------------------------------
@Override
public Thread newThread(final Runnable r)
{
final Thread t = new Thread(r);
t.setDaemon(true);
return t;
}
//-------------------------------------------------------------------------
}
| 844 | 20.125 | 76 | java |
Ludii | Ludii-master/Common/src/main/DatabaseInformation.java | package main;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
public class DatabaseInformation
{
//-------------------------------------------------------------------------
private static final String RESOURCE_PATH = "/help/GameRulesets.csv";
//-------------------------------------------------------------------------
/**
* @param rulesetHeading The heading of the ruleset.
* @return the database name for a given ruleset.
*/
public static String getRulesetDBName(final String rulesetHeading)
{
try
{
final String[] rulesetNameArray = rulesetHeading.split("[/(]");
String rulesetNameString = "";
for (int i = 1; i < rulesetNameArray.length-1; i++)
rulesetNameString += rulesetNameArray[i] + "(";
rulesetNameString = rulesetNameString.substring(0, rulesetNameString.length()-1);
return rulesetNameString.trim();
}
catch (@SuppressWarnings("unused") final Exception e)
{
return rulesetHeading;
}
}
//-------------------------------------------------------------------------
/**
* @param gameName
* @param rulesetName
* @return the database Id for a given ruleset.
*/
public static int getRulesetId(final String gameName, final String rulesetName)
{
try (final InputStream resource = DatabaseInformation.class.getResourceAsStream(RESOURCE_PATH))
{
if (resource != null)
{
try
(
final InputStreamReader isr = new InputStreamReader(resource, "UTF-8");
final BufferedReader rdr = new BufferedReader(isr)
)
{
final List<Integer> allRulesetIdsForGame = new ArrayList<>();
String line;
while ((line = rdr.readLine()) != null)
{
final String[] lineArray = line.replaceAll("\"", "").split(",");
if (lineArray[1].equals(gameName))
{
allRulesetIdsForGame.add(Integer.valueOf(lineArray[2]));
if (lineArray[3].equals(rulesetName) || lineArray[3].equals(getRulesetDBName(rulesetName)))
return Integer.valueOf(lineArray[2]);
}
}
// Check if there is only one ruleset for this game.
if (rulesetName.length() == 0 && allRulesetIdsForGame.size() == 1)
return allRulesetIdsForGame.get(0);
}
}
}
catch (final IOException e)
{
e.printStackTrace();
}
return -1;
}
//-------------------------------------------------------------------------
/**
* @param gameName
* @return the database Id for a given game.
*/
public static int getGameId(final String gameName)
{
try (final InputStream resource = DatabaseInformation.class.getResourceAsStream(RESOURCE_PATH))
{
if (resource != null)
{
try
(
final InputStreamReader isr = new InputStreamReader(resource, "UTF-8");
final BufferedReader rdr = new BufferedReader(isr)
)
{
String line;
while ((line = rdr.readLine()) != null)
{
final String[] lineArray = line.replaceAll("\"", "").split(",");
if (lineArray[1].equals(gameName))
return Integer.valueOf(lineArray[0]);
}
}
}
}
catch (final IOException e)
{
e.printStackTrace();
}
return -1;
}
//-------------------------------------------------------------------------
}
| 3,339 | 24.891473 | 98 | java |
Ludii | Ludii-master/Common/src/main/EditorHelpData.java | package main;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
/**
* This class contains data loaded from the Common/res/help/EditorHelp.txt file.
*
* This file is under version control, and can be regenerated by running the
* main method of LudiiDocGen/main/GenerateLudiiEditorHelpFileMain.java
*
* @author Dennis Soemers and cambolbro
*/
public final class EditorHelpData
{
/**
* There can be only one.
* Since this is used only by the editor and we don't want a long pause on first key press, lazy initialisation is a bad idea
*/
private static final EditorHelpData SINGLETON = loadData();
//-------------------------------------------------------------------------
/** Path where we expect our data to be generated */
private static final String RESOURCE_PATH = "/help/EditorHelp.txt";
/**
* Mapping from type-strings to strings. The key should be a fully qualified
* type name such as "game.Game". The map gives the class-level documentation
* for this type
*/
private final Map<String, String> typeDocStrings;
/**
* Mapping from type-strings to lists of strings. The key should be a fully
* qualified type name such as "game.Game". For every constructor of this
* type, the list will contain a line that fully describes that constructor.
*/
private final Map<String, List<String>> constructorLines;
/**
* Mapping from type-strings to lists of lists of strings. The key should be
* a fully qualified type name such as "game.Game". For every constructor of
* this type, we have a List of Strings, where each String is a documentation
* line for a single parameter of that constructor.
*/
private final Map<String, List<List<String>>> constructorParamLines;
/**
* Mapping from type-strings to lists of lists of strings. The key should be
* a fully qualified type name such as "game.Game". For every constructor of
* this type, we have a List of Strings, where each String is an example line
* for that constructor.
*/
private final Map<String, List<List<String>>> constructorExampleLines;
/**
* Mapping from define-names to strings. The key should be the name of a define,
* such as "HopCapture". The map gives the documentation string for this define.
*/
private final Map<String, String> defineDocStrings;
/**
* Mapping from define-names to lists of strings. The key should be the name of
* a define, such as "HopCapture". The map gives a List of Strings, where every
* String is an example line for the define.
*/
private final Map<String, List<String>> defineExampleLines;
/**
* Mapping from type-strings to lists of strings. The key should be a fully
* qualified type name of an enum such as "game.functions.graph.generators.basis.brick.BrickShapeType".
* For every constant in this enum, the list will contain a line that describes that
* enum constant.
*/
private final Map<String, List<String>> enumConstantLines;
/**
* Mapping from Abstract/Interface type-strings to lists of strings. The key
* should be a fully qualified type name of an Abstract class or Interface.
* For every subclass of this abstract type, the will will contain a line
* that describes that subclass.
*/
private final Map<String, List<String>> subclassDocLines;
/**
* Mapping from type-strings to strings. The key should be a fully qualified
* type name such as "game.Game". The map gives @remarks documentation for this
* type.
*/
private final Map<String, String> typeRemarksStrings;
static boolean trace = false;
//-------------------------------------------------------------------------
/**
* Constructor. Private, should call the static loadData() method to instantiate.
*
* @param typeDocStrings
* @param constructorLines
* @param constructorParamLines
* @param constructorExampleLines
* @param defineDocStrings
* @param defineExampleLines
* @param enumConstantLines
* @param subclassDocLines
* @param typeRemarksStrings
*/
private EditorHelpData
(
final Map<String, String> typeDocStrings,
final Map<String, List<String>> constructorLines,
final Map<String, List<List<String>>> constructorParamLines,
final Map<String, List<List<String>>> constructorExampleLines,
final Map<String, String> defineDocStrings,
final Map<String, List<String>> defineExampleLines,
final Map<String, List<String>> enumConstantLines,
final Map<String, List<String>> subclassDocLines,
final Map<String, String> typeRemarksStrings
)
{
this.typeDocStrings = typeDocStrings;
this.constructorLines = constructorLines;
this.constructorParamLines = constructorParamLines;
this.constructorExampleLines = constructorExampleLines;
this.defineDocStrings = defineDocStrings;
this.defineExampleLines = defineExampleLines;
this.enumConstantLines = enumConstantLines;
this.subclassDocLines = subclassDocLines;
this.typeRemarksStrings = typeRemarksStrings;
}
//-------------------------------------------------------------------------
/**
* @return the one and only EditorHelpData object
*/
public static EditorHelpData get()
{
return SINGLETON;
}
/**
* @param type Fully qualified type name
* @param n Which constructor do we want?
* @return Grammar-like line describing the format of the nth constructor
* of given type.
*/
public String nthConstructorLine(final String type, final int n)
{
return constructorLines.get(type).get(n);
}
/**
* @param type Fully qualified type name
* @param n Which constructor do we want?
* @return List of strings, containing one string (javadoc comment) for every
* parameter of the nth constructor of given type
*/
public List<String> nthConstructorParamLines(final String type, final int n)
{
return constructorParamLines.get(type).get(n);
}
/**
* @param type Fully qualified type name
* @param n Which constructor do we want?
* @return List of strings, where each string is an example for the nth
* constructor of given type
*/
public List<String> nthConstructorExampleLines(final String type, final int n)
{
return constructorExampleLines.get(type).get(n);
}
/**
* @param type Fully qualified type name
* @return The number of constructors that the given type has
*/
public int numConstructors(final String type)
{
final List<String> lines = constructorLines.get(type);
// if (lines == null)
// System.out.println("Lines not found for "+type);
return lines == null ? 0 : lines.size();
}
/**
* @param type Fully qualified type name (of an enum)
* @return List of strings, each describing a single enum constant.
* Will be null for non-enum types.
*/
public List<String> enumConstantLines(final String type)
{
return enumConstantLines.get(type);
}
/**
* @param type Fully qualified type name (of an Abstract class or Interface)
* @return List of strings, each describing a single subclass.
* Will be null for non-abstract types.
*/
public List<String> subclassDocLines(final String type)
{
return subclassDocLines.get(type);
}
/**
* @param type Fully qualified type name
* @return Documentation for the type (i.e. class-level javadoc)
*/
public String typeDocString(final String type)
{
return typeDocStrings.get(type);
}
/**
* @param type Fully qualified type name
* @return Remarks documentation for the type (i.e. @remarks in class-level javadoc)
*/
public String typeRemarksString(final String type)
{
return typeRemarksStrings.get(type);
}
/**
* @param defineName Name of a define
* @return Documentation string for the given define
*/
public String defineDocString(final String defineName)
{
return defineDocStrings.get(defineName);
}
/**
* @param defineName Name of a define
* @return List of example lines for the given define
*/
public List<String> defineExampleLines(final String defineName)
{
return defineExampleLines.get(defineName);
}
//-------------------------------------------------------------------------
/**
* @return Loads the help data for the Ludii editor from the resource file.
*/
private static EditorHelpData loadData()
{
final Map<String, String> typeDocStrings = new HashMap<String, String>();
final Map<String, List<String>> constructorLines = new HashMap<String, List<String>>();
final Map<String, List<List<String>>> constructorParamLines = new HashMap<String, List<List<String>>>();
final Map<String, List<List<String>>> constructorExampleLines = new HashMap<String, List<List<String>>>();
final Map<String, String> defineDocStrings = new HashMap<String, String>();
final Map<String, List<String>> defineExampleLines = new HashMap<String, List<String>>();
final Map<String, List<String>> enumConstantLines = new HashMap<String, List<String>>();
final Map<String, List<String>> subclassDocLines = new HashMap<String, List<String>>();
final Map<String, String> typeRemarksStrings = new HashMap<String, String>();
// In this map we'll just collect the fully qualified names of subclasses.
// At the end we'll use those to access the javadoc of those types
final Map<String, List<String>> subclasses = new HashMap<String, List<String>>();
try (final InputStream resource = EditorHelpData.class.getResourceAsStream(RESOURCE_PATH))
{
if (resource == null)
{
System.err.println("Cannot locate resource " + RESOURCE_PATH + " - not all functionality will be available.\nThis file can be generated by running the\n" +
" main method of LudiiDocGen/main/GenerateLudiiEditorHelpFileMain.java");
return new EditorHelpData(
typeDocStrings, constructorLines, constructorParamLines, constructorExampleLines,
defineDocStrings, defineExampleLines, enumConstantLines, subclassDocLines,
typeRemarksStrings
);
}
try
(
final InputStreamReader isr = new InputStreamReader(resource, "UTF-8");
final BufferedReader rdr = new BufferedReader(isr)
)
{
String currType = null;
int currConstructor = -1;
String currDefine = null;
String line;
while ((line = rdr.readLine()) != null)
{
if (line.startsWith("TYPE: "))
{
// We're starting to read data for a new type
currType = line.substring("TYPE: ".length());
constructorLines.put(currType, new ArrayList<String>());
constructorParamLines.put(currType, new ArrayList<List<String>>());
constructorExampleLines.put(currType, new ArrayList<List<String>>());
currConstructor = -1;
}
else if (line.startsWith("TYPE JAVADOC: "))
{
// Type-level javadoc
typeDocStrings.put(currType, line.substring("TYPE JAVADOC: ".length()));
}
else if (line.equals("NEW CTOR"))
{
// We're starting multiple lines of text for a new constructor
++currConstructor;
// Instantiate new list to contain per-param docs
constructorParamLines.get(currType).add(new ArrayList<String>());
// And same for examples
constructorExampleLines.get(currType).add(new ArrayList<String>());
}
else if (line.startsWith("PARAM JAVADOC: "))
{
// A single-param doc line
constructorParamLines.get(currType).get(currConstructor).add(line.substring("PARAM JAVADOC: ".length()));
}
else if (line.startsWith("EXAMPLE: "))
{
// An example for this constructor
// TODO: probably want to format the example code nicely BEFORE inserting in the map?
// example code as it is right now is always a single, unformatted line
constructorExampleLines.get(currType).get(currConstructor).add(line.substring("EXAMPLE: ".length()));
}
else if (line.startsWith("DEFINE: "))
{
// We're starting to read data for a new define
currDefine = line.substring("DEFINE: ".length());
defineExampleLines.put(currDefine, new ArrayList<String>());
}
else if (line.startsWith("DEFINE JAVADOC: "))
{
// Javadoc for a define
defineDocStrings.put(currDefine, line.substring("DEFINE JAVADOC: ".length()));
}
else if (line.startsWith("DEFINE EXAMPLE: "))
{
// An example for current define
defineExampleLines.get(currDefine).add(line.substring("DEFINE EXAMPLE: ".length()));
}
else if (line.startsWith("CONST JAVADOC: "))
{
// An enum const line
if (!enumConstantLines.containsKey(currType))
enumConstantLines.put(currType, new ArrayList<String>());
enumConstantLines.get(currType).add(line.substring("CONST JAVADOC: ".length()));
// // Split the enum constant name from its help line
// final String data = line.substring("CONST JAVADOC: ".length());
// final int c = data.indexOf(':');
// final String name = data.substring(0, c);
// final String help = data.substring(c + 1);
//
// if (!enumConstantLines.containsKey(currType))
// enumConstantLines.put(currType, new ArrayList<String>());
// enumConstantLines.get(currType).add(name);
//
// typeDocStrings.put(currType, help);
}
else if (line.startsWith("SUBCLASS: "))
{
// A subclass line of an abstract type
if (!subclasses.containsKey(currType))
subclasses.put(currType, new ArrayList<String>());
subclasses.get(currType).add(line.substring("SUBCLASS: ".length()));
}
else if (line.startsWith("REMARKS: "))
{
// Type-level remarks line
typeRemarksStrings.put(currType, line.substring("REMARKS: ".length()));
}
else
{
// A single line describing a full constructor
constructorLines.get(currType).add(line);
}
}
}
}
catch (final IOException e)
{
e.printStackTrace();
}
// Populate our map of subclass javadoc lines for abstract types
for (final Entry<String, List<String>> entry : subclasses.entrySet())
{
final String abstractType = entry.getKey();
final List<String> subclassTypes = entry.getValue();
final List<String> docLines = new ArrayList<String>(subclassTypes.size());
for (final String subclassType : subclassTypes)
{
String typeDoc = typeDocStrings.get(subclassType);
if (typeDoc == null)
{
typeDoc = "";
if (trace) System.err.println("WARNING: no type doc for subclass " + subclassType + " of abstract type " + abstractType + "!");
}
docLines.add("<" + subclassType + "> : " + typeDoc);
}
// System.out.println("abstractType = " + abstractType);
// for (final String docLine : docLines)
// {
// System.out.println("subclass docline = " + docLine);
// }
subclassDocLines.put(abstractType, docLines);
}
return new EditorHelpData(
typeDocStrings, constructorLines, constructorParamLines, constructorExampleLines,
defineDocStrings, defineExampleLines, enumConstantLines, subclassDocLines,
typeRemarksStrings
);
}
//-------------------------------------------------------------------------
}
| 15,200 | 33.391403 | 160 | java |
Ludii | Ludii-master/Common/src/main/FileHandling.java | package main;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Enumeration;
import java.util.List;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.regex.Pattern;
import java.util.zip.ZipEntry;
/**
* Common file handling routines.
* @author cambolbro and Dennis Soemers and Matthew.Stephenson
*/
public class FileHandling
{
//-------------------------------------------------------------------------
/** Only need to compute this once, afterwards we can just return it immediately */
private static String[] gamesList = null;
//-------------------------------------------------------------------------
/**
* @return List of all the games that we can automatically find (i.e. the built-in games).
*/
public static String[] listGames()
{
if (gamesList == null)
{
// Try loading from JAR file
String[] choices = FileHandling.getResourceListing(FileHandling.class, "lud/", ".lud");
final List<String> names = new ArrayList<>();
if (choices == null)
{
try
{
// Try loading from memory in IDE
// Start with known .lud file
final URL url = FileHandling.class.getResource("/lud/board/space/line/Tic-Tac-Toe.lud");
String path = new File(url.toURI()).getPath();
path = path.substring(0, path.length() - "board/space/line/Tic-Tac-Toe.lud".length());
//System.out.println(path);
// Get the list of .lud files in this directory and subdirectories
visit(path, names);
Collections.sort(names);
choices = names.toArray(new String[names.size()]);
}
catch (final URISyntaxException exception)
{
exception.printStackTrace();
}
}
// We check the proprietary games.
// final List<String> proprieatryNames = new ArrayList<>();
// final String pathProprietaryGames = "../../LudiiPrivate/ProprietaryGames/res";
// final File file = new File(pathProprietaryGames.replaceAll(Pattern.quote("\\"), "/"));
// if (file.exists())
// visit(file.getAbsolutePath().replaceAll(Pattern.quote("\\"), "/") + File.separator, proprieatryNames);
// We add them to the list if some are found.
// if(!proprieatryNames.isEmpty())
// {
// for(int i = 0 ; i < proprieatryNames.size();i++)
// {
// final String name = proprieatryNames.get(i).substring(proprieatryNames.get(i).indexOf("lud")-1);
// proprieatryNames.set(i, name);
// }
// for(String name: choices)
// names.add(name);
//
// names.addAll(proprieatryNames);
// Collections.sort(names);
// choices = names.toArray(new String[names.size()]);
// }
gamesList = choices;
}
// To protect against users accidentally modifying this array, we return a copy
return Arrays.stream(gamesList).filter(s -> !shouldIgnoreLud(s)).toArray(String[]::new);
}
//-------------------------------------------------------------------------
/**
* @param lud
* @return True if we wish to ignore the given lud
*/
public static boolean shouldIgnoreLud(final String lud)
{
return
(
lud.contains("lud/bad/") ||
lud.contains("lud/bad_playout/") ||
lud.contains("lud/wishlist/")
);
}
//-------------------------------------------------------------------------
/**
* @param lud
* @return True if we wish to ignore the given lud (release version)
*/
public static boolean shouldIgnoreLudRelease(final String lud)
{
return
(
shouldIgnoreLudAnalysis(lud) ||
lud.contains("/proprietary/")
);
}
//-------------------------------------------------------------------------
/**
* @param lud
* @return True if we wish to ignore the given lud (release version)
*/
public static boolean shouldIgnoreLudThumbnails(final String lud)
{
return
(
shouldIgnoreLud(lud) ||
lud.contains("/proprietary/") ||
lud.contains("/subgame/") ||
lud.contains("/test/") ||
lud.contains("/wip/")
);
}
//-------------------------------------------------------------------------
/**
* @param lud
* @return True if we wish to ignore the given lud (remote version)
*/
public static boolean shouldIgnoreLudRemote(final String lud)
{
return
(
shouldIgnoreLudRelease(lud) ||
lud.contains("/puzzle/") ||
lud.contains("/simulation/")
);
}
//-------------------------------------------------------------------------
/**
* @param lud
* @return True if we wish to ignore the given lud (evaluation version)
*/
public static boolean shouldIgnoreLudEvaluation(final String lud)
{
return
(
shouldIgnoreLudRelease(lud) ||
lud.contains("/puzzle/") ||
lud.contains("/simulation/")
);
}
//-------------------------------------------------------------------------
/**
* @param lud
* @return True if we wish to ignore the given lud (analysis version)
*/
public static boolean shouldIgnoreLudAnalysis(final String lud)
{
return
(
shouldIgnoreLud(lud) ||
lud.contains("/subgame/") ||
lud.contains("/test/") ||
lud.contains("/wip/") ||
lud.contains("/WishlistDLP/") ||
lud.contains("/simulation/") ||
lud.contains("/reconstruction/")
);
}
//-------------------------------------------------------------------------
static void visit(final String path, final List<String> names)
{
final File root = new File( path );
final File[] list = root.listFiles();
if (list == null)
return;
for (final File file : list)
{
if (file.isDirectory())
{
visit(path + file.getName() + File.separator, names);
}
else
{
if (file.getName().contains(".lud") && !shouldIgnoreLud(path))
{
// Add this game name to the list of choices
final String name = new String(file.getName());
if(path.contains("LudiiPrivate"))
names.add(file.getAbsolutePath().replaceAll(Pattern.quote("\\"), "/"));
else if (containsGame(path + File.separator + file.getName()))
names.add(path.substring(path.indexOf(File.separator + "lud" + File.separator)) + name);
}
}
}
}
//-------------------------------------------------------------------------
/**
* @param filePath
* @return Whether this file contains a game description (not tested).
*/
public static boolean containsGame(final String filePath)
{
final File file = new File(filePath);
if (file != null)
{
InputStream in = null;
String path = file.getPath().replaceAll(Pattern.quote("\\"), "/");
path = path.substring(path.indexOf("/lud/"));
final URL url = FileHandling.class.getResource(path);
try
{
in = new FileInputStream(new File(url.toURI()));
}
catch (final FileNotFoundException | URISyntaxException e)
{
e.printStackTrace();
}
try (BufferedReader rdr = new BufferedReader(new InputStreamReader(in)))
{
String line;
while ((line = rdr.readLine()) != null)
if (line.contains("(game"))
return true;
}
catch (final Exception e)
{
System.out.println("FileHandling.containsGame(): Failed to load " + filePath + ".");
e.printStackTrace();
}
}
return false;
}
//-------------------------------------------------------------------------
/**
*
* @param filePath
* @return Text contents from file.
* @throws IOException
* @throws FileNotFoundException
*/
public static String loadTextContentsFromFile(final String filePath) throws FileNotFoundException, IOException
{
// Load the string from file
final StringBuilder sb = new StringBuilder();
String line = null;
try
(
final InputStreamReader isr = new InputStreamReader(new FileInputStream(filePath), StandardCharsets.UTF_8);
final BufferedReader bufferedReader = new BufferedReader(isr)
)
{
while ((line = bufferedReader.readLine()) != null)
sb.append(line + "\n");
}
return sb.toString();
}
//-------------------------------------------------------------------------
/**
* Based on: http://www.uofr.net/~greg/java/get-resource-listing.html
*
* Changed a lot after copying from that source! Made recursive.
*
* Recursively lists directory contents for a resource folder.
* Works for regular files and also JARs.
*
* @author Greg Briggs
* @param cls
* @param path Should end with "/", but not start with one.
* @param filter
* @return Just the name of each member item, not the full paths (or actually maybe full paths).
*/
public static String[] getResourceListing
(
final Class<?> cls, final String path, final String filter
)
{
URL dirURL = cls.getClassLoader().getResource(path);
if (dirURL == null)
{
// If a jar file, can't find directory, assume the same jar as cls
final String me = cls.getName().replace(".", "/") + ".class";
dirURL = cls.getClassLoader().getResource(me);
}
if (dirURL != null && dirURL.getProtocol().equals("file"))
{
// File path: return its contents
try
{
final String dirPath = dirURL.toURI().toString().substring("file:/".length()).replaceAll(Pattern.quote("%20"), " ");
final String[] toReturn = listFilesOfType(dirPath, filter).toArray(new String[0]);
for (int i = 0; i < toReturn.length; ++i)
{
toReturn[i] = toReturn[i].replaceAll(Pattern.quote("\\"), "/");
toReturn[i] = "/" + toReturn[i].substring(toReturn[i].indexOf(path));
}
return toReturn;
}
catch (final URISyntaxException e)
{
e.printStackTrace();
}
}
if (dirURL.getProtocol().equals("jar"))
{
// JAR path
final String jarPath = dirURL.getPath().substring(5, dirURL.getPath().indexOf("!")); //strip out only the JAR file
JarFile jar = null;
try
{
jar = new JarFile(URLDecoder.decode(jarPath, "UTF-8"));
}
catch (final UnsupportedEncodingException e)
{
e.printStackTrace();
}
catch (final IOException e)
{
e.printStackTrace();
}
final Enumeration<JarEntry> entries = jar.entries(); //gives all entries in jar
final List<String> result = new ArrayList<>();
while (entries.hasMoreElements())
{
final String filePath = entries.nextElement().getName();
if (filePath.endsWith(filter) && filePath.startsWith(path))
{
result.add(File.separator + filePath);
}
}
try
{
jar.close();
}
catch (final IOException e)
{
e.printStackTrace();
}
Collections.sort(result);
return result.toArray(new String[result.size()]);
}
return null;
}
/**
* Optimised version of getResourceListing() for cases where we expect to find only
* a single entry in the returned array (but it will fall back to return the full
* listing if we can't immediately access just the single file).
*
* @param cls
* @param path
* @param filter
* @return Listing of resources (containing just a single element if we could find it immediately)
*/
public static String[] getResourceListingSingle(final Class<?> cls, final String path, final String filter)
{
URL dirURL = cls.getClassLoader().getResource(path);
if (dirURL == null)
{
// If a jar file, can't find directory, assume the same jar as cls
final String me = cls.getName().replace(".", "/") + ".class";
dirURL = cls.getClassLoader().getResource(me);
}
if (dirURL != null && dirURL.getProtocol().equals("file"))
{
// File path: return its contents
try
{
final String dirPath = dirURL.toURI().toString().substring("file:/".length()).replaceAll(Pattern.quote("%20"), " ");
if (new File(dirPath + filter).exists())
{
// We can just return this one file immediately
return new String[]{ "/" + path + filter };
}
final String[] toReturn = listFilesOfType(dirPath, filter).toArray(new String[0]);
for (int i = 0; i < toReturn.length; ++i)
{
toReturn[i] = toReturn[i].replaceAll(Pattern.quote("\\"), "/");
toReturn[i] = "/" + toReturn[i].substring(toReturn[i].indexOf(path));
}
return toReturn;
}
catch (final URISyntaxException e)
{
e.printStackTrace();
}
}
if (dirURL.getProtocol().equals("jar"))
{
// JAR path
final String jarPath = dirURL.getPath().substring(5, dirURL.getPath().indexOf("!")); //strip out only the JAR file
JarFile jar = null;
try
{
jar = new JarFile(URLDecoder.decode(jarPath, "UTF-8"));
}
catch (final UnsupportedEncodingException e)
{
e.printStackTrace();
}
catch (final IOException e)
{
e.printStackTrace();
}
final ZipEntry entry = jar.getEntry(path + filter);
if (entry != null)
{
// We'll just immediately return this one
return new String[] { File.separator + path + filter };
}
// Search through JAR
final Enumeration<JarEntry> entries = jar.entries(); //gives all entries in jar
final List<String> result = new ArrayList<>();
while (entries.hasMoreElements())
{
final String filePath = entries.nextElement().getName();
if (filePath.endsWith(filter) && filePath.startsWith(path))
{
System.out.println("filePath = " + filePath);
result.add(File.separator + filePath);
}
}
try
{
jar.close();
}
catch (final IOException e)
{
e.printStackTrace();
}
Collections.sort(result);
return result.toArray(new String[result.size()]);
}
return null;
}
//-------------------------------------------------------------------------
public static List<String> listFilesOfType(final String path, final String extension)
{
final List<String> files = new ArrayList<String>();
walk(path, files, extension);
return files;
}
static void walk(final String path, final List<String> files, final String extension)
{
final File root = new File("/" + path);
final File[] list = root.listFiles();
if (list == null)
return;
for (final File file : list)
{
if (file.isDirectory())
{
//System.out.println("Dir:" + file.getAbsoluteFile());
walk(file.getAbsolutePath(), files, extension);
}
else
{
//System.out.println("File:" + file.getAbsoluteFile());
if (file.getName().contains(extension))
files.add(new String(file.getAbsolutePath()));
}
}
}
//-------------------------------------------------------------------------
public static void findMissingConstructors()
{
final List<String> files = listFilesOfType("/Users/cambolbro/Ludii/dev/Core/src/game", ".java");
System.out.println(files.size() + " .java files found.");
for (final String path : files)
{
int c = path.length()-1;
while (c >= 0 && path.charAt(c) != '/')
c--;
if (c < 0)
continue;
final String className = path.substring(c+1, path.length()-5);
final String constructorName = "public " + className;
//System.out.println("Path: " + path + ", className: " + className + ", constructorName: " + constructorName);
boolean abstractClass = false;
boolean constructorFound = false;
try (final BufferedReader reader = new BufferedReader(
new InputStreamReader(new FileInputStream(path), "UTF-8")))
{
String line;
while (true)
{
line = reader.readLine();
if (line == null)
break;
if (line.contains("abstract class"))
{
abstractClass = true;
break;
}
if (line.contains(constructorName) || line.contains(" construct()"))
{
constructorFound = true;
break;
}
//System.out.println(line);
}
}
catch (final Exception e)
{
e.printStackTrace();
}
if (!abstractClass && !constructorFound)
System.out.println("Missing " + path); //className + ".");
}
}
//-------------------------------------------------------------------------
public static void findEmptyRulesets()
{
final List<String> files = listFilesOfType("/Users/cambolbro/Ludii/dev/Common/res/lud", ".lud");
System.out.println(files.size() + " .lud files found.");
for (final String path : files)
{
int c = path.length()-1;
while (c >= 0 && path.charAt(c) != '/')
c--;
if (c < 0)
continue;
final StringBuilder sb = new StringBuilder();
try (final BufferedReader reader = new BufferedReader(
new InputStreamReader(new FileInputStream(path), "UTF-8")))
{
String line;
do
{
line = reader.readLine();
sb.append(line);
} while (line != null);
}
catch (final Exception e)
{
e.printStackTrace();
}
final String str = sb.toString();
int r = str.indexOf("(ruleset");
if (r >= 0)
{
// File contains ruleset
while (r < str.length() && str.charAt(r) != '{')
r++;
if (r < str.length())
{
// We have a curly brace
final int rr = StringRoutines.matchingBracketAt(str, r);
if (rr < 0)
throw new RuntimeException("No closing '}' in ruleset: " + str);
final String sub = str.substring(r+1, rr);
boolean isChar = false;
for (int s = 0; s < sub.length(); s++)
{
final char ch = sub.charAt(s);
if
(
StringRoutines.isTokenChar(ch)
||
StringRoutines.isNameChar(ch)
||
StringRoutines.isNumeric(ch)
||
StringRoutines.isBracket(ch)
)
isChar = true;
}
if (!isChar)
System.out.println(path + " has an empty ruleset.");
}
}
// catch (Exception e)
// {
// e.printStackTrace();
// }
}
}
//-------------------------------------------------------------------------
/**
* Print game options per .lud to file.
* @param fileName
* @throws IOException
*/
public static void printOptionsToFile(final String fileName) throws IOException
{
final String[] list = listGames();
// Prepare the output file
final File file = new File(fileName);
if (!file.exists())
file.createNewFile();
try (final FileWriter fw = new FileWriter(file.getName(), false))
{
try (final BufferedWriter writer = new BufferedWriter(fw))
{
for (final String name : list)
{
final String str = gameAsString(name);
System.out.println(name + "(" + str.length() + " chars).");
final String[] subs = str.split("\n");
writer.write("\n" + name + "(" + str.length() + " chars):\n");
for (int n = 0; n < subs.length; n++)
if (subs[n].contains("(option "))
writer.write(subs[n] + "\n");
}
// writer.close();
}
}
}
//-------------------------------------------------------------------------
/**
* Print game options per .lud to file.
* @throws IOException
*/
public static void saveReconstruction
(
final String name, final String content
) throws IOException
{
final String outFileName = "../Common/res/out/recons/" + name + ".lud";
// Prepare the output file
final File file = new File(outFileName);
if (!file.exists())
file.createNewFile();
try
(
final PrintWriter writer =
new PrintWriter
(
new BufferedWriter(new FileWriter(outFileName, false))
)
)
{
writer.write(content);
}
}
//-------------------------------------------------------------------------
/**
* @param name Path of game file (.lud) with name.
* @return Contents of specified .lud file as string.
*/
public static String gameAsString(final String name)
{
// Not opening - just locating resource at the moment
InputStream in = FileHandling.class.getResourceAsStream(name.startsWith("/lud/") ? name : "/lud/" + name);
if (in == null)
{
// exact match with full filepath under /lud/ not found; let's try
// to see if we can figure out which game the user intended
final String[] allGameNames = FileHandling.listGames();
int shortestNonMatchLength = Integer.MAX_VALUE;
String bestMatchFilepath = null;
final String givenName = name.toLowerCase().replaceAll(Pattern.quote("\\"), "/");
for (final String gameName : allGameNames)
{
final String str = gameName.toLowerCase().replaceAll(Pattern.quote("\\"), "/");
if (str.endsWith(givenName))
{
final int nonMatchLength = str.length() - givenName.length();
if (nonMatchLength < shortestNonMatchLength)
{
shortestNonMatchLength = nonMatchLength;
bestMatchFilepath = "..\\Common\\res\\" + gameName;
}
}
}
String resourceStr = bestMatchFilepath.replaceAll(Pattern.quote("\\"), "/");
resourceStr = resourceStr.substring(resourceStr.indexOf("/lud/"));
in = FileHandling.class.getResourceAsStream(resourceStr);
}
// Open the resource and use it.
final StringBuilder sb = new StringBuilder();
try (final BufferedReader rdr = new BufferedReader(new InputStreamReader(in)))
{
String line;
while ((line = rdr.readLine()) != null)
sb.append(line + "\n");
}
catch (final IOException e)
{
e.printStackTrace();
}
return sb.toString();
}
//-------------------------------------------------------------------------
/**
* @param fileContents The contents of the file.
* @param filePath The path of the file.
* @param fileName The name of the file.
*/
public static void saveStringToFile
(
final String fileContents, final String filePath, final String fileName
)
{
try
{
final File file = new File(filePath + fileName);
try (final PrintWriter out = new PrintWriter(file.getAbsolutePath()))
{
out.println(fileContents);
}
catch (final FileNotFoundException e)
{
e.printStackTrace();
}
}
catch (final Exception e)
{
e.printStackTrace();
}
}
//-------------------------------------------------------------------------
/**
* @return Whether cambolbro is compiling this project.
*/
public static boolean isCambolbro()
{
return isUser("/Users/cambolbro/eclipse/Ludii/dev/Player");
}
/**
* @return Whether the specified person is compiling this project.
*/
public static boolean isUser(final String userName)
{
final Path path = Paths.get(System.getProperty("user.dir"));
//System.out.println("user.dir: " + path);
return path.toString().contains(userName);
}
//-------------------------------------------------------------------------
}
| 23,153 | 26.272085 | 120 | java |
Ludii | Ludii-master/Common/src/main/GameNames.java | package main;
/**
* Game Names.
*
* @author Matthew.Stephenson
*/
public enum GameNames
{
GAME_War("War" , "", ""),
GAME_Chopsticks("Chopsticks" , "", ""),
GAME_RockPaperScissors("Rock-Paper-Scissors" , "", ""),
GAME_Nim("Nim" , "", ""),
GAME_Bricks("Bricks" , "", ""),
GAME_FillAPix("Fill A Pix" , "", ""),
GAME_Futoshiki("Futoshiki" , "", ""),
GAME_Hashiwokakero("Hashiwokakero" , "", ""),
GAME_InshinoHeya("Inshi no Heya" , "", ""),
GAME_Juosan("Juosan" , "", ""),
GAME_Kakuro("Kakuro" , "", ""),
GAME_KillerSudoku("Killer Sudoku" , "", ""),
GAME_LatinSquare("Latin Square" , "", ""),
GAME_MagicHexagon("Magic Hexagon" , "", ""),
GAME_MagicSquare("Magic Square" , "", ""),
GAME_NQueens("N Queens" , "", ""),
GAME_Nawabari("Nawabari" , "", ""),
GAME_Slitherlink("Slitherlink" , "", ""),
GAME_Squaro("Squaro" , "", ""),
GAME_Sudoku("Sudoku" , "", ""),
GAME_Takuzu("Takuzu" , "", ""),
GAME_ChessPuzzle("Chess Puzzle" , "", ""),
GAME_Insanity("Insanity" , "", ""),
GAME_KnightsTour("Knight's Tour" , "", ""),
GAME_NPuzzles("N Puzzles" , "", ""),
GAME_PegSolitaire("Peg Solitaire" , "", ""),
GAME_SafePassage("Safe Passage" , "", ""),
GAME_ShogiPuzzle("Shogi Puzzle" , "", ""),
GAME_TowerofHanoi("Tower of Hanoi" , "", ""),
GAME_Chatauranga("Chatauranga" , "", ""),
GAME_Chaturaji("Chaturaji" , "", ""),
GAME_Shatranj("Shatranj" , "", ""),
GAME_AmazonChess("Amazon Chess" , "", ""),
GAME_CapturetheQueen("Capture the Queen" , "", ""),
GAME_Chess("Chess" , "", ""),
GAME_Chex("Chex" , "", ""),
GAME_DoubleChess("Double Chess" , "", ""),
GAME_HalfChess("Half Chess" , "", ""),
GAME_HordeChess("Horde Chess" , "", ""),
GAME_LoopChess("Loop Chess" , "", ""),
GAME_LosAlamoschess("Los Alamos chess" , "", ""),
GAME_MaharajahChess("Maharajah Chess" , "", ""),
GAME_SkirmishGDL("Skirmish (GDL)" , "", ""),
GAME_AtariGo("Atari Go" , "", ""),
GAME_Castello("Castello" , "", ""),
GAME_Fanorona("Fanorona" , "", ""),
GAME_Lattaque("L'attaque" , "", ""),
GAME_LudusLatrunculorum("Ludus Latrunculorum" , "", ""),
GAME_Mehen("Mehen" , "", ""),
GAME_Ploy("Ploy" , "", ""),
GAME_PressUps("Press Ups" , "", ""),
GAME_Seega("Seega" , "", ""),
GAME_Surakarta("Surakarta" , "", ""),
GAME_Triad("Triad" , "", ""),
GAME_HasamiShogi("Hasami Shogi" , "", ""),
GAME_Minishogi("Minishogi" , "", ""),
GAME_Shogi("Shogi" , "", ""),
GAME_TaikyokuShogi("Taikyoku Shogi" , "", ""),
GAME_Janggi("Janggi" , "", ""),
GAME_Manzhouqi("Manzhouqi" , "", ""),
GAME_Xiangqi("Xiangqi" , "", ""),
GAME_Adugo("Adugo" , "", ""),
GAME_BaghChal("Bagh-Chal" , "", ""),
GAME_Coyote("Coyote" , "", ""),
GAME_DeCercarLaLiebre("De Cercar La Liebre" , "", ""),
GAME_Demaladiviyankeliya("Demala diviyan keliya" , "", ""),
GAME_DiviyanKeliya("Diviyan Keliya" , "", ""),
GAME_FoxandGeese("Fox and Geese" , "", ""),
GAME_GowiththeFloe("Go with the Floe" , "", ""),
GAME_HatDiviyanKeliya("Hat Diviyan Keliya" , "", ""),
GAME_Koapppawna("Ko-app-paw-na" , "", ""),
GAME_Komikan("Komikan" , "", ""),
GAME_Merimuengrimuengdo("Merimueng-rimueng-do" , "", ""),
GAME_Ponchochotl("Pon chochotl" , "", ""),
GAME_WolfandSheep("Wolf and Sheep" , "", ""),
GAME_AleaEvangelii("Alea Evangelii" , "", ""),
GAME_ArdRi("ArdRi" , "", ""),
GAME_Brandub("Brandub" , "", ""),
GAME_Hnefatafl("Hnefatafl" , "", ""),
GAME_Tablut("Tablut" , "", ""),
GAME_Tawlbwrdd("Tawlbwrdd" , "", ""),
GAME_20Squares("20 Squares" , "", ""),
GAME_58Holes("58 Holes" , "", ""),
GAME_RoyalGameofUr("Royal Game of Ur" , "", ""),
GAME_Senet("Senet" , "", ""),
GAME_XIIScripta("XII Scripta" , "", ""),
GAME_Camelot("Camelot" , "", ""),
GAME_ChineseCheckers("Chinese Checkers" , "", ""),
GAME_Grasshopper("Grasshopper" , "", ""),
GAME_Halma("Halma" , "", ""),
GAME_OPatKono("O-Pat-Kono" , "", ""),
GAME_Salta("Salta" , "", ""),
GAME_Arimaa("Arimaa" , "", ""),
GAME_Ashtapada("Ashtapada" , "", ""),
GAME_BreakThrough("BreakThrough" , "", ""),
GAME_Conspirateurs("Conspirateurs" , "", ""),
GAME_GameoftheGoose("Game of the Goose" , "", ""),
GAME_GyanChaupar("Gyan Chaupar" , "", ""),
GAME_Jungle("Jungle" , "", ""),
GAME_KnightThrough("KnightThrough" , "", ""),
GAME_Pachisi("Pachisi" , "", ""),
GAME_Sneakthrough("Sneakthrough" , "", ""),
GAME_Amazons("Amazons" , "", ""),
GAME_BlueNile("Blue Nile" , "", ""),
GAME_Contagion("Contagion" , "", ""),
GAME_FrenchMilitaryGame("French Military Game" , "", ""),
GAME_Horseshoe("Horseshoe" , "", ""),
GAME_LGame("L Game" , "", ""),
GAME_Madelinette("Madelinette" , "", ""),
GAME_MuTorere("Mu Torere" , "", ""),
GAME_NoGo("NoGo" , "", ""),
GAME_QuantumLeap("Quantum Leap" , "", ""),
GAME_Snowpaque("Snowpaque" , "", ""),
GAME_Spots("Spots" , "", ""),
GAME_Susan("Susan" , "", ""),
GAME_Tron("Tron" , "", ""),
GAME_Chameleon("Chameleon" , "", ""),
GAME_Cross("Cross" , "", ""),
GAME_Gonnect("Gonnect" , "", ""),
GAME_Havannah("Havannah" , "", ""),
GAME_Hex("Hex" , "", ""),
GAME_Trax("Trax" , "", ""),
GAME_YHex("Y (Hex)" , "", ""),
GAME_FeedtheDucks("Feed the Ducks" , "", ""),
GAME_Groups("Groups" , "", ""),
GAME_LinesofAction("Lines of Action" , "", ""),
GAME_Manalath("Manalath" , "", ""),
GAME_Odd("Odd" , "", ""),
GAME_Omega("Omega" , "", ""),
GAME_Achi("Achi" , "", ""),
GAME_AllQueensChess("All Queens Chess" , "", ""),
GAME_Andantino("Andantino" , "", ""),
GAME_Connect4("Connect 4" , "", ""),
GAME_Connect6("Connect6" , "", ""),
GAME_DaiHasamiShogi("Dai Hasami Shogi" , "", ""),
GAME_Dala("Dala" , "", ""),
GAME_Dra("Dra" , "", ""),
GAME_FiveMensMorris("Five Men's Morris" , "", ""),
GAME_Gomoku("Gomoku" , "", ""),
GAME_NineMensMorris("Nine Men's Morris" , "", ""),
GAME_Pentalath("Pentalath" , "", ""),
GAME_Picaria("Picaria" , "", ""),
GAME_PushingmeXO("Pushing me XO" , "", ""),
GAME_RoundMerels("Round Merels" , "", ""),
GAME_Shisima("Shisima" , "", ""),
GAME_SixMensMorris("Six Men's Morris" , "", ""),
GAME_Spline("Spline" , "", ""),
GAME_Squava("Squava" , "", ""),
GAME_TantFant("Tant Fant" , "", ""),
GAME_ThreeMensMorris("Three Men's Morris" , "", ""),
GAME_TicTacFour("Tic-Tac-Four" , "", ""),
GAME_TicTacMo("Tic-Tac-Mo" , "", ""),
GAME_TicTacToe("Tic-Tac-Toe" , "", ""),
GAME_TwelveMensMorris("Twelve Men's Morris" , "", ""),
GAME_Yavalade("Yavalade" , "", ""),
GAME_Yavalanchor("Yavalanchor" , "", ""),
GAME_Yavalath("Yavalath" , "", ""),
GAME_Kensington("Kensington" , "", ""),
GAME_Ataxx("Ataxx" , "", ""),
GAME_DotsandBoxes("Dots and Boxes" , "", ""),
GAME_Go("Go" , "", ""),
GAME_Lotus("Lotus" , "", ""),
GAME_Reversi("Reversi" , "", ""),
GAME_Alquerque("Alquerque" , "", ""),
GAME_HewakamKeliya("Hewakam Keliya" , "", ""),
GAME_Kharbaga("Kharbaga" , "", ""),
GAME_KotuEllima("Kotu Ellima" , "", ""),
GAME_MogulPutthan("Mogul Putt'han" , "", ""),
GAME_Peralikatuma("Peralikatuma" , "", ""),
GAME_Terhuchu("Terhuchu" , "", ""),
GAME_Tuknanavuhpi("Tuknanavuhpi" , "", ""),
GAME_Zamma("Zamma" , "", ""),
GAME_BrazilianDraughts("Brazilian Draughts" , "", ""),
GAME_CanadianDraughts("Canadian Draughts" , "", ""),
GAME_Dama("Dama" , "", ""),
GAME_EnglishDraughts("English Draughts" , "", ""),
GAME_HexDame("HexDame" , "", ""),
GAME_InternationalDraughts("International Draughts" , "", ""),
GAME_Lasca("Lasca" , "", ""),
GAME_Awithlaknannai("Awithlaknannai" , "", ""),
GAME_Dashguti("Dash-guti" , "", ""),
GAME_EgaraGuti("Egara Guti" , "", ""),
GAME_Felli("Felli" , "", ""),
GAME_Golekuish("Gol-ekuish" , "", ""),
GAME_Konane("Konane" , "", ""),
GAME_LauKataKati("Lau Kata Kati" , "", ""),
GAME_NeiPatKono("Nei-Pat-Kono" , "", ""),
GAME_Pretwa("Pretwa" , "", ""),
GAME_BaokiarabuZanzibar1("Bao ki arabu (Zanzibar 1)" , "", ""),
GAME_BaokiarabuZanzibar2("Bao ki arabu (Zanzibar 2)" , "", ""),
GAME_Hawalis("Hawalis" , "", ""),
GAME_HusDamara("Hus (Damara)" , "", ""),
GAME_Mefuvha("Mefuvha" , "", ""),
GAME_MuvalavalaB("Muvalavala B" , "", ""),
GAME_OwelaBenguela("Owela (Benguela)" , "", ""),
GAME_Akookwe("Ako okwe" , "", ""),
GAME_AwliOnnamOttjin("Aw-li On-nam Ot-tjin" , "", ""),
GAME_Bosh("Bosh" , "", ""),
GAME_Dabuda("Dabuda" , "", ""),
GAME_DasBohnenspiel("Das Bohnenspiel" , "", ""),
GAME_EnGehe("En Gehe" , "", ""),
GAME_EnglishWariStLucia("English Wari (St. Lucia)" , "", ""),
GAME_FrenchWari("French Wari" , "", ""),
GAME_Halusa("Halusa" , "", ""),
GAME_Kalah("Kalah" , "", ""),
GAME_Kara("Kara" , "", ""),
GAME_MangalaTurkey("Mangala (Turkey)" , "", ""),
GAME_Mbangbi("Mbangbi" , "", ""),
GAME_Meusueb("Meusueb" , "", ""),
GAME_Oware("Oware" , "", ""),
GAME_ToguzKumalak("Toguz Kumalak" , "", ""),
GAME_UmelBagara("Um el-Bagara" , "", "");
//-------------------------------------------------------------------------
private String ludName;
private String nativeName;
private String[] aliases;
//--------------------------------------------------------------------------
GameNames(final String ludName, final String nativeName, final String[] aliases)
{
this.ludName = ludName;
this.nativeName = nativeName;
this.aliases = aliases;
}
GameNames(final String ludName, final String nativeName, final String aliases)
{
this.ludName = ludName;
this.nativeName = nativeName;
this.aliases = new String[]{aliases};
}
//-------------------------------------------------------------------------
public String ludName()
{
return ludName;
}
public String nativeName()
{
return nativeName;
}
public String[] aliases()
{
return aliases;
}
}
| 9,504 | 35.140684 | 81 | java |
Ludii | Ludii-master/Common/src/main/ReflectionUtils.java | package main;
import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* Some useful methods for Reflection
*
* @author Dennis Soemers
*/
public class ReflectionUtils
{
//-------------------------------------------------------------------------
/**
* Converts an object which should be an array according to reflection, into
* an array.
*
* @param array
* @return The given object, but as an array of Objects
*/
public static Object[] castArray(final Object array)
{
final Object[] casted = new Object[Array.getLength(array)];
for (int i = 0; i < casted.length; ++i)
{
casted[i] = Array.get(array, i);
}
return casted;
}
/**
* Helper method to collect all declared fields of a class, including
* fields inherited from superclasses.
* @param clazz
* @return All fields of the given class (including inherited fields)
*/
public static List<Field> getAllFields(final Class<?> clazz)
{
final List<Field> fields = new ArrayList<Field>();
fields.addAll(Arrays.asList(clazz.getDeclaredFields()));
if (clazz.getSuperclass() != null)
{
fields.addAll(getAllFields(clazz.getSuperclass()));
}
return fields;
}
//-------------------------------------------------------------------------
}
| 1,345 | 22.206897 | 77 | java |
Ludii | Ludii-master/Common/src/main/Status.java | package main;
import java.io.Serializable;
/**
* Final status of a trial (will be null if game is still in progress).
*
* @author cambolbro
*/
public final class Status implements Serializable
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/**
* Ways in which a trial can end
*
* @author Dennis Soemers
*/
public static enum EndType
{
/** Trial didn't end yet (Status should be null, so this should never happen) */
NoEnd,
/** Don't know how the Trial ended (likely old trial where we didn't record this) */
Unknown,
/** A normal end to a game */
NaturalEnd,
/** Reached artificial move limit */
MoveLimit,
/** Reached artificial turn limit */
TurnLimit
}
//-------------------------------------------------------------------------
/** The winner of the game. */
private final int winner;
/** Way in which a trial ended */
private final EndType endType;
//-------------------------------------------------------------------------
/**
* Constructor. NOTE: assumes trial ended naturally
*
* @param winner
*/
public Status(final int winner)
{
this.winner = winner;
this.endType = EndType.NaturalEnd;
}
/**
* Constructor.
*
* @param winner
* @param endType
*/
public Status(final int winner, final EndType endType)
{
this.winner = winner;
this.endType = endType;
}
/**
* To copy the status.
* @param status The status.
*/
public Status(final Status status)
{
this.winner = status.winner;
this.endType = status.endType;
}
//-------------------------------------------------------------------------
/**
* @return Index of winner, else 0 if none (draw, tie, abandoned).
*/
public int winner()
{
return winner;
}
/**
* @return Type describing how this game ended
*/
public EndType endType()
{
return endType;
}
//-------------------------------------------------------------------------
@Override
public int hashCode()
{
final int prime = 31;
int result = 1;
result = prime * result + winner;
return result;
}
@Override
public boolean equals(final Object other)
{
if (!(other instanceof Status))
{
return false;
}
final Status otherStatus = (Status) other;
return (winner == otherStatus.winner);
}
@Override
public String toString()
{
String str = "";
if (winner == 0)
{
str = "Nobody wins.";
}
else
{
str = "Player " + winner + " wins.";
}
return str;
}
//-------------------------------------------------------------------------
}
| 2,620 | 17.721429 | 86 | java |
Ludii | Ludii-master/Common/src/main/StringRoutines.java | package main;
import java.util.List;
import java.util.regex.Pattern;
/**
* Miscellaneous string manipulation routines.
*
* @author cambolbro and Eric.Piette
*/
public final class StringRoutines
{
//-------------------------------------------------------------------------
public final static char[][] brackets =
{
{ '(', ')' },
{ '{', '}' },
{ '[', ']' },
{ '<', '>' },
};
public static final int Opening = 0;
public static final int Closing = 1;
//-------------------------------------------------------------------------
public static boolean isOpenBracket(final char ch)
{
for (int n = 0; n < brackets.length; n++)
if (ch == brackets[n][0])
return true;
return false;
}
public static boolean isCloseBracket(final char ch)
{
for (int n = 0; n < brackets.length; n++)
if (ch == brackets[n][1])
return true;
return false;
}
public static boolean isBracket(final char ch)
{
return isOpenBracket(ch) || isCloseBracket(ch);
}
public static int numOpenBrackets(final String str)
{
int num = 0;
for (int c = 0; c < str.length(); c++)
if (isOpenBracket(str.charAt(c)))
num++;
return num;
}
public static int numCloseBrackets(final String str)
{
int num = 0;
for (int c = 0; c < str.length(); c++)
if (isCloseBracket(str.charAt(c)))
num++;
return num;
}
public static boolean balancedBrackets(final String str)
{
return numOpenBrackets(str) == numCloseBrackets(str);
}
public static int numChar(final String str, final char ch)
{
int num = 0;
for (int c = 0; c < str.length(); c++)
if (str.charAt(c) == ch)
num++;
return num;
}
public static int bracketIndex(final char ch, final int openOrClosed)
{
for (int n = 0; n < brackets.length; n++)
if (brackets[n][openOrClosed] == ch)
return n;
return -1;
}
/**
* @param str
* @param from
* @return Location of matching closing bracket (including nesting), else -1 if none.
*/
public static int matchingBracketAt(final String str, final int from)
{
return matchingBracketAt(str, from, true);
}
/**
* @param str
* @param from
* @param doNesting
* @return Location of matching closing bracket, else -1 if none.
*/
public static int matchingBracketAt(final String str, final int from, final boolean doNesting)
{
// Check is actually opening bracket
int c = from;
final char ch = str.charAt(c);
final int bid = bracketIndex(ch, Opening);
if (bid == -1)
{
System.out.println("** Specified char '" + ch + "' is not an open bracket.");
return -1;
}
// Check for matching closing bracket
int bracketDepth = 0;
boolean inString = false;
while (c < str.length())
{
final char chB = str.charAt(c);
if (chB == '"')
inString = !inString;
if (!inString)
{
final char chA = (c == 0) ? '?' : str.charAt(c - 1);
if (chB == brackets[bid][Opening])
{
if (chA != '(' || chB != '<') // check is not a (< ...) or (<= ...) ludeme
bracketDepth++;
}
else if (chB == brackets[bid][Closing])
{
if (chA != '(' || chB != '>') // check is not a (> ...) or (>= ...) ludeme
{
if (!doNesting)
break; // stop on first matching closing bracket, e.g. option "<<>"
bracketDepth--;
}
}
}
if (bracketDepth == 0)
break; // found bracket that closes opening bracket
c++;
}
if (c >= str.length())
return -1; // no matching closing bracket found
//throw new IllegalArgumentException("No matching closing bracket " + brackets[bid][Closing] + " found.");
return c;
}
public static int matchingQuoteAt(final String str, final int from)
{
int c = from;
final char ch = str.charAt(c);
if (ch != '"')
throw new IllegalArgumentException("String expected but no opening \" found.");
// System.out.println("\nString is:");
c++;
while (c < str.length())
{
final char chC = str.charAt(c);
// System.out.println("chC=" + chC);
switch (chC)
{
case '\\':
//System.out.println("Slash!");
if (c < str.length() - 1 && str.charAt(c+1) == '"')
c++; // skip embedded "\""
break;
//case '\':
// c++;
// break;
case '"':
return c;
default:
// Do nothing
}
c++;
}
//throw new IllegalArgumentException("No closing \" found when parsing String.");
// Closing quote not found, but this may be valid,
// e.g. parsing comments before rulesets expanded.
return -1;
}
//-------------------------------------------------------------------------
public static String toDromedaryCase(final String className)
{
return className.substring(0, 1).toLowerCase() + className.substring(1);
}
public static String highlightText(final String fullText, final String highlight, final String tag, final String colour)
{
final String replacement = "<"+tag+" color="+colour+">"+highlight+"</"+tag+">";
System.out.println(highlight + " --> " + replacement);
return fullText.replace (highlight, replacement);
}
public static String escapeText(final String text)
{
return text
.replace("&", "&")
.replace("'", "'")
.replace("\"", """)
.replace("<", "<")
.replace(">", ">")
.replace("\t", " ")
.replace(" ", " ")
.replace("\n", "<br/>");
}
/**
* @param gameName
* @return A "clean" version of the given game name, with no spaces, brackets, etc.
* Should be safe for use in filepaths (for outputs, experiments, analysis, etc.)
*/
public static String cleanGameName(final String gameName)
{
return gameName
.trim()
.replaceAll(Pattern.quote(" "), "_")
.replaceAll(Pattern.quote(".lud"), "")
.replaceAll(Pattern.quote("'"), "")
.replaceAll(Pattern.quote("("), "")
.replaceAll(Pattern.quote(")"), "");
}
/**
* @param rulesetName
* @return A "clean" version of the given ruleset name
*/
public static String cleanRulesetName(final String rulesetName)
{
return rulesetName
.trim()
.replaceAll(Pattern.quote(" "), "_")
.replaceAll(Pattern.quote("("), "")
.replaceAll(Pattern.quote(")"), "")
.replaceAll(Pattern.quote(","), "")
.replaceAll(Pattern.quote("\""), "")
.replaceAll(Pattern.quote("'"), "")
.replaceAll(Pattern.quote("["), "")
.replaceAll(Pattern.quote("]"), "");
}
/**
* @param str
* @return A copy of the given string, with cleaned up whitespace.
* This means that we replace newlines by spaces, trim whitespace from
* the beginning and end, and replace any sequence of more than one
* space (including tabs) by a single space.
*/
public static String cleanWhitespace(final String str)
{
return str.trim().replaceAll("\\s+", " ");
}
//-------------------------------------------------------------------------
/**
* From: https://stackoverflow.com/questions/5439529/determine-if-a-string-is-an-integer-in-java
* Rather hacky but guarantees that parseInt() will return an integer value.
* @param str
* @return Whether str describes an integer.
*/
public static boolean isInteger(final String str)
{
try
{
Integer.parseInt(str);
}
catch (@SuppressWarnings("unused") final Exception e)
{
return false;
}
return true;
}
// **
// ** isFloat() and isFloat() may not be safe. They hang the Token.format() using ZhangShasha.
// **
/**
* From: https://stackoverflow.com/questions/5439529/determine-if-a-string-is-an-integer-in-java
* Rather hacky but guarantees that parseDouble() will return a double value.
* @param str
* @return Whether str describes a double.
*/
public static boolean isFloat(final String str)
{
// String strF = "123";
// float f = Float.parseFloat(strF);
// System.out.println("f=" + f + " (" + StringRoutines.isFloat(strF) + ")");
// if (str.indexOf('.') < 0)
// return false; // hack: require floats to contain decimal point
try
{
Float.parseFloat(str);
}
catch (@SuppressWarnings("unused") final Exception e)
{
try
{
Integer.parseInt(str);
}
catch (@SuppressWarnings("unused") final Exception e2)
{
return false;
}
//return false;
}
return true;
}
/**
* From: https://stackoverflow.com/questions/5439529/determine-if-a-string-is-an-integer-in-java
* Rather hacky but guarantees that parseDouble() will return a double value.
* @param str
* @return Whether str describes a double.
*/
public static boolean isDouble(final String str)
{
try
{
Double.parseDouble(str);
}
catch (@SuppressWarnings("unused") final Exception e)
{
return false;
}
return true;
}
// public static boolean isNumber(final String str)
// {
// if (str == "")
// return false;
// return isNumber(str) || isFloat(str) || isDouble(str);
// }
//-------------------------------------------------------------------------
public static boolean isDigit(final char ch)
{
return ch >= '0' && ch <= '9';
}
public static boolean isLetter(final char ch)
{
return ch >= 'a' && ch <= 'z' || ch >= 'A' && ch <= 'Z';
}
public static boolean isNumeric(final char ch)
{
return ch >= '0' && ch <= '9' || ch == '.' || ch == 'e' || ch == '-'; // // || ch == '+'
}
//-------------------------------------------------------------------------
/**
* @param str
* @return String with first character converted to lowercase.
*/
public static String lowerCaseInitial(final String str)
{
if (str.length() < 1)
return "";
return Character.toLowerCase(str.charAt(0)) + str.substring(1);
}
/**
* @param str
* @return String with first character converted to uppercase.
*/
public static String upperCaseInitial(final String str)
{
if (str.length() < 1)
return "";
return Character.toUpperCase(str.charAt(0)) + str.substring(1);
}
//-------------------------------------------------------------------------
/**
* @param strings
* @return New array of strings, where each of the given strings has its
* first character converted to uppercase.
*/
public static String[] upperCaseInitialEach(final String... strings)
{
final String[] ret = new String[strings.length];
for (int i = 0; i < ret.length; ++i)
ret[i] = upperCaseInitial(strings[i]);
return ret;
}
//-------------------------------------------------------------------------
public static boolean isToken(final String str)
{
final int lpos = str.indexOf(':');
if (lpos == -1)
return false;
for (int c = 0; c < lpos; c++)
if (!isTokenChar(str.charAt(c)))
return false;
return true;
}
public static boolean isName(final String str)
{
final int lpos = str.indexOf(':');
if (lpos == -1)
return false;
for (int c = 0; c < lpos; c++)
if (!isNameChar(str.charAt(c)))
return false;
return true;
}
/**
* @return Whether the string is a coordinate, e.g. "A1", "ZZ123", "37"
*/
public static boolean isCoordinate(final String str)
{
if (str == null)
return false;
int c = str.length() - 1;
if (!isDigit(str.charAt(c)))
return false; // last character should always be a digit
while (c >= 0 && isDigit(str.charAt(c)))
c--;
if (c < 0)
return true; // string is all digits, e.g. custom board with no axes
if (c > 2)
return false; // coordinate should have no more two letters
if (c > 1 && str.length() > 1 && str.charAt(0) != str.charAt(1))
return false; // if first two chars are a letter, they should be the same, e.g. "AA1".
while (c >= 0 && isLetter(str.charAt(c)))
c--;
return c < 0; // whether string is all letters followed by all digits
}
//-------------------------------------------------------------------------
/**
* ASCII chart: https://bluesock.org/~willg/dev/ascii.html
* @return Whether character is a visible ASCII character.
*/
public static boolean isVisibleChar(final char ch)
{
// <Space> is 32
return ch >= 32 && ch < 127;
}
/**
* @return Whether character can occur in a named parameter.
*/
public static boolean isNameChar(final char ch)
{
return
ch >= 'a' && ch <= 'z'
||
ch >= 'A' && ch <= 'Z'
||
ch >= '0' && ch <= '9'
||
ch == '_'
||
ch == '-'
;
}
// **
// ** NOTE: Any tokens in aliases, such as math symbols, must be listed here!
// **
public static boolean isTokenChar(final char ch)
{
return
ch >= 'a' && ch <= 'z'
||
ch >= 'A' && ch <= 'Z'
||
ch >= '0' && ch <= '9'
||
ch == '_'
||
ch == '"' // string
||
ch == '-' // negative number
||
ch == '.' // floating point number
||
ch == '+' // math notation in alias
||
ch == '-' // math notation in alias
||
ch == '*' // math notation in alias
||
ch == '/' // math notation in alias
||
ch == '%' // math notation in alias
||
ch == '=' // math notation in alias
||
ch == '!' // math notation in alias
||
ch == 'v' // math notation in alias
||
ch == '^' // math notation in alias
||
ch == '~' // math notation in alias
||
ch == '<' // math notation in alias
||
ch == '>' // math notation in alias
||
ch == '&' // math notation in alias
||
ch == '|' // math notation in alias
||
ch == '#' // hash for hex colour codes #123456
;
}
//-------------------------------------------------------------------------
/**
* @return First token in string, else empty string.
*/
public static String getFirstToken(final String str)
{
if (str == "")
return "";
final int len = str.length();
int c = 0;
while (c < len && !isTokenChar(str.charAt(c)))
c++;
if (c >= len)
return ""; // no token chars
int cc = c + 1;
while (cc < len && isTokenChar(str.charAt(cc)))
cc++;
if (cc >= len)
cc = len; // - 1;
return str.substring(c, cc);
}
//-------------------------------------------------------------------------
/**
* @return Number at end of string, else -1 if none.
* This will typically be a player index e.g. "Ball1".
*/
public static int numberAtEnd(final String strIn)
{
final String str = strIn.trim();
boolean found = false;
int index = 0;
int tens = 1;
for (int n = str.length()-1; n >= 0; n--)
{
final char ch = str.charAt(n);
if (!StringRoutines.isDigit(ch))
break;
found = true;
index += (ch - '0') * tens;
tens *= 10;
}
return found ? index : -1;
}
//-------------------------------------------------------------------------
/**
* Converts given float to a String approximating the float as a fraction
* of two integers
*
* Based on: https://stackoverflow.com/a/5968920/6735980
*
* @param fIn
* @param factor Maximum number we try dividing by
* @return String representation of fraction
*/
public static String floatToFraction(final float fIn, final int factor)
{
final StringBuilder sb = new StringBuilder();
float f = fIn;
if (f < 0.f)
{
sb.append('-');
f = -f;
}
final long l = (long) f;
if (l != 0)
sb.append(l);
f -= l;
float error = Math.abs(f);
int bestDenominator = 1;
for (int i = 2; i <= factor; ++i)
{
final float error2 = Math.abs(f - (float) Math.round(f * i) / i);
if (error2 < error)
{
error = error2;
bestDenominator = i;
}
}
if (bestDenominator > 1)
sb.append(Math.round(f * bestDenominator)).append('/') .append(bestDenominator);
else
sb.append(Math.round(f));
return sb.toString();
}
/**
* @param joinStr
* @param strings
* @return All the given strings merged into a single string, with "joinStr"
* used to separate the parts.
*/
public static String join(final String joinStr, final List<String> strings)
{
return join(joinStr, strings.toArray(new String[strings.size()]));
}
/**
* @param joinStr
* @param strings
* @return All the given strings merged into a single string, with "joinStr"
* used to separate the parts.
*/
public static String join(final String joinStr, final String... strings)
{
final StringBuilder sb = new StringBuilder();
for (int i = 0; i < strings.length; ++i)
{
if (i > 0)
sb.append(joinStr);
sb.append(strings[i]);
}
return sb.toString();
}
/**
* @param joinStr
* @param objects
* @return Strings of all the given objects merged into a single string, with "joinStr"
* used to separate the parts.
*/
public static String join(final String joinStr, final Object... objects)
{
final StringBuilder sb = new StringBuilder();
for (int i = 0; i < objects.length; ++i)
{
if (i > 0)
sb.append(joinStr);
sb.append(objects[i].toString());
}
return sb.toString();
}
/**
* @param str
* @return The given string, wrapped in a pair of quotes: "str"
*/
public static String quote(final String str)
{
return "\"" + str + "\"";
}
//-------------------------------------------------------------------------
/**
* @return Whitespace indent of suitable length.
*/
public static String indent(final int tabSize, final int tabCount)
{
final StringBuilder sb = new StringBuilder();
final int numSpaces = tabSize * tabCount;
for (int s = 0; s < numSpaces; s++)
sb.append(" ");
return sb.toString();
}
//-------------------------------------------------------------------------
/**
* Removes the trailing numbers from a String.
* @param string
*/
public static String removeTrailingNumbers(final String string)
{
String newString = string;
if (!newString.chars().allMatch(Character::isDigit))
{
int valueToRemove = 0;
for (int i = newString.length() - 1; i >= 0; i--)
{
if (newString.charAt(i) >= '0' && newString.charAt(i) <= '9')
valueToRemove++;
else
break;
}
newString = newString.substring(0, newString.length() - valueToRemove);
}
return newString;
}
//-------------------------------------------------------------------------
/**
* Gets the trailing numbers from a String.
* @param string
*/
public static String getTrailingNumbers(final String string)
{
String newString = string;
if (!newString.chars().allMatch(Character::isDigit))
{
int valueToRemove = 0;
for (int i = newString.length() - 1; i >= 0; i--)
{
if (newString.charAt(i) >= '0' && newString.charAt(i) <= '9')
valueToRemove++;
else
break;
}
newString = newString.substring(newString.length() - valueToRemove);
}
return newString;
}
//-------------------------------------------------------------------------
/**
* @return Unique name of this game, which will be the first String
* argument in (game "Game Name" ...).
*/
public static String gameName(final String str)
{
int c = str.indexOf("(game ");
if (c < 0)
{
// Don't want to throw exception as might be (match ...)
return null;
//throw new RuntimeException("gameName(): Game object not found.");
}
c += 5;
while (c < str.length() && str.charAt(c) != '"')
c++;
if (c >= str.length())
throw new RuntimeException("gameName(): Game name not found.");
final int cc = StringRoutines.matchingQuoteAt(str, c);
if (cc < 0 || cc >= str.length())
throw new RuntimeException("gameName(): Game name not found.");
return str.substring(c+1, cc);
}
//-------------------------------------------------------------------------
public static String getPlural(final String string)
{
if
(
string.endsWith("s")
||
string.endsWith("sh")
||
string.endsWith("ch")
||
string.endsWith("x")
||
string.endsWith("z")
)
{
return "es";
}
return "s";
}
//-------------------------------------------------------------------------
/**
* @param originalDesc Description of a ruleset after expansion.
* @return Formatted description on a single line.
*/
public static String formatOneLineDesc(final String originalDesc)
{
final StringBuffer formattedDesc = new StringBuffer("");
// Remove the spaces at the beginning of the description.
String desc = originalDesc;
for(int i = 0; i < originalDesc.length(); i++)
{
final char c = originalDesc.charAt(i);
if(!Character.isSpaceChar(c))
{
desc = originalDesc.substring(i);
break;
}
}
for(int i = 0; i < desc.length(); i++)
{
final char c = desc.charAt(i);
if(Character.isLetterOrDigit(c) || c == '(' || c == ')' || c == '{'
|| c == '}' || c == '"' || c == '.' || c == ',' || c == ':'
|| c == '=' || c == '<' || c == '>' || c == '+' || c == '-'
|| c == '/' || c == '^' || c == '%' || c == '*' || c == '['
|| c == ']' || c == '#' || c == '?' || c == '|' || c == '!'
|| Character.isSpaceChar(c)
)
{
if(i != 0 && Character.isSpaceChar(c))
{
final char lastChar = formattedDesc.toString().charAt(formattedDesc.length()-1);
if(!Character.isSpaceChar(lastChar))
{
formattedDesc.append(c);
}
}
else
{
formattedDesc.append(c);
if(c == '{') // add a space after the open curly bracket to not be next to an open parenthesis.
formattedDesc.append(' ');
}
}
}
return formattedDesc.toString();
}
/**
* @param desc The description of a ruleset on a single line.
* @return The description on multiple lines.
*/
public static String unformatOneLineDesc(final String desc)
{
final StringBuffer formattedDesc = new StringBuffer("");
formattedDesc.append('(');
boolean insideQuote = false;
for(int i = 1; i < desc.length(); i++) // Start at 1 to not break line at the first parenthesis.
{
final char c = desc.charAt(i);
if(c == '"')
insideQuote = !insideQuote;
if(!insideQuote)
{
if(c == '(' && desc.charAt(desc.length()-1) != ':')
formattedDesc.append("\n");
formattedDesc.append(c);
if(c == ')' || c == '}')
formattedDesc.append("\n");
}
else
formattedDesc.append(c);
}
return formattedDesc.toString();
}
}
| 22,183 | 22.982703 | 121 | java |
Ludii | Ludii-master/Common/src/main/UnixPrintWriter.java | package main;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
/**
* Subclass for PrintWriter that will always print Unix line endings.
*
* See: https://stackoverflow.com/a/14749004/6735980
*
* @author Dennis Soemers
*/
public class UnixPrintWriter extends PrintWriter
{
/**
* Constructor
* @param file
* @throws FileNotFoundException
*/
public UnixPrintWriter(final File file) throws FileNotFoundException
{
super(file);
}
/**
* Constructor
* @param file
* @param csn
* @throws FileNotFoundException
* @throws UnsupportedEncodingException
*/
public UnixPrintWriter(final File file, final String csn) throws FileNotFoundException, UnsupportedEncodingException
{
super(file, csn);
}
@Override
public void println()
{
write('\n');
}
}
| 869 | 17.510638 | 117 | java |
Ludii | Ludii-master/Common/src/main/Utilities.java | package main;
/**
* A home for miscellaneous useful routines. Like stackTrace().
*
* @author cambolbro
*/
public final class Utilities
{
//-------------------------------------------------------------------------
/**
* Show a stack trace.
*/
public static void stackTrace()
{
final StackTraceElement[] ste = Thread.currentThread().getStackTrace();
System.out.println("======================");
for (int n = 0; n < ste.length; n++)
System.out.println(ste[n]);
System.out.println("======================");
}
//-------------------------------------------------------------------------
/**
* Get a stack trace.
*/
public static String stackTraceString()
{
String stackTrace = "";
final StackTraceElement[] ste = Thread.currentThread().getStackTrace();
stackTrace += "======================";
for (int n = 0; n < ste.length; n++)
stackTrace += ste[n];
stackTrace += "======================";
return stackTrace;
}
//-------------------------------------------------------------------------
}
| 1,046 | 22.795455 | 76 | java |
Ludii | Ludii-master/Common/src/main/collections/ArrayUtils.java | package main.collections;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Locale;
/**
* Some utility methods for arrays
*
* @author Dennis Soemers
*/
public class ArrayUtils
{
//-------------------------------------------------------------------------
/**
* Constructor
*/
private ArrayUtils()
{
// Should not be used
}
//-------------------------------------------------------------------------
/**
* @param arr
* @param val
* @return True if given array contains given value, false otherwise
*/
public static boolean contains(final boolean[] arr, final boolean val)
{
for (int i = 0; i < arr.length; ++i)
{
if (arr[i] == val)
return true;
}
return false;
}
/**
* @param arr
* @param val
* @return True if given array contains given value, false otherwise
*/
public static boolean contains(final int[] arr, final int val)
{
for (int i = 0; i < arr.length; ++i)
{
if (arr[i] == val)
return true;
}
return false;
}
/**
* @param arr
* @param val
* @return True if given array contains given value, false otherwise
*/
public static boolean contains(final double[] arr, final double val)
{
for (int i = 0; i < arr.length; ++i)
{
if (arr[i] == val)
return true;
}
return false;
}
/**
* @param arr
* @param val
* @return True if given array contains given object, false otherwise
*/
public static boolean contains(final Object[] arr, final Object val)
{
for (int i = 0; i < arr.length; ++i)
{
if (arr[i] == null && val == null)
return true;
else if (arr[i] != null && arr[i].equals(val))
return true;
}
return false;
}
/**
* @param val
* @param arr
* @return (First) index of given val in given array. -1 if not found
*/
public static int indexOf(final int val, final int[] arr)
{
for (int i = 0; i < arr.length; ++i)
{
if (arr[i] == val)
return i;
}
return -1;
}
/**
* @param val
* @param arr
* @return (First) index of given val in given array. -1 if not found
*/
public static int indexOf(final Object val, final Object[] arr)
{
for (int i = 0; i < arr.length; ++i)
{
if (arr[i].equals(val))
return i;
}
return -1;
}
/**
* @param arr
* @return Maximum value in given array
*/
public static int max(final int[] arr)
{
int max = Integer.MIN_VALUE;
for (final int val : arr)
{
if (val > max)
max = val;
}
return max;
}
/**
* @param arr
* @return Maximum value in given array
*/
public static float max(final float[] arr)
{
float max = Float.NEGATIVE_INFINITY;
for (final float val : arr)
{
if (val > max)
max = val;
}
return max;
}
/**
* @param arr
* @return Minimum value in given array
*/
public static float min(final float[] arr)
{
float min = Float.POSITIVE_INFINITY;
for (final float val : arr)
{
if (val < min)
min = val;
}
return min;
}
/**
* @param arr
* @param val
* @return Number of occurrences of given value in given array
*/
public static int numOccurrences(final double[] arr, final double val)
{
int num = 0;
for (int i = 0; i < arr.length; ++i)
{
if (arr[i] == val)
++num;
}
return num;
}
/**
* Replaces all occurrences of oldVal with newVal in the given array
* @param arr
* @param oldVal
* @param newVal
*/
public static void replaceAll(final int[] arr, final int oldVal, final int newVal)
{
for (int i = 0; i < arr.length; ++i)
{
if (arr[i] == oldVal)
arr[i] = newVal;
}
}
//-------------------------------------------------------------------------
/**
* Note: probably kind of slow. Not intended for use in
* performance-sensitive situations.
*
* @param matrix
* @param numDecimals
* @return A nicely-formatted String describing the given matrix
*/
public static String matrixToString(final float[][] matrix, final int numDecimals)
{
int maxStrLength = 0;
for (final float[] arr : matrix)
{
for (final float element : arr)
{
final int length = String.valueOf((int) element).length();
if (length > maxStrLength)
maxStrLength = length;
}
}
final StringBuilder sb = new StringBuilder();
int digitsFormat = 1;
for (int i = 1; i < maxStrLength; ++i)
{
digitsFormat *= 10;
}
for (int i = 0; i < matrix.length; ++i)
{
for (int j = 0; j < matrix[i].length; ++j)
{
sb.append(String.format(Locale.ROOT, "%" + digitsFormat + "." + numDecimals + "f", matrix[i][j]));
if (j < matrix[i].length - 1)
sb.append(",");
}
sb.append("\n");
}
return sb.toString();
}
//-------------------------------------------------------------------------
/**
* @param numEntries
* @param comp
* @return A list of indices (ranging from 0 up to numEntries (exclusive), sorted
* using the given comparator.
*/
public static List<Integer> sortedIndices(final int numEntries, final Comparator<Integer> comp)
{
final List<Integer> list = new ArrayList<Integer>(numEntries);
for (int i = 0; i < numEntries; ++i)
{
list.add(Integer.valueOf(i));
}
list.sort(comp);
return list;
}
//-------------------------------------------------------------------------
}
| 5,336 | 18.060714 | 102 | java |
Ludii | Ludii-master/Common/src/main/collections/ChunkSet.java | package main.collections;
/*
* Copyright 1995-2007 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.ObjectStreamField;
import java.lang.reflect.Field;
import java.util.Arrays;
import gnu.trove.list.array.TIntArrayList;
import main.math.BitTwiddling;
//-----------------------------------------------------------------------------
/**
* This class implements a vector of bits that grows as needed. Each component
* of the bit set has a {@code boolean} value. The bits of a {@code BitSet} are
* indexed by nonnegative integers. Individual indexed bits can be examined,
* set, or cleared. One {@code BitSet} may be used to modify the contents of
* another {@code BitSet} through logical AND, logical inclusive OR, and logical
* exclusive OR operations.
*
* <p>
* By default, all bits in the set initially have the value {@code false}.
*
* <p>
* Every bit set has a current size, which is the number of bits of space
* currently in use by the bit set. Note that the size is related to the
* implementation of a bit set, so it may change with implementation. The length
* of a bit set relates to logical length of a bit set and is defined
* independently of implementation.
*
* <p>
* Unless otherwise noted, passing a null parameter to any of the methods in a
* {@code BitSet} will result in a {@code NullPointerException}.
*
* <p>
* A {@code BitSet} is not safe for multithreaded use without external
* synchronization.
*
* @author Arthur van Hoff
* @author Michael McCloskey
* @author Martin Buchholz
* @since JDK1.0
*/
public final class ChunkSet implements Cloneable, java.io.Serializable
{
/*
* BitSets are packed into arrays of "words." Currently a word is a long, which
* consists of 64 bits, requiring 6 address bits. The choice of word size is
* determined purely by performance concerns.
*/
/** */
private final static int ADDRESS_BITS_PER_WORD = 6;
/** */
private final static int BITS_PER_WORD = 1 << ADDRESS_BITS_PER_WORD;
/**
* The internal field corresponding to the serialField "bits".
*/
private long[] words;
/**
* The number of words in the logical size of this BitSet.
*/
private transient int wordsInUse = 0;
/**
* Whether the size of "words" is user-specified. If so, we assume the user
* knows what he's doing and try harder to preserve it.
*/
private transient boolean sizeIsSticky = false;
/**
* Modified serialVersionUID from BitSet, (de)serialization processes have been customized,
* not compatible with JDKs standard BitSet implementation
*/
private static final long serialVersionUID = 1L;
/** */
// private final static int BIT_INDEX_MASK = BITS_PER_WORD - 1;
/** Used to shift left or right for a partial word mask */
private static final long WORD_MASK = 0xffffffffffffffffL;
/** 0x1010101010101010101010101010101010101010101010101010101010101010 */
final static long MASK_NOT_1 = 0xaaaaaaaaaaaaaaaaL;
/** 0x1100110011001100110011001100110011001100110011001100110011001100 */
final static long MASK_NOT_2 = 0xccccccccccccccccL;
/** 0x1111000011110000111100001111000011110000111100001111000011110000 */
final static long MASK_NOT_4 = 0xf0f0f0f0f0f0f0f0L;
/** 0x1111111100000000111111110000000011111111000000001111111100000000 */
final static long MASK_NOT_8 = 0xff00ff00ff00ff00L;
/** 0x1111111111111111000000000000000011111111111111110000000000000000 */
final static long MASK_NOT_16 = 0xffff0000ffff0000L;
/** 0x1111111111111111111111111111111100000000000000000000000000000000 */
final static long MASK_NOT_32 = 0xffffffff00000000L;
/**
* Number of bits per chunk. Must be a power of 2 up to 32: 1, 2, 4, 8, 16, 32.
*/
protected final int chunkSize;
/** Mask for this chunk size. */
protected final long chunkMask; // = (0x1L << chunkSize) - 1L;
final static long[] bitNMasks = new long[64];
{
for (int n = 0; n < 64; n++)
{
bitNMasks[n] = (0x1L << n) - 0x1L;
//System.out.println(n + ": " + bitNMasks[n]);
}
}
//-------------------------------------------------------------------------
/**
* Creates a new bit set. All bits are initially {@code false}.
*/
public ChunkSet()
{
initWords(BITS_PER_WORD);
sizeIsSticky = false;
this.chunkSize = 1;
this.chunkMask = (0x1L << chunkSize) - 1;
}
/**
* Creates a bit set whose initial size is large enough to explicitly represent
* bits with indices in the range {@code 0} through {@code nbits-1}. All bits
* are initially {@code false}.
*
* @param chunkSize
* @param numChunks
* @throws NegativeArraySizeException if the specified initial size is negative
*/
public ChunkSet(final int chunkSize, final int numChunks)
{
// **
// ** Do not store numChunks as a final, as board may grow.
// **
this.chunkSize = chunkSize;
this.chunkMask = (0x1L << chunkSize) - 1;
assert (BitTwiddling.isPowerOf2(chunkSize));
// if (!BitTwiddling.isPowerOf2(chunkSize))
// {
// System.out.println("** BitSetS: chunkSize " + chunkSize + " is not a power of 2.");
// Utilities.stackTrace();
// }
final int nbits = chunkSize * numChunks;
// System.out.print("BitSetS(" + chunkSize + "," + numChunks + "): nbits=" + nbits + ".");
// nbits can't be negative; size 0 is OK
assert (nbits >= 0);
// if (nbits < 0)
// throw new NegativeArraySizeException("nbits < 0: " + nbits);
initWords(nbits);
sizeIsSticky = true;
// System.out.println(", size=" + size() + ", length=" + length() + ".");
}
//-------------------------------------------------------------------------
/**
* @serialField bits long[]
*
* The bits in this BitSet. The ith bit is stored in bits[i/64] at
* bit position i % 64 (where bit position 0 refers to the least
* significant bit and 63 refers to the most significant bit).
*/
private static final ObjectStreamField[] serialPersistentFields =
{ new ObjectStreamField("bits", long[].class),};
/**
* Given a bit index, return word index containing it.
*
* @param bitIndex
* @return Word index containing bit.
*/
private static int wordIndex(int bitIndex)
{
return bitIndex >> ADDRESS_BITS_PER_WORD;
}
/**
* Every public method must preserve these invariants.
*/
private void checkInvariants()
{
assert (wordsInUse == 0 || words[wordsInUse - 1] != 0);
assert (wordsInUse >= 0 && wordsInUse <= words.length);
assert (wordsInUse == words.length || words[wordsInUse] == 0);
}
/**
* Sets the field wordsInUse to the logical size in words of the bit set.
* WARNING:This method assumes that the number of words actually in use is less
* than or equal to the current value of wordsInUse!
*/
private void recalculateWordsInUse()
{
// Traverse the bitset until a used word is found
int i;
for (i = wordsInUse - 1; i >= 0; i--)
if (words[i] != 0)
break;
wordsInUse = i + 1; // The new logical size
}
/**
* @param nbits
*/
private void initWords(int nbits)
{
words = new long[wordIndex(nbits - 1) + 1];
}
// /**
// * Creates a bit set using words as the internal representation.
// * The last word (if there is one) must be non-zero.
// * @param words
// */
// private BitSetS(long[] words)
// {
// this.words = words;
// this.wordsInUse = words.length;
// checkInvariants();
// }
/**
* Ensures that the BitSet can hold enough words.
*
* @param wordsRequired the minimum acceptable number of words.
*/
private void ensureCapacity(int wordsRequired)
{
if (words.length < wordsRequired)
{
// Allocate larger of doubled size or required size
final int request = Math.max(2 * words.length, wordsRequired);
words = Arrays.copyOf(words, request);
sizeIsSticky = false;
}
}
/**
* Ensures that the BitSet can accommodate a given wordIndex, temporarily
* violating the invariants. The caller must restore the invariants before
* returning to the user, possibly using recalculateWordsInUse().
*
* @param wordIndex the index to be accommodated.
*/
private void expandTo(int wordIndex)
{
final int wordsRequired = wordIndex + 1;
if (wordsInUse < wordsRequired)
{
ensureCapacity(wordsRequired);
wordsInUse = wordsRequired;
}
}
/**
* Checks that fromIndex ... toIndex is a valid range of bit indices.
*
* @param fromIndex
* @param toIndex
*/
private static void checkRange(int fromIndex, int toIndex)
{
if (fromIndex < 0)
throw new IndexOutOfBoundsException("fromIndex < 0: " + fromIndex);
if (toIndex < 0)
throw new IndexOutOfBoundsException("toIndex < 0: " + toIndex);
if (fromIndex > toIndex)
throw new IndexOutOfBoundsException("fromIndex: " + fromIndex + " > toIndex: " + toIndex);
}
/**
* Sets the bit at the specified index to the complement of its current value.
*
* @param bitIndex the index of the bit to flip
* @throws IndexOutOfBoundsException if the specified index is negative
* @since 1.4
*/
public void flip(int bitIndex)
{
if (bitIndex < 0)
throw new IndexOutOfBoundsException("bitIndex < 0: " + bitIndex);
final int wordIndex = wordIndex(bitIndex);
expandTo(wordIndex);
words[wordIndex] ^= (1L << bitIndex);
recalculateWordsInUse();
checkInvariants();
}
/**
* Sets each bit from the specified {@code fromIndex} (inclusive) to the
* specified {@code toIndex} (exclusive) to the complement of its current value.
*
* @param fromIndex index of the first bit to flip
* @param toIndex index after the last bit to flip
* @throws IndexOutOfBoundsException if {@code fromIndex} is negative, or
* {@code toIndex} is negative, or
* {@code fromIndex} is larger than
* {@code toIndex}
* @since 1.4
*/
public void flip(int fromIndex, int toIndex)
{
checkRange(fromIndex, toIndex);
if (fromIndex == toIndex)
return;
final int startWordIndex = wordIndex(fromIndex);
final int endWordIndex = wordIndex(toIndex - 1);
expandTo(endWordIndex);
final long firstWordMask = WORD_MASK << fromIndex;
final long lastWordMask = WORD_MASK >>> -toIndex;
if (startWordIndex == endWordIndex)
{
// Case 1: One word
words[startWordIndex] ^= (firstWordMask & lastWordMask);
} else
{
// Case 2: Multiple words
// Handle first word
words[startWordIndex] ^= firstWordMask;
// Handle intermediate words, if any
for (int i = startWordIndex + 1; i < endWordIndex; i++)
words[i] ^= WORD_MASK;
// Handle last word
words[endWordIndex] ^= lastWordMask;
}
recalculateWordsInUse();
checkInvariants();
}
/**
* Sets the bit at the specified index to {@code true}.
*
* @param bitIndex a bit index
* @throws IndexOutOfBoundsException if the specified index is negative
* @since JDK1.0
*/
public void set(int bitIndex)
{
if (bitIndex < 0)
throw new IndexOutOfBoundsException("bitIndex < 0: " + bitIndex);
final int wordIndex = wordIndex(bitIndex);
expandTo(wordIndex);
words[wordIndex] |= (1L << bitIndex); // Restores invariants
checkInvariants();
}
/**
* Sets the bit at the specified index to the specified value.
*
* @param bitIndex a bit index
* @param value a boolean value to set
* @throws IndexOutOfBoundsException if the specified index is negative
* @since 1.4
*/
public void set(int bitIndex, boolean value)
{
if (value)
set(bitIndex);
else
clear(bitIndex);
}
/**
* Sets the bits from the specified {@code fromIndex} (inclusive) to the
* specified {@code toIndex} (exclusive) to {@code true}.
*
* @param fromIndex index of the first bit to be set
* @param toIndex index after the last bit to be set
* @throws IndexOutOfBoundsException if {@code fromIndex} is negative, or
* {@code toIndex} is negative, or
* {@code fromIndex} is larger than
* {@code toIndex}
* @since 1.4
*/
public void set(int fromIndex, int toIndex)
{
checkRange(fromIndex, toIndex);
if (fromIndex == toIndex)
return;
// Increase capacity if necessary
final int startWordIndex = wordIndex(fromIndex);
final int endWordIndex = wordIndex(toIndex - 1);
expandTo(endWordIndex);
final long firstWordMask = WORD_MASK << fromIndex;
final long lastWordMask = WORD_MASK >>> -toIndex;
if (startWordIndex == endWordIndex)
{
// Case 1: One word
words[startWordIndex] |= (firstWordMask & lastWordMask);
} else
{
// Case 2: Multiple words
// Handle first word
words[startWordIndex] |= firstWordMask;
// Handle intermediate words, if any
for (int i = startWordIndex + 1; i < endWordIndex; i++)
words[i] = WORD_MASK;
// Handle last word (restores invariants)
words[endWordIndex] |= lastWordMask;
}
checkInvariants();
}
/**
* Sets the bits from the specified {@code fromIndex} (inclusive) to the
* specified {@code toIndex} (exclusive) to the specified value.
*
* @param fromIndex index of the first bit to be set
* @param toIndex index after the last bit to be set
* @param value value to set the selected bits to
* @throws IndexOutOfBoundsException if {@code fromIndex} is negative, or
* {@code toIndex} is negative, or
* {@code fromIndex} is larger than
* {@code toIndex}
* @since 1.4
*/
public void set(int fromIndex, int toIndex, boolean value)
{
if (value)
set(fromIndex, toIndex);
else
clear(fromIndex, toIndex);
}
/**
* Sets the bit specified by the index to {@code false}.
*
* @param bitIndex the index of the bit to be cleared
* @throws IndexOutOfBoundsException if the specified index is negative
* @since JDK1.0
*/
public void clear(int bitIndex)
{
if (bitIndex < 0)
throw new IndexOutOfBoundsException("bitIndex < 0: " + bitIndex);
final int wordIndex = wordIndex(bitIndex);
if (wordIndex >= wordsInUse)
return;
words[wordIndex] &= ~(1L << bitIndex);
recalculateWordsInUse();
checkInvariants();
}
/**
* Sets the bits from the specified {@code fromIndex} (inclusive) to the
* specified {@code toIndex} (exclusive) to {@code false}.
*
* @param fromIndex index of the first bit to be cleared
* @param toIndex index after the last bit to be cleared
* @throws IndexOutOfBoundsException if {@code fromIndex} is negative, or
* {@code toIndex} is negative, or
* {@code fromIndex} is larger than
* {@code toIndex}
* @since 1.4
*/
public void clear(int fromIndex, int toIndex)
{
checkRange(fromIndex, toIndex);
if (fromIndex == toIndex)
return;
final int startWordIndex = wordIndex(fromIndex);
if (startWordIndex >= wordsInUse)
return;
int to = toIndex;
int endWordIndex = wordIndex(to - 1);
if (endWordIndex >= wordsInUse)
{
to = length();
endWordIndex = wordsInUse - 1;
}
final long firstWordMask = WORD_MASK << fromIndex;
final long lastWordMask = WORD_MASK >>> -to;
if (startWordIndex == endWordIndex)
{
// Case 1: One word
words[startWordIndex] &= ~(firstWordMask & lastWordMask);
} else
{
// Case 2: Multiple words
// Handle first word
words[startWordIndex] &= ~firstWordMask;
// Handle intermediate words, if any
for (int i = startWordIndex + 1; i < endWordIndex; i++)
words[i] = 0;
// Handle last word
words[endWordIndex] &= ~lastWordMask;
}
recalculateWordsInUse();
checkInvariants();
}
/**
* Sets all of the bits in this BitSet to {@code false}.
*
* @since 1.4
*/
public void clear()
{
while (wordsInUse > 0)
words[--wordsInUse] = 0;
}
/**
* Returns the value of the bit with the specified index. The value is
* {@code true} if the bit with the index {@code bitIndex} is currently set in
* this {@code BitSet}; otherwise, the result is {@code false}.
*
* @param bitIndex the bit index
* @return the value of the bit with the specified index
* @throws IndexOutOfBoundsException if the specified index is negative
*/
public boolean get(int bitIndex)
{
if (bitIndex < 0)
throw new IndexOutOfBoundsException("bitIndex < 0: " + bitIndex);
checkInvariants();
final int wordIndex = wordIndex(bitIndex);
return (wordIndex < wordsInUse) && ((words[wordIndex] & (1L << bitIndex)) != 0);
}
// /**
// * Returns a new {@code BitSet} composed of bits from this {@code BitSet}
// * from {@code fromIndex} (inclusive) to {@code toIndex} (exclusive).
// *
// * @param fromIndex index of the first bit to include
// * @param toIndex index after the last bit to include
// * @return a new {@code BitSet} from a range of this {@code BitSet}
// * @throws IndexOutOfBoundsException if {@code fromIndex} is negative,
// * or {@code toIndex} is negative, or {@code fromIndex} is
// * larger than {@code toIndex}
// * @since 1.4
// */
// public BitSetS get(int fromIndex, int toIndex)
// {
// checkRange(fromIndex, toIndex);
//
// checkInvariants();
//
// int len = length();
//
// // If no set bits in range return empty bitset
// if (len <= fromIndex || fromIndex == toIndex)
// return new BitSetS(0);
//
// // An optimization
// if (toIndex > len)
// toIndex = len;
//
// BitSetS result = new BitSetS(toIndex - fromIndex);
// int targetWords = wordIndex(toIndex - fromIndex - 1) + 1;
// int sourceIndex = wordIndex(fromIndex);
// boolean wordAligned = ((fromIndex & BIT_INDEX_MASK) == 0);
//
// // Process all words but the last word
// for (int i = 0; i < targetWords - 1; i++, sourceIndex++)
// result.words[i] = wordAligned ? words[sourceIndex] :
// (words[sourceIndex] >>> fromIndex) |
// (words[sourceIndex+1] << -fromIndex);
//
// // Process the last word
// long lastWordMask = WORD_MASK >>> -toIndex;
// result.words[targetWords - 1] =
// ((toIndex-1) & BIT_INDEX_MASK) < (fromIndex & BIT_INDEX_MASK)
// ? /* straddles source words */
// ((words[sourceIndex] >>> fromIndex) |
// (words[sourceIndex+1] & lastWordMask) << -fromIndex)
// :
// ((words[sourceIndex] & lastWordMask) >>> fromIndex);
//
// // Set wordsInUse correctly
// result.wordsInUse = targetWords;
// result.recalculateWordsInUse();
// result.checkInvariants();
//
// return result;
// }
/**
* Returns the index of the first bit that is set to {@code true} that occurs on
* or after the specified starting index. If no such bit exists then {@code -1}
* is returned.
*
* <p>
* To iterate over the {@code true} bits in a {@code BitSet}, use the following
* loop:
*
* <pre>
* {@code
* for (int i = bs.nextSetBit(0); i >= 0; i = bs.nextSetBit(i+1)) {
* // operate on index i here
* }}
* </pre>
*
* @param fromIndex the index to start checking from (inclusive)
* @return the index of the next set bit, or {@code -1} if there is no such bit
* @throws IndexOutOfBoundsException if the specified index is negative
* @since 1.4
*/
public int nextSetBit(int fromIndex)
{
if (fromIndex < 0)
throw new IndexOutOfBoundsException("fromIndex < 0: " + fromIndex);
checkInvariants();
int u = wordIndex(fromIndex);
if (u >= wordsInUse)
return -1;
long word = words[u] & (WORD_MASK << fromIndex);
while (true)
{
if (word != 0)
return (u * BITS_PER_WORD) + Long.numberOfTrailingZeros(word);
if (++u == wordsInUse)
return -1;
word = words[u];
}
}
/**
* Returns the index of the first bit that is set to {@code false} that occurs
* on or after the specified starting index.
*
* @param fromIndex the index to start checking from (inclusive)
* @return the index of the next clear bit
* @throws IndexOutOfBoundsException if the specified index is negative
* @since 1.4
*/
public int nextClearBit(int fromIndex)
{
// Neither spec nor implementation handle bitsets of maximal length.
// See 4816253.
if (fromIndex < 0)
throw new IndexOutOfBoundsException("fromIndex < 0: " + fromIndex);
checkInvariants();
int u = wordIndex(fromIndex);
if (u >= wordsInUse)
return fromIndex;
long word = ~words[u] & (WORD_MASK << fromIndex);
while (true)
{
if (word != 0)
return (u * BITS_PER_WORD) + Long.numberOfTrailingZeros(word);
if (++u == wordsInUse)
return wordsInUse * BITS_PER_WORD;
word = ~words[u];
}
}
/**
* Returns the "logical size" of this {@code BitSet}: the index of the highest
* set bit in the {@code BitSet} plus one. Returns zero if the {@code BitSet}
* contains no set bits.
*
* @return the logical size of this {@code BitSet}
* @since 1.2
*/
public int length()
{
if (wordsInUse == 0)
return 0;
return BITS_PER_WORD * (wordsInUse - 1) + (BITS_PER_WORD - Long.numberOfLeadingZeros(words[wordsInUse - 1]));
}
/**
* Returns true if this {@code BitSet} contains no bits that are set to
* {@code true}.
*
* @return boolean indicating whether this {@code BitSet} is empty
* @since 1.4
*/
public boolean isEmpty()
{
return wordsInUse == 0;
}
/**
* Returns true if the specified {@code BitSet} has any bits set to {@code true}
* that are also set to {@code true} in this {@code BitSet}.
*
* @param set {@code BitSet} to intersect with
* @return boolean indicating whether this {@code BitSet} intersects the
* specified {@code BitSet}
* @since 1.4
*/
public boolean intersects(final ChunkSet set)
{
for (int i = Math.min(wordsInUse, set.wordsInUse) - 1; i >= 0; i--)
if ((words[i] & set.words[i]) != 0)
return true;
return false;
}
/**
* Returns the number of bits set to {@code true} in this {@code BitSet}.
*
* @return the number of bits set to {@code true} in this {@code BitSet}
* @since 1.4
*/
public int cardinality()
{
int sum = 0;
for (int i = 0; i < wordsInUse; i++)
sum += Long.bitCount(words[i]);
return sum;
}
/**
* Performs a logical <b>AND</b> of this target bit set with the argument bit
* set. This bit set is modified so that each bit in it has the value
* {@code true} if and only if it both initially had the value {@code true} and
* the corresponding bit in the bit set argument also had the value
* {@code true}.
*
* @param set a bit set
*/
public void and(final ChunkSet set)
{
if (this == set)
return;
while (wordsInUse > set.wordsInUse)
words[--wordsInUse] = 0;
// Perform logical AND on words in common
for (int i = 0; i < wordsInUse; i++)
words[i] &= set.words[i];
recalculateWordsInUse();
checkInvariants();
}
/**
* Performs a logical <b>OR</b> of this bit set with the bit set argument. This
* bit set is modified so that a bit in it has the value {@code true} if and
* only if it either already had the value {@code true} or the corresponding bit
* in the bit set argument has the value {@code true}.
*
* @param set a bit set
*/
public void or(final ChunkSet set)
{
if (this == set)
return;
final int wordsInCommon = Math.min(wordsInUse, set.wordsInUse);
if (wordsInUse < set.wordsInUse)
{
ensureCapacity(set.wordsInUse);
wordsInUse = set.wordsInUse;
}
// Perform logical OR on words in common
for (int i = 0; i < wordsInCommon; i++)
words[i] |= set.words[i];
// Copy any remaining words
if (wordsInCommon < set.wordsInUse)
System.arraycopy(set.words, wordsInCommon, words, wordsInCommon, wordsInUse - wordsInCommon);
// recalculateWordsInUse() is unnecessary
checkInvariants();
}
// /**
// * Performs a logical <b>OR</b> of this bit set with the bit set
// * argument. This bit set is modified so that a bit in it has the
// * value {@code true} if and only if it either already had the
// * value {@code true} or the corresponding bit in the bit set
// * argument has the value {@code true}.
// *
// * @param set a bit set
// */
// public void deepCopy(final BitSetS set)
// {
// if (this == set)
// return;
//
// //int wordsInCommon = Math.max(wordsInUse, set.wordsInUse);
//
// if (wordsInUse != set.wordsInUse)
// {
// ensureCapacity(set.wordsInUse);
// wordsInUse = set.wordsInUse;
// }
//
//// // Perform copy of words in common
//// for (int i = 0; i < wordsInUse; i++)
//// words[i] = set.words[i];
//
// // Copy any remaining words
// System.arraycopy
// (
// set.words, 0, words, 0, wordsInUse
// );
//
// // recalculateWordsInUse() is unnecessary
// checkInvariants();
// }
/**
* Performs a logical <b>XOR</b> of this bit set with the bit set argument. This
* bit set is modified so that a bit in it has the value {@code true} if and
* only if one of the following statements holds:
* <ul>
* <li>The bit initially has the value {@code true}, and the corresponding bit
* in the argument has the value {@code false}.
* <li>The bit initially has the value {@code false}, and the corresponding bit
* in the argument has the value {@code true}.
* </ul>
*
* @param set a bit set
*/
public void xor(ChunkSet set)
{
final int wordsInCommon = Math.min(wordsInUse, set.wordsInUse);
if (wordsInUse < set.wordsInUse)
{
ensureCapacity(set.wordsInUse);
wordsInUse = set.wordsInUse;
}
// Perform logical XOR on words in common
for (int i = 0; i < wordsInCommon; i++)
words[i] ^= set.words[i];
// Copy any remaining words
if (wordsInCommon < set.wordsInUse)
System.arraycopy(set.words, wordsInCommon, words, wordsInCommon, set.wordsInUse - wordsInCommon);
recalculateWordsInUse();
checkInvariants();
}
/**
* Clears all of the bits in this {@code BitSet} whose corresponding bit is set
* in the specified {@code BitSet}.
*
* @param set the {@code BitSet} with which to mask this {@code BitSet}
* @since 1.2
*/
public void andNot(ChunkSet set)
{
// Perform logical (a & !b) on words in common
for (int i = Math.min(wordsInUse, set.wordsInUse) - 1; i >= 0; i--)
words[i] &= ~set.words[i];
recalculateWordsInUse();
checkInvariants();
}
/**
* Returns a hash code value for this bit set. The hash code depends only on
* which bits have been set within this <code>BitSet</code>. The algorithm used
* to compute it may be described as follows.
* <p>
* Suppose the bits in the <code>BitSet</code> were to be stored in an array of
* <code>long</code> integers called, say, <code>words</code>, in such a manner
* that bit <code>k</code> is set in the <code>BitSet</code> (for nonnegative
* values of <code>k</code>) if and only if the expression
*
* <pre>
* ((k >> 6) < words.length) && ((words[k >> 6] & (1L << (bit & 0x3F))) != 0)
* </pre>
*
* is true. Then the following definition of the <code>hashCode</code> method
* would be a correct implementation of the actual algorithm:
*
* <pre>
* public int hashCode()
* {
* long h = 1234;
* for (int i = words.length; --i >= 0;)
* {
* h ^= words[i] * (i + 1);
* }
* return (int) ((h >> 32) ^ h);
* }
* </pre>
*
* Note that the hash code values change if the set of bits is altered.
* <p>
* Overrides the <code>hashCode</code> method of <code>Object</code>.
*
* @return a hash code value for this bit set.
*/
@Override
public int hashCode()
{
long h = 1234;
for (int i = wordsInUse; --i >= 0;)
h ^= words[i] * (i + 1);
return (int) ((h >> 32) ^ h);
}
/**
* Returns the number of bits of space actually in use by this {@code BitSet} to
* represent bit values. The maximum element in the set is the size - 1st
* element.
*
* @return the number of bits currently in this bit set
*/
public int size()
{
return words.length * BITS_PER_WORD;
}
/**
* Compares this object against the specified object. The result is {@code true}
* if and only if the argument is not {@code null} and is a {@code Bitset}
* object that has exactly the same set of bits set to {@code true} as this bit
* set. That is, for every nonnegative {@code int} index {@code k},
*
* <pre>
* ((BitSet) obj).get(k) == this.get(k)
* </pre>
*
* must be true. The current sizes of the two bit sets are not compared.
*
* @param obj the object to compare with
* @return {@code true} if the objects are the same; {@code false} otherwise
* @see #size()
*/
@Override
public boolean equals(Object obj)
{
if (!(obj instanceof ChunkSet))
return false;
if (this == obj)
return true;
final ChunkSet set = (ChunkSet) obj;
checkInvariants();
set.checkInvariants();
if (wordsInUse != set.wordsInUse)
return false;
// Check words in use by both BitSets
for (int i = 0; i < wordsInUse; i++)
if (words[i] != set.words[i])
return false;
return true;
}
/**
* Cloning this {@code BitSet} produces a new {@code BitSet} that is equal to
* it. The clone of the bit set is another bit set that has exactly the same
* bits set to {@code true} as this bit set.
*
* @return a clone of this bit set
* @see #size()
*/
@Override
public ChunkSet clone()
{
if (!sizeIsSticky)
trimToSize();
try
{
final ChunkSet result = (ChunkSet) super.clone();
result.words = words.clone();
result.checkInvariants();
return result;
}
catch (final CloneNotSupportedException e)
{
e.printStackTrace();
throw new InternalError();
}
}
/**
* Attempts to reduce internal storage used for the bits in this bit set.
* Calling this method may, but is not required to, affect the value returned by
* a subsequent call to the {@link #size()} method.
*/
public void trimToSize()
{
if (wordsInUse != words.length)
{
words = Arrays.copyOf(words, wordsInUse);
checkInvariants();
}
}
/**
* Save the state of the {@code BitSet} instance to a stream (i.e., serialize
* it).
*
* @param s
* @throws IOException
*/
private void writeObject(ObjectOutputStream s) throws IOException
{
checkInvariants();
if (!sizeIsSticky)
trimToSize();
s.writeObject(words);
s.writeInt(chunkSize);
s.writeLong(chunkMask);
}
/**
* Reconstitute the {@code BitSet} instance from a stream (i.e., deserialize
* it).
*
* @param s
* @throws IOException
* @throws ClassNotFoundException
*/
private void readObject(ObjectInputStream s) throws IOException, ClassNotFoundException
{
words = (long[]) s.readObject();
final int newChunkSize = s.readInt();
final long newChunkMask = s.readLong();
// chunkSize and chunkMask are final, so need Reflection to set them
try
{
final Field chunkSizeField = getClass().getDeclaredField("chunkSize");
chunkSizeField.setAccessible(true);
chunkSizeField.set(this, newChunkSize);
final Field chunkMaskField = getClass().getDeclaredField("chunkMask");
chunkMaskField.setAccessible(true);
chunkMaskField.set(this, newChunkMask);
}
catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException e) {
e.printStackTrace();
}
// Assume maximum length then find real length
// because recalculateWordsInUse assumes maintenance
// or reduction in logical size
wordsInUse = words.length;
recalculateWordsInUse();
sizeIsSticky = (words.length > 0 && words[words.length - 1] == 0L); // heuristic
checkInvariants();
}
/**
* Returns a string representation of this bit set. For every index for which
* this {@code BitSet} contains a bit in the set state, the decimal
* representation of that index is included in the result. Such indices are
* listed in order from lowest to highest, separated by ", " (a comma and a
* space) and surrounded by braces, resulting in the usual mathematical notation
* for a set of integers.
*
* <p>
* Example:
*
* <pre>
* BitSet drPepper = new BitSet();
* </pre>
*
* Now {@code drPepper.toString()} returns "{@code {}}".
* <p>
*
* <pre>
* drPepper.set(2);
* </pre>
*
* Now {@code drPepper.toString()} returns "{@code {2}}".
* <p>
*
* <pre>
* drPepper.set(4);
* drPepper.set(10);
* </pre>
*
* Now {@code drPepper.toString()} returns "{@code {2, 4, 10}}".
*
* @return a string representation of this bit set
*/
@Override
public String toString()
{
checkInvariants();
final int numBits = (wordsInUse > 128) ? cardinality() : wordsInUse * BITS_PER_WORD;
final StringBuilder b = new StringBuilder(6 * numBits + 2);
b.append('{');
int i = nextSetBit(0);
if (i != -1)
{
b.append(i);
for (i = nextSetBit(i + 1); i >= 0; i = nextSetBit(i + 1))
{
final int endOfRun = nextClearBit(i);
do
{
b.append(", ").append(i);
} while (++i < endOfRun);
}
}
b.append('}');
return b.toString();
}
// =========================================================================
// NEW ADDITIONS FOR CHUNKING
// =========================================================================
/**
* @return Number of bits per chunk. Will be a power of 2 up to 32: 1, 2, 4, 8,
* 16, 32.
*/
public int chunkSize()
{
return chunkSize;
}
/**
* @return Number of complete chunks.
*/
public int numChunks()
{
return (chunkSize == 0) ? 0 : size() / chunkSize;
}
/**
* @return Number of chunks that have at least one set bit
*/
public int numNonZeroChunks()
{
int count = 0;
final int numChunks = numChunks();
for (int i = 0; i < numChunks; ++i)
{
if (getChunk(i) != 0)
{
++count;
}
}
return count;
}
// /**
// * @param fromIndex Index of bit to start at.
//// * @param numBits Chunk size in bits (< 32).
// * @return Integer defined by the specified bits.
// */
// public int getChunk(final int fromIndex) //, final int numBits)
// {
// final int toIndex = fromIndex + chunkSize;
// final int wordIndexTo = wordIndex(toIndex);
// if (wordIndexTo > wordsInUse)
// return 0; // out of range: partial or non-existent chunk of bits
//
// final long chunkMask = (0x1L << chunkSize) - 1;
// final int down = fromIndex % 64;
//
// final int startWordIndex = wordIndex(fromIndex);
// final int endWordIndex = wordIndex(toIndex - 1);
//
// final int value = (startWordIndex == endWordIndex)
// ? (int)((words[startWordIndex] >>> down) & chunkMask) // single word
// : (int)( // straddles two words
// ((words[startWordIndex] >>> down) & chunkMask)
// |
// ((words[endWordIndex] << (64-down)) & chunkMask)
// );
//
// checkInvariants();
// return value; // & (int)chunkMask;
// }
/**
* If chunk is out of range, this function will return 0.
* This is for compatibility with setChunk, which will grow the array as needed.
*
* Chunks will not straddle word boundaries as chunkSize is a power of 2. //
* @param chunk Chunk to get. // * @param numBits Chunk size in bits (power of 2
* <= 32, i.e. 1, 2, 4, 8, 16 or 32).
* @return Integer defined by the specified bits.
*/
public int getChunk(final int chunk) // , final int numBits)
{
final int bitIndex = chunk * chunkSize;
final int wordIndex = bitIndex >> 6; // is (n / 64)
if (wordIndex >= words.length) return 0;
// final long chunkMask = (0x1L << chunkSize) - 1;
final int down = bitIndex & 63; // is (n % 64)
// System.out.println("fromIndex=" + fromIndex + ", numBits=" + numBits + ".");
// System.out.println("wordIndex=" + wordIndex + ", wordsInUse=" + wordsInUse +
// ", words.length=" + words.length + ".");
return (int) ((words[wordIndex] >>> down) & chunkMask);
}
/**
* @return A list of indices of all the non-zero chunks
*/
public TIntArrayList getNonzeroChunks()
{
final TIntArrayList indices = new TIntArrayList();
final int chunksPerWord = Long.SIZE / chunkSize;
for (int wordIdx = 0; wordIdx < words.length; ++wordIdx)
{
final long word = words[wordIdx];
if (word != 0)
{
for (int chunkWord = 0; chunkWord < chunksPerWord; ++chunkWord)
{
if ((word & (chunkMask << (chunkWord * chunkSize))) != 0L)
indices.add(wordIdx * chunksPerWord + chunkWord);
}
}
}
return indices;
}
// /**
// * Chunks will not straddle word boundaries as chunkSize is a power of 2.
//// * @param fromIndex Index of bit to start at.
// * @param chunk Chunk to get.
//// * @param numBits Chunk size in bits (power of 2 <= 32, i.e. 1, 2, 4, 8, 16 or 32).
// * @param offset
// * @param mask
// * @return Integer defined by the specified bits.
// */
// public int getSubchunk(final int chunk, final int offset, final long mask)
// {
// final int bitIndex = chunk * chunkSize;
// final int wordIndex = bitIndex >> 6;
//
//// final long chunkMask = (0x1L << chunkSize) - 1;
// final int down = bitIndex % 64 + offset;
//
// //System.out.println("fromIndex=" + fromIndex + ", numBits=" + numBits + ".");
// //System.out.println("wordIndex=" + wordIndex + ", wordsInUse=" + wordsInUse + ", words.length=" + words.length + ".");
//
// return (int)((words[wordIndex] >>> down) & mask);
// }
//-------------------------------------------------------------------------
// /**
// * Encode integer value in the specified bits. Increase the Bitset size if necessary.
// * @param fromIndex Index of bit to start at.
//// * @param numBits Chunk size in bits (< 32).
// * @param value Value to encode.
// */
// public void setChunk(final int fromIndex, final int value) //final int numBits, final int value)
// {
// if (chunkSize == 0)
// return;
//
// final int toIndex = fromIndex + chunkSize;
// checkRange(fromIndex, toIndex);
//
// // Increase capacity if necessary
// final int startWordIndex = wordIndex(fromIndex);
// final int endWordIndex = wordIndex(toIndex - 1);
// expandTo(endWordIndex);
//
// final long chunkMask = (0x1L << chunkSize) - 1;
// final int up = fromIndex % 64;
//
// words[startWordIndex] &= ~(chunkMask << up);
// words[startWordIndex] |= ((value & chunkMask) << up);
//
// if (startWordIndex != endWordIndex)
// {
// // Straddles two words
// final int down = (64 - up);
// words[endWordIndex] &= ~(chunkMask >>> down);
// words[endWordIndex] |= ((value & chunkMask) >>> down);
// }
// checkInvariants();
// }
// /**
// * Encode integer value in the specified bits. Increase the Bitset size if necessary.
// * Chunks will not straddle word boundaries as chunkSize is a power of 2.
// * @param fromIndex Index of bit to start at.
//// * @param numBits Chunk size in bits (power of 2 <= 32, i.e. 1, 2, 4, 8, 16 or 32).
// * @param value Value to encode.
// */
// public void setChunk(final int fromIndex, final int value) //final int numBits, final int value)
// {
// if (chunkSize == 0)
// return;
//
// final int wordIndex = fromIndex >> 6;
// expandTo(wordIndex);
//
// final long chunkMask = (0x1L << chunkSize) - 1;
// final int up = fromIndex % 64;
//
// words[wordIndex] &= ~(chunkMask << up);
// words[wordIndex] |= ((value & chunkMask) << up);
// }
/**
* Encode integer value in the specified bits. Increase the Bitset size if
* necessary. Chunks will not straddle word boundaries as chunkSize is a power
* of 2. // * @param fromIndex Index of bit to start at.
*
* @param chunk Chunk to set. // * @param numBits Chunk size in bits (power of 2
* <= 32, i.e. 1, 2, 4, 8, 16 or 32).
* @param value Value to encode.
*/
public void setChunk(final int chunk, final int value) // final int numBits, final int value)
{
if (value < 0 || value >= (1<<chunkSize))
throw new IllegalArgumentException ("Chunk value " + value + " is out of range for size = " + chunkSize);
if (chunkSize == 0)
return;
final int bitIndex = chunk * chunkSize;
final int wordIndex = bitIndex >> 6; // is (n / 64)
expandTo(wordIndex);
// final long chunkMask = (0x1L << chunkSize) - 1;
final int up = bitIndex & 63; // is (n % 64)
words[wordIndex] &= ~(chunkMask << up);
words[wordIndex] |= (((long)value) << up);
recalculateWordsInUse();
checkInvariants();
}
/**
* Sets the value for the given chunk, and returns the value the chunk
* had prior to setting. This is a useful optimisation because we often
* want to get and immediately after set, and they partially share the
* same implementation.
*
* @param chunk
* @param value
* @return Integer defined by the specified bits (prior to setting new value).
*/
public int getAndSetChunk(final int chunk, final int value)
{
if (value < 0 || value >= (1<<chunkSize))
throw new IllegalArgumentException ("Chunk value " + value + " is out of range for size = " + chunkSize);
if (chunkSize == 0)
return 0;
final int bitIndex = chunk * chunkSize;
final int wordIndex = bitIndex >> 6; // is (n / 64)
expandTo(wordIndex);
final int down = bitIndex & 63; // is (n % 64)
final int oldVal = (int) ((words[wordIndex] >>> down) & chunkMask);
words[wordIndex] &= ~(chunkMask << down);
words[wordIndex] |= (((long)value) << down);
recalculateWordsInUse();
checkInvariants();
return oldVal;
}
// /**
// * Encode integer value in the specified bits. Increase the Bitset size if necessary.
// * Chunks will not straddle word boundaries as chunkSize is a power of 2.
//// * @param fromIndex Index of bit to start at.
// * @param chunk Chunk to set.
//// * @param numBits Chunk size in bits (power of 2 <= 32, i.e. 1, 2, 4, 8, 16 or 32).
// * @param value Value to encode.
// * @param offset
// * @param mask
// */
// public void setSubchunk(final int chunk, final int value, final int offset, final long mask)
// {
// if (chunkSize == 0)
// return;
//
// final int bitIndex = chunk * chunkSize;
//
// final int wordIndex = bitIndex >> 6;
// expandTo(wordIndex);
//
//// final long chunkMask = (0x1L << chunkSize) - 1;
// final int up = bitIndex % 64 + offset;
//
// words[wordIndex] &= ~(mask << up);
// words[wordIndex] |= ((value & mask) << up);
// }
//-------------------------------------------------------------------------
// /**
// * Clear the specified bits. Does not increase Bitset size.
// * @param fromIndex Index of bit to start at.
//// * @param numBits Chunk size in bits (< 32).
// */
// public void clearChunk(final int fromIndex) //, final int numBits)
// {
// if (chunkSize == 0)
// return;
//
// final int toIndex = fromIndex + chunkSize;
// checkRange(fromIndex, toIndex);
//
// // DO NOT increase capacity!
// final int startWordIndex = wordIndex(fromIndex);
// final int endWordIndex = wordIndex(toIndex - 1);
// //expandTo(endWordIndex);
//
//// final long chunkMask = (0x1L << chunkSize) - 1;
// final int up = fromIndex % 64;
//
// words[startWordIndex] &= ~(chunkMask << up);
//
// if (startWordIndex != endWordIndex && endWordIndex <= wordsInUse)
// { // MAYBE THIS SHOULD BE: endWordIndex < wordsInUse)
// // Straddles two words
// final int down = (64 - up);
// words[endWordIndex] &= ~(chunkMask >>> down);
// }
// checkInvariants();
// }
/**
* Clear the specified chunk. Chunks will not straddle word boundaries as
* chunkSize is a power of 2. // * @param fromIndex Index of bit to start at.
*
* @param chunk Chunk to clear. // * @param numBits Chunk size in bits (power of
* 2 <= 32, i.e. 1, 2, 4, 8, 16 or 32).
*/
public void clearChunk(final int chunk) // , final int numBits)
{
if (chunkSize == 0)
return;
final int bitIndex = chunk * chunkSize;
final int wordIndex = bitIndex >> 6; // is (n / 64)
if (wordIndex > wordsInUse) // or: if (wordIndex >= wordsInUse) ???
return;
// final long chunkMask = (0x1L << chunkSize) - 1;
final int up = bitIndex & 63; // is (n % 64)
words[wordIndex] &= ~(chunkMask << up);
recalculateWordsInUse();
checkInvariants();
}
// /**
// * Clear the specified chunk.
// * Chunks will not straddle word boundaries as chunkSize is a power of 2.
//// * @param fromIndex Index of bit to start at.
// * @param chunk Chunk to clear.
//// * @param numBits Chunk size in bits (power of 2 <= 32, i.e. 1, 2, 4, 8, 16 or 32).
// * @param offset
// * @param mask
// */
// public void clearSubchunk(final int chunk, final int offset, final long mask)
// {
// if (chunkSize == 0)
// return;
//
// final int bitIndex = chunk * chunkSize;
//
// final int wordIndex = bitIndex >> 6;
// if (wordIndex > wordsInUse) // or: if (wordIndex >= wordsInUse) ???
// return;
//
//// final long chunkMask = (0x1L << chunkSize) - 1;
// final int up = bitIndex % 64 + offset;
//
// words[wordIndex] &= ~(mask << up);
// }
/**
* Sets all of the bits in this BitSet to {@code false} without resizing.
*/
public void clearNoResize()
{
for (int w = 0; w < wordsInUse; w++)
words[w] = 0;
wordsInUse = 0;
checkInvariants();
}
//-------------------------------------------------------------------------
// Bit routines for CSP puzzle states
public int getBit(final int chunk, final int bit)
{
final int bitIndex = chunk * chunkSize;
final int wordIndex = bitIndex >> 6; // is (n / 64)
final int down = bitIndex & 63; // is (n % 64)
return (int) ((words[wordIndex] >>> (down + bit)) & 0x1L);
}
public void setBit(final int chunk, final int bit, final boolean value)
{
if (chunkSize == 0)
return;
final int bitIndex = chunk * chunkSize;
final int wordIndex = bitIndex >> 6; // is (n / 64)
expandTo(wordIndex);
final int up = bitIndex & 63; // is (n % 64)
final long bitMask = 0x1L << (up + bit);
if (value)
words[wordIndex] |= bitMask;
else
words[wordIndex] &= ~bitMask;
recalculateWordsInUse();
checkInvariants();
}
public void toggleBit(final int chunk, final int bit)
{
if (chunkSize == 0)
return;
final int bitIndex = chunk * chunkSize;
final int wordIndex = bitIndex >> 6; // is (n / 64)
expandTo(wordIndex);
final int up = bitIndex & 63; // is (n % 64)
final long bitMask = 0x1L << (up + bit);
words[wordIndex] ^= bitMask;
recalculateWordsInUse();
checkInvariants();
}
public void setNBits(final int chunk, final int numBits, final boolean value)
{
if (chunkSize == 0)
return;
final int bitIndex = chunk * chunkSize;
final int wordIndex = bitIndex >> 6; // is (n / 64)
expandTo(wordIndex);
final int up = bitIndex & 63; // is (n % 64)
final long bitsNMask = bitNMasks[numBits] << up;
if (value)
words[wordIndex] |= bitsNMask;
else
words[wordIndex] &= ~bitsNMask;
recalculateWordsInUse();
checkInvariants();
}
public void resolveToBit(final int chunk, final int bit)
{
if (chunkSize == 0)
return;
final int bitIndex = chunk * chunkSize;
final int wordIndex = bitIndex >> 6; // is (n / 64)
expandTo(wordIndex);
final int up = bitIndex & 63; // is (n % 64)
final long bitMask = 0x1L << (up + bit);
words[wordIndex] &= ~(chunkMask << up);
words[wordIndex] |= bitMask;
recalculateWordsInUse();
checkInvariants();
}
public int numBitsOn(final int chunk)
{
final int bitIndex = chunk * chunkSize;
final int wordIndex = bitIndex >> 6; // is (n / 64)
final int down = bitIndex & 63; // is (n % 64)
final int value = (int)((words[wordIndex] >>> down) & chunkMask);
// Count on-bits in the chunk
int numBits = 0;
for (int b = 0; b < chunkSize; b++)
if (((0x1 << b) & value) != 0)
numBits++;
return numBits;
}
public boolean isResolved(final int chunk)
{
return numBitsOn(chunk) == 1;
}
/**
* @param chunk
* @return Resolved value, else 0 if not resolved yet.
*/
public int resolvedTo(final int chunk)
{
final int bitIndex = chunk * chunkSize;
final int wordIndex = bitIndex >> 6; // is (n / 64)
final int down = bitIndex & 63; // is (n % 64)
final int value = (int)((words[wordIndex] >>> down) & chunkMask);
// Check the on-bits in the chunk
int result = -1;
int numBits = 0;
for (int b = 0; b < chunkSize; b++)
if (((0x1 << b) & value) != 0)
{
result = b;
numBits++;
}
return (numBits == 1) ? result : 0;
}
//-------------------------------------------------------------------------
/**
* Equivalent to: this <<= numBits;
*
* @param numBits Number of bits to shift (< 64).
* @param expand Whether to expand the bitset if necessary.
*/
public void shiftL(final int numBits, final boolean expand)
{
if (numBits == 0)
return;
if (expand)
{
// Ensure that no shifted bits will be lost
final int maxIndex = wordIndex(length() + numBits);
expandTo(maxIndex);
}
final int remnant = 64 - numBits;
long carry = 0;
for (int idx = 0; idx < wordsInUse; idx++)
{
final long temp = words[idx] >>> remnant;
words[idx] = (words[idx] << numBits) | carry;
carry = temp;
}
if (!expand)
{
// Mask out unused bits of highest word so that original size is not exceeded
final int size = size();
if ((size & 63) > 0)
{
final long mask = (0x1L << (size & 63)) - 1;
words[wordsInUse - 1] &= mask;
}
}
// Any leftover bits are either added to expanded bitset or lost, as specified
recalculateWordsInUse();
checkInvariants();
}
/**
* Equivalent to: this >>>= numBits;
*
* @param numBits Number of bits to shift (< 64).
*/
public void shiftR(final int numBits)
{
if (numBits == 0)
return;
final int remnant = 64 - numBits;
long carry = 0;
for (int idx = wordsInUse - 1; idx >= 0; idx--)
{
final long temp = words[idx] << remnant;
words[idx] = (words[idx] >>> numBits) | carry;
carry = temp;
}
// Any leftover bits are lost
recalculateWordsInUse();
checkInvariants();
}
//-------------------------------------------------------------------------
/**
* We say that this ChunkSet matches the specified pattern if and only
* if all the bits covered by the given mask in this ChunkSet are equal
* to the corresponding bits in the given pattern.
*
* @param mask
* @param pattern
* @return Whether this ChunkSet (masked) matches the specified pattern.
*/
public boolean matches(final ChunkSet mask, final ChunkSet pattern)
{
final int maskWordsInUse = mask.wordsInUse;
if (wordsInUse < maskWordsInUse)
return false;
for (int n = 0; n < maskWordsInUse; n++)
if ((words[n] & mask.words[n]) != pattern.words[n])
return false;
return true;
}
/**
* @param wordIdx
* @param mask
* @param matchingWord
* @return True if the word at wordIdx, after masking by mask, matches the given word
*/
public boolean matchesWord(final int wordIdx, final long mask, final long matchingWord)
{
if (words.length <= wordIdx)
return false;
return ((words[wordIdx] & mask) == matchingWord);
}
/**
* Adds given mask to given word
* @param wordIdx
* @param mask
*/
public void addMask(final int wordIdx, final long mask)
{
expandTo(wordIdx);
words[wordIdx] |= mask;
checkInvariants();
}
//-------------------------------------------------------------------------
/**
* We say that this ChunkSet violates the specified not-pattern if and only
* if there exists at least one chunk in this ChunkSet which is covered by
* the given mask and which is equal to the corresponding chunk in the
* given pattern.
*
* @param mask
* @param pattern
* @return Whether this ChunkSet (masked) violates the specified
* not-pattern.
*/
public boolean violatesNot(final ChunkSet mask, final ChunkSet pattern)
{
return violatesNot(mask, pattern, 0);
}
/**
* We say that this ChunkSet violates the specified not-pattern if and only
* if there exists at least one chunk in this ChunkSet which is covered by
* the given mask and which is equal to the corresponding chunk in the
* given pattern.
*
* @param mask
* @param pattern
* @param startWord The first word to start looping at
* @return Whether this ChunkSet (masked) violates the specified
* not-pattern.
*/
public boolean violatesNot
(
final ChunkSet mask, final ChunkSet pattern, final int startWord
)
{
// TODO I don't think we want this check here...
/*
if (wordsInUse < mask.wordsInUse)
{
System.out.println("wordsInUse < mask.wordsInUse in violatesNot()!");
System.out.println("this = " + this);
System.out.println("mask = " + mask);
System.out.println("pattern = " + pattern);
return true;
}
*/
final int wordsToCheck = Math.min(wordsInUse, mask.wordsInUse);
for (int n = startWord; n < wordsToCheck; n++)
{
// if ((words[n] & mask.words[n]) != pattern.words[n])
// return false;
// TODO: Remove ifs?
// Redundant ifs?
long temp = ~(words[n] ^ pattern.words[n]) & mask.words[n];
if (chunkSize > 1)
{
temp = ((temp & MASK_NOT_1) >>> 1) & temp;
if (chunkSize > 2)
{
temp = ((temp & MASK_NOT_2) >>> 2) & temp;
if (chunkSize > 4)
{
temp = ((temp & MASK_NOT_4) >>> 4) & temp;
if (chunkSize > 8)
{
temp = ((temp & MASK_NOT_8) >>> 8) & temp;
if (chunkSize > 16)
{
temp = ((temp & MASK_NOT_16) >>> 16) & temp;
if (chunkSize > 32)
{
temp = ((temp & MASK_NOT_32) >>> 32) & temp;
}
}
}
}
}
}
if (temp != 0)
return true; // violation
}
return false; // no violation
}
//-------------------------------------------------------------------------
/**
* @return A string-representation that conveniently shows the values of
* non-zero chunks.
*/
public String toChunkString()
{
checkInvariants();
final int numBits = (wordsInUse > 128) ? cardinality() : wordsInUse * BITS_PER_WORD;
final StringBuilder b = new StringBuilder(6 * numBits + 2);
b.append('{');
for (int i = 0; i < numChunks(); ++i)
{
final int value = getChunk(i);
if (value != 0)
{
if (b.toString().length() > 1)
{
b.append(", ");
}
b.append("chunk " + i + " = " + value);
}
}
b.append('}');
return b.toString();
}
//-------------------------------------------------------------------------
}
| 56,314 | 27.600813 | 129 | java |
Ludii | Ludii-master/Common/src/main/collections/ChunkStack.java | package main.collections;
import java.io.Serializable;
import main.math.BitTwiddling;
/**
* The three possible ChunkSets for each level of each site (for stacking
* games).
*
* @author Eric.Piette
*
*/
public final class ChunkStack implements Serializable
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/** 'what' */
public static final int TYPE_DEFAULT_STATE = 0;
/** 'what' + 'who' */
public static final int TYPE_PLAYER_STATE = 1;
/** 'what' + 'who' + 'state' + 'rotation' + 'value' */
public static final int TYPE_INDEX_STATE = 2;
/**
* if
*
* type == 1 --> Player State
*
* type == 2 --> Index State
*
* type == 3 --> index local state, rotation, value.
*/
protected final int type;
/** What ChunkSet. */
private final ChunkSet what;
/** Who ChunkSet. */
private final ChunkSet who;
/** State ChunkSet. */
private final ChunkSet state;
/** Rotation ChunkSet. */
private final ChunkSet rotation;
/** Value ChunkSet. */
private final ChunkSet value;
/** Hidden Array ChunkSet. */
private final ChunkSet[] hidden;
/** Hidden What Array ChunkSet. */
private final ChunkSet[] hiddenWhat;
/** Hidden Who Array ChunkSet. */
private final ChunkSet[] hiddenWho;
/** Hidden Count Array ChunkSet. */
private final ChunkSet[] hiddenCount;
/** Hidden State Array ChunkSet. */
private final ChunkSet[] hiddenState;
/** Hidden Rotation Array ChunkSet. */
private final ChunkSet[] hiddenRotation;
/** Hidden Value Array ChunkSet. */
private final ChunkSet[] hiddenValue;
/** The number of components on the stack. */
private int size;
/**
*
* Constructor.
*
* @param numComponents The number of components.
* @param numPlayers The number of players.
* @param numStates The number of states.
* @param numRotation The number of rotations.
* @param numValues The number of rotations.
* @param type The type of the chunkStack.
* @param hidden True if the game involves hidden info.
*/
public ChunkStack
(
final int numComponents,
final int numPlayers,
final int numStates,
final int numRotation,
final int numValues,
final int type,
final boolean hidden
)
{
this.type = type;
this.size = 0;
final int chunkSizeWhat = BitTwiddling.nextPowerOf2(BitTwiddling.bitsRequired(numComponents));
// What
this.what = new ChunkSet(chunkSizeWhat, 1);
final int chunkSizeWho = BitTwiddling.nextPowerOf2(BitTwiddling.bitsRequired(numPlayers + 1));
// Who
if (type > 0)
this.who = new ChunkSet(chunkSizeWho, 1);
else
this.who = null;
final int chunkSizeState = BitTwiddling.nextPowerOf2(BitTwiddling.bitsRequired(numStates));
// State
if (type > 1)
this.state = new ChunkSet(chunkSizeState, 1);
else
this.state = null;
final int chunkSizeRotation = BitTwiddling.nextPowerOf2(BitTwiddling.bitsRequired(numRotation));
// Rotation
if (type >= 2)
this.rotation = new ChunkSet(chunkSizeRotation, 1);
else
this.rotation = null;
final int chunkSizeValue = BitTwiddling.nextPowerOf2(BitTwiddling.bitsRequired(numValues));
// Value
if (type >= 2)
this.value = new ChunkSet(chunkSizeValue, 1);
else
this.value = null;
// Hidden info
if (hidden)
{
final int chunkSizeHidden = BitTwiddling.nextPowerOf2(BitTwiddling.bitsRequired(2));
this.hidden = new ChunkSet[numPlayers + 1];
for (int i = 1; i < numPlayers + 1; i++)
this.hidden[i] = new ChunkSet(chunkSizeHidden, 1);
this.hiddenWhat = new ChunkSet[numPlayers + 1];
for (int i = 1; i < numPlayers + 1; i++)
this.hiddenWhat[i] = new ChunkSet(chunkSizeHidden, 1);
if (type > 0)
{
this.hiddenWho = new ChunkSet[numPlayers + 1];
for (int i = 1; i < numPlayers + 1; i++)
this.hiddenWho[i] = new ChunkSet(chunkSizeHidden, 1);
if (type > 1)
{
this.hiddenState = new ChunkSet[numPlayers + 1];
for (int i = 1; i < numPlayers + 1; i++)
this.hiddenState[i] = new ChunkSet(chunkSizeHidden, 1);
if (type >= 2)
{
this.hiddenRotation = new ChunkSet[numPlayers + 1];
for (int i = 1; i < numPlayers + 1; i++)
this.hiddenRotation[i] = new ChunkSet(chunkSizeHidden, 1);
this.hiddenCount = new ChunkSet[numPlayers + 1];
for (int i = 1; i < numPlayers + 1; i++)
this.hiddenCount[i] = new ChunkSet(chunkSizeHidden, 1);
this.hiddenValue = new ChunkSet[numPlayers + 1];
for (int i = 1; i < numPlayers + 1; i++)
this.hiddenValue[i] = new ChunkSet(chunkSizeHidden, 1);
}
else
{
this.hiddenRotation = null;
this.hiddenCount = null;
this.hiddenValue = null;
}
}
else
{
this.hiddenState = null;
this.hiddenRotation = null;
this.hiddenCount = null;
this.hiddenValue = null;
}
}
else
{
this.hiddenWho = null;
this.hiddenState = null;
this.hiddenRotation = null;
this.hiddenCount = null;
this.hiddenValue = null;
}
}
else
{
this.hidden = null;
this.hiddenWhat = null;
this.hiddenWho = null;
this.hiddenState = null;
this.hiddenRotation = null;
this.hiddenCount = null;
this.hiddenValue = null;
}
}
/**
* Copy constructor
* @param other
*/
public ChunkStack(final ChunkStack other)
{
this.type = other.type;
this.size = other.size;
this.what = (other.what == null) ? null : other.what.clone();
this.who = (other.who == null) ? null : other.who.clone();
this.state = (other.state == null) ? null : other.state.clone();
this.rotation = (other.rotation == null) ? null : other.rotation.clone();
this.value = (other.value == null) ? null : other.value.clone();
if (other.hidden == null)
{
this.hidden = null;
this.hiddenWhat = null;
this.hiddenWho = null;
this.hiddenState = null;
this.hiddenRotation = null;
this.hiddenCount = null;
this.hiddenValue = null;
}
else
{
this.hidden = new ChunkSet[other.hidden.length];
this.hiddenWhat = new ChunkSet[other.hiddenWhat.length];
for (int i = 1; i < this.hidden.length; ++i)
{
this.hidden[i] = other.hidden[i].clone();
this.hiddenWhat[i] = other.hiddenWhat[i].clone();
}
if (type > 0)
{
this.hiddenWho = new ChunkSet[other.hiddenWho.length];
for (int i = 1; i < this.hiddenWho.length; ++i)
{
this.hiddenWho[i] = other.hiddenWho[i].clone();
}
if (type > 1)
{
this.hiddenState = new ChunkSet[other.hiddenState.length];
for (int i = 1; i < this.hiddenState.length; ++i)
{
this.hiddenState[i] = other.hiddenState[i].clone();
}
if (type >= 2)
{
this.hiddenRotation = new ChunkSet[other.hiddenRotation.length];
this.hiddenCount = new ChunkSet[other.hiddenCount.length];
this.hiddenValue = new ChunkSet[other.hiddenValue.length];
for (int i = 1; i < this.hiddenRotation.length; ++i)
{
this.hiddenRotation[i] = other.hiddenRotation[i].clone();
this.hiddenCount[i] = other.hiddenCount[i].clone();
this.hiddenValue[i] = other.hiddenValue[i].clone();
}
}
else
{
this.hiddenRotation = null;
this.hiddenCount = null;
this.hiddenValue = null;
}
}
else
{
this.hiddenState = null;
this.hiddenRotation = null;
this.hiddenCount = null;
this.hiddenValue = null;
}
}
else
{
this.hiddenWho = null;
this.hiddenState = null;
this.hiddenRotation = null;
this.hiddenCount = null;
this.hiddenValue = null;
}
}
}
/**
* @return what ChunkSet.
*/
public ChunkSet whatChunkSet()
{
return what;
}
/**
* @return who ChunkSet.
*/
public ChunkSet whoChunkSet()
{
return who;
}
/**
* @return local state ChunkSet.
*/
public ChunkSet stateChunkSet()
{
return state;
}
/**
* @return rotation state ChunkSet.
*/
public ChunkSet rotationChunkSet()
{
return rotation;
}
/**
* @return value state ChunkSet.
*/
public ChunkSet valueChunkSet()
{
return value;
}
/**
*
* @return hidden info array ChunkSet.
*/
public ChunkSet[] hidden()
{
return hidden;
}
/**
*
* @return hidden what info array ChunkSet.
*/
public ChunkSet[] hiddenWhat()
{
return hiddenWhat;
}
/**
*
* @return hidden who info array ChunkSet.
*/
public ChunkSet[] hiddenWho()
{
return hiddenWho;
}
/**
*
* @return hidden state info array ChunkSet.
*/
public ChunkSet[] hiddenState()
{
return hiddenState;
}
/**
*
* @return hidden rotation info array ChunkSet.
*/
public ChunkSet[] hiddenRotation()
{
return hiddenRotation;
}
/**
*
* @return hidden count info array ChunkSet.
*/
public ChunkSet[] hiddenCount()
{
return hiddenCount;
}
/**
*
* @return hidden piece value info array ChunkSet.
*/
public ChunkSet[] hiddenValue()
{
return hiddenValue;
}
/**
* @return Current size of the stack
*/
public int size()
{
return this.size;
}
/**
* Size ++
*/
public void incrementSize()
{
this.size++;
}
/**
* Size --
*/
public void decrementSize()
{
if (size > 0)
this.size--;
}
//--------------------- State -------------------------
/**
* @return state of the top.
*/
public int state()
{
if (type >= 2 && size > 0)
return state.getChunk(size-1);
return 0;
}
/**
* @param level
* @return state.
*/
public int state(final int level)
{
if (type >= 2 && level < size)
return state.getChunk(level);
return 0;
}
/**
* Set state.
*
* @param val
*/
public void setState(final int val)
{
if (type >= 2 && size > 0)
state.setChunk(size-1, val);
}
/**
* Set state.
*
* @param val
* @param level
*/
public void setState(final int val, final int level)
{
if (type >= 2 && level < size)
state.setChunk(level, val);
}
//----------------------- Rotation ----------------------------
/**
* @return rotation of the top.
*/
public int rotation()
{
if (type >= 2 && size > 0)
return rotation.getChunk(size - 1);
return 0;
}
/**
* @param level
* @return rotation.
*/
public int rotation(final int level)
{
if (type >= 2 && level < size)
return rotation.getChunk(level);
return 0;
}
/**
* Set rotation.
*
* @param val
*/
public void setRotation(final int val)
{
if (type >= 2 && size > 0)
rotation.setChunk(size - 1, val);
}
/**
* Set rotation.
*
* @param val
* @param level
*/
public void setRotation(final int val, final int level)
{
if (type >= 2 && level < size)
rotation.setChunk(level, val);
}
//--------------------------- Value ---------------------------------
/**
* @return value of the top.
*/
public int value()
{
if (type >= 2 && size > 0)
return value.getChunk(size - 1);
return 0;
}
/**
* @param level
* @return value.
*/
public int value(final int level)
{
if (type >= 2 && level < size)
return value.getChunk(level);
return 0;
}
/**
* Set value.
*
* @param val
*/
public void setValue(final int val)
{
if (type >= 2 && size > 0)
value.setChunk(size - 1, val);
}
/**
* Set value.
*
* @param val
* @param level
*/
public void setValue(final int val, final int level)
{
if (type >= 2 && level < size)
value.setChunk(level, val);
}
//--------------------------- What ------------------------------
/**
* @return what.
*/
public int what()
{
if (size > 0)
return what.getChunk(size-1);
return 0;
}
/**
* @param level
* @return what.
*/
public int what(final int level)
{
if (level < size)
return what.getChunk(level);
return 0;
}
/**
* Set what.
*
* @param val
*/
public void setWhat(final int val)
{
if (size > 0)
what.setChunk(size-1, val);
}
/**
* Set what.
*
* @param val
* @param level
*/
public void setWhat(final int val, final int level)
{
if (level < size)
what.setChunk(level, val);
}
//--------------------------- Who -----------------------------
/**
* @return who.
*/
public int who()
{
if (size > 0)
{
if (type > 0)
return who.getChunk(size-1);
return what.getChunk(size-1);
}
return 0;
}
/**
* @return who.
*/
public int who(final int level)
{
if (level < size)
{
if (type > 0)
return who.getChunk(level);
return what.getChunk(level);
}
return 0;
}
/**
* Set who.
*
* @param val
*/
public void setWho(final int val)
{
if (size > 0)
{
if (type > 0)
who.setChunk(size-1, val);
}
}
/**
* Set who.
*
* @param val
*/
public void setWho(final int val, final int level)
{
if (level < size)
{
if (type > 0)
who.setChunk(level, val);
}
}
//--------------------------- Hidden Info All -----------------------------
/**
* @param pid The player id.
* @return True if the site has some hidden information for the player.
*/
public boolean isHidden(final int pid)
{
if (this.hidden != null && size > 0)
return this.hidden[pid].getChunk(size - 1) == 1;
return false;
}
/**
* @param pid The player id.
* @param level The level.
* @return True if the site has some hidden information for the player at that
* level.
*/
public boolean isHidden(final int pid, final int level)
{
if (this.hidden != null && level < size)
return this.hidden[pid].getChunk(level) == 1;
return false;
}
/**
* Set Hidden for a player.
*
* @param pid
*/
public void setHidden(final int pid, final boolean on)
{
if (this.hidden != null && size > 0)
this.hidden[pid].setChunk(size - 1, on ? 1 : 0);
}
/**
* Set Hidden for a player at a specific level.
*
* @param pid The player id.
* @param level The level.
*/
public void setHidden(final int pid, final int level, final boolean on)
{
if (this.hidden != null && level < size)
this.hidden[pid].setChunk(level, on ? 1 : 0);
}
//--------------------------- Hidden Info What -----------------------------
/**
* @param pid The player id.
* @return True if for the site the what information is hidden for the player.
*/
public boolean isHiddenWhat(final int pid)
{
if (this.hiddenWhat != null && size > 0)
return this.hiddenWhat[pid].getChunk(size - 1) == 1;
return false;
}
/**
* @param pid The player id.
* @param level The level.
* @return True if for the site the what information is hidden for the player at
* that level.
*/
public boolean isHiddenWhat(final int pid, final int level)
{
if (this.hiddenWhat != null && level < size)
return this.hiddenWhat[pid].getChunk(level) == 1;
return false;
}
/**
* Set what Hidden for a player.
*
* @param pid
*/
public void setHiddenWhat(final int pid, final boolean on)
{
if (this.hiddenWhat != null && size > 0)
this.hidden[pid].setChunk(size - 1, on ? 1 : 0);
}
/**
* Set What Hidden for a player at a specific level.
*
* @param pid The player id.
* @param level The level.
*/
public void setHiddenWhat(final int pid, final int level, final boolean on)
{
if (this.hiddenWhat != null && level < size)
this.hiddenWhat[pid].setChunk(level, on ? 1 : 0);
}
//--------------------------- Hidden Info Who -----------------------------
/**
* @param pid The player id.
* @return True if for the site the who information is hidden for the player.
*/
public boolean isHiddenWho(final int pid)
{
if (this.hiddenWho != null && size > 0)
return this.hiddenWho[pid].getChunk(size - 1) == 1;
return false;
}
/**
* @param pid The player id.
* @param level The level.
* @return True if for the site the who information is hidden for the player at
* that level.
*/
public boolean isHiddenWho(final int pid, final int level)
{
if (this.hiddenWho != null && level < size)
return this.hiddenWho[pid].getChunk(level) == 1;
return false;
}
/**
* Set Who Hidden for a player.
*
* @param pid
*/
public void setHiddenWho(final int pid, final boolean on)
{
if (this.hiddenWho != null && size > 0)
this.hiddenWho[pid].setChunk(size - 1, on ? 1 : 0);
}
/**
* Set Who Hidden for a player at a specific level.
*
* @param pid The player id.
* @param level The level.
*/
public void setHiddenWho(final int pid, final int level, final boolean on)
{
if (this.hiddenWho != null && level < size)
this.hiddenWho[pid].setChunk(level, on ? 1 : 0);
}
//--------------------------- Hidden Info State -----------------------------
/**
* @param pid The player id.
* @return True if for the site the state information is hidden for the player.
*/
public boolean isHiddenState(final int pid)
{
if (this.hiddenState != null && size > 0)
return this.hiddenState[pid].getChunk(size - 1) == 1;
return false;
}
/**
* @param pid The player id.
* @param level The level.
* @return True if for the site the state information is hidden for the player
* at that level.
*/
public boolean isHiddenState(final int pid, final int level)
{
if (this.hiddenState != null && level < size)
return this.hiddenState[pid].getChunk(level) == 1;
return false;
}
/**
* Set State Hidden for a player.
*
* @param pid
*/
public void setHiddenState(final int pid, final boolean on)
{
if (this.hiddenState != null && size > 0)
this.hiddenState[pid].setChunk(size - 1, on ? 1 : 0);
}
/**
* Set State Hidden for a player at a specific level.
*
* @param pid The player id.
* @param level The level.
*/
public void setHiddenState(final int pid, final int level, final boolean on)
{
if (this.hiddenState != null && level < size)
this.hiddenState[pid].setChunk(level, on ? 1 : 0);
}
//--------------------------- Hidden Info Rotation -----------------------------
/**
* @param pid The player id.
* @return True if for the site the rotation information is hidden for the
* player.
*/
public boolean isHiddenRotation(final int pid)
{
if (this.hiddenRotation != null && size > 0)
return this.hiddenRotation[pid].getChunk(size - 1) == 1;
return false;
}
/**
* @param pid The player id.
* @param level The level.
* @return True if for the site the rotation information is hidden for the
* player at that level.
*/
public boolean isHiddenRotation(final int pid, final int level)
{
if (this.hiddenRotation != null && level < size)
return this.hiddenRotation[pid].getChunk(level) == 1;
return false;
}
/**
* Set Rotation Hidden for a player.
*
* @param pid
*/
public void setHiddenRotation(final int pid, final boolean on)
{
if (this.hiddenRotation != null && size > 0)
this.hiddenRotation[pid].setChunk(size - 1, on ? 1 : 0);
}
/**
* Set Rotation Hidden for a player at a specific level.
*
* @param pid The player id.
* @param level The level.
*/
public void setHiddenRotation(final int pid, final int level, final boolean on)
{
if (this.hiddenRotation != null && level < size)
this.hiddenRotation[pid].setChunk(level, on ? 1 : 0);
}
//--------------------------- Hidden Info Count -----------------------------
/**
* @param pid The player id.
* @return True if for the site the count information is hidden for the player.
*/
public boolean isHiddenCount(final int pid)
{
if (this.hiddenCount != null && size > 0)
return this.hiddenCount[pid].getChunk(size - 1) == 1;
return false;
}
/**
* @param pid The player id.
* @param level The level.
* @return True if for the site the count information is hidden for the player
* at that level.
*/
public boolean isHiddenCount(final int pid, final int level)
{
if (this.hiddenCount != null && level < size)
return this.hiddenCount[pid].getChunk(level) == 1;
return false;
}
/**
* Set Count Hidden for a player.
*
* @param pid
*/
public void setHiddenCount(final int pid, final boolean on)
{
if (this.hiddenCount != null && size > 0)
this.hiddenCount[pid].setChunk(size - 1, on ? 1 : 0);
}
/**
* Set Count Hidden for a player at a specific level.
*
* @param pid The player id.
* @param level The level.
*/
public void setHiddenCount(final int pid, final int level, final boolean on)
{
if (this.hiddenCount != null && level < size)
this.hiddenCount[pid].setChunk(level, on ? 1 : 0);
}
//--------------------------- Hidden Info Value -----------------------------
/**
* @param pid The player id.
* @return True if for the site the value information is hidden for the player.
*/
public boolean isHiddenValue(final int pid)
{
if (this.hiddenValue != null && size > 0)
return this.hiddenValue[pid].getChunk(size - 1) == 1;
return false;
}
/**
* @param pid The player id.
* @param level The level.
* @return True if for the site the value information is hidden for the player
* at that level.
*/
public boolean isHiddenValue(final int pid, final int level)
{
if (this.hiddenValue != null && level < size)
return this.hiddenValue[pid].getChunk(level) == 1;
return false;
}
/**
* Set Value Hidden for a player.
*
* @param pid
*/
public void setHiddenValue(final int pid, final boolean on)
{
if (this.hiddenValue != null && size > 0)
this.hiddenValue[pid].setChunk(size - 1, on ? 1 : 0);
}
/**
* Set Value Hidden for a player at a specific level.
*
* @param pid The player id.
* @param level The level.
*/
public void setHiddenValue(final int pid, final int level, final boolean on)
{
if (this.hiddenValue != null && level < size)
this.hiddenValue[pid].setChunk(level, on ? 1 : 0);
}
}
| 21,766 | 20.051257 | 98 | java |
Ludii | Ludii-master/Common/src/main/collections/FVector.java | package main.collections;
import java.io.Serializable;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;
import gnu.trove.list.array.TFloatArrayList;
import gnu.trove.list.array.TIntArrayList;
/**
* Wrapper around an array of floats, with various "vectorised" methods
* that conveniently do the looping over a raw array for us.
*
* This class should be more efficient than something like TFloatArrayList
* when the dimensionality of vectors remain fixed. This is especially the
* case when various vector-wide math operations supported by this class
* are used, rather than manual loops over the data.
*
* Whenever we want to insert or cut out entries (modify the dimensionality),
* we have to construct new instances. This is less efficient.
*
* @author Dennis Soemers
*/
public final class FVector implements Serializable
{
//-------------------------------------------------------------------------
/** */
private static final long serialVersionUID = 1L;
/** Our raw array of floats */
protected final float[] floats;
//-------------------------------------------------------------------------
/**
* Creates a new vector of dimensionality d (filled with 0s)
* @param d
*/
public FVector(final int d)
{
floats = new float[d];
}
/**
* Creates a new vector of dimensionality d filled with the given value in
* all entries
* @param d
* @param fillValue
*/
public FVector(final int d, final float fillValue)
{
floats = new float[d];
Arrays.fill(floats, fillValue);
}
/**
* Creates a new vector with a copy of the given array of floats as data.
* If a copy is not necessary, use FVector.wrap(floats) or
* FVector(floats, true) instead!
* @param floats
*/
public FVector(final float[] floats)
{
this.floats = new float[floats.length];
System.arraycopy(floats, 0, this.floats, 0, floats.length);
}
/**
* Copy constructor
* @param other
*/
public FVector(final FVector other)
{
this(other.floats);
}
/**
* Constructor
* @param floats
*/
public FVector(final TFloatArrayList floats)
{
this.floats = floats.toArray();
}
/**
* Creates a new vector that "steals" the given array of floats if
* steal = true (directly uses it as raw data rather than copying it).
* @param floats
* @param steal
*/
public FVector(final float[] floats, final boolean steal)
{
if (!steal)
{
throw new IllegalArgumentException(
"steal must be true when instantiating a vector that "
+ "steals data");
}
this.floats = floats;
}
/**
* @return A copy of this vector (slightly shorter to type than
* the copy constructor)
*/
public FVector copy()
{
return new FVector(this);
}
//-------------------------------------------------------------------------
/**
* @param d Dimensionality
* @return A vector filled with 1s of the given dimensionality
*/
public static FVector ones(final int d)
{
final FVector ones = new FVector(d);
ones.fill(0, d, 1.f);
return ones;
}
/**
* @param d Dimensionality
* @return A vector filled with 0s of the given dimensionality
*/
public static FVector zeros(final int d)
{
return new FVector(d);
}
/**
* Note that this method will "steal" the array it is given (it will
* directly use the same reference for its data).
*
* @param floats
* @return A new vector that wraps around the given array of floats.
*/
public static FVector wrap(final float[] floats)
{
return new FVector(floats, true);
}
//-------------------------------------------------------------------------
/**
* @return Index of the maximum value in this vector
*/
public int argMax()
{
float max = Float.NEGATIVE_INFINITY;
final int d = floats.length;
int maxIdx = -1;
for (int i = 0; i < d; ++i)
{
if (floats[i] > max)
{
max = floats[i];
maxIdx = i;
}
}
return maxIdx;
}
/**
* @return Index of the maximum value in this vector, with random
* tie-breaking
*/
public int argMaxRand()
{
float max = Float.NEGATIVE_INFINITY;
final int d = floats.length;
int maxIdx = -1;
int numMaxFound = 0;
for (int i = 0; i < d; ++i)
{
final float val = floats[i];
if (val > max)
{
max = val;
maxIdx = i;
numMaxFound = 1;
}
else if
(
val == max &&
ThreadLocalRandom.current().nextInt() % ++numMaxFound == 0
)
{
maxIdx = i;
}
}
return maxIdx;
}
/**
* @return Index of the minimum value in this vector
*/
public int argMin()
{
float min = Float.POSITIVE_INFINITY;
final int d = floats.length;
int minIdx = -1;
for (int i = 0; i < d; ++i)
{
if (floats[i] < min)
{
min = floats[i];
minIdx = i;
}
}
return minIdx;
}
/**
* @return Index of the minimum value in this vector, with random
* tie-breaking
*/
public int argMinRand()
{
float min = Float.POSITIVE_INFINITY;
final int d = floats.length;
int minIdx = -1;
int numMinFound = 0;
for (int i = 0; i < d; ++i)
{
final float val = floats[i];
if (val < min)
{
min = val;
minIdx = i;
numMinFound = 1;
}
else if (val == min &&
ThreadLocalRandom.current().nextInt() % ++numMinFound == 0)
{
minIdx = i;
}
}
return minIdx;
}
/**
* @return Dimensionality of the vector
*/
public int dim()
{
return floats.length;
}
/**
* @param entry
* @return Entry at given index
*/
public float get(final int entry)
{
return floats[entry];
}
/**
* @return Maximum value in this vector
*/
public float max()
{
float max = Float.NEGATIVE_INFINITY;
final int d = floats.length;
for (int i = 0; i < d; ++i)
{
if (floats[i] > max)
{
max = floats[i];
}
}
return max;
}
/**
* @return Minimum value in this vector
*/
public float min()
{
float min = Float.POSITIVE_INFINITY;
final int d = floats.length;
for (int i = 0; i < d; ++i)
{
if (floats[i] < min)
{
min = floats[i];
}
}
return min;
}
/**
* @return Mean of all the entries in this vector
*/
public float mean()
{
return sum() / floats.length;
}
/**
* @return The norm (L2-norm) of the vector
*/
public double norm()
{
float sumSquares = 0.f;
final int d = floats.length;
for (int i = 0; i < d; ++i)
{
sumSquares += floats[i] * floats[i];
}
return Math.sqrt(sumSquares);
}
/**
* Sets the given entry to the given value
* @param entry
* @param value
*/
public void set(final int entry, final float value)
{
floats[entry] = value;
}
/**
* @return Sum of the values in this vector
*/
public float sum()
{
float sum = 0.f;
final int d = floats.length;
for (int i = 0; i < d; ++i)
{
sum += floats[i];
}
return sum;
}
//-------------------------------------------------------------------------
/**
* Replaces every entry in the vector with the absolute value of that entry.
* Note that this modifies the vector in-place
*/
public void abs()
{
final int d = floats.length;
for (int i = 0; i < d; ++i)
{
floats[i] = Math.abs(floats[i]);
}
}
/**
* Adds the given value to all entries. Note that this is a mathematical
* add operation, not an append operation!
* Note that this modifies the vector in-place
* @param value
*/
public void add(final float value)
{
final int d = floats.length;
for (int i = 0; i < d; ++i)
{
floats[i] += value;
}
}
/**
* Adds the entries in the given array to the corresponding entries
* in this vector.
* Note that this modifies the vector in-place.
* @param toAdd
*/
public void add(final float[] toAdd)
{
final int d = floats.length;
for (int i = 0; i < d; ++i)
{
floats[i] += toAdd[i];
}
}
/**
* Adds the given other vector to this one.
* Note that this modifies the vector in-place
* @param other
*/
public void add(final FVector other)
{
add(other.floats);
}
/**
* Adds the given value to one specific entry.
* Note that this modifies the vector in-place
* @param entry
* @param value
*/
public void addToEntry(final int entry, final float value)
{
floats[entry] += value;
}
/**
* Adds the given other vector, scaled by the given scalar, to this one.
* Note that this modifies this vector in-place, but does not modify the
* other vector.
*
* Using this method is slightly more efficient than copying the other
* vector, scaling it, and then adding it (because it avoids the copy),
* but still avoids modifying the other vector without a copy.
*
* @param other
* @param scalar
*/
public void addScaled(final FVector other, final float scalar)
{
final int d = floats.length;
final float[] otherFloats = other.floats;
for (int i = 0; i < d; ++i)
{
floats[i] += otherFloats[i] * scalar;
}
}
/**
* Divides the vector by the given scalar.
* Note that this modifies the vector in-place
* @param scalar
*/
public void div(final float scalar)
{
final int d = floats.length;
final float mult = 1.f / scalar;
for (int i = 0; i < d; ++i)
{
floats[i] *= mult;
}
}
/**
* Performs element-wise division by the other vector.
* Note that this modifies the vector in-place
* @param other
*/
public void elementwiseDivision(final FVector other)
{
final int d = floats.length;
final float[] otherFloats = other.floats;
for (int i = 0; i < d; ++i)
{
floats[i] /= otherFloats[i];
}
}
/**
* Computes the hadamard (i.e. element-wise) product with other vector.
* Note that this modifies the vector in-place
* @param other
*/
public void hadamardProduct(final FVector other)
{
final int d = floats.length;
final float[] otherFloats = other.floats;
for (int i = 0; i < d; ++i)
{
floats[i] *= otherFloats[i];
}
}
/**
* Takes the natural logarithm of every entry.
* Note that this modifies the vector in-place
*/
public void log()
{
final int d = floats.length;
for (int i = 0; i < d; ++i)
{
floats[i] = (float) Math.log(floats[i]);
}
}
/**
* Multiplies the vector with the given scalar.
* Note that this modifies the vector in-place
* @param scalar
*/
public void mult(final float scalar)
{
final int d = floats.length;
for (int i = 0; i < d; ++i)
{
floats[i] *= scalar;
}
}
/**
* Raises all entries in the vector to the given power.
* Note that this modifies the vector in-place
* @param power
*/
public void raiseToPower(final double power)
{
final int d = floats.length;
for (int i = 0; i < d; ++i)
{
floats[i] = (float) Math.pow(floats[i], power);
}
}
/**
* Normalises this vector such that it sums up to 1, by
* dividing all entries by the sum of entries.
*/
public void normalise()
{
final int d = floats.length;
float sum = 0.f;
for (int i = 0; i < d; ++i)
{
sum += floats[i];
}
if (sum == 0.f)
{
// Probably a single-element vector with a 0.f entry; just make it uniform
Arrays.fill(floats, 1.f / floats.length);
}
else
{
final float scalar = 1.f / sum;
for (int i = 0; i < d; ++i)
{
floats[i] *= scalar;
}
}
}
/**
* Replaces every entry in the vector with the sign of that entry (-1.f, 0.f, or +1.f).
* Note that this modifies the vector in-place
*/
public void sign()
{
final int d = floats.length;
for (int i = 0; i < d; ++i)
{
floats[i] = (floats[i]) > 0.f ? +1.f : (floats[i] < 0.f ? -1.f : 0.f);
}
}
/**
* Computes the softmax of this vector.
* Note that this modifies the vector in-place
*/
public void softmax()
{
final int d = floats.length;
// for numeric stability, subtract max entry before computing exponent
final float max = max();
double sumExponents = 0.0;
for (int i = 0; i < d; ++i)
{
final double exp = Math.exp(floats[i] - max);
sumExponents += exp;
floats[i] = (float) exp; // already put the exponent in the array
}
// now just need to divide all entries by sum of exponents
div((float) sumExponents);
}
/**
* This method assumes that the vector currently already encodes a discrete
* probability distribution, computed by a softmax. It incrementally updates
* the vector to account for the new information that the entry at the given
* index is invalid. The invalid entry will be set to 0.0, and any other
* entries will be updated such that the vector is equal as if the softmax
* had been computed from scratch without the invalid entry.
*
* @param invalidEntry
*/
public void updateSoftmaxInvalidate(final int invalidEntry)
{
final float invalidProb = floats[invalidEntry];
floats[invalidEntry] = 0.f;
if (invalidProb < 1.f)
{
final float scalar = 1.f / (1.f - invalidProb);
final int d = floats.length;
for (int i = 0; i < d; ++i)
{
floats[i] *= scalar;
}
}
}
/**
* Computes the softmax of this vector, with a temperature parameter
* (making it the same as computing a Boltzmann distribution).
*
* Temperature --> 0 puts all probability mass on max.
* Temperature = 1 gives regular softmax.
* Temperature > 1 gives more uniform distribution.
*
* Note that this modifies the vector in-place
*/
public void softmax(final double temperature)
{
final int d = floats.length;
// for numeric stability, subtract max entry before computing exponent
final float max = max();
double sumExponents = 0.0;
for (int i = 0; i < d; ++i)
{
final double exp = Math.exp((floats[i] - max) / temperature);
sumExponents += exp;
floats[i] = (float) exp; // already put the exponent in the array
}
// now just need to divide all entries by sum of exponents
div((float) sumExponents);
}
/**
* Takes the square root of every element in the vector
*/
public void sqrt()
{
final int d = floats.length;
for (int i = 0; i < d; ++i)
{
floats[i] = (float) Math.sqrt(floats[i]);
}
}
/**
* Subtracts the given value from all entries.
* Note that this modifies the vector in-place
* @param value
*/
public void subtract(final float value)
{
final int d = floats.length;
for (int i = 0; i < d; ++i)
{
floats[i] -= value;
}
}
/**
* Subtracts the entries in the given array from the corresponding entries
* in this vector.
* Note that this modifies the vector in-place.
* @param toSubtract
*/
public void subtract(final float[] toSubtract)
{
final int d = floats.length;
for (int i = 0; i < d; ++i)
{
floats[i] -= toSubtract[i];
}
}
/**
* Subtracts the given other vector from this one.
* Note that this modifies the vector in-place
* @param other
*/
public void subtract(final FVector other)
{
subtract(other.floats);
}
//-------------------------------------------------------------------------
/**
* Samples an index from the discrete distribution encoded by this vector.
* This can, for example, be used to sample from a vector that has been
* transformed into a distribution using softmax().
*
* NOTE: implementation assumes that the vector already is a proper
* distribution, i.e. that it sums up to 1. This is not verified.
*
* @return Index sampled from discrete distribution
*/
public int sampleFromDistribution()
{
final float rand = ThreadLocalRandom.current().nextFloat();
final int d = floats.length;
float accum = 0.f;
for (int i = 0; i < d; ++i)
{
accum += floats[i];
if (rand < accum)
{
return i;
}
}
// This should never happen mathematically,
// but guess it might sometimes due to floating point inaccuracies
for (int i = d - 1; i > 0; --i)
{
if (floats[i] > 0.f)
return i;
}
// This should REALLY never happen
return 0;
}
/**
* Samples an index proportional to the values in this vector. For example,
* if the value at index 0 is twice as large as all other values, index 0
* has twice as large a probability of being sampled as each of those other
* indices.
*
* This method does not require the vector to encode a probability
* distribution (the entries do not need to sum up to 1.0). However, if it
* DOES encode a probability distribution (if the entries do sum up to 1.0),
* every value will simply denote the probability of that index getting
* picked.
*
* Note that using this method to sample from a raw vector will lead to a
* different distribution than if it is used to sampled from a raw vector
* that has been transformed to a proper probability distribution using a
* non-linear transformation (such as softmax).
*
* Implicitly assumes that all values in the vector are >= 0.0, but does
* not check for this!
*
* @return An index sampled proportionally to the values in this vector.
*/
public int sampleProportionally()
{
final float sum = sum();
if (sum == 0.0)
{
// Special case: just sample uniformly if the values sum up to 0.0
return ThreadLocalRandom.current().nextInt(floats.length);
}
final float rand = ThreadLocalRandom.current().nextFloat();
final int d = floats.length;
float accum = 0.f;
for (int i = 0; i < d; ++i)
{
accum += floats[i] / sum;
if (rand < accum)
{
return i;
}
}
// this should never happen mathematically,
// but guess it might sometimes due to floating point inaccuracies
return d - 1;
}
//-------------------------------------------------------------------------
/**
* @param other
* @return Computes the dot product with the other vector
*/
public float dot(final FVector other)
{
float sum = 0.f;
final float[] otherFloats = other.floats;
final int d = floats.length;
for (int i = 0; i < d; ++i)
{
sum += floats[i] * otherFloats[i];
}
return sum;
}
/**
* @param sparseBinary
* @return Dot product between this vector and a TIntArrayList interpreted
* as a sparse binary vector
*/
public float dotSparse(final TIntArrayList sparseBinary)
{
float sum = 0.f;
final int numOnes = sparseBinary.size();
for (int i = 0; i < numOnes; ++i)
{
sum += floats[sparseBinary.getQuick(i)];
}
return sum;
}
/**
* @param sparseBinary
* @param offset We'll add this offset to every index
* @return Dot product between this vector and a TIntArrayList interpreted
* as a sparse binary vector
*/
public float dotSparse(final TIntArrayList sparseBinary, final int offset)
{
float sum = 0.f;
final int numOnes = sparseBinary.size();
for (int i = 0; i < numOnes; ++i)
{
sum += floats[sparseBinary.getQuick(i) + offset];
}
return sum;
}
/**
* @return Normalised entropy of the vector (assumed to be a distribution)
*/
public double normalisedEntropy()
{
final int dim = dim();
if (dim <= 1)
return 0.0;
// compute unnormalised entropy
// (in nats, unit won't matter after normalisation)
double entropy = 0.0;
for (int i = 0; i < dim; ++i)
{
final float prob = floats[i];
if (prob > 0.f)
entropy -= prob * Math.log(prob);
}
// normalise and return
return (entropy / Math.log(dim));
}
/**
* @return True if this vector contains at least one NaN entry. Useful for debugging.
*/
public boolean containsNaN()
{
for (int i = 0; i < floats.length; ++i)
{
if (Float.isNaN(floats[i]))
return true;
}
return false;
}
//-------------------------------------------------------------------------
/**
* Fills a block of this vector with the given value
* @param startInclusive Index to start filling (inclusive)
* @param endExclusive Index at which to end filling (exclusive)
* @param val Value to fill with
*/
public void fill
(
final int startInclusive,
final int endExclusive,
final float val
)
{
Arrays.fill(floats, startInclusive, endExclusive, val);
}
/**
* Copies floats from given vector into this vector
* @param src Vector to copy from
* @param srcPos Index in source vector from which to start copying
* @param destPos Index in this vector in which to start inserting
* @param length Number of entries to copy
*/
public void copyFrom
(
final FVector src,
final int srcPos,
final int destPos,
final int length
)
{
System.arraycopy(src.floats, srcPos, floats, destPos, length);
}
/**
* @param fromInclusive
* @param toExclusive
* @return New vector containing only the part in the given range of indices
*/
public FVector range(final int fromInclusive, final int toExclusive)
{
final float[] newArr = Arrays.copyOfRange(floats, fromInclusive, toExclusive);
return FVector.wrap(newArr);
}
//-------------------------------------------------------------------------
/**
* @param newValue
* @return A new vector with the given value appended as extra entry
*/
public FVector append(final float newValue)
{
final FVector newVector = new FVector(floats.length + 1);
System.arraycopy(floats, 0, newVector.floats, 0, floats.length);
newVector.floats[floats.length] = newValue;
return newVector;
}
/**
* @param entry
* @return A new vector where the given entry is cut out
*/
public FVector cut(final int entry)
{
return cut(entry, entry + 1);
}
/**
* @param startEntryInclusive
* @param endEntryExclusive
* @return A new vector where all entries between startEntryInclusive and
* endEntryExclusive are cut out
*/
public FVector cut
(
final int startEntryInclusive,
final int endEntryExclusive
)
{
final int newD =
floats.length - (endEntryExclusive - startEntryInclusive);
final FVector newVector = new FVector(newD);
System.arraycopy(floats, 0, newVector.floats, 0, startEntryInclusive);
System.arraycopy(
floats,
endEntryExclusive, newVector.floats,
startEntryInclusive, floats.length - endEntryExclusive);
return newVector;
}
/**
* @param index
* @param value
* @return A new vector where the given extra value is inserted at the
* given index
*/
public FVector insert(final int index, final float value)
{
FVector newVector = new FVector(floats.length + 1);
System.arraycopy(floats, 0, newVector.floats, 0, index);
newVector.floats[index] = value;
System.arraycopy(
floats,
index, newVector.floats, index + 1, floats.length - index);
return newVector;
}
/**
* @param index
* @param values
* @return A new vector with the given block of values inserted at the
* given index
*/
public FVector insert(final int index, final float[] values)
{
FVector newVector = new FVector(floats.length + values.length);
System.arraycopy(floats, 0, newVector.floats, 0, index);
System.arraycopy(values, 0, newVector.floats, index, values.length);
System.arraycopy(
floats,
index, newVector.floats,
index + values.length, floats.length - index);
return newVector;
}
/**
* @param a
* @param b
* @return The concatenation of two vectors a and b (new object)
*/
public static FVector concat(final FVector a, final FVector b)
{
final FVector concat = new FVector(a.dim() + b.dim());
System.arraycopy(a.floats, 0, concat.floats, 0, a.dim());
System.arraycopy(b.floats, 0, concat.floats, a.dim(), b.dim());
return concat;
}
//-------------------------------------------------------------------------
/**
* @param trueDist
* @param estDist
* @return Cross-entropy between a "true" and an "estimated" distribution
* (both discrete distributions encoded by float vectors)
*/
public static float crossEntropy(final FVector trueDist, final FVector estDist)
{
final int d = trueDist.dim();
final float[] trueFloats = trueDist.floats;
final float[] estFloats = estDist.floats;
float result = 0.f;
for (int i = 0; i < d; ++i)
{
result -= trueFloats[i] * Math.log(estFloats[i]);
}
return result;
}
/**
* @param a
* @param b
* @return A new vector containing the element-wise maximum value of
* the two given vectors for every entry.
*/
public static FVector elementwiseMax(final FVector a, final FVector b)
{
final int d = a.dim();
final float[] aFloats = a.floats;
final float[] bFloats = b.floats;
final float[] result = new float[d];
for (int i = 0; i < d; ++i)
{
result[i] = Math.max(aFloats[i], bFloats[i]);
}
return FVector.wrap(result);
}
/**
* NOTE: we compute KL divergence using natural log, so the unit will be
* nats rather than bits.
*
* @param trueDist
* @param estDist
* @return KL Divergence = D_{KL} (trueDist || estDist) between true and
* estimated discrete distributions
*/
public static float klDivergence
(
final FVector trueDist,
final FVector estDist
)
{
final int d = trueDist.dim();
final float[] trueFloats = trueDist.floats;
final float[] estFloats = estDist.floats;
float result = 0.f;
for (int i = 0; i < d; ++i)
{
if (trueFloats[i] != 0.f)
{
result -= trueFloats[i] * Math.log(estFloats[i] / trueFloats[i]);
}
}
return result;
}
/**
* @param vectors
* @return The mean vector from the given array of vectors
* (i.e. a vector with, at every entry i, the mean of the entries i of
* all vectors)
*/
public static FVector mean(final FVector[] vectors)
{
final int d = vectors[0].dim();
final float[] means = new float[d];
for (final FVector vector : vectors)
{
final float[] vals = vector.floats;
for (int i = 0; i < d; ++i)
{
means[i] += vals[i];
}
}
final FVector meanVector = FVector.wrap(means);
meanVector.mult(1.f / vectors.length);
return meanVector;
}
/**
* @param vectors
* @return The mean vector from the given list of vectors
* (i.e. a vector with, at every entry i, the mean of the entries i of
* all vectors)
*/
public static FVector mean(final List<FVector> vectors)
{
final int d = vectors.get(0).dim();
final float[] means = new float[d];
for (final FVector vector : vectors)
{
final float[] vals = vector.floats;
for (int i = 0; i < d; ++i)
{
means[i] += vals[i];
}
}
final FVector meanVector = FVector.wrap(means);
meanVector.mult(1.f / vectors.size());
return meanVector;
}
//-------------------------------------------------------------------------
/**
* Similar to numpy's linspace function. Creates a vector with evenly-spaced
* numbers over a specified interval.
*
* @param start First value of the vector
* @param stop Value to stop at
* @param num Number of values to generate
* @param endInclusive If true, the vector will include "stop" as last element
* @return Constructed vector
*/
public static FVector linspace
(
final float start,
final float stop,
final int num,
final boolean endInclusive
)
{
final FVector result = new FVector(num);
final float step = endInclusive ? (stop - start) / (num - 1) : (stop - start) / num;
for (int i = 0; i < num; ++i)
{
result.set(i, start + i * step);
}
return result;
}
//-------------------------------------------------------------------------
/**
* @return A string representation of this vector containing only numbers
* and commas, i.e. no kinds of brackets. Useful for writing vectors to
* files.
*/
public String toLine()
{
String result = "";
for (int i = 0; i < floats.length; ++i)
{
result += floats[i];
if (i < floats.length - 1)
{
result += ",";
}
}
return result;
}
@Override
public String toString()
{
return String.format("[%s]", toLine());
}
//-------------------------------------------------------------------------
@Override
public int hashCode()
{
final int prime = 31;
int result = 1;
result = prime * result + Arrays.hashCode(floats);
return result;
}
@Override
public boolean equals(final Object obj)
{
if (this == obj)
return true;
if (obj == null)
return false;
if (!(obj instanceof FVector))
return false;
final FVector other = (FVector) obj;
return (Arrays.equals(floats, other.floats));
}
//-------------------------------------------------------------------------
}
| 28,267 | 22.000814 | 88 | java |
Ludii | Ludii-master/Common/src/main/collections/FastArrayList.java | package main.collections;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.Arrays;
import java.util.ConcurrentModificationException;
import java.util.Iterator;
import java.util.Objects;
/**
* Less flexible, but faster alternative to ArrayList
*
* @author Dennis Soemers
* @param <E> Type of elements to contain in this list
*/
public class FastArrayList<E> implements Iterable<E>, Serializable
{
//-------------------------------------------------------------------------
/** */
private static final long serialVersionUID = 1L;
/** Our backing array */
transient protected Object[] data;
/** The size of the ArrayList (the number of elements it contains). */
private int size;
/** Default initial capacity. */
private static final int DEFAULT_CAPACITY = 10;
/** Used to check for concurrent modifications */
protected transient int modCount = 0;
//-------------------------------------------------------------------------
/**
* Constructor
*/
public FastArrayList()
{
this(DEFAULT_CAPACITY);
}
/**
* Constructor
* @param initialCapacity
*/
public FastArrayList(final int initialCapacity)
{
this.data = new Object[initialCapacity];
}
/**
* Constructor
* @param other
*/
public FastArrayList(final FastArrayList<E> other) {
data = Arrays.copyOf(other.data, other.size);
size = data.length;
}
/**
* Constructor
* @param elements
*/
public FastArrayList(@SuppressWarnings("unchecked") final E... elements)
{
data = Arrays.copyOf(elements, elements.length);
size = data.length;
}
//-------------------------------------------------------------------------
/**
* Adds object e to list
* @param e
*/
public void add(final E e)
{
++modCount;
ensureCapacityInternal(size + 1);
data[size++] = e;
}
/**
* Adds object e to list at a specific index.
*
* @param index
* @param e
*/
public void add(final int index, final E e)
{
modCount++;
final int s;
if ((s = size) == this.data.length)
grow(size + 1);
System.arraycopy(data, index, data, index + 1, s - index);
data[index] = e;
size = s + 1;
}
/**
* Adds all elements from the other given list
*
* @param other
*/
public void addAll(final FastArrayList<E> other)
{
final Object[] otherData = other.data;
++modCount;
final int numNew = other.size();
ensureCapacityInternal(size + numNew);
System.arraycopy(otherData, 0, data, size, numNew);
size += numNew;
}
/**
* @param index Index at which to remove element
* @return Remove item at the specified index and return.
*/
@SuppressWarnings("unchecked")
public E remove(final int index)
{
final E r = (E)data[index];
modCount++;
if (index != --size)
System.arraycopy(data, index + 1, data, index, size - index);
// Aid for garbage collection by releasing this pointer.
data[size] = null;
return r;
}
/**
* Removes element at given index, and returns it.
* Elements behind it are not shifted to the left, but only
* the last element is swapped into the given idx.
*
* @param index
* @return Removed element
*/
@SuppressWarnings("unchecked")
public E removeSwap(final int index)
{
final E r = (E)data[index];
modCount++;
if (index != --size)
data[index] = data[size];
// Aid for garbage collection by releasing this pointer.
data[size] = null;
return r;
}
/**
* Replaces the element at the specified position in this list with
* the specified element.
*
* @param index
* @param element
*/
public void set(final int index, final E element)
{
data[index] = element;
}
/**
* Clears the list
*/
public void clear()
{
++modCount;
for (int i = 0; i < size; ++i)
data[i] = null;
size = 0;
}
/**
* @param o
* @return True if o is contained in this list
*/
public boolean contains(final Object o)
{
return indexOf(o) >= 0;
}
/**
* {@inheritDoc}
*/
@Override
public boolean equals(final Object o)
{
if (o == this)
{
return true;
}
if (!(o instanceof FastArrayList))
{
return false;
}
final int expectedModCount = modCount;
try
{
@SuppressWarnings("unchecked")
final FastArrayList<E> other = (FastArrayList<E>) o;
if (size != other.size)
{
return false;
}
for (int i = 0; i < size; ++i)
{
if (!Objects.equals(data[i], other.data[i]))
{
return false;
}
}
}
finally
{
checkForComodification(expectedModCount);
}
return true;
}
/**
* {@inheritDoc}
*/
@Override
public int hashCode()
{
final int expectedModCount = modCount;
int hash = 1;
for (int i = 0; i < size; ++i)
{
final Object e = data[i];
hash = 31 * hash + (e == null ? 0 : e.hashCode());
}
checkForComodification(expectedModCount);
return hash;
}
/**
* @param i
* @return Element at index i. WARNING: does not check index bounds, may return
* null if i is greater than or equal to size but lower than capacity of backing array.
*/
@SuppressWarnings("unchecked")
public E get(final int i)
{
return (E) data[i];
}
/**
* @param o
* @return First index of o in this list, or -1 if it is not in the list
*/
public int indexOf(final Object o)
{
if (o == null)
{
for (int i = 0; i < size; i++)
if (data[i] == null)
return i;
}
else
{
for (int i = 0; i < size; i++)
if (o.equals(data[i]))
return i;
}
return -1;
}
/**
* @return Whether this list is currently empty
*/
public boolean isEmpty()
{
return size == 0;
}
/**
* Removes all elements from this list except for those that are also in the other list
* @param other
*/
public void retainAll(final FastArrayList<E> other)
{
batchRemove(other, true);
}
/**
* @return Current size of list
*/
public int size()
{
return size;
}
/**
* @return Copy of the backing array, limited to size
*/
public Object[] toArray() {
return Arrays.copyOf(data, size);
}
/**
* @param a
* @return Copy of the backing array (placed inside the given array if it fits)
*/
@SuppressWarnings("unchecked")
public <T> T[] toArray(final T[] a) {
if (a.length < size)
// Make a new array of a's runtime type, but my contents:
return (T[]) Arrays.copyOf(data, size, a.getClass());
System.arraycopy(data, 0, a, 0, size);
if (a.length > size)
a[size] = null;
return a;
}
//-------------------------------------------------------------------------
@Override
public String toString()
{
final int iMax = size - 1;
if (iMax == -1)
return "[]";
final StringBuilder b = new StringBuilder();
b.append('[');
for (int i = 0; ; i++) {
b.append(data[i]);
if (i == iMax)
return b.append(']').toString();
b.append(", ");
}
}
//-------------------------------------------------------------------------
@Override
public Iterator<E> iterator()
{
return new Itr();
}
/**
* Iterator for FastArrayList
* @author Dennis Soemers
*/
private class Itr implements Iterator<E>
{
private int cursor = 0;
@Override
public boolean hasNext()
{
return cursor != size;
}
@SuppressWarnings("unchecked")
@Override
public E next()
{
if (cursor >= data.length)
throw new ConcurrentModificationException();
return (E) data[cursor++];
}
}
//-------------------------------------------------------------------------
/**
* Removes a batch based on what's in the other list
* @param c
* @param complement If true, we keep elements in the other list.
* If false, we remove elements in the other list
*/
private void batchRemove(final FastArrayList<E> other, boolean complement)
{
final Object[] dataN = this.data;
int r = 0, w = 0;
try
{
for (; r < size; r++)
if (other.contains(dataN[r]) == complement)
dataN[w++] = dataN[r];
}
finally
{
modCount += size - w;
if (r != size)
{
System.arraycopy(dataN, r,
dataN, w,
size - r);
w += size - r;
}
if (w != size)
{
// clear to let GC do its work
for (int i = w; i < size; i++)
dataN[i] = null;
size = w;
}
}
}
/**
* Throws ConcurrentModificationException if modCount does not equal
* expected modCount
* @param expectedModCount
*/
private void checkForComodification(final int expectedModCount)
{
if (modCount != expectedModCount)
{
throw new ConcurrentModificationException();
}
}
/**
* Ensures we have at least the given amount of capacity
* @param minCapacity
*/
private void ensureCapacityInternal(final int minCapacity)
{
if (minCapacity - data.length > 0)
grow(minCapacity);
}
/**
* Grows the backing array
* @param minCapacity
*/
private void grow(final int minCapacity)
{
final int oldCapacity = data.length;
int newCapacity = oldCapacity + (oldCapacity >> 1);
if (newCapacity - minCapacity < 0)
newCapacity = minCapacity;
data = Arrays.copyOf(data, newCapacity);
}
//-------------------------------------------------------------------------
/**
* Serializes list
* @param s
* @throws java.io.IOException
*/
private void writeObject(final ObjectOutputStream s) throws java.io.IOException
{
final int expectedModCount = modCount;
s.defaultWriteObject();
// Write out size as capacity for behavioural compatibility with clone()
s.writeInt(size);
// Write out all elements in the proper order.
for (int i = 0; i < size; ++i)
{
s.writeObject(data[i]);
}
if (modCount != expectedModCount)
{
throw new ConcurrentModificationException();
}
}
/**
* Deserializes list
* @param s
* @throws java.io.IOException
* @throws ClassNotFoundException
*/
private void readObject(final ObjectInputStream s) throws java.io.IOException, ClassNotFoundException
{
data = new Object[10];
// Read in size, and any hidden stuff
s.defaultReadObject();
// Read in capacity
s.readInt(); // ignored
if (size > 0)
{
// be like clone(), allocate array based upon size not capacity
ensureCapacityInternal(size);
final Object[] a = data;
// Read in all elements in the proper order.
for (int i = 0; i < size; i++)
{
a[i] = s.readObject();
}
}
}
//-------------------------------------------------------------------------
}
| 12,291 | 22.458015 | 106 | java |
Ludii | Ludii-master/Common/src/main/collections/FastTIntArrayList.java | package main.collections;
import gnu.trove.list.array.TIntArrayList;
/**
* Even more optimised version of TIntArrayList; provides a
* faster copy constructor.
*
* @author Dennis Soemers
*/
public final class FastTIntArrayList extends TIntArrayList
{
//-------------------------------------------------------------------------
/** Shared empty array instance used for empty instances. */
private static final int[] EMPTY_ELEMENTDATA = {};
//-------------------------------------------------------------------------
/**
* Constructor
*/
public FastTIntArrayList()
{
super();
}
/**
* Constructor
* @param capacity
*/
public FastTIntArrayList(final int capacity)
{
super(capacity);
}
/**
* Optimised copy constructor
* @param other
*/
public FastTIntArrayList(final FastTIntArrayList other)
{
this.no_entry_value = -99;
final int length = other.size();
if (length > 0)
{
_data = new int[length];
System.arraycopy(other._data, 0, _data, 0, length);
_pos = length;
}
else
{
_data = EMPTY_ELEMENTDATA;
_pos = 0;
}
}
//-------------------------------------------------------------------------
/**
* Optimised implementation for adding all elements from another FastTIntArrayList
* @param other
* @return True if the collection was modified, false otherwise
*/
public boolean addAll(final FastTIntArrayList other)
{
final int numToAdd = other.size();
ensureCapacity(_pos + numToAdd);
System.arraycopy(other._data, 0, _data, _pos, numToAdd);
_pos += numToAdd;
return numToAdd > 0;
}
//-------------------------------------------------------------------------
}
| 1,720 | 20.78481 | 83 | java |
Ludii | Ludii-master/Common/src/main/collections/FastTLongArrayList.java | package main.collections;
import gnu.trove.list.array.TLongArrayList;
/**
* Even more optimised version of TLongArrayList; provides a
* faster copy constructor.
*
* @author Dennis Soemers
*/
public final class FastTLongArrayList extends TLongArrayList
{
//-------------------------------------------------------------------------
/** Shared empty array instance used for empty instances. */
private static final long[] EMPTY_ELEMENTDATA = {};
//-------------------------------------------------------------------------
/**
* Constructor
*/
public FastTLongArrayList()
{
super();
}
/**
* Optimised copy constructor
* @param other
*/
public FastTLongArrayList(final FastTLongArrayList other)
{
this.no_entry_value = -99L;
final int length = other.size();
if (length > 0)
{
_data = new long[length];
System.arraycopy(other._data, 0, _data, 0, length);
_pos = length;
}
else
{
_data = EMPTY_ELEMENTDATA;
_pos = 0;
}
}
//-------------------------------------------------------------------------
}
| 1,092 | 19.240741 | 79 | java |
Ludii | Ludii-master/Common/src/main/collections/ListStack.java | package main.collections;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import gnu.trove.list.array.TIntArrayList;
/**
* The three possible lists for each level of each site (for card
* games).
*
* @author Eric.Piette
*
*/
public final class ListStack implements Serializable
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/** 'what' */
public static final int TYPE_DEFAULT_STATE = 0;
/** 'what' + 'who' */
public static final int TYPE_PLAYER_STATE = 1;
/** 'what' + 'who' + 'state' */
public static final int TYPE_INDEX_STATE = 2;
/** Just store 'who' */
public static final int TYPE_INDEX_LOCAL_STATE = 3;
/**
* if
*
* type == 1 --> Player State
*
* type == 2 --> Index State
*
* type == 3 --> index local state, rotation, value.
*/
private final int type;
/** What ChunkSet. */
private final TIntArrayList what;
/** Who ChunkSet. */
private final TIntArrayList who;
/** State ChunkSet. */
private final TIntArrayList state;
/** Rotation ChunkSet. */
private final TIntArrayList rotation;
/** Value ChunkSet. */
private final TIntArrayList value;
/** Hidden Information. */
private final List<TIntArrayList> hidden;
/** Hidden What Information. */
private final List<TIntArrayList> hiddenWhat;
/** Hidden Who Information. */
private final List<TIntArrayList> hiddenWho;
/** Hidden Count Information. */
private final List<TIntArrayList> hiddenCount;
/** Hidden State Information. */
private final List<TIntArrayList> hiddenState;
/** Hidden Rotation Information. */
private final List<TIntArrayList> hiddenRotation;
/** Hidden Value Information. */
private final List<TIntArrayList> hiddenValue;
/** The number of components on the stack */
private int size;
/**
*
* Constructor.
*
* @param numComponents The number of components.
* @param numPlayers The number of players.
* @param numStates The number of states.
* @param numRotation The number of rotations.
* @param numValues The number of rotations.
* @param type The type of the chunkStack.
* @param hidden True if the game involves hidden info.
*/
public ListStack
(
final int numComponents,
final int numPlayers,
final int numStates,
final int numRotation,
final int numValues,
final int type,
final boolean hidden
)
{
this.type = type;
size = 0;
// What
what = new TIntArrayList();
// Who
if (type > 0)
who = new TIntArrayList();
else
who = null;
// State
if (type > 1)
state = new TIntArrayList();
else
state = null;
// Rotation and Value
if (type >= 2)
{
rotation = new TIntArrayList();
value = new TIntArrayList();
}
else
{
rotation = null;
value = null;
}
if(hidden)
{
this.hidden = new ArrayList<TIntArrayList>();
this.hidden.add(null);
for (int i = 1; i < numPlayers + 1; i++)
this.hidden.add(new TIntArrayList());
this.hiddenWhat = new ArrayList<TIntArrayList>();
this.hiddenWhat.add(null);
for (int i = 1; i < numPlayers + 1; i++)
this.hiddenWhat.add(new TIntArrayList());
if (type > 0)
{
this.hiddenWho = new ArrayList<TIntArrayList>();
this.hiddenWho.add(null);
for (int i = 1; i < numPlayers + 1; i++)
this.hiddenWho.add(new TIntArrayList());
if (type > 1)
{
this.hiddenState = new ArrayList<TIntArrayList>();
this.hiddenState.add(null);
for (int i = 1; i < numPlayers + 1; i++)
this.hiddenState.add(new TIntArrayList());
if (type >= 2)
{
this.hiddenCount = new ArrayList<TIntArrayList>();
this.hiddenCount.add(null);
for (int i = 1; i < numPlayers + 1; i++)
this.hiddenCount.add(new TIntArrayList());
this.hiddenRotation = new ArrayList<TIntArrayList>();
this.hiddenRotation.add(null);
for (int i = 1; i < numPlayers + 1; i++)
this.hiddenRotation.add(new TIntArrayList());
this.hiddenValue = new ArrayList<TIntArrayList>();
this.hiddenValue.add(null);
for (int i = 1; i < numPlayers + 1; i++)
this.hiddenValue.add(new TIntArrayList());
}
else
{
this.hiddenRotation = null;
this.hiddenCount = null;
this.hiddenValue = null;
}
}
else
{
this.hiddenState = null;
this.hiddenRotation = null;
this.hiddenCount = null;
this.hiddenValue = null;
}
}
else
{
this.hiddenWho = null;
this.hiddenState = null;
this.hiddenRotation = null;
this.hiddenCount = null;
this.hiddenValue = null;
}
}
else
{
this.hidden = null;
this.hiddenWhat = null;
this.hiddenWho = null;
this.hiddenCount = null;
this.hiddenState = null;
this.hiddenRotation = null;
this.hiddenValue = null;
}
}
/**
* Copy constructor
* @param other
*/
public ListStack(final ListStack other)
{
type = other.type;
size = other.size;
what = (other.what == null) ? null : new TIntArrayList(other.what);
who = (other.who == null) ? null : new TIntArrayList(other.who);
state = (other.state == null) ? null : new TIntArrayList(other.state);
rotation = (other.rotation == null) ? null : new TIntArrayList(other.rotation);
value = (other.value == null) ? null : new TIntArrayList(other.value);
if (other.hidden == null)
{
this.hidden = null;
this.hiddenWhat = null;
this.hiddenWho = null;
this.hiddenState = null;
this.hiddenRotation = null;
this.hiddenCount = null;
this.hiddenValue = null;
}
else
{
hidden = new ArrayList<TIntArrayList>(other.hidden);
hiddenWhat = new ArrayList<TIntArrayList>(other.hiddenWhat);
for (int i = 1; i < this.hidden.size(); ++i)
{
this.hidden.set(i, new TIntArrayList(other.hidden.get(i)));
this.hiddenWhat.set(i, new TIntArrayList(other.hiddenWhat.get(i)));
}
if (type > 0)
{
hiddenWho = new ArrayList<TIntArrayList>(other.hiddenWho);
for (int i = 1; i < this.hiddenWho.size(); ++i)
this.hiddenWho.set(i, new TIntArrayList(other.hiddenWho.get(i)));
if (type > 1)
{
hiddenState = new ArrayList<TIntArrayList>(other.hiddenState);
for (int i = 1; i < this.hiddenState.size(); ++i)
this.hiddenState.set(i, new TIntArrayList(other.hiddenState.get(i)));
if (type >= 2)
{
hiddenCount = new ArrayList<TIntArrayList>(other.hiddenCount);
for (int i = 1; i < this.hiddenCount.size(); ++i)
this.hiddenCount.set(i, new TIntArrayList(other.hiddenCount.get(i)));
hiddenRotation = new ArrayList<TIntArrayList>(other.hiddenRotation);
for (int i = 1; i < this.hiddenRotation.size(); ++i)
this.hiddenRotation.set(i, new TIntArrayList(other.hiddenRotation.get(i)));
hiddenValue = new ArrayList<TIntArrayList>(other.hiddenValue);
for (int i = 1; i < this.hiddenValue.size(); ++i)
this.hiddenValue.set(i, new TIntArrayList(other.hiddenValue.get(i)));
}
else
{
this.hiddenRotation = null;
this.hiddenCount = null;
this.hiddenValue = null;
}
}
else
{
this.hiddenState = null;
this.hiddenRotation = null;
this.hiddenCount = null;
this.hiddenValue = null;
}
}
else
{
this.hiddenWho = null;
this.hiddenState = null;
this.hiddenRotation = null;
this.hiddenCount = null;
this.hiddenValue = null;
}
}
}
/**
*
* @return what list.
*/
public TIntArrayList whatChunkSet()
{
return what;
}
/**
*
* @return who list.
*/
public TIntArrayList whoChunkSet()
{
return who;
}
/**
*
* @return local state list.
*/
public TIntArrayList stateChunkSet()
{
return state;
}
/**
*
* @return rotation state list.
*/
public TIntArrayList rotationChunkSet()
{
return rotation;
}
/**
*
* @return value state list.
*/
public TIntArrayList valueChunkSet()
{
return value;
}
/**
*
* @return hidden list for each player.
*/
public List<TIntArrayList> hiddenList()
{
return hidden;
}
/**
*
* @return hidden what list for each player.
*/
public List<TIntArrayList> hiddenWhatList()
{
return hiddenWhat;
}
/**
*
* @return hidden who list for each player.
*/
public List<TIntArrayList> hiddenWhoList()
{
return hiddenWho;
}
/**
*
* @return hidden Count list for each player.
*/
public List<TIntArrayList> hiddenCountList()
{
return hiddenCount;
}
/**
*
* @return hidden Rotation list for each player.
*/
public List<TIntArrayList> hiddenRotationList()
{
return hiddenRotation;
}
/**
*
* @return hidden State list for each player.
*/
public List<TIntArrayList> hiddenStateList()
{
return hiddenState;
}
/**
*
* @return hidden Value list for each player.
*/
public List<TIntArrayList> hiddenValueList()
{
return hiddenValue;
}
/**
* @return Current size of the stack
*/
public int size()
{
return size;
}
/**
* Size ++
*/
public void incrementSize()
{
size++;
}
/**
* Size --
*/
public void decrementSize()
{
if (size > 0)
size--;
}
/**
* To remove the top site on the stack.
*/
public void remove()
{
if(what != null && what.size() > 0 )
what.removeAt(what.size()-1);
if(who != null && who.size() > 0 )
who.removeAt(who.size()-1);
if(state != null && state.size() > 0 )
state.removeAt(state.size()-1);
if(rotation != null && rotation.size() > 0 )
rotation.removeAt(rotation.size()-1);
if(value != null && value.size() > 0 )
value.removeAt(value.size()-1);
}
/**
* To remove the a site at a specific level.
* @param level The level.
*/
public void remove(final int level)
{
if(what != null && what.size() > level && what.size() > 0)
what.removeAt(level);
if(who != null && who.size() > level && who.size() > 0)
who.removeAt(level);
if(state != null && state.size() > level && state.size() > 0)
state.removeAt(level);
if(rotation != null && rotation.size() > level && rotation.size() > 0)
rotation.removeAt(level);
if(value != null && value.size() > level && value.size() > 0)
value.removeAt(level);
}
//--------------------- State -------------------------
/**
* @return state of the top.
*/
public int state()
{
if (type >= 2 && size > 0 && !state.isEmpty())
return state.getQuick(state.size() -1);
return 0;
}
/**
* @param level
* @return state.
*/
public int state(final int level)
{
if (type >= 2 && level < state.size() && level < size)
return state.getQuick(level);
return 0;
}
/**
* Set state.
*
* @param val
*/
public void setState(final int val)
{
if(type >= 2 && size > 0)
state.add(val);
}
/**
* Set state.
*
* @param val
* @param level
*/
public void setState(final int val, final int level)
{
if(type >= 2 && level < state.size() && level < size)
state.set(level, val);
}
//----------------------- Rotation ----------------------------
/**
* @return rotation of the top.
*/
public int rotation()
{
if (type >= 2 && size > 0 && !rotation.isEmpty() && rotation != null)
return rotation.getQuick(rotation.size() - 1);
return 0;
}
/**
* @param level
* @return rotation.
*/
public int rotation(final int level)
{
if (type >= 2 && level < rotation.size() && rotation != null && level < size)
return rotation.getQuick(level);
return 0;
}
/**
* Set rotation.
*
* @param val
*/
public void setRotation(final int val)
{
if (type >= 2 && size > 0)
rotation.add(val);
}
/**
* Set rotation.
*
* @param val
* @param level
*/
public void setRotation(final int val, final int level)
{
if (type >= 2 && level < rotation.size() && level < size)
rotation.set(level, val);
}
//--------------------------- Value ---------------------------------
/**
* @return value of the top.
*/
public int value()
{
if (type >= 2 && size > 0 && !value.isEmpty() && value != null)
return value.getQuick(value.size() - 1);
return 0;
}
/**
* @param level
* @return value.
*/
public int value(final int level)
{
if (type >= 2 && level < value.size() && value != null && level < size)
return value.getQuick(level);
return 0;
}
/**
* Set value.
*
* @param val
*/
public void setValue(final int val)
{
if (type >= 2 && size > 0)
value.add(val);
}
/**
* Set value.
*
* @param val
* @param level
*/
public void setValue(final int val, final int level)
{
if (type >= 2 && level < value.size() && level < size)
value.set(level, val);
}
//--------------------------- What ------------------------------
/**
* @return what.
*/
public int what()
{
if (size > 0 && !what.isEmpty())
return what.getQuick(what.size()-1);
return 0;
}
/**
* @param level
* @return what.
*/
public int what(final int level)
{
if (level < size && level < what.size())
return what.getQuick(level);
return 0;
}
/**
* Set what.
*
* @param val
*/
public void setWhat(final int val)
{
what.add(val);
}
/**
* Set what.
*
* @param val
* @param level
*/
public void setWhat(final int val, final int level)
{
if(level < size && level < what.size())
what.set(level, val);
}
/**
* Set what.
*
* @param val
* @param level
*/
public void insertWhat(final int val, final int level)
{
if (level < size && level < what.size())
what.insert(level, val);
}
//--------------------------- Who -----------------------------
/**
* @return who.
*/
public int who()
{
if (size > 0)
{
if (type > 0 && !who.isEmpty())
return who.getQuick(size-1);
return 0;
}
return 0;
}
/**
* @return who.
*/
public int who(final int level)
{
if (level < size)
{
if (type > 0 && level < who.size())
return who.getQuick(level);
return 0;
}
return 0;
}
/**
* Set who.
*
* @param val
*/
public void setWho(final int val)
{
if (type > 0)
who.add(val);
}
/**
* Set who.
*
* @param val
*/
public void setWho(final int val, final int level)
{
if (level < size && level < who.size() && type > 0)
who.set(level, val);
}
//--------------------------- Hidden Info All -----------------------------
/**
* @param pid The player id.
* @return True if the site has some hidden information for the player.
*/
public boolean isHidden(final int pid)
{
if (this.hidden != null && size > 0)
return hidden.get(pid).getQuick(size - 1) == 1;
return false;
}
/**
* @param pid The player id.
* @param level The level.
* @return True if the site has some hidden information for the player at that
* level.
*/
public boolean isHidden(final int pid, final int level)
{
if (this.hidden != null && level < size)
return hidden.get(pid).getQuick(level) == 1;
return false;
}
/**
* Set Hidden for a player.
*
* @param pid
*/
public void setHidden(final int pid, final boolean on)
{
if (this.hidden != null && size > 0)
hidden.get(pid).set(size - 1, on ? 1 : 0);
}
/**
* Set Hidden for a player at a specific level.
*
* @param pid The player id.
* @param level The level.
*/
public void setHidden(final int pid, final int level, final boolean on)
{
if (this.hidden != null && level < size)
hidden.get(pid).set(level, on ? 1 : 0);
}
//--------------------------- Hidden Info What -----------------------------
/**
* @param pid The player id.
* @return True if for the site the what information is hidden for the player.
*/
public boolean isHiddenWhat(final int pid)
{
if (this.hiddenWhat != null && size > 0)
return hiddenWhat.get(pid).getQuick(size - 1) == 1;
return false;
}
/**
* @param pid The player id.
* @param level The level.
* @return True if for the site the what information is hidden for the player at
* that level.
*/
public boolean isHiddenWhat(final int pid, final int level)
{
if (this.hiddenWhat != null && level < size)
return hiddenWhat.get(pid).getQuick(level) == 1;
return false;
}
/**
* Set what Hidden for a player.
*
* @param pid
*/
public void setHiddenWhat(final int pid, final boolean on)
{
if (this.hiddenWhat != null && size > 0)
this.hidden.get(pid).setQuick(size - 1, on ? 1 : 0);
}
/**
* Set What Hidden for a player at a specific level.
*
* @param pid The player id.
* @param level The level.
*/
public void setHiddenWhat(final int pid, final int level, final boolean on)
{
if (this.hiddenWhat != null && level < size)
this.hiddenWhat.get(pid).setQuick(level, on ? 1 : 0);
}
//--------------------------- Hidden Info Who -----------------------------
/**
* @param pid The player id.
* @return True if for the site the who information is hidden for the player.
*/
public boolean isHiddenWho(final int pid)
{
if (this.hiddenWho != null && size > 0)
return hiddenWho.get(pid).getQuick(size - 1) == 1;
return false;
}
/**
* @param pid The player id.
* @param level The level.
* @return True if for the site the who information is hidden for the player at
* that level.
*/
public boolean isHiddenWho(final int pid, final int level)
{
if (this.hiddenWho != null && level < size)
return hiddenWho.get(pid).getQuick(level) == 1;
return false;
}
/**
* Set Who Hidden for a player.
*
* @param pid
*/
public void setHiddenWho(final int pid, final boolean on)
{
if (this.hiddenWho != null && size > 0)
this.hiddenWho.get(pid).setQuick(size - 1, on ? 1 : 0);
}
/**
* Set Who Hidden for a player at a specific level.
*
* @param pid The player id.
* @param level The level.
*/
public void setHiddenWho(final int pid, final int level, final boolean on)
{
if (this.hiddenWho != null && level < size)
hiddenWho.get(pid).set(level, on ? 1 : 0);
}
//--------------------------- Hidden Info State -----------------------------
/**
* @param pid The player id.
* @return True if for the site the state information is hidden for the player.
*/
public boolean isHiddenState(final int pid)
{
if (this.hiddenState != null && size > 0)
return hiddenState.get(pid).getQuick(size - 1) == 1;
return false;
}
/**
* @param pid The player id.
* @param level The level.
* @return True if for the site the state information is hidden for the player
* at that level.
*/
public boolean isHiddenState(final int pid, final int level)
{
if (this.hiddenState != null && level < size)
return hiddenState.get(pid).getQuick(level) == 1;
return false;
}
/**
* Set State Hidden for a player.
*
* @param pid
*/
public void setHiddenState(final int pid, final boolean on)
{
if (this.hiddenState != null && size > 0)
this.hiddenState.get(pid).setQuick(size - 1, on ? 1 : 0);
}
/**
* Set State Hidden for a player at a specific level.
*
* @param pid The player id.
* @param level The level.
*/
public void setHiddenState(final int pid, final int level, final boolean on)
{
if (this.hiddenState != null && level < size)
this.hiddenState.get(pid).setQuick(level, on ? 1 : 0);
}
//--------------------------- Hidden Info Rotation -----------------------------
/**
* @param pid The player id.
* @return True if for the site the rotation information is hidden for the
* player.
*/
public boolean isHiddenRotation(final int pid)
{
if (this.hiddenRotation != null && size > 0)
return hiddenRotation.get(pid).getQuick(size - 1) == 1;
return false;
}
/**
* @param pid The player id.
* @param level The level.
* @return True if for the site the rotation information is hidden for the
* player at that level.
*/
public boolean isHiddenRotation(final int pid, final int level)
{
if (this.hiddenRotation != null && level < size)
return hiddenRotation.get(pid).getQuick(level) == 1;
return false;
}
/**
* Set Rotation Hidden for a player.
*
* @param pid
*/
public void setHiddenRotation(final int pid, final boolean on)
{
if (this.hiddenRotation != null && size > 0)
this.hiddenRotation.get(pid).setQuick(size - 1, on ? 1 : 0);
}
/**
* Set Rotation Hidden for a player at a specific level.
*
* @param pid The player id.
* @param level The level.
*/
public void setHiddenRotation(final int pid, final int level, final boolean on)
{
if (this.hiddenRotation != null && level < size)
this.hiddenRotation.get(pid).setQuick(level, on ? 1 : 0);
}
//--------------------------- Hidden Info Count -----------------------------
/**
* @param pid The player id.
* @return True if for the site the count information is hidden for the player.
*/
public boolean isHiddenCount(final int pid)
{
if (this.hiddenCount != null && size > 0)
return hiddenCount.get(pid).getQuick(size - 1) == 1;
return false;
}
/**
* @param pid The player id.
* @param level The level.
* @return True if for the site the count information is hidden for the player
* at that level.
*/
public boolean isHiddenCount(final int pid, final int level)
{
if (this.hiddenCount != null && level < size)
return hiddenCount.get(pid).getQuick(level) == 1;
return false;
}
/**
* Set Count Hidden for a player.
*
* @param pid
*/
public void setHiddenCount(final int pid, final boolean on)
{
if (this.hiddenCount != null && size > 0)
this.hiddenCount.get(pid).setQuick(size - 1, on ? 1 : 0);
}
/**
* Set Count Hidden for a player at a specific level.
*
* @param pid The player id.
* @param level The level.
*/
public void setHiddenCount(final int pid, final int level, final boolean on)
{
if (this.hiddenCount != null && level < size)
this.hiddenCount.get(pid).setQuick(level, on ? 1 : 0);
}
//--------------------------- Hidden Info Value -----------------------------
/**
* @param pid The player id.
* @return True if for the site the value information is hidden for the player.
*/
public boolean isHiddenValue(final int pid)
{
if (this.hiddenValue != null && size > 0)
return hiddenValue.get(pid).getQuick(size - 1) == 1;
return false;
}
/**
* @param pid The player id.
* @param level The level.
* @return True if for the site the value information is hidden for the player
* at that level.
*/
public boolean isHiddenValue(final int pid, final int level)
{
if (this.hiddenValue != null && level < size)
return hiddenValue.get(pid).getQuick(level) == 1;
return false;
}
/**
* Set Value Hidden for a player.
*
* @param pid
*/
public void setHiddenValue(final int pid, final boolean on)
{
if (this.hiddenValue != null && size > 0)
this.hiddenValue.get(pid).setQuick(size - 1, on ? 1 : 0);
}
/**
* Set Value Hidden for a player at a specific level.
*
* @param pid The player id.
* @param level The level.
*/
public void setHiddenValue(final int pid, final int level, final boolean on)
{
if (this.hiddenValue != null && level < size)
hiddenValue.get(pid).set(level, on ? 1 : 0);
}
}
| 23,242 | 20.521296 | 82 | java |
Ludii | Ludii-master/Common/src/main/collections/ListUtils.java | package main.collections;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;
import java.util.function.Predicate;
import gnu.trove.list.array.TFloatArrayList;
import gnu.trove.list.array.TIntArrayList;
/**
* Utility methods for lists
*
* @author Dennis Soemers
*/
public class ListUtils
{
//-------------------------------------------------------------------------
/**
* Constructor
*/
private ListUtils()
{
// Should not be used
}
//-------------------------------------------------------------------------
/**
* @param list A single list
* @return A list containing all possible permutations of the given list
*/
public static List<TIntArrayList> generatePermutations(final TIntArrayList list)
{
if (list.size() == 0)
{
List<TIntArrayList> perms = new ArrayList<TIntArrayList>(1);
perms.add(new TIntArrayList(0, list.getNoEntryValue()));
return perms;
}
final int lastElement = list.removeAt(list.size() - 1);
final List<TIntArrayList> perms = new ArrayList<TIntArrayList>();
final List<TIntArrayList> smallPerms = generatePermutations(list);
for (final TIntArrayList smallPerm : smallPerms)
{
for (int i = smallPerm.size(); i >= 0; --i)
{
TIntArrayList newPerm = new TIntArrayList(smallPerm);
newPerm.insert(i, lastElement);
perms.add(newPerm);
}
}
return perms;
}
/**
* NOTE: it's theoretically possible that we generate duplicate permutations, but for large lists
* and a small number of samples this is very unlikely.
*
* @param list A single list
* @param numPermutations Number of permutations we want to generate
* @return A list containing a sample of all possible permutations of the given list (with replacement)
*/
public static List<TIntArrayList> samplePermutations(final TIntArrayList list, final int numPermutations)
{
final List<TIntArrayList> perms = new ArrayList<TIntArrayList>(numPermutations);
for (int i = 0; i < numPermutations; ++i)
{
final TIntArrayList randomPerm = new TIntArrayList(list);
randomPerm.shuffle(ThreadLocalRandom.current());
perms.add(randomPerm);
}
return perms;
}
/**
* NOTE: this may not be the most efficient implementation. Do NOT use
* for performance-sensitive situations
*
* @param optionsLists List of n lists of options.
* @return List containing all possible n-tuples. Officially, this is called Cartesian Product :)
*/
public static <E> List<List<E>> generateTuples(final List<List<E>> optionsLists)
{
final List<List<E>> allTuples = new ArrayList<List<E>>();
if (optionsLists.size() > 0)
{
final List<E> firstEntryOptions = optionsLists.get(0);
final List<List<E>> remainingOptionsLists = new ArrayList<List<E>>();
for (int i = 1; i < optionsLists.size(); ++i)
{
remainingOptionsLists.add(optionsLists.get(i));
}
final List<List<E>> nMinOneTuples = generateTuples(remainingOptionsLists);
for (int i = 0; i < firstEntryOptions.size(); ++i)
{
for (final List<E> nMinOneTuple : nMinOneTuples)
{
final List<E> newTuple = new ArrayList<E>(nMinOneTuple);
newTuple.add(0, firstEntryOptions.get(i));
allTuples.add(newTuple);
}
}
}
else
{
allTuples.add(new ArrayList<E>(0));
}
return allTuples;
}
//-------------------------------------------------------------------------
/**
* @param maxExclusive
* @return Exactly like python's range() function, generates a list from 0 to maxExclusive
*/
public static TIntArrayList range(final int maxExclusive)
{
final TIntArrayList list = new TIntArrayList(maxExclusive);
for (int i = 0; i < maxExclusive; ++i)
{
list.add(i);
}
return list;
}
//-------------------------------------------------------------------------
/**
* @param list
* @return Index of maximum entry in the list
* (breaks ties by taking the lowest index).
*/
public static int argMax(final TFloatArrayList list)
{
int argMax = 0;
float maxVal = list.getQuick(0);
for (int i = 1; i < list.size(); ++i)
{
final float val = list.getQuick(i);
if (val > maxVal)
{
maxVal = val;
argMax = i;
}
}
return argMax;
}
//-------------------------------------------------------------------------
/**
* Removes element at given index. Does not shift all subsequent elements,
* but only swaps the last element into the removed index.
* @param <E>
* @param list
* @param idx
*/
public static <E> void removeSwap(final List<E> list, final int idx)
{
final int lastIdx = list.size() - 1;
list.set(idx, list.get(lastIdx));
list.remove(lastIdx);
}
/**
* Removes element at given index. Does not shift all subsequent elements,
* but only swaps the last element into the removed index.
* @param list
* @param idx
*/
public static void removeSwap(final TIntArrayList list, final int idx)
{
final int lastIdx = list.size() - 1;
list.setQuick(idx, list.getQuick(lastIdx));
list.removeAt(lastIdx);
}
/**
* Removes element at given index. Does not shift all subsequent elements,
* but only swaps the last element into the removed index.
* @param list
* @param idx
*/
public static void removeSwap(final TFloatArrayList list, final int idx)
{
final int lastIdx = list.size() - 1;
list.setQuick(idx, list.getQuick(lastIdx));
list.removeAt(lastIdx);
}
/**
* Removes all elements from the given list that satisfy the given predicate, using
* remove-swap (which means that the order of the list may not be preserved).
* @param list
* @param predicate
*/
public static <E> void removeSwapIf(final List<E> list, final Predicate<E> predicate)
{
for (int i = list.size() - 1; i >= 0; --i)
{
if (predicate.test(list.get(i)))
removeSwap(list, i);
}
}
//-------------------------------------------------------------------------
/**
* Generates all combinations of given target combination-length from
* the given list of candidates (without replacement, order does not
* matter). Typical initial call would look like:<br>
* <br>
* <code>generateAllCombinations(candidates, targetLength, 0, new int[targetLength], outList)</code>
*
* @param candidates
* @param combinationLength
* @param startIdx Index at which to start filling up results array
* @param currentCombination (partial) combination constructed so far
* @param combinations List of all result combinations
*/
public static void generateAllCombinations
(
final TIntArrayList candidates,
final int combinationLength,
final int startIdx,
final int[] currentCombination,
final List<TIntArrayList> combinations
)
{
if (combinationLength == 0)
{
combinations.add(new TIntArrayList(currentCombination));
}
else
{
for (int i = startIdx; i <= candidates.size() - combinationLength; ++i)
{
currentCombination[currentCombination.length - combinationLength] = candidates.getQuick(i);
generateAllCombinations(candidates, combinationLength - 1, i + 1, currentCombination, combinations);
}
}
}
/**
* @param numItems Number of items from which we can pick
* @param combinationLength How many items should we pick per combination
* @return How many combinations of N items are there, if we sample with replacement
* (and order does not matter)?
*/
public static final int numCombinationsWithReplacement(final int numItems, final int combinationLength)
{
// We have to compute:
//
// (n + r - 1)!
// -------------
// r! * (n - 1)!
//
// Where n = numItems, r = combinationLength
long numerator = 1L;
long denominator = 1L;
if (combinationLength >= (numItems - 1))
{
// Divide numerator and denominator by r!
// Retain (n - 1)! as denominator
// Retain (r + 1) * (r + 2) * (r + 3) * ... * (n + r - 1) as numerator
for (int i = combinationLength + 1; i <= (numItems + combinationLength - 1); ++i)
{
numerator *= i;
}
for (int i = 1; i <= (numItems - 1); ++i)
{
denominator *= i;
}
}
else
{
// Divide numerator and denominator by (n - 1)!
// Retain r! as denominator
// Retain n * (n + 1) * (n + 2) * ... * (n + r - 1) as
for (int i = numItems; i <= (numItems + combinationLength - 1); ++i)
{
numerator *= i;
}
for (int i = 1; i <= combinationLength; ++i)
{
denominator *= i;
}
}
return (int) (numerator / denominator);
}
/**
* @param items
* @param combinationLength
* @return All possible combinations of n selections of given array of items,
* sampled with replacement. Order does not matter.
*/
public static Object[][] generateCombinationsWithReplacement
(
final Object[] items,
final int combinationLength
)
{
if (combinationLength == 0)
return new Object[0][];
final int numCombinations = numCombinationsWithReplacement(items.length, combinationLength);
final Object[][] combinations = new Object[numCombinations][combinationLength];
int nextCombIdx = 0;
final int[] indices = new int[combinationLength];
int idxToIncrement = indices.length - 1;
while (true)
{
final Object[] arr = new Object[combinationLength];
for (int i = 0; i < indices.length; ++i)
{
arr[i] = items[indices[i]];
}
combinations[nextCombIdx++] = arr;
while (idxToIncrement >= 0)
{
if (++indices[idxToIncrement] == items.length)
{
indices[idxToIncrement--] = 0;
}
else
{
break;
}
}
if (idxToIncrement < 0)
break;
// Order does not matter
for (int i = idxToIncrement + 1; i < indices.length; ++i)
{
indices[i] = indices[idxToIncrement];
}
idxToIncrement = indices.length - 1;
}
if (nextCombIdx != numCombinations)
System.err.println("ERROR: Expected to generate " + numCombinations + " combinations, but only generated " + nextCombIdx);
return combinations;
}
//-------------------------------------------------------------------------
/**
* NOTE: this should only be used for diagnosing performance issues / temporary code!
* This uses reflection and is way too slow and should not be necessary for
* any permanent code.
*
* @param l
* @return The capacity (maximum size before requiring re-allocation) of given ArrayList
*/
public static int getCapacity(final ArrayList<?> l)
{
try
{
final Field dataField = ArrayList.class.getDeclaredField("elementData");
dataField.setAccessible(true);
return ((Object[]) dataField.get(l)).length;
}
catch
(
final NoSuchFieldException |
SecurityException |
IllegalArgumentException |
IllegalAccessException exception
)
{
exception.printStackTrace();
}
return -1;
}
//-------------------------------------------------------------------------
}
| 10,932 | 25.536408 | 125 | java |
Ludii | Ludii-master/Common/src/main/collections/Pair.java | package main.collections;
/**
* String pair (key, value) for metadata.
* @author Michel--Delétie Cyprien
*/
public class Pair<A,B>
{
private final A key;
private final B value;
/**
* Constructor
* @param key
* @param value
*/
public Pair(final A key, final B value)
{
this.key = key;
this.value = value;
}
/**
* @return Pair's first element (the key)
*/
public A key()
{
return key;
}
/**
* @return Pair's second element (the value)
*/
public B value()
{
return value;
}
}
| 522 | 12.410256 | 45 | java |
Ludii | Ludii-master/Common/src/main/collections/ScoredInt.java | package main.collections;
import java.util.Comparator;
/**
* A pair of a score (double) and an object (of type int).
*
* The ASCENDING or DESCENDING comparator objects from this class can be used for sorting based on scores.
*
* @author Dennis Soemers
*/
public class ScoredInt
{
private final int object;
private final double score;
/**
* Constructor
*
* @param object
* @param score
*/
public ScoredInt(final int object, final double score)
{
this.object = object;
this.score = score;
}
/**
* @return The object
*/
public int object()
{
return object;
}
/**
* @return The score
*/
public double score()
{
return score;
}
/**
* Can be used for sorting in ascending order (with respect to scores)
*/
public static Comparator<ScoredInt> ASCENDING =
new Comparator<ScoredInt>()
{
@Override
public int compare(final ScoredInt o1, final ScoredInt o2)
{
if (o1.score < o2.score)
return -1;
if (o1.score > o2.score)
return 1;
return 0;
}
};
/**
* Can be used for sorting in ascending order (with respect to scores)
*/
public static Comparator<ScoredInt> DESCENDING =
new Comparator<ScoredInt>()
{
@Override
public int compare(final ScoredInt o1, final ScoredInt o2)
{
if (o1.score < o2.score)
return 1;
if (o1.score > o2.score)
return -1;
return 0;
}
};
}
| 1,456 | 15.370787 | 106 | java |
Ludii | Ludii-master/Common/src/main/collections/ScoredObject.java | package main.collections;
import java.util.Comparator;
/**
* A pair of a score (double) and an object (of any type E).
*
* The ASCENDING or DESCENDING comparator objects from this class can be used for sorting based on scores.
*
* @author Dennis Soemers
* @param <E> Type of object for which we have a score
*/
public class ScoredObject<E>
{
private final E object;
private final double score;
/**
* Constructor
*
* @param object
* @param score
*/
public ScoredObject(final E object, final double score)
{
this.object = object;
this.score = score;
}
/**
* @return The object
*/
public E object()
{
return object;
}
/**
* @return The score
*/
public double score()
{
return score;
}
/**
* Can be used for sorting in ascending order (with respect to scores)
*/
public static Comparator<ScoredObject<?>> ASCENDING =
new Comparator<ScoredObject<?>>()
{
@Override
public int compare(final ScoredObject<?> o1, final ScoredObject<?> o2)
{
if (o1.score < o2.score)
return -1;
if (o1.score > o2.score)
return 1;
return 0;
}
};
/**
* Can be used for sorting in ascending order (with respect to scores)
*/
public static Comparator<ScoredObject<?>> DESCENDING =
new Comparator<ScoredObject<?>>()
{
@Override
public int compare(final ScoredObject<?> o1, final ScoredObject<?> o2)
{
if (o1.score < o2.score)
return 1;
if (o1.score > o2.score)
return -1;
return 0;
}
};
}
| 1,565 | 16.4 | 106 | java |
Ludii | Ludii-master/Common/src/main/collections/SpeedTests.java | package main.collections;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import gnu.trove.list.array.TIntArrayList;
/**
* Speed tests for custom collection types.
* @author cambolbro
*/
public class SpeedTests
{
@SuppressWarnings("unused")
void test()
{
// // Stephen's (mrraow) "Integer == Integer" quirk
// Integer a = 100;
// Integer b = 100;
// System.out.println(a == b);
//
// a = 200;
// b = 200;
// System.out.println(a == b);
//=====================================================================
// System.out.println("Working Directory = " + System.getProperty("user.dir"));
//
// final String name = "../Core/src/game/functions/ints/IntConstant.java";
// final File file = new File(name);
// System.out.println("File " + name + " loaded, length is " + file.length() + ".");
//=====================================================================
final int N = 1000000;
long startAt, stopAt;
double secs;
final List<Integer> ints = new ArrayList<>();
final FastArrayList<Integer> fints = new FastArrayList<>();
final TIntArrayList tints = new TIntArrayList();
final List<String> strings = new ArrayList<>();
final FastArrayList<String> fstrings = new FastArrayList<>();
//---------------------------------
// Warm them up...
for (int n = 0; n < N; n++)
ints.add(n);
for (int n = 0; n < N; n++)
fints.add(n);
for (int n = 0; n < N; n++)
tints.add(n);
for (int n = 0; n < N; n++)
strings.add("" + n);
for (int n = 0; n < N; n++)
fstrings.add("" + n);
//---------------------------------
System.out.println("Adding integers to list:");
startAt = System.nanoTime();
ints.clear();
for (int n = 0; n < N; n++)
ints.add(n);
stopAt = System.nanoTime();
secs = (stopAt - startAt) / 1000000000.0;
System.out.println(N + " Integers added to ArrayList in " + secs + "s.");
startAt = System.nanoTime();
fints.clear();
for (int n = 0; n < N; n++)
fints.add(n);
stopAt = System.nanoTime();
secs = (stopAt - startAt) / 1000000000.0;
System.out.println(N + " Integers added to FastArrayList in " + secs + "s.");
startAt = System.nanoTime();
tints.clear();
for (int n = 0; n < N; n++)
tints.add(n);
stopAt = System.nanoTime();
secs = (stopAt - startAt) / 1000000000.0;
System.out.println(N + " ints added to TIntArrayList in " + secs + "s.");
//---------------------------------
System.out.println("\nAdding strings to list:");
startAt = System.nanoTime();
strings.clear();
for (int n = 0; n < N; n++)
strings.add("" + n);
stopAt = System.nanoTime();
secs = (stopAt - startAt) / 1000000000.0;
System.out.println(N + " Strings added to ArrayList in " + secs + "s.");
startAt = System.nanoTime();
fstrings.clear();
for (int n = 0; n < N; n++)
fstrings.add("" + n);
stopAt = System.nanoTime();
secs = (stopAt - startAt) / 1000000000.0;
System.out.println(N + " Strings added to FastArrayList in " + secs + "s.");
//---------------------------------
System.out.println("\nAdding ints to list and retrieving then as ints:");
startAt = System.nanoTime();
ints.clear();
for (int n = 0; n < N; n++)
ints.add(n);
for (final Integer i : ints)
{
final int x = i.intValue();
}
stopAt = System.nanoTime();
secs = (stopAt - startAt) / 1000000000.0;
System.out.println(N + " Integers added to ArrayList and retrieved in " + secs + "s.");
startAt = System.nanoTime();
fints.clear();
for (int n = 0; n < N; n++)
fints.add(n);
for (final Integer i : fints)
{
final int x = i.intValue();
}
stopAt = System.nanoTime();
secs = (stopAt - startAt) / 1000000000.0;
System.out.println(N + " Integers added to FastArrayList and retrieved in " + secs + "s.");
startAt = System.nanoTime();
tints.clear();
for (int n = 0; n < N; n++)
tints.add(n);
for (int i = 0; i < tints.size(); i++)
{
final int x = tints.get(i);
}
stopAt = System.nanoTime();
secs = (stopAt - startAt) / 1000000000.0;
System.out.println(N + " ints added to TIntArrayList and retrieved in " + secs + "s.");
//---------------------------------
System.out.println("\nAdding and sorting integers:");
startAt = System.nanoTime();
ints.clear();
for (int n = 0; n < N; n++)
ints.add(N - n);
Collections.sort(ints);
stopAt = System.nanoTime();
secs = (stopAt - startAt) / 1000000000.0;
System.out.println(N + " Integers added to ArrayList and sorted in " + secs + "s.");
// startAt = System.nanoTime();
//
// fints.clear();
// for (int n = 0; n < N; n++)
// fints.add(N - n);
//
// stopAt = System.nanoTime();
// secs = (stopAt - startAt) / 1000000000.0;
// System.out.println(N + " Integers added to FastArrayList and sorted in " + secs + "s.");
System.out.println("** Sort not implemented for FastArrayList.");
startAt = System.nanoTime();
tints.clear();
for (int n = 0; n < N; n++)
tints.add(N - n);
tints.sort();
stopAt = System.nanoTime();
secs = (stopAt - startAt) / 1000000000.0;
System.out.println(N + " int added to TIntArrayList and sorted in " + secs + "s.");
//---------------------------------
System.out.println("\nAdding and sorting strings:");
startAt = System.nanoTime();
strings.clear();
for (int n = 0; n < N; n++)
strings.add("" + (N - n));
Collections.sort(strings);
stopAt = System.nanoTime();
secs = (stopAt - startAt) / 1000000000.0;
System.out.println(N + " Strings added to ArrayList and sorted in " + secs + "s.");
// startAt = System.nanoTime();
//
// fstrings.clear();
// for (int n = 0; n < N; n++)
// fstrings.add("" + (N - n));
//
// stopAt = System.nanoTime();
// secs = (stopAt - startAt) / 1000000000.0;
// System.out.println(N + " Integers added to FastArrayList and sorted in " + secs + "s.");
System.out.println("** Sort not implemented for FastArrayList.");
//---------------------------------
}
//-------------------------------------------------------------------------
public static void main(final String[] args)
{
final SpeedTests app = new SpeedTests();
app.test();
}
}
| 6,312 | 24.662602 | 93 | java |
Ludii | Ludii-master/Common/src/main/collections/StringPair.java | package main.collections;
import java.util.regex.Pattern;
import main.StringRoutines;
/**
* String pair (key, value) for metadata.
* @author cambolbro, Dennis Soemers
*/
public class StringPair
{
private final String key;
private final String value;
/**
* Constructor
* @param key
* @param value
*/
public StringPair(final String key, final String value)
{
this.key = key;
this.value = value;
}
/**
* @return Pair's first element (the key)
*/
public String key()
{
return key;
}
/**
* @return Pair's second element (the value)
*/
public String value()
{
return value;
}
@Override
public String toString()
{
return "{ " + StringRoutines.quote(key) + " " + StringRoutines.quote(value) + " }";
}
/**
* @param str
* @return StringPair generated from given string (in { "key" "value" } format)
*/
public static StringPair fromString(final String str)
{
String s = str.replaceAll(Pattern.quote("{"), "");
s = s.replaceAll(Pattern.quote("}"), "");
s = s.replaceAll(Pattern.quote("\""), "");
s = s.trim();
final String[] split = s.split(Pattern.quote(" "));
return new StringPair(split[0], split[1]);
}
}
| 1,183 | 17.5 | 85 | java |
Ludii | Ludii-master/Common/src/main/grammar/Baptist.java | package main.grammar;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
//-----------------------------------------------------------------------------
/**
* Creates random but plausible names.
*
* @author cambolbro
*/
public class Baptist
{
private final List<String> names = new ArrayList<String>();
final char[] chars =
{
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j',
'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't',
'u', 'v', 'w', 'x', 'y', 'z', '.',
};
private final int DOT = chars.length - 1;
private final int[][][] counts = new int[chars.length][chars.length][chars.length];
private final int[][] totals = new int[chars.length][chars.length];
//-------------------------------------------------------------------------
private static volatile Baptist singleton = null;
//-------------------------------------------------------------------------
private Baptist()
{
loadNames("/npp-names-2.txt");
//loadNames("src/main/grammar/latin-out.txt");
//loadNames("src/main/grammar/english-2000-2.txt");
processNames();
}
//-------------------------------------------------------------------------
public static Baptist baptist()
{
if (singleton == null)
{
synchronized(Baptist.class)
{
singleton = new Baptist();
}
}
return singleton;
}
//-------------------------------------------------------------------------
void loadNames(final String filePath)
{
names.clear();
try(InputStream is = getClass().getResourceAsStream(filePath))
{
String line;
final BufferedReader reader = new BufferedReader(new InputStreamReader(is));
if (is != null)
{
while ((line = reader.readLine()) != null)
{
names.add(new String(line));
}
}
}
catch (final Exception e)
{
e.printStackTrace();
}
// System.out.println(names.size() + " names loaded.");
// System.out.println("Name 100 is " + names.get(100) + ".");
}
//-------------------------------------------------------------------------
void processNames()
{
for (final String name : names)
processName(name);
// for (int c0 = 0; c0 < chars.length; c0++)
// for (int c1 = 0; c1 < chars.length; c1++)
// {
// if (totals[c0][c1] == 0)
// continue;
//
// System.out.println("\n" + chars[c0] + chars[c1] + " has " + totals[c0][c1] + " hits:");
// for (int c2 = 0; c2 < chars.length; c2++)
// if (table[c0][c1][c2] > 0)
// System.out.println("" + chars[c0] + chars[c1] + chars[c2] + " = " + table[c0][c1][c2]);
// }
// for (int n = 0; n < chars.length; n++)
// System.out.println("counts[.][.][" + chars[n] + "]=" + counts[DOT][DOT][n]);
}
void processName(final String name)
{
final String str = ".." + name.toLowerCase() + "..";
for (int c = 0; c < str.length() - 3; c++)
{
int ch0 = str.charAt(c) - 'a';
int ch1 = str.charAt(c + 1) - 'a';
int ch2 = str.charAt(c + 2) - 'a';
if (ch0 < 0 || ch0 >= 26)
ch0 = DOT;
if (ch1 < 0 || ch1 >= 26)
ch1 = DOT;
if (ch2 < 0 || ch2 >= 26)
ch2 = DOT;
counts[ch0][ch1][ch2]++;
totals[ch0][ch1]++;
}
}
//-------------------------------------------------------------------------
/**
* @return Generate a name from the given seed, of minimum length.
*/
public String name(final long seed, final int minLength)
{
String result = "";
final Random rng = new Random(seed);
rng.nextInt(); // Burn the first value, or will get the same first nextInt(R)
// if the seed is small and the range R is a power of 2!
// int iteration = 0;
do
{
if (result != "")
result += " ";
// rng.setSeed(seed + iteration++);
// rng.nextInt(); // Burn the first value, or will get the same first nextInt(R)
// if the seed is small and the range R is a power of 2!
result += name(rng);
} while (result.length() < minLength);
return result;
}
//-------------------------------------------------------------------------
/**
* @return Generate a name using the given RNG.
*/
public String name(final Random rng)
{
final int[] token = { DOT, DOT, DOT };
String str = "";
while (true)
{
if (token[2] != DOT)
str += (str == "") ? Character.toUpperCase(chars[token[2]]) : chars[token[2]];
token[0] = token[1];
token[1] = token[2];
final int total = totals[token[0]][token[1]];
if (total == 0)
break;
final int target = rng.nextInt(total) + 1;
int tally = 0;
for (int n = 0; n < chars.length; n++)
{
if (counts[token[0]][token[1]][n] == 0)
continue;
tally += counts[token[0]][token[1]][n];
if (tally >= target)
{
token[2] = n;
break;
}
}
}
return str;
}
//-------------------------------------------------------------------------
public static void main(final String[] args)
{
for (int n = 0; n < 20; n++)
System.out.println(baptist().name(n, 5));
System.out.println();
String str = "Yavalath";
System.out.println("'" + str + "' is called: " + baptist().name(str.hashCode(), 5));
str = "Cameron";
System.out.println("'" + str + "' is called: " + baptist().name(str.hashCode(), 5));
System.out.println();
for (int n = 0; n < 100; n++)
System.out.println(baptist().name((int)System.nanoTime(), 5));
System.out.println();
for (int n = 0; n < 10000000; n++)
{
final int seed = (int)System.nanoTime();
final String name = baptist().name(seed, 5);
if (name.equals("Yavalath"))
{
System.out.println(name + " found after " + n + " tries (seed = " + seed + ").");
break;
}
}
System.out.println("Done.");
}
//-------------------------------------------------------------------------
}
| 5,972 | 24.096639 | 95 | java |
Ludii | Ludii-master/Common/src/main/grammar/Call.java |
package main.grammar;
import java.io.FileWriter;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import annotations.Alias;
import main.StringRoutines;
//-----------------------------------------------------------------------------
/**
* Instance of an item actually compiled.
* @author cambolbro and matthew.stephenson
*/
public class Call
{
public enum CallType
{
Null,
Class,
Array,
Terminal
}
private CallType type = null;
//---------------------------------------------------------
/**
* Record of instance that created this call.
* Only keep necessary info from Instance to minimise memory usage.
*/
//private final Instance instance;
private final Symbol symbol;
private final Object object;
private final String constant;
/** Expected type for this call. */
private final Class<?> expected;
/** Arguments for the call (if class). */
private final List<Call> args = new ArrayList<>();
/** Indent level for formatting. */
private final int TAB_SIZE = 4;
/** Named parameter in grammar for this argument, if any. */
private String label = null;
//-------------------------------------------------------------------------
/**
* Default constructor for Array call.
*/
public Call(final CallType type)
{
this.type = type;
symbol = null;
object = null;
constant = null;
expected = null;
}
/**
* Constructor for Terminal call.
*/
public Call(final CallType type, final Instance instance, final Class<?> expected)
{
this.type = type;
symbol = instance.symbol();
object = instance.object();
constant = instance.constant();
this.expected = expected;
}
//-------------------------------------------------------------------------
public CallType type()
{
return type;
}
public Symbol symbol()
{
return symbol;
}
public Class<?> cls()
{
return symbol == null ? null : symbol.cls();
}
public Object object()
{
return object;
}
public String constant()
{
return constant;
}
public List<Call> args()
{
return Collections.unmodifiableList(args);
}
public Class<?> expected()
{
return expected;
}
public String label()
{
return label;
}
public void setLabel(final String str)
{
label = new String(str);
}
//-------------------------------------------------------------------------
/**
* Add argument to the list.
*/
public void addArg(final Call arg)
{
args.add(arg);
}
// /**
// * Remove the last argument (if any).
// */
// public void removeLastArg()
// {
// if (args.size() == 0)
// System.out.println("** Call.removeLastArg(): No args to remove!");
//
// args.remove(args.size() - 1);
// }
//-------------------------------------------------------------------------
/**
* @return Number of tokens in the tree from this token down.
*/
public int count()
{
int count = 1;
for (final Call sub : args)
count += sub.count();
return count;
}
/**
* @return Number of tokens in the tree from this token down.
*/
public int countClasses()
{
int count = type() == CallType.Class ? 1 : 0;
for (final Call sub : args)
count += sub.countClasses();
return count;
}
/**
* @return Number of tokens in the tree from this token down.
*/
public int countTerminals()
{
int count = type() == CallType.Terminal ? 1 : 0;
for (final Call sub : args)
count += sub.countTerminals();
return count;
}
/**
* @return Number of tokens in the tree from this token down.
*/
public int countClassesAndTerminals()
{
int count = type() != CallType.Array ? 1 : 0;
for (final Call sub : args)
count += sub.countClassesAndTerminals();
return count;
}
//-------------------------------------------------------------------------
/**
* Export this call node (and its args) to file.
* @param fileName
*/
public void export(final String fileName)
{
try (final FileWriter writer = new FileWriter(fileName))
{
final String str = toString();
writer.write(str);
}
catch (final IOException e)
{
e.printStackTrace();
}
}
//-------------------------------------------------------------------------
@Override
public String toString()
{
return format(0, true);
}
//-------------------------------------------------------------------------
@Override
public boolean equals(final Object o)
{
return ludemeFormat(0).equals(((Call) o).ludemeFormat(0));
}
@Override
public int hashCode()
{
return ludemeFormat(0).hashCode();
}
//-------------------------------------------------------------------------
/**
* @return String representation of callTree for display purposes.
*/
String format(final int depth, final boolean includeLabels)
{
final StringBuilder sb = new StringBuilder();
final String indent = StringRoutines.indent(TAB_SIZE, depth);
switch (type())
{
case Null:
sb.append(indent + "-\n");
break;
case Array:
sb.append(indent + "{\n");
for (final Call arg : args)
sb.append(arg.format(depth, includeLabels));
if (includeLabels && label != null)
sb.append(" \"" + label + ":\"");
break;
case Class:
sb.append(indent + cls().getName());
if (!cls().getName().equals(expected.getName()))
sb.append(" (" + expected.getName() + ")");
if (includeLabels && label != null)
sb.append(" \"" + label + ":\"");
sb.append("\n");
for (final Call arg : args)
sb.append(arg.format(depth + 1, includeLabels));
break;
case Terminal:
if (object().getClass().getSimpleName().equals("String"))
sb.append(indent + "\"" + object() + "\" (" + expected.getName() + ")");
else
sb.append(indent + object() + " (" + expected.getName() + ")");
if (includeLabels && label != null)
sb.append(" \"" + label + ":\"");
if (constant != null)
sb.append(" Constant=" + constant);
sb.append("\n");
break;
default:
System.out.println("** Call.format() should never hit default.");
break;
}
if (type() == CallType.Array)
sb.append(indent + "}\n");
return sb.toString();
}
//-------------------------------------------------------------------------
// /**
// * @return LudemeInfo list representation of callTree for ludemeplex analysis purposes.
// */
// public List<LudemeInfo> analysisFormatList(final int depth, final List<LudemeInfo> ludemes)
// {
// final List<LudemeInfo> ludemesFound = new ArrayList<>();
//
// switch (type)
// {
// case Null:
// break;
// case Array:
// for (final Call arg : args)
// ludemesFound.addAll(arg.analysisFormatList(depth, ludemes));
// break;
// case Class:
// final LudemeInfo ludemeInfo = LudemeInfo.findLudemeInfo(this, ludemes);
// if (ludemeInfo != null)
// {
// ludemesFound.add(ludemeInfo);
// if (args.size() > 0)
// for (final Call arg : args)
// ludemesFound.addAll(arg.analysisFormatList(depth + 1, ludemes));
// }
// break;
// case Terminal:
// final LudemeInfo ludemeInfo2 = LudemeInfo.findLudemeInfo(this, ludemes);
// if (ludemeInfo2 != null)
// ludemesFound.add(ludemeInfo2);
// break;
// default:
// System.out.println("** Call.format() should never hit default.");
// break;
// }
//
// return new ArrayList<>(new HashSet<>(ludemesFound));
// }
/**
* @return LudemeInfo dictionary representation of callTree for ludemeplex analysis purposes.
*/
public Map<LudemeInfo, Integer> analysisFormat(final int depth, final List<LudemeInfo> ludemes)
{
final Map<LudemeInfo, Integer> ludemesFound = new HashMap<>();
for (final LudemeInfo ludemeInfo : ludemes)
ludemesFound.put(ludemeInfo, 0);
switch (type)
{
case Null:
break;
case Array:
for (final Call arg : args)
{
final Map<LudemeInfo, Integer> ludemesFound2 = arg.analysisFormat(depth, ludemes);
for (final LudemeInfo ludemeInfo : ludemesFound2.keySet())
ludemesFound.put(ludemeInfo, ludemesFound.get(ludemeInfo) + ludemesFound2.get(ludemeInfo));
}
break;
case Class:
final LudemeInfo ludemeInfo = LudemeInfo.findLudemeInfo(this, ludemes);
if (ludemeInfo != null)
{
ludemesFound.put(ludemeInfo, ludemesFound.get(ludemeInfo) + 1);
for (final Call arg : args)
{
final Map<LudemeInfo, Integer> ludemesFound2 = arg.analysisFormat(depth + 1, ludemes);
for (final LudemeInfo ludemeInfoChildren : ludemesFound2.keySet())
ludemesFound.put(ludemeInfoChildren, ludemesFound.get(ludemeInfoChildren) + ludemesFound2.get(ludemeInfoChildren));
}
}
break;
case Terminal:
final LudemeInfo ludemeInfo2 = LudemeInfo.findLudemeInfo(this, ludemes);
if (ludemeInfo2 != null)
ludemesFound.put(ludemeInfo2, ludemesFound.get(ludemeInfo2) + 1);
break;
default:
System.out.println("** Call.format() should never hit default.");
break;
}
// remove ludemes with a count of zero.
final Map<LudemeInfo, Integer> ludemesFoundGreaterZero = new HashMap<>();
for (final LudemeInfo ludemeInfo : ludemesFound.keySet())
if (ludemesFound.get(ludemeInfo) > 0)
ludemesFoundGreaterZero.put(ludemeInfo, ludemesFound.get(ludemeInfo));
return ludemesFoundGreaterZero;
}
//-------------------------------------------------------------------------
/**
* @return String representation of call tree in preorder notation, e.g. f(a b(c)).
*/
public String preorderFormat(final int depth, final List<LudemeInfo> ludemes)
{
String ludemesFound = "";
switch (type)
{
case Null:
break;
case Array:
String newString = "(";
for (final Call arg : args)
newString += arg.preorderFormat(depth, ludemes) + " ";
newString += ")";
if (newString.replaceAll("\\s+","").length() > 2)
ludemesFound += "Array" + newString;
break;
case Class:
final LudemeInfo ludemeInfo = LudemeInfo.findLudemeInfo(this, ludemes);
if (ludemeInfo != null)
{
String newString2 = "(";
if (args.size() > 0)
for (final Call arg : args)
newString2 += arg.preorderFormat(depth + 1, ludemes) + " ";
newString2 += ")";
if (newString2.replaceAll("\\s+","").length() > 2)
ludemesFound += ludemeInfo.symbol().name() + newString2;
else
ludemesFound += ludemeInfo.symbol().name();
}
break;
case Terminal:
final LudemeInfo ludemeInfo2 = LudemeInfo.findLudemeInfo(this, ludemes);
if (ludemeInfo2 != null)
ludemesFound += ludemeInfo2.symbol().name() + " ";
break;
default:
System.out.println("** Call.format() should never hit default.");
break;
}
return ludemesFound;
}
//-------------------------------------------------------------------------
/**
* @return String representation of callTree for database storing purposes (mimics game description style).
*/
public List<String> ludemeFormat(final int depth)
{
List<String> stringList = new ArrayList<String>();
switch (type)
{
case Null:
break;
case Array:
if (label != null && depth > 0)
stringList.add(label + ":");
stringList.add("{");
for (final Call arg : args)
{
stringList.addAll(arg.ludemeFormat(depth));
stringList.add(" ");
}
break;
case Class:
final Annotation[] annotations = cls().getAnnotations();
String name = cls().getName().split("\\.")[cls().getName().split("\\.").length-1];
for (final Annotation annotation : annotations)
if (annotation instanceof Alias)
name = ((Alias)annotation).alias();
name = Character.toLowerCase(name.charAt(0)) + name.substring(1);
if (label != null && depth > 0)
stringList.add(label + ":");
stringList.add("(");
stringList.add(name);
if (args.size() > 0)
{
stringList.add(" ");
for (final Call arg : args)
stringList.addAll(arg.ludemeFormat(depth + 1));
stringList = removeCharsFromStringList(stringList, 1);
}
stringList.add(") ");
break;
case Terminal:
if (label != null)
stringList.add(label + ":");
if (constant != null)
stringList.add(constant + " ");
else if (object().getClass().getSimpleName().equals("String"))
stringList.add("\"" + object() + "\" ");
else
stringList.add(object() + " ");
break;
default:
System.out.println("** Call.format() should never hit default.");
break;
}
if (type == CallType.Array)
{
if (!stringList.get(stringList.size()-1).equals("{"))
stringList = removeCharsFromStringList(stringList, 2);
stringList.add("} ");
}
return stringList;
}
//-------------------------------------------------------------------------
/**
* Removes a specified number of chars from a list of Strings, starting at the end and working backwards.
*/
private static List<String> removeCharsFromStringList(final List<String> originalStringList, final int numChars)
{
final List<String> stringList = originalStringList;
for (int i = 0; i < numChars; i++)
{
final String oldString = stringList.get(stringList.size()-1);
final String newString = oldString.substring(0, oldString.length()-1);
stringList.remove(stringList.size()-1);
if (newString.length() > 0)
stringList.add(newString);
}
return stringList;
}
//-------------------------------------------------------------------------
}
| 13,447 | 23.720588 | 121 | java |
Ludii | Ludii-master/Common/src/main/grammar/Clause.java | package main.grammar;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.Collections;
import java.util.List;
//-----------------------------------------------------------------------------
/**
* Clause on RHS of rule delimited by "|".
* @author cambolbro
*/
public class Clause
{
// Clauses can be either:
// 1. Constructors : denoted (name ...) with arg list (terminal except for args).
// 2. Type references : denoted <name> with no arg list (non-terminal).
/** Symbol describing base type. */
private final Symbol symbol;
/** List of constructor arguments (null if not constructor). */
private final List<ClauseArg> args;
/** Whether this clause is hidden from the grammar. */
private final boolean isHidden;
/**
* Which arguments are mandatory, taking @Or groups into account.
* This info can be obtained from the args themselves, but is useful
* to store here in one BitSet for fast parsing.
*/
private BitSet mandatory = new BitSet();
//-------------------------------------------------------------------------
/**
* Constructor for non-Class clauses (no args).
* @param symbol
*/
public Clause(final Symbol symbol)
{
this.symbol = symbol;
this.args = null;
this.isHidden = false;
}
/**
* Constructor for Class clauses (with args).
*
* @param symbol
* @param args
*/
public Clause(final Symbol symbol, final List<ClauseArg> args, final boolean isHidden)
{
this.symbol = symbol;
this.args = new ArrayList<ClauseArg>();
for (final ClauseArg arg : args)
this.args.add(new ClauseArg(arg));
this.isHidden = isHidden;
setMandatory();
}
/**
* Copy constructor.
*
* @param other
*/
public Clause(final Clause other)
{
this.symbol = other.symbol;
if (other.args == null)
{
args = null;
}
else
{
this.args = (other.args == null) ? null : new ArrayList<ClauseArg>();
if (this.args != null)
for (final ClauseArg arg : other.args)
this.args.add(new ClauseArg(arg));
}
this.isHidden = other.isHidden;
this.mandatory = (BitSet)other.mandatory.clone();
}
//-------------------------------------------------------------------------
/**
* @return Symbol describing base type.
*/
public Symbol symbol()
{
return symbol;
}
/**
* @return List of constructor arguments (null if not constructor).
*/
public List<ClauseArg> args()
{
if (args == null)
return null;
return Collections.unmodifiableList(args);
}
/**
* @return Whether this clause is a constructor.
*/
public boolean isConstructor()
{
return args != null;
}
/**
* @return Whether this clause is hidden from the grammar.
*/
public boolean isHidden()
{
return isHidden;
}
public BitSet mandatory()
{
return mandatory;
}
//-------------------------------------------------------------------------
public boolean matches(final Clause other)
{
return symbol.matches(other.symbol);
}
//-------------------------------------------------------------------------
public void setMandatory()
{
mandatory.clear();
for (int a = 0; a < args.size(); a++)
{
final ClauseArg arg = args.get(a);
if (!arg.optional() && arg.orGroup() == 0)
mandatory.set(a, true); // this argument *must* exist
}
}
//-------------------------------------------------------------------------
/**
* @param other
* @return Whether this sequence is a subset of the other.
*/
public boolean isSubsetOf(final Clause other)
{
if (!symbol.path().equals(other.symbol().path()))
return false; // different base symbols
for (final ClauseArg argA : args)
{
int p;
for (p = 0; p < other.args.size(); p++)
{
final ClauseArg argB = other.args.get(p);
if
(
(argA.label() == null || argB.label() == null || argA.label().equals(argB.label()))
&&
argA.symbol().path().equals(argB.symbol().path())
&&
argA.nesting() == argB.nesting()
// &&
// argA.isList() == argB.isList()
)
break; // arg found in other clause
}
if (p >= other.args.size())
return false;
}
return true;
}
//-------------------------------------------------------------------------
@Override
public String toString()
{
String str = "";
//System.out.println("symbol: " + symbol);
// if (symbol == null)
// System.out.println("** Clause.toString(): null symbol.");
//System.out.println("\n" + symbol.info() + "\n");
final String safeKeyword = symbol.grammarLabel();
if (args != null)
{
// Clause is a constructor
str += "(";
// if (!symbol.hiddenName())
str += symbol.token(); // + " ";
// TODO: If all args in an @Or group are optional, then the entire group should be marked optional [(a | b ...)].
// Show ([a] | [b] | [c]) as [a | b | c]
ClauseArg prevArg = null;
for (int p = 0; p < args.size(); p++)
{
final ClauseArg arg = args.get(p);
str += " ";
final int orGroup = arg.orGroup();
final int andGroup = arg.andGroup();
final boolean isAnd = arg.andGroup() != 0;
if (orGroup != 0)
{
if (prevArg == null && !arg.optional())
{
// Open an @Or group at start
str += "(";
}
else if (prevArg != null && orGroup != prevArg.orGroup())
{
// Open a new @Or group
if (prevArg.orGroup() != 0 && !prevArg.optional())
{
// Close the previous @Or group
str += ") ";
}
if (!arg.optional())
{
// Open the new group
str += "(";
}
}
else if (prevArg != null && orGroup == prevArg.orGroup() && (andGroup == 0 || andGroup != prevArg.andGroup()))
{
// Continue an @Or choice
str += "| ";
}
}
if (orGroup == 0 && prevArg != null && prevArg.orGroup() != 0 && !prevArg.optional())
{
// Close an @Or choice (in middle of clause)
str += ") ";
}
boolean prevAnd = false;
boolean nextAnd = false;
if (prevArg != null)
prevAnd = ((orGroup == 0 || orGroup != 0 && orGroup == prevArg.orGroup()) && andGroup == prevArg.andGroup());
if (p < args.size()-1)
{
final ClauseArg nextArg = args.get(p+1);
nextAnd = ((orGroup == 0 || orGroup != 0 && orGroup == nextArg.orGroup()) && andGroup == nextArg.andGroup());
}
String argString = arg.toString();
if (prevAnd && orGroup != 0 && argString.charAt(0) == '[')
{
// Strip opening optional bracket '['
argString = argString.substring(1);
}
if (nextAnd && orGroup != 0 && argString.charAt(argString.length()-1) == ']')
{
// Strip closing optional bracket ']'
argString = argString.substring(0, argString.length()-1);
}
if (isAnd)
{
// Mark up @And args so that optional @And args can be processed below
argString = "&" + argString + "&";
}
str += new String(argString);
if (orGroup != 0 && p == args.size() - 1 && !arg.optional())
{
// Close an @Or choice (at end of clause)
str += ")";
}
prevArg = arg;
}
// Close this clause
str += ")";
// Correct consecutive optional @And args
str = str.replace("]& &[", " ");
str = str.replace("&", "");
// Tidy up constructors with no parameters
str = str.replace(" )", ")");
}
else
{
// Clause is not a constructor
switch (symbol.ludemeType())
{
case Primitive:
case Predefined:
case Constant:
str = symbol.token();
break;
case Ludeme:
case SuperLudeme:
case SubLudeme:
case Structural:
str = "<" + safeKeyword + ">";
break;
default:
str += "[UNKNOWN]";
}
}
for (int n = 0; n < symbol.nesting(); n++)
str = "{" + str + "}";
return str;
}
//-------------------------------------------------------------------------
}
| 7,916 | 22.014535 | 116 | java |
Ludii | Ludii-master/Common/src/main/grammar/ClauseArg.java | package main.grammar;
//-----------------------------------------------------------------------------
/**
* Argument in a symbol's clause (i.e. a constructor) with an optional label.
*
* @author cambolbro
*/
public class ClauseArg
{
/** Parameter name in the code base. */
private final String actualParameterName;
/** Local parameter name if parameter has @Name annotation, else null. */
private String label = null;
/** Symbol representing parameter type. */
private Symbol symbol = null;
/** Whether arg is [optional]. */
private final boolean optional;
/** Which @Or groups this arg belongs to (0 is none). */
private final int orGroup;
/** Which @And groups this arg belongs to (0 is none). */
private final int andGroup;
/** Degree of array nesting (0 for none). */
private int nesting = 0;
//-------------------------------------------------------------------------
/**
* Constructor.
*
* @param label
* @param symbol
* @param optional
*/
public ClauseArg
(
final Symbol symbol, final String actualParameterName, final String label, final boolean optional,
final int orGroup, final int andGroup
)
{
this.symbol = symbol;
this.actualParameterName = (actualParameterName == null) ? null : new String(actualParameterName);
this.label = (label == null) ? null : new String(label);
this.optional = optional;
this.orGroup = orGroup;
this.andGroup = andGroup;
}
/**
* Copy constructor.
*
* @param other
*/
public ClauseArg(final ClauseArg other)
{
symbol = other.symbol;
actualParameterName = (other.actualParameterName == null) ? null : new String(other.actualParameterName);
label = (other.label == null) ? null : new String(other.label);
optional = other.optional;
orGroup = other.orGroup;
andGroup = other.andGroup;
nesting = other.nesting;
}
//-------------------------------------------------------------------------
/**
* @return Parameter name in the code base.
*/
public String actualParameterName()
{
return actualParameterName;
}
/**
* @return Local parameter name if parameter has @Name annotation, else null.
*/
public String label()
{
return label;
}
/**
* @return Symbol representing parameter type.
*/
public Symbol symbol()
{
return symbol;
}
/**
* @param val
*/
public void setSymbol(final Symbol val)
{
symbol = val;
}
/**
* @return Degree of nesting (array depth).
*/
public int nesting()
{
return nesting;
}
/**
* @param val
*/
public void setNesting(final int val)
{
nesting = val;
}
/**
* @return Whether arg is optional.
*/
public boolean optional()
{
return optional;
}
public int orGroup()
{
return orGroup;
}
public int andGroup()
{
return andGroup;
}
//-------------------------------------------------------------------------
@Override
public String toString()
{
String str = "";
if (symbol == null)
return "NULL";
switch (symbol.ludemeType())
{
case Primitive:
// System.out.println("** Arg " + symbol.name() + " is a primitive.");
str = symbol.token();
break;
case Constant:
// str = "<" + symbol.keyword() + ">";
str = symbol.token();
break;
case Predefined:
case Ludeme:
case SuperLudeme:
case SubLudeme:
case Structural:
// Hack to convert "<String>" args to "string" in the grammar
if (symbol.token().equals("String"))
str = "string";
else
str = "<" + symbol.grammarLabel() + ">";
break;
default:
str += "[UNKNOWN]";
}
for (int n = 0; n < nesting; n++)
str = "{" + str + "}";
if (label != null)
{
String labelSafe = new String(label);
if (Character.isUpperCase(labelSafe.charAt(0)))
{
// First char is capital, probably If, Else, etc.
labelSafe = Character.toLowerCase(labelSafe.charAt(0)) + labelSafe.substring(1);
}
str = labelSafe + ":" + str; // named parameter
}
if (optional)
str = "[" + str + "]";
return str;
}
//-------------------------------------------------------------------------
}
| 4,042 | 19.419192 | 107 | java |
Ludii | Ludii-master/Common/src/main/grammar/Combo.java | package main.grammar;
//import java.util.BitSet;
/**
* Combination for assigning null and non-null arguments in parameter lists.
*
* @author cambolbro
*/
public class Combo
{
private final int[] array;
private final int count;
// private final BitSet bits = new BitSet();
//-------------------------------------------------------------------------
public Combo(final int n, final int seed)
{
array = new int[n];
int on = 0;
for (int b = 0; b < n; b++)
if ((seed & (0x1 << b)) != 0)
{
array[b] = ++on;
// bits.set(b, true);
}
count = on;
}
//-------------------------------------------------------------------------
public int[] array()
{
return array;
}
// public BitSet bits()
// {
// return bits;
// }
//-------------------------------------------------------------------------
/**
* @return Total length of combo include on-bits and off-bits.
*/
public int length()
{
return array.length;
}
// /**
// * @return Number of on-bits.
// */
// public int count()
// {
// return bits.cardinality();
// }
/**
* @return Number of on-bits.
*/
public int count()
{
return count;
}
//-------------------------------------------------------------------------
}
| 1,246 | 16.082192 | 76 | java |
Ludii | Ludii-master/Common/src/main/grammar/Define.java | package main.grammar;
/**
* Record of a "(define ...)" instance
* @author cambolbro
*/
public class Define
{
private final String tag;
private String expression; // expression may be modified if recursive defines
private final boolean parameterised;
private final boolean isKnown; // whether is a known define from Common/res/def
//---------------------------------------------------- --------------------
/**
* @param tag
* @param expression
*/
public Define(final String tag, final String expression, final boolean isKnown)
{
this.tag = new String(tag);
this.expression = new String(expression);
this.isKnown = isKnown;
parameterised = expression.contains("#");
}
//---------------------------------------------------- --------------------
/**
* @return The tag.
*/
public String tag()
{
return tag;
}
/**
* @return The expression.
*/
public String expression()
{
return expression;
}
/**
* Set the expression.
*
* @param expr
*/
public void setExpression(final String expr)
{
expression = expr;
}
/**
* @return True if it is parameterised.
*/
public boolean parameterised()
{
return parameterised;
}
/**
* @return Whether this is a known define from Common/res/def.
*/
public boolean isKnown()
{
return isKnown;
}
//---------------------------------------------------- --------------------
public String formatted()
{
return "(define " + tag + " " + expression + ")";
}
//---------------------------------------------------- --------------------
@Override
public String toString()
{
String str = "";
str += "{tag:" + tag + ", expression:" + expression + ", parameterised:" + parameterised + "}";
return str;
}
//---------------------------------------------------- --------------------
}
| 1,824 | 18.414894 | 97 | java |
Ludii | Ludii-master/Common/src/main/grammar/DefineInstances.java | package main.grammar;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* Record of a define instances in a game description.
* @author cambolbro
*/
public class DefineInstances
{
private final Define define;
private final List<String> instances = new ArrayList<String>();
//---------------------------------------------------- --------------------
/**
* @param define The define in entry.
*/
public DefineInstances(final Define define)
{
this.define = define;
}
//---------------------------------------------------- --------------------
public Define define()
{
return define;
}
public List<String> instances()
{
return Collections.unmodifiableList(instances);
}
//---------------------------------------------------- --------------------
public void addInstance(final String instance)
{
instances.add(instance);
}
//---------------------------------------------------- --------------------
@Override
public String toString()
{
final StringBuilder sb = new StringBuilder();
sb.append("~~~~~~~~~~~~~~~~~~~~\nDefine: " + define);
for (final String instance : instances)
sb.append("\nInstance: " + instance);
return sb.toString();
}
//---------------------------------------------------- --------------------
}
| 1,326 | 19.734375 | 76 | java |
Ludii | Ludii-master/Common/src/main/grammar/Description.java | package main.grammar;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import main.Constants;
import main.StringRoutines;
import main.options.GameOptions;
import main.options.Ruleset;
//-----------------------------------------------------------------------------
/**
* Game description with full details after expansion.
*
* @author cambolbro
*/
public class Description
{
// Raw, unprocessed description, with defines and options, as manually authored by user
private String raw = null;
// // Description with options expanded
// private String optionsExpanded = null;
// Full description with all defines, options, instances, etc. expanded
private String expanded = null;
// Metadata description after expansion and filtering to current option set
private String metadata = null;
// GameOptions defined in game description
private final GameOptions gameOptions = new GameOptions();
// Rulesets defined in game description
private final List<Ruleset> rulesets = new ArrayList<Ruleset>();
// Tree(s) of tokens making up the (expanded) game description
private final TokenForest tokenForest = new TokenForest();
// Tree of items corresponding to tokens, for parsing
private ParseItem parseTree = null;
// Tree of classes and objects actually called by compiled item
private Call callTree = null;
// File path that the description came from.
private String filePath = null;
// Whether this description was completed as a reconstruction
private boolean isReconstruction = false;
// Maximum number of reconstructions to generate (if using reconstruction syntax).
private int maxReconstructions = 1;
// Map of define instances used in the current game expansion.
private final Map<String, DefineInstances> defineInstances = new HashMap<String, DefineInstances>();
//-------------------------------------------------------------------------
public Description(final String raw)
{
this.raw = new String(raw);
}
//-------------------------------------------------------------------------
public String raw()
{
return raw;
}
public void setRaw(final String str)
{
raw = new String(str);
}
public String expanded()
{
return expanded;
}
public void setExpanded(final String str)
{
expanded = new String(str);
}
public String metadata()
{
return metadata;
}
public void setMetadata(final String str)
{
metadata = new String(str);
}
public GameOptions gameOptions()
{
return gameOptions;
}
public List<Ruleset> rulesets()
{
return Collections.unmodifiableList(rulesets);
}
public TokenForest tokenForest()
{
return tokenForest;
}
public ParseItem parseTree()
{
return parseTree;
}
public void setParseTree(final ParseItem tree)
{
parseTree = tree;
}
public Call callTree()
{
return callTree;
}
public void setCallTree(final Call tree)
{
callTree = tree;
}
public String filePath()
{
return filePath;
}
public void setFilePath(final String filePath)
{
this.filePath = filePath;
}
/**
* @return Whether this description was completed as a reconstruction.
*/
public boolean isReconstruction()
{
return isReconstruction;
}
public void setIsRecontruction(final boolean value)
{
isReconstruction = value;
}
/**
* @return Maximum number of reconstructions to generate (if using reconstruction syntax).
*/
public int maxReconstructions()
{
return maxReconstructions;
}
public void setMaxReconstructions(final int num)
{
maxReconstructions = num;
}
public final Map<String, DefineInstances> defineInstances()
{
return defineInstances;
}
//-------------------------------------------------------------------------
public void clearRulesets()
{
rulesets.clear();
}
public void add(final Ruleset ruleset)
{
rulesets.add(ruleset);
}
//-------------------------------------------------------------------------
/**
* Creates parse tree from the first Token tree.
*/
public void createParseTree()
{
parseTree = createParseTree(tokenForest.tokenTree(), null);
}
/**
* @return Parse tree created from this token and its parent.
*/
private static ParseItem createParseTree(final Token token, final ParseItem parent)
{
final ParseItem item = new ParseItem(token, parent);
for (final Token arg : token.arguments())
item.add(createParseTree(arg, item));
return item;
}
//-------------------------------------------------------------------------
/**
* @param selectedOptions List of strings describing selected options
* @return Index of ruleset to be selected automatically based on selected
* options. Returns Constants.UNDEFINED if there is no match.
*/
public int autoSelectRuleset(final List<String> selectedOptions)
{
final List<String> allActiveOptions = gameOptions.allOptionStrings(selectedOptions);
for (int i = 0; i < rulesets.size(); ++i)
{
if (!rulesets.get(i).optionSettings().isEmpty()) // Eric wants to hide unimplemented rulesets
{
boolean fullMatch = true;
for (final String requiredOpt : rulesets.get(i).optionSettings())
{
if (!allActiveOptions.contains(requiredOpt))
{
fullMatch = false;
break;
}
}
if (fullMatch)
return i;
}
}
return Constants.UNDEFINED;
}
//-------------------------------------------------------------------------
/**
* @return "(game ...)" ludeme from raw description.
*/
public String rawGameDescription()
{
final int c = raw.indexOf("(game");
// This description does not contain a (game ...) ludeme
if (c < 0)
return "";
final int cc = StringRoutines.matchingBracketAt(raw, c);
final String sub = raw.substring(c, cc + 1);
//System.out.println("Raw game description: " + sub);
return sub;
}
//-------------------------------------------------------------------------
}
| 6,131 | 21.711111 | 103 | java |
Ludii | Ludii-master/Common/src/main/grammar/GrammarRule.java | package main.grammar;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import main.grammar.Symbol.LudemeType;
//-----------------------------------------------------------------------------
/**
* Rule within the grammar.
* @author cambolbro
*/
public class GrammarRule
{
/** LHS symbol, which must be non-terminal or primitive -- not constant! */
private Symbol lhs = null;
/** RHS expression, consisting of clauses separated by "|". */
private List<Clause> rhs = new ArrayList<Clause>();
//-------------------------------------------------------------------------
// Formatting
/** Maximum number of chars per line. */
public static final int MAX_LINE_WIDTH = 80;
/** Separator to delineate main types. */
//public static final String SEPARATOR = " ";
/** Separator to delineate main types. */
public static final String IMPLIES = " ::= ";
/** Tab for lining up "::=" in grammar. */
public static final int TAB_LHS = 10;
/** Tab for lining up expressions in grammar. */
public static final int TAB_RHS = TAB_LHS + IMPLIES.length();
//-------------------------------------------------------------------------
/**
* Constructor.
* @param lhs
*/
public GrammarRule(final Symbol lhs)
{
this.lhs = lhs;
lhs.setRule(this);
}
//-------------------------------------------------------------------------
public Symbol lhs()
{
return lhs;
}
public List<Clause> rhs()
{
if (rhs == null)
return null;
return Collections.unmodifiableList(rhs);
}
//-------------------------------------------------------------------------
public void addToRHS(final Clause clause)
{
rhs.add(clause);
}
public void removeFromRHS(final int n)
{
rhs.remove(n);
}
public void clearRHS()
{
rhs.clear();
}
//-------------------------------------------------------------------------
/**
* @param clause
* @return Whether this rule's RHS expression already contains the specified clause.
*/
public boolean containsClause(final Clause clause)
{
final String str = clause.toString();
for (Clause clauseR : rhs)
if (clauseR.toString().equals(str))
return true;
return false;
}
//-------------------------------------------------------------------------
public void alphabetiseClauses()
{
Collections.sort(rhs, new Comparator<Clause>()
{
@Override
public int compare(final Clause a, final Clause b)
{
// return a.symbol().name().compareTo(b.symbol().name());
// return a.symbol().className().compareTo(b.symbol().className());
return a.symbol().token().compareTo(b.symbol().token());
}
});
// Move constructor clauses to front of list
for (int n = 0; n < rhs.size(); n++)
{
final Clause clause = rhs.get(n);
if (clause.args() != null)
{
// Clause is for a constructor
rhs.remove(n);
rhs.add(0, clause);
//System.out.println("Clause is constructor: " + clause);
}
}
}
//-------------------------------------------------------------------------
@Override
public String toString()
{
String ruleStr = "";
if (lhs == null)
return "** No LHS. **";
//ruleStr += (lhs.type() == SymbolType.Constant) ? lhs.name() : lhs.toString(true); // force lowerCamelCase on LHS
ruleStr += (lhs.ludemeType() == LudemeType.Constant) ? lhs.grammarLabel() : lhs.toString(true); // force lowerCamelCase on LHS
//ruleStr += " (" + lhs.cls().getName() + ")";
// Special handling for IntArrayFunction
final boolean isInts = ruleStr.equals("<int>{<int>}");
if (isInts)
ruleStr = "<ints>";
while (ruleStr.length() < TAB_LHS)
ruleStr += " ";
ruleStr += IMPLIES;
// Assemble string description for RHS
String rhsStr = "";
if (isInts)
rhsStr = "{<int>}";
for (final Clause clause : rhs)
{
// if (clause.isHidden())
// continue; // denoted with a @Hide annotation
if (!rhsStr.isEmpty())
rhsStr += " | ";
String expStr = clause.toString();
rhsStr += expStr;
// System.out.println("Clause is: " + clause);
}
ruleStr += rhsStr;
// Prepare tab if needed
String tab = "";
for (int c = 0; c < TAB_RHS; c++)
tab += " ";
// Split line as needed
int lastBreakAt = 0;
for (int c = 0; c < ruleStr.length(); c++)
{
if (c - lastBreakAt > MAX_LINE_WIDTH) // - 1)
{
// Break the line
//
// Backtrack to previous '|' symbol (if any)
int barAt = c;
while (barAt > 2 && ruleStr.charAt(barAt - 2) != '|')
barAt--;
if (barAt < lastBreakAt + tab.length())
{
// Look for next '|' symbol
barAt = c;
while (barAt < ruleStr.length() && ruleStr.charAt(barAt) != '|')
barAt++;
}
if (barAt > 0 && barAt < ruleStr.length())
ruleStr = ruleStr.substring(0, barAt) + "\n" + tab + ruleStr.substring(barAt);
lastBreakAt = barAt;
}
}
return ruleStr;
}
//-------------------------------------------------------------------------
}
| 5,071 | 22.590698 | 129 | java |
Ludii | Ludii-master/Common/src/main/grammar/Instance.java | package main.grammar;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
//-----------------------------------------------------------------------------
/**
* Instance of a symbol which may be a compiled object (compile stage) or a list
* of possible clauses (parse stage).
*/
public class Instance
{
// Symbol corresponding to a token in the game definition.
// Tokens can map to multiple symbols.
protected final Symbol symbol;
// Possible clauses this symbol might match with.
private List<Clause> clauses = null;
// The compiled object (may be created from a class, enum constant, primitive or Java wrapper class).
protected Object object = null;
/** Name of constant if derived from application constant, e.g. "Off", "End", "Repeat", ... */
private final String constant;
//-------------------------------------------------------------------------
/**
* Constructor for Compiler specifying actual object compiled.
*/
public Instance(final Symbol symbol, final Object object)
{
this.symbol = symbol;
this.object = object;
this.constant = null;
}
/**
* Constructor for Compiler specifying actual object compiled.
*/
public Instance(final Symbol symbol, final Object object, final String constant)
{
this.symbol = symbol;
this.object = object;
this.constant = constant;
}
//-------------------------------------------------------------------------
public Symbol symbol()
{
return symbol;
}
public List<Clause> clauses()
{
if (clauses == null)
return null;
return Collections.unmodifiableList(clauses);
}
public void setClauses(final List<Clause> list)
{
clauses = new ArrayList<Clause>();
clauses.addAll(list);
}
public Object object()
{
return object;
}
public void setObject(final Object object)
{
this.object = object;
}
public String constant()
{
return constant;
}
//-------------------------------------------------------------------------
/**
* @return Class for this symbol. Can assume it is unique over all symbols(?)
*/
public Class<?> cls()
{
if (symbol.cls() == null)
System.out.println("** Instance: null symbol.cls() for symbol " + symbol.name() + ".");
return symbol.cls();
}
//-------------------------------------------------------------------------
@Override
public String toString()
{
if (symbol == null)
return "Unknown";
return symbol.grammarLabel()
+
(cls() == null ? " (null)" : ", cls: " + cls().getName())
+
(object == null ? " (null)" : ", object: " + object);
}
//-------------------------------------------------------------------------
}
| 2,684 | 22.146552 | 103 | java |
Ludii | Ludii-master/Common/src/main/grammar/LudemeInfo.java | package main.grammar;
import java.util.List;
/**
* Convenience class containing ludeme info to store in database.
* @author cambolbro and Matthew.Stephenson
*/
public class LudemeInfo
{
/** Ludeme's unique id in the database. 0 means unassigned. */
private int id = 0;
/**
* Grammar symbol corresponding to this ludeme.
* Use symbol.keyword() to get this ludeme's token as used in game descriptions.
* Use symbol.grammarLabel() to get the minimally scoped token used in the grammar.
* Use symbol.cls() to get class that generated this ludeme.
* Use symbol.type() to get the ludeme type: Ludeme/SuperLudeme/Constant/Predefined/Primitive
*/
private final Symbol symbol;
/** Short description of ludeme (maybe taken from JavaDoc). */
private String description = "";
private String packagePath = "";
//-------------------------------------------------------------------------
public LudemeInfo(final Symbol symbol)
{
this.symbol = symbol;
packagePath = symbol.cls().getName();
}
//-------------------------------------------------------------------------
public int id()
{
return id;
}
public void setId(final int id)
{
this.id = id;
}
public Symbol symbol()
{
return symbol;
}
public String description()
{
return description;
}
public void setDescription(final String description)
{
this.description = description;
}
//-------------------------------------------------------------------------
public String getDBString()
{
return symbol.name() + "," +
packagePath + "," +
symbol.ludemeType() + "," +
symbol.token() + "," +
symbol.grammarLabel() + "," +
(symbol.usedInGrammar() ? 1 : 0) + "," +
(symbol.usedInMetadata() ? 1 : 0) + "," +
(symbol.usedInDescription() ? 1 : 0) + ",\"" +
description + "\"";
}
//-------------------------------------------------------------------------
/**
* @return First LudemeInfo in list that matches a Call object.
*/
public static LudemeInfo findLudemeInfo
(
final Call call, final List<LudemeInfo> ludemes
)
{
// Pass 1: Check for special constants
if (call.constant() != null)
for (final LudemeInfo ludemeInfo : ludemes)
if (call.constant().equals(ludemeInfo.symbol().name()))
return ludemeInfo;
// Pass 2: Check for exact match
for (final LudemeInfo ludemeInfo : ludemes)
if (ludemeInfo.symbol().path().equals(call.symbol().atomicLudeme().path()))
return ludemeInfo;
// **
// ** TODO: Check that closest compatible type is returned, i.e.
// ** superclass, else its superclass, else its superclass, ...?
// **
// Pass 3: Check for compatible type
// for (final LudemeInfo ludemeInfo : ludemes)
// if (ludemeInfo.symbol().compatibleWith(call.symbol()))
// return allParentLudemes(ludemeInfo, ludemes);
// // Pass 3: Check for primitive wrappers
// for (final LudemeInfo ludemeInfo : ludemes)
// if
// (
// (
// (
// call.symbol().name().equals("Integer")
// ||
// call.symbol().name().equals("IntConstant")
// ||
// call.symbol().name().equals("DimConstant")
// )
// &&
// ludemeInfo.symbol().name().equals("int")
// )
// ||
// (
// (
// call.symbol().name().equals("Boolean")
// ||
// call.symbol().name().equals("BooleanConstant")
// )
// &&
// ludemeInfo.symbol().name().equals("boolean")
// )
// ||
// (
// (
// call.symbol().name().equals("Float")
// ||
// call.symbol().name().equals("FloatConstant")
// )
// &&
// ludemeInfo.symbol().name().equals("float")
// )
// )
// return allParentLudemes(ludemeInfo, ludemes);
//
// // Pass 4: Check the return type (only for specific cases like Graph and Dim)
// final List<LudemeInfo> ludemeInfoFound = new ArrayList<>();
// for (final LudemeInfo ludemeInfo : ludemes)
// if (ludemeInfo.symbol().returnType().equals(call.symbol().returnType()))
// ludemeInfoFound.add(ludemeInfo);
// if (ludemeInfoFound.size() > 1)
// System.out.println(ludemeInfoFound);
// if (ludemeInfoFound.size() == 1)
// return allParentLudemes(ludemeInfoFound.get(0), ludemes);
// System.out.println("\nERROR! Matching Ludeme not found.");
// //System.out.println("Call: " + call.toString().strip());
// System.out.println("Symbol name: " + call.symbol().name());
// System.out.println("Symbol path: " + call.symbol().path());
// System.out.println("Symbol token: " + call.symbol().token());
// System.out.println("Symbol return type: " + call.symbol().returnType());
//
// System.out.println(call);
return null;
}
//-------------------------------------------------------------------------
// @SuppressWarnings("unused")
// public static Set<LudemeInfo> allParentLudemes(final LudemeInfo ludemeinfo, final List<LudemeInfo> ludemeInfos)
// {
// final Set<LudemeInfo> parentLudemes = new HashSet<>();
// parentLudemes.add(ludemeinfo);
//
// // JUST A TEMPORARY CHECK FOR CAMERON
//// if (ludemeinfo.symbol().name().equals("N"))
//// System.out.println(ludemeinfo.symbol().ancestors());
//
//// // Add this symbol's ancestors to the list
//// for (final Symbol ancestor : ludemeinfo.symbol().ancestors())
//// for (final LudemeInfo info : ludemeInfos)
//// if (info.symbol().equals(ancestor))
//// parentLudemes.add(info);
//
// return parentLudemes;
// }
}
| 5,435 | 27.610526 | 114 | java |
Ludii | Ludii-master/Common/src/main/grammar/PackageInfo.java | package main.grammar;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
//-----------------------------------------------------------------------------
/**
* Java package in class hierarchy.
* @author cambolbro
*/
public class PackageInfo
{
protected String path = "";
protected List<GrammarRule> rules = new ArrayList<GrammarRule>();
//-------------------------------------------------------------------------
/**
* Constructor.
* @param path
*/
public PackageInfo(final String path)
{
this.path = path;
}
//-------------------------------------------------------------------------
/**
* @return Package name.
*/
public String path()
{
return path;
}
/**
* @return Final term of package name.
*/
public String shortName()
{
final String[] subs = path.split("\\.");
if (subs.length == 0)
return path;
return subs[subs.length - 1];
}
/**
* @return Rules in this package.
*/
public List<GrammarRule> rules()
{
return Collections.unmodifiableList(rules);
}
//-------------------------------------------------------------------------
public void add(final GrammarRule rule)
{
rules.add(rule);
}
public void add(final int n, final GrammarRule rule)
{
rules.add(n, rule);
}
public void remove(final int n)
{
rules.remove(n);
}
//-------------------------------------------------------------------------
/**
* Order rules within package alphabetically.
*/
public void listAlphabetically()
{
Collections.sort(rules, new Comparator<GrammarRule>()
{
@Override
public int compare(final GrammarRule a, final GrammarRule b)
{
// return a.lhs().name().compareTo(b.lhs().name());
return a.lhs().grammarLabel().compareTo(b.lhs().grammarLabel());
}
});
}
//-------------------------------------------------------------------------
@Override
public String toString()
{
String str = "";
str += "//";
while (str.length() < GrammarRule.MAX_LINE_WIDTH) // shorten so that prints neatly
str += "-";
str += "\n";
str += "// " + path + "\n\n";
int numUsed = 0;
for (GrammarRule rule : rules)
{
// if (rule.remove())
// continue;
if
(
!rule.lhs().usedInGrammar()
&&
!rule.lhs().usedInDescription()
&&
!rule.lhs().usedInMetadata()
)
continue;
if (rule.rhs() == null || rule.rhs().isEmpty())
continue;
str += rule.toString() + "\n";
numUsed++;
}
str += "\n";
if (numUsed == 0)
return ""; // no rules -- ignore this package
return str;
}
//-------------------------------------------------------------------------
}
| 2,745 | 18.475177 | 85 | java |
Ludii | Ludii-master/Common/src/main/grammar/ParseItem.java | package main.grammar;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.Collections;
import java.util.List;
import main.grammar.Token.TokenType;
//-----------------------------------------------------------------------------
/**
* An item in the parse tree corresponding to a token in the game description.
*
* @author cambolbro
*/
public class ParseItem
{
// Parse token that this item corresponds to.
private final Token token;
private final List<ParseItem> arguments = new ArrayList<ParseItem>();
// Parent item. Will be null for the root of the parse tree.
private final ParseItem parent;
// List of symbols and grammar clauses that match this item.
private final List<Instance> instances = new ArrayList<Instance>();
// Whether this token and its arguments all parse
private boolean doesParse = false;
// Whether token was visited during parse
private boolean visited = false;
// Depth in tree
private final int depth;
//-------------------------------------------------------------------------
public ParseItem(final Token token, final ParseItem parent)
{
this.token = token;
this.parent = parent;
depth = (parent == null) ? 0 : parent.depth() + 1;
}
//-------------------------------------------------------------------------
public Token token()
{
return token;
}
public List<ParseItem> arguments()
{
return Collections.unmodifiableList(arguments);
}
public ParseItem parent()
{
return parent;
}
public List<Instance> instances()
{
return Collections.unmodifiableList(instances);
}
public boolean doesParse()
{
return doesParse;
}
public boolean visited()
{
return visited;
}
public int depth()
{
return depth;
}
//-------------------------------------------------------------------------
public void clearInstances()
{
instances.clear();
}
public void add(final Instance instance)
{
instances.add(instance);
}
public void add(final ParseItem arg)
{
arguments.add(arg);
}
//-------------------------------------------------------------------------
// private static int DEBUG = 0;
//
// public void matchSymbols(final Grammar grammar, final Report report)
// {
// instances.clear();
//
// Arg arg;
// switch (token.type())
// {
// case Terminal: // String, number, enum, True, False
// arg = new ArgTerminal(token.name(), token.parameterLabel());
// arg.matchSymbols(grammar, report); // instantiates actual object(s), not need for clauses
//
// for (final Instance instance : arg.instances())
// //if (!instance.symbol().isAbstract())
// instances.add(instance);
//
// if (DEBUG != 0)
// {
// System.out.println("\nTerminal token '" + token.name() + "' has " + instances.size() + " instances:");
// for (final Instance instance : instances)
// {
// System.out.println(":: " + instance.toString());
//
// if (instance.object() != null)
// System.out.println("=> " + instance.object());
//
// if (instance.clauses() != null)
// for (final Clause clause : instance.clauses())
// System.out.println("---- " + clause.toString());
// }
// }
// break;
// case Class:
// // Find matching symbols and their clauses
// arg = new ArgClass(token.name(), token.parameterLabel());
// arg.matchSymbols(grammar, report);
//
// for (final Instance instance : arg.instances())
// //if (!instance.symbol().isAbstract())
// instances.add(instance);
//
// // Associate clauses with each instance of arg
// for (final Instance instance : instances)
// {
// final GrammarRule rule = instance.symbol().rule();
// if (rule == null)
// {
// // **
// // ** This should not occur!
// // ** Possibly ludeme has same name as a predefined Grammar ludeme, e.g. State.
// // **
// System.out.println("** ParseItem.matchSymbols(): Null rule for symbol " + instance.symbol() +
// ", parent is " + (parent == null ? "null" : parent.token()) + ".");
// }
// else
// {
// //final List<Clause> clauses = rule.rhs();
// instance.setClauses(rule.rhs());
// }
// }
//
// if (DEBUG != 0)
// {
// System.out.println("\nClass token '" + token.name() + "' has " + instances.size() + " instances:");
// for (final Instance instance : instances)
// {
// System.out.println(":: " + instance.toString());
//
// if (instance.object() != null)
// System.out.println("=> " + instance.object());
//
// if (instance.clauses() != null)
// for (final Clause clause : instance.clauses())
// System.out.println("---- " + clause.toString());
// }
// }
// break;
// case Array:
// // Do nothing: use instances of each element on a case-by-case basis
// break;
// }
// }
//-------------------------------------------------------------------------
public boolean parse(final Symbol expected, final Report report, final String tab)
{
if (tab != null)
System.out.println("\n" + tab + "Parsing token " + token.name() + ", expected type is " +
(expected == null ? "null" : expected.name()) + ".");
visited = true;
switch (token.type())
{
case Terminal:
return parseTerminal(expected, tab);
case Array:
return parseArray(expected, report, tab);
case Class:
return parseClass(expected, report, tab);
default:
// Do nothing
}
return doesParse;
}
//-------------------------------------------------------------------------
private boolean parseTerminal(final Symbol expected, final String tab)
{
// Handle terminal
if (tab != null)
System.out.println(tab + "Handling terminal...");
for (final Instance instance : instances)
{
if (tab != null)
{
System.out.print(tab + "Instance: " + instance.symbol().name());
System.out.println(" => " + instance.symbol().returnType().name() + "... ");
}
if (instance.clauses() != null)
continue; // terminals don't have clauses
// Check whether symbol is of expected return type
if (expected != null && !expected.compatibleWith(instance.symbol()))
{
if (tab != null)
System.out.println(tab + "No match, move onto next instance...");
continue;
}
if (tab != null)
System.out.println(tab + "++++ Terminal '" + instance.symbol().name() + "' parses. ++++");
doesParse = true;
return true;
}
return false;
}
//-------------------------------------------------------------------------
private boolean parseArray(final Symbol expected, final Report report, final String tab)
{
// Handle array
if (tab != null)
System.out.println(tab + "Handling array...");
if (tab != null)
{
System.out.println(tab + "> Expected: " + expected.name());
for (final ParseItem element : arguments)
System.out.println(tab + "> " + element.token().name());
}
// Check that elements can be parsed with the expected type
for (int e = 0; e < arguments.size(); e++)
{
final ParseItem element = arguments.get(e);
if (!element.parse(expected, report, (tab == null ? null : tab + " ")))
{
// Array fails if any element fails
if (tab != null)
System.out.println(tab + " X: Couldn't parse array element " + e + ".");
return false;
}
}
// All array elements parsed without error
if (tab != null)
System.out.println(tab + "++++ Array of '" + expected.name() + "' parses. ++++");
doesParse = true;
return true;
}
//-------------------------------------------------------------------------
private boolean parseClass(final Symbol expected, final Report report, final String tab)
{
// Handle class
if (tab != null)
System.out.println(tab + "Handling class...");
// Find possible instances that match expected return type
for (final Instance instance : instances)
{
if (tab != null)
{
System.out.print(tab + "Class instance: " + instance.symbol().name());
System.out.print(" => " + instance.symbol().returnType().name() + "... ");
}
// Check whether symbol is of expected return type
if (expected != null && !expected.compatibleWith(instance.symbol()))
{
if (tab != null)
System.out.println("no match, move onto next instance...");
continue;
}
if (tab != null)
System.out.println("possible match.");
// Try possible clauses of this instance
//if (tab != null)
// System.out.println(tab + "Symbol match, checking possible clauses...");
if (instance.clauses() == null)
{
//System.out.println("** No clauses for instance: " + instance);
continue;
}
int c;
for (c = 0; c < instance.clauses().size(); c++)
{
final Clause clause = instance.clauses().get(c);
if (tab != null)
System.out.println(tab + (c+1) + ". Trying clause: " + clause);
if (arguments.size() > 0 && clause.args() == null)
{
if (tab != null)
System.out.println(tab + " X: Item has arguments but clauses does not.");
continue;
}
if (arguments.size() > clause.args().size())
{
if (tab != null)
System.out.println(tab + " X: Too many arguments for this clause.");
continue;
}
// if (clause.args().size() > ArgCombos.MAX_ARGS)
// {
// if (tab != null)
// System.out.println(tab + " X: " + clause.symbol().name() + " has more than " + ArgCombos.MAX_ARGS + " args.");
// report.addWarning(clause.symbol().name() + " has more than " + ArgCombos.MAX_ARGS + " args.");
// continue;
// }
// **
// ** Don't check each argument individually, as position in list can dictate what type it is
// **
final int numSlots = clause.args().size();
final int clauseSize = clause.args().size();
final int argsSize = arguments.size();
// Generate all combinations of on-bits up to the maximum expected size
for (int seed = 0; seed < (0x1 << clauseSize); seed++)
{
if (Integer.bitCount(seed) != argsSize)
continue; // wrong number of on-bits
final BitSet combo = BitSet.valueOf(new long[] { seed });
// Try this arg combo
final BitSet subset = (BitSet)combo.clone();
subset.and(clause.mandatory());
if (!subset.equals(clause.mandatory()))
continue; // some mandatory arguments are null
if (tab != null)
{
System.out.print(tab + " Trying arg combo: ");
int index = 0;
for (int n = 0; n < numSlots; n++)
System.out.print((combo.get(n) ? "-" : ++index) + " ");
System.out.println();
}
final BitSet orGroups = new BitSet();
int index = 0;
int a;
for (a = 0; a < numSlots; a++)
{
if (!combo.get(a))
{
// Arg will be null; check that's optional (or an @Or)
final ClauseArg clauseArg = clause.args().get(a);
final boolean canSkip = clauseArg.optional() || clauseArg.orGroup() > 0;
if (!canSkip)
{
//System.out.println(tab + "Arg " + a + " can't be null.");
break; // this arg can't be null
}
}
else
{
final ParseItem arg = arguments.get(index++);
final ClauseArg clauseArg = clause.args().get(a);
// Check that @Or group is valid (if any)
final int orGroup = clauseArg.orGroup();
if (orGroup > 0)
{
//System.out.println("orGroup is " + orGroup);
if (orGroups.get(orGroup))
break; // too many non-null args in this @Or group
orGroups.set(orGroup, true);
}
// Check that names are valid (if any)
final String argName = arg.token().parameterLabel();
final String clauseArgName = clauseArg.label();
//System.out.println("\narg.token().parameterLabel()=" + arg.token().parameterLabel());
//System.out.println("clauseArg.label()=" + clauseArg.label());
if
(
argName == null && clauseArgName != null
||
argName != null && clauseArgName == null
||
argName != null && !argName.equalsIgnoreCase(clauseArgName)
)
{
// **
// ** FIXME: This still allows users to misspell argument names,
// ** by capitalising badly.
// **
//System.out.println("Name clash.";
break; // name mismatch
}
if (!arg.parse(clauseArg.symbol(), report, (tab == null ? null : tab + " ")))
{
if (tab != null)
System.out.println(tab + " X: Couldn't parse arg " + index + ".");
break;
}
}
}
if (a >= numSlots)
{
// This arg combo matches this clause
if (tab != null)
System.out.println(tab + "++++ Class '" + instance.symbol().name() + "' parses. ++++");
doesParse = true;
return true;
}
if (tab != null)
System.out.println(tab + "Failed to parse this combo, trying next...");
}
}
}
return false;
}
//-------------------------------------------------------------------------
/**
* @return Depth of deepest item that does not parse.
*/
public int deepestFailure()
{
int result = (doesParse || !visited) ? -1 : depth;
for (final ParseItem arg : arguments)
{
final int argResult = arg.deepestFailure();
if (argResult > result)
result = argResult;
}
return result;
}
public void reportFailures(final Report report, final int failureDepth)
{
if (!doesParse && visited && depth == failureDepth)
{
// This token could not be parsed
if (parent == null)
{
final String clause = Report.clippedString(tokenClause(), 32);
report.addError("Unexpected syntax '" + clause + "'.");
}
else
{
final String clause = Report.clippedString(tokenClause(), 24);
final String parentClause = Report.clippedString(parent.tokenClause(), 32);
report.addError("Unexpected syntax '" + clause + "' in '" + parentClause +"'.");
}
}
for (final ParseItem arg : arguments)
arg.reportFailures(report, failureDepth);
}
//-------------------------------------------------------------------------
public String dump(final String indent)
{
final String TAB = " ";
final StringBuilder sb = new StringBuilder();
//final String label = "" + token.type().name().charAt(0) + token.type().name().charAt(1) + ": ";
final String label = (doesParse ? "+" : "-") + " ";
sb.append(label + indent);
if (token.parameterLabel() != null)
sb.append(token.parameterLabel() + ":");
if (token.open() != 0)
sb.append(token.open());
if (token.name() != null)
sb.append(token.name());
// if (token.parameterLabel() != null)
// sb.append(" (" + token.parameterLabel() + ":)");
if (arguments.size() > 0)
{
sb.append("\n");
for (final ParseItem arg : arguments)
sb.append(arg.dump(indent + TAB));
if (token.close() != 0)
sb.append(label + indent + token.close());
}
else
{
if (token.close() != 0)
sb.append(token.close());
}
sb.append("\n");
return sb.toString();
}
//-------------------------------------------------------------------------
public String compare()
{
final StringBuilder sb = new StringBuilder();
// if (token.type() != TokenType.Class)
// {
// System.out.println("** Class expected but " + token.name() + " found.");
// return sb.toString();
// }
// final String label = "" + type().name().charAt(0) + type().name().charAt(type().name().length()-1) + ": ";
// final String label = ""; // + token.type().name().charAt(0) + token.type().name().charAt(1) + ": ";
sb.append("--------------------------\n");
// 1. Show the token of this clause
sb.append(tokenClause());
// 2. Show the potential clauses
if (token.type() == TokenType.Array)
{
sb.append(" => Array\n");
}
else if (token.type() == TokenType.Terminal)
{
if (instances == null || instances.size() < 1)
return "** compare(): No instances for terminal " + token.name() + ".\n";
sb.append(" => " + instances.get(0).symbol().cls().getSimpleName() + "\n");
}
else
{
sb.append("\n");
for (final Instance instance : instances)
{
if (instance != null && instance.clauses() != null)
{
for (int c = 0; c < instance.clauses().size(); c++)
{
final Clause clause = instance.clauses().get(c);
// sb.append(clause.toString() + " ==> " + clause.symbol().grammarLabel() + "\n");
sb.append("" + (c+1) + ". " + clause.symbol().grammarLabel() + ": " + clause.toString());
sb.append(" => " + instance.symbol().cls().getSimpleName());
sb.append("\n");
}
}
}
}
for (final ParseItem arg : arguments)
sb.append(arg.compare());
return sb.toString();
}
//-------------------------------------------------------------------------
public String tokenClause()
{
final StringBuilder sb = new StringBuilder();
if (token.parameterLabel() != null)
sb.append(token.parameterLabel() + ":");
if (token.open() != 0)
sb.append(token.open());
if (token.name() != null)
sb.append(token.name());
for (int a = 0; a < arguments.size(); a++)
{
final ParseItem arg = arguments.get(a);
if (a > 0 || token.name() != null)
sb.append(" ");
sb.append(arg.tokenClause());
}
if (token.close() != 0)
sb.append(token.close());
return sb.toString();
}
//-------------------------------------------------------------------------
}
| 17,547 | 26.164087 | 120 | java |
Ludii | Ludii-master/Common/src/main/grammar/Report.java | package main.grammar;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* Report generated by expand/parse/compile process.
*
* @author cambolbro
*/
public class Report
{
private final List<String> errors = new ArrayList<String>();
private final List<String> warnings = new ArrayList<String>();
private final List<String> notes = new ArrayList<String>();
// Ongoing report log to replace printlns to Console
private final StringBuilder log = new StringBuilder();
private ReportMessenger reportMessageFunctions;
//-------------------------------------------------------------------------
public List<String> errors()
{
return Collections.unmodifiableList(errors);
}
public List<String> warnings()
{
return Collections.unmodifiableList(warnings);
}
public List<String> notes()
{
return Collections.unmodifiableList(notes);
}
//-------------------------------------------------------------------------
// Error log
/**
* Clear the error log.
*/
public void clearLog()
{
log.setLength(0);
}
/**
* Add a string to the error log.
*/
public void addLog(final String str)
{
log.append(str);
}
/**
* Add a line to the error log.
*/
public void addLogLine(final String str)
{
log.append(str + "\n");
}
/**
* @return Current error log as a string.
*/
public String log()
{
return log.toString();
}
//-------------------------------------------------------------------------
public void addError(final String error)
{
if (!errors.contains(error))
errors.add(error);
}
public void addWarning(final String warning)
{
if (!warnings.contains(warning))
warnings.add(warning);
}
public void addNote(final String note)
{
if (!notes.contains(note))
notes.add(note);
}
//-------------------------------------------------------------------------
public boolean isError()
{
return !errors.isEmpty();
}
public boolean isWarning()
{
return !warnings.isEmpty();
}
public boolean isNote()
{
return !notes.isEmpty();
}
//-------------------------------------------------------------------------
public void clear()
{
errors.clear();
warnings.clear();
notes.clear();
log.setLength(0);
}
//-------------------------------------------------------------------------
/**
* @return Input string clipped to maximum char length.
*/
public static String clippedString(final String str, final int maxChars)
{
if (str.length() < maxChars)
return str;
return str.substring(0, maxChars-3) + "...";
}
//-------------------------------------------------------------------------
@Override
public String toString()
{
final StringBuilder sb = new StringBuilder();
for (final String error : errors)
sb.append(error);
for (final String warning : warnings)
sb.append("Warning: " + warning);
for (final String note : notes)
sb.append("Note: " + note);
return sb.toString();
}
//-------------------------------------------------------------------------
/**
* Report Messenger interface for printing report messages as needed.
*
* @author Matthew.Stephenson
*/
public interface ReportMessenger
{
void printMessageInStatusPanel(String s);
void printMessageInAnalysisPanel(String s);
}
public ReportMessenger getReportMessageFunctions()
{
return reportMessageFunctions;
}
public void setReportMessageFunctions(final ReportMessenger reportMessageFunctions)
{
this.reportMessageFunctions = reportMessageFunctions;
}
//-------------------------------------------------------------------------
}
| 3,655 | 19.311111 | 85 | java |
Ludii | Ludii-master/Common/src/main/grammar/Symbol.java | package main.grammar;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import main.Constants;
//-----------------------------------------------------------------------------
/**
* Symbol within the grammar, either:
* 1. Primitive : primitive data type (terminal).
* 2. Predefined : predefined utility class, e.g. BitSet.
* 3. Constant : enum constant (terminal).
* 4. Class : denoted by <name> (non-terminal).
*
* @author cambolbro
*/
public class Symbol
{
//-------------------------------------------------------------------------
/**
* Types of of ludemes implemented.
*/
public static enum LudemeType
{
/** Standard ludeme class, e.g. (from ...). */
Ludeme,
/** Super ludeme class, e.g. (move Add ...). */
SuperLudeme,
/** Sub ludeme class implements a case of super ludeme, e.g. MoveAdd. */
SubLudeme,
/** Appears in the grammar (as rule?) but never instantiated in descriptions. */
Structural,
/** Enum constant, e.g. Orthogonal. */
Constant,
/** Predefined data type and wrapper classes, e.g. String, Integer, etc. */
Predefined,
/** Primitive data types, e.g. int, float, boolean, etc. */
Primitive,
}
/** Ludeme type of this symbol. */
private LudemeType ludemeType;
//---------------------------------------------------------
/** Symbol class name without decoration. */
private String name = "";
/** Path for loading associated class. */
private String path = "";
/** Keyword in lowerCamelCase form, derived from name. */
private String token = "";
/**
* Unique name in grammar, made from keyword + minimal necessary scoping from package names.
* e.g. moves.if, ints.math.if, booleans.math.if, etc.
*/
private String grammarLabel = null;
// /** Symbol name as it appears in descriptions, without scope. */
// private String nameLowerCamelCase = "";
/** Location of file. For Primitives and Predefined classes, this is
* a notional package for ordering types logically in code base. */
private String notionalLocation = "";
private final boolean hasAlias;
//---------------------------------------------------------
/** Whether symbol describes an abstract class. */
private boolean isAbstract = false;
/** Return type based on "eval()" method, else lhs if Class and no "eval()". */
private Symbol returnType = null;
/** Whether symbol should be hidden from grammar, e.g. a behind-the-scenes support class. */
private boolean hidden = false;
// /** Whether the symbol name should not be shown in the constructor, e.g. ItemCount(). */
// private boolean hiddenName = false;
/** Degree of array nesting: 0=none, 1=[], 2=[][], 3=[][][], etc. */
private int nesting = 0;
//---------------------------------------------------------
/**
* Whether symbol occurs anywhere in the current grammar.
* This includes game logic, metadata and implied <rules> that don't instantiate.
*/
private boolean usedInGrammar = false;
/**
* Whether symbol can occur in a .lud game description (game logic part only).
* Must be an instantiable RHS clause.
*/
private boolean usedInDescription = false;
/** Whether symbol can occur in the metadata section. */
private boolean usedInMetadata = false;
//---------------------------------------------------------
/** Whether symbol has been visited (avoid infinite loops during grammar generation). */
private boolean visited = false;
/** Depth in grammar hierarchy. */
private int depth = Constants.UNDEFINED;
//---------------------------------------------------------
/** Production rule with this symbol as LHS (null if terminal). */
private GrammarRule rule = null;
/** Package that this symbol belongs to. */
private PackageInfo pack = null;
/** Class associated with this symbol (null if not a class). */
private final Class<?> cls; // = null;
/** List of ancestors in class hierarchy. */
private final List<Symbol> ancestors = new ArrayList<>();
/** Super ludeme that this symbol is a subludeme of (if any). */
private Symbol subLudemeOf = null;
/**
* The "official" atomic ludeme that represents this symbol in the database.
* e.g. int, Integer, IntFunction, IntConstant all map to the same ludeme (class.Integer).
*/
private Symbol atomicLudeme = null;
//-------------------------------------------------------------------------
/**
* Default constructor.
* @param type
* @param path
* @param alias
* @param cls
*/
public Symbol
(
final LudemeType type, final String path, final String alias, final Class<?> cls
)
{
this.ludemeType = type;
this.path = new String(path);
this.cls = cls;
this.hasAlias = (alias != null && alias != "");
extractPackagePath();
extractName();
deriveKeyword(alias);
grammarLabel = new String(token); // lowerCamelCase version?
// if (path.equals("game.functions.ints.IntFunction"))
// {
// System.out.println("Symbol(): name=" + name + ", keyword=" + token + ", grammarLabel=" + grammarLabel);
// }
// System.out.println("\nname: " + name);
// System.out.println("path: " + path);
// System.out.println("notionalLocation: " + notionalLocation);
}
/**
* Constructor for Constant types.
* @param type
* @param path
* @param alias
* @param notionalLocation
* @param cls
*/
public Symbol
(
final LudemeType type, final String path, final String alias,
final String notionalLocation, final Class<?> cls
)
{
this.ludemeType = type;
this.path = new String(path);
this.notionalLocation = new String(notionalLocation);
this.cls = cls;
this.hasAlias = (alias != null && alias != "");
extractName();
deriveKeyword(alias);
grammarLabel = new String(name);
}
/**
* Copy constructor.
* @param other
*/
public Symbol(final Symbol other)
{
// deepCopy(other);
// symbolType = other.symbolType;
ludemeType = other.ludemeType;
name = new String(other.name);
path = new String(other.path);
token = new String(other.token);
hasAlias = other.hasAlias;
// nameLowerCamelCase = new String(other.nameLowerCamelCase);
grammarLabel = new String(other.grammarLabel);
notionalLocation = new String(other.notionalLocation);
isAbstract = other.isAbstract;
returnType = other.returnType;
// isList = other.isList;
nesting = other.nesting;
usedInGrammar = other.usedInGrammar;
usedInDescription = other.usedInDescription;
usedInMetadata = other.usedInMetadata;
visited = other.visited;
rule = other.rule;
pack = other.pack;
cls = other.cls;
}
//-------------------------------------------------------------------------
// /**
// * @return Symbol type.
// */
// public SymbolType symbolType()
// {
// return symbolType;
// }
//
// /**
// * @param type Symbol type to set.
// */
// public void setSymbolType(final SymbolType type)
// {
// symbolType = type;
// }
/**
* @return Ludeme type.
*/
public LudemeType ludemeType()
{
return ludemeType;
}
/**
* @param type Ludeme type to set.
*/
public void setLudemeType(final LudemeType type)
{
ludemeType = type;
}
/**
* @return Element (class) name.
*/
public String name()
{
return name;
}
/**
* @return Absolute path.
*/
public String path()
{
return path;
}
/**
* @return Keyword in lowerCamelCase form.
*/
public String token()
{
return token;
}
public void setToken(final String word)
{
token = word;
}
/**
* @return Unique label within the grammar (for classes).
*/
public String grammarLabel()
{
return grammarLabel;
}
// /**
// * @return Symbol name as it appears in grammar, without scope.
// */
// public String nameLowerCamelCase()
// {
// return nameLowerCamelCase;
// }
public void setGrammarLabel(final String gl)
{
grammarLabel = new String(gl);
}
public boolean hasAlias()
{
return hasAlias;
}
/**
* @return Package path.
*/
public String notionalLocation()
{
return notionalLocation;
}
/**
* @return Whether this element is based on an abstract class.
*/
public boolean isAbstract()
{
return isAbstract;
}
/**
* @param val
*/
public void setIsAbstract(final boolean val)
{
isAbstract = val;
}
/**
* @return Whether symbol should be hidden from grammar.
*/
public boolean hidden()
{
return hidden;
}
/**
* @param val
*/
public void setHidden(final boolean val)
{
hidden = val;
}
// /**
// * @return Whether symbol name should not be shown in constructor.
// */
// public boolean hiddenName()
// {
// return hiddenName;
// }
//
// public void setHiddenName(final boolean val)
// {
// hiddenName = val;
// }
/**
* @return Return type based on "apply()" method, else lhs if Class and no "apply()".
*/
public Symbol returnType()
{
return returnType;
}
/**
* @param symbol
*/
public void setReturnType(final Symbol symbol)
{
returnType = symbol;
}
/**
* @return Degree of nesting (array depth).
*/
public int nesting()
{
return nesting;
}
/**
* @param val
*/
public void setNesting(final int val)
{
nesting = val;
}
/**
* @return Whether this symbol is used anywhere in the grammar.
*/
public boolean usedInGrammar()
{
return usedInGrammar;
}
/**
* @param value Whether this symbol is used anywhere in the grammar.
*/
public void setUsedInGrammar(final boolean value)
{
usedInGrammar = value;
}
/**
* @return Whether this symbol can occur in game descriptions.
*/
public boolean usedInDescription()
{
return usedInDescription;
}
/**
* @param value Whether this symbol can occur in game description.
*/
public void setUsedInDescription(final boolean value)
{
usedInDescription = value;
}
/**
* @return Whether this symbol can occur in the metadata.
*/
public boolean usedInMetadata()
{
return usedInMetadata;
}
/**
* @param value Whether this symbol can occur in the metadata.
*/
public void setUsedInMetadata(final boolean value)
{
usedInMetadata = value;
}
/**
* @return Whether this symbol has been visited.
*/
public boolean visited()
{
return visited;
}
/**
* @param value
*/
public void setVisited(final boolean value)
{
visited = value;
}
public int depth()
{
return depth;
}
public void setDepth(final int value)
{
depth = value;
}
/**
* @return Rule that this symbol is LHS for (null if terminal).
*/
public GrammarRule rule()
{
return rule;
}
/**
* @param r
*/
public void setRule(final GrammarRule r)
{
rule = r;
}
/**
* @return Package that this symbol belongs to.
*/
public PackageInfo pack()
{
return pack;
}
/**
* @param pi
*/
public void setPack(final PackageInfo pi)
{
pack = pi;
}
public Class<?> cls()
{
return cls;
}
public List<Symbol> ancestors()
{
return Collections.unmodifiableList(ancestors);
}
public Symbol subLudemeOf()
{
return subLudemeOf;
}
public void setSubLudemeOf(final Symbol symbol)
{
subLudemeOf = symbol;
}
public Symbol atomicLudeme()
{
return atomicLudeme;
}
public void setAtomicLudeme(final Symbol symbol)
{
atomicLudeme = symbol;
}
//-------------------------------------------------------------------------
public void addAncestor(final Symbol ancestor)
{
if (!ancestors.contains(ancestor))
ancestors.add(ancestor);
}
public void addAncestorsFrom(final Symbol other)
{
for (final Symbol ancestor : other.ancestors)
addAncestor(ancestor);
}
//-------------------------------------------------------------------------
/**
* @return Whether this element is a (typically non-terminal) ludeme class.
*/
public boolean isClass()
{
return
ludemeType == LudemeType.Ludeme
||
ludemeType == LudemeType.SuperLudeme
||
ludemeType == LudemeType.SubLudeme
||
ludemeType == LudemeType.Structural;
}
/**
* @return Whether this element is a terminal symbol.
*/
public boolean isTerminal()
{
return !isClass(); //symbolType == SymbolType.Primitive || symbolType == SymbolType.Predefined || symbolType == SymbolType.Constant;
}
//-------------------------------------------------------------------------
// /**
// * @return What type of ludeme this symbol represents.
// */
// public LudemeType ludemeType()
// {
// if (cls.isEnum())
// return LudemeType.Constant;
//
// if
// (
// cls.getSimpleName().equals("String")
// ||
// cls.getSimpleName().equals("Integer")
// ||
// cls.getSimpleName().equals("Float")
// ||
// cls.getSimpleName().equals("Boolean")
// )
// return LudemeType.Predefined;
//
// if
// (
// cls.getSimpleName().equals("int")
// ||
// cls.getSimpleName().equals("float")
// ||
// cls.getSimpleName().equals("boolean")
// )
// return LudemeType.Primitive;
//
// if (cls.isInterface())
// {
// // Assume is structural rule that links subrules but is never instantiated
// //System.out.println("** Is an interface: " + this);
// return LudemeType.Structural;
// }
//
// final Constructor<?>[] constructors = cls.getConstructors();
// if (constructors.length == 0)
// {
// // No constructors: probably a super ludeme
// //System.out.println("** No constructors found for: " + this);
// return LudemeType.SuperLudeme;
// }
//
//// if (constructors[0].isSynthetic())
//// return LudemeType.SuperLudeme;
//
// return LudemeType.Ludeme;
// }
//-------------------------------------------------------------------------
/**
* @return Whether this symbol matches the specified one.
*/
public boolean matches(final Symbol other)
{
return
//path.equalsIgnoreCase(other.path())
path.equals(other.path())
&&
nesting == other.nesting;
}
//-------------------------------------------------------------------------
/**
* @return Whether this symbol matches the specified one.
*/
public boolean compatibleWith(final Symbol other)
{
if (cls.isAssignableFrom(other.cls()))
return true;
if (cls.isAssignableFrom(other.returnType().cls()))
return true;
if (name.equals("Play"))
{
if (other.name().equals("Phase"))
return true;
}
else if (name.equals("Item"))
{
if (other.name().equals("Regions")) //returnType().name().equalsIgnoreCase("Item"))
return true;
}
else if (name.equals("BooleanFunction"))
{
if
(
other.returnType().name().equalsIgnoreCase("boolean")
||
other.returnType().name().equals("Boolean")
||
other.returnType().name().equals("BooleanConstant")
)
return true;
}
else if (name.equals("IntFunction"))
{
if
(
other.returnType().name().equals("int")
||
other.returnType().name().equals("Integer")
||
other.returnType().name().equals("IntConstant")
)
return true;
}
// else if (name.equals("DimFunction"))
// {
// if
// (
// other.returnType().name().equals("int")
// ||
// other.returnType().name().equals("Integer")
// )
// return true;
// }
else if (name.equals("FloatFunction"))
{
if
(
other.returnType().name().equals("float")
||
other.returnType().name().equals("Float")
||
other.returnType().name().equals("FloatConstant")
)
return true;
}
else if (name.equals("RegionFunction"))
{
if
(
other.returnType().name().equals("Region")
||
other.returnType().name().equals("Sites")
)
return true;
}
else if (name.equals("GraphFunction"))
{
if
(
other.returnType().name().equals("Graph")
||
other.returnType().name().equals("Tiling")
)
return true;
}
else if (name.equals("RangeFunction"))
{
if (other.returnType().name().equals("Range"))
return true;
}
// else if (name.equals("DimFunction"))
// {
// if (other.returnType().name().equals("Dim"))
// return true;
// }
else if (name.equals("Directions"))
{
if (other.returnType().name().equals("Directions"))
return true;
}
else if (name.equals("IntArrayFunction"))
{
if (other.returnType().name().equals("int[]"))
return true;
}
// else if (name.equals("TrackStep"))
// {
// if
// (
// other.returnType().name().equals("TrackStep")
// ||
// other.returnType().name().equals("Dim")
// ||
// other.returnType().name().equals("TrackStepType")
// ||
// other.returnType().name().equals("CompassDirection")
// )
// return true;
// }
return false;
}
//-------------------------------------------------------------------------
/**
* Scopes the keyword with the rightmost package name.
* @return Shortest label that disambiguates this symbol name from the other symbol name.
*/
public String disambiguation(final Symbol other)
{
// System.out.println("path=" + path);
final String label = isClass() ? token : name;
final String labelOther = isClass() ? other.token : other.name;
final String[] subs = path.split("\\.");
final String[] subsOther = other.path.split("\\.");
for (int level = 1; level < subs.length; level++)
{
String newLabel = new String(label); //keyword);
for (int ll = 1; ll < level; ll++)
newLabel = subs[subs.length-ll-1] + "." + newLabel;
String newLabelOther = new String(labelOther); //other.keyword);
for (int ll = 1; ll < level; ll++)
newLabelOther = subsOther[subsOther.length-ll-1] + "." + newLabelOther;
if (!newLabel.equals(newLabelOther))
{
// Successfully disambiguated
//grammarLabel = new String(newLabel);
//other.grammarLabel = new String(newLabelOther);
return newLabel;
}
}
//System.out.println("!! FAILED TO DISAMBIGUATE: " + toString() + " from " + other.toString() + ".");
return null;
}
//-------------------------------------------------------------------------
/**
* @param arg
* @return Whether this symbol is a valid return type of the specified arg.
*/
public boolean validReturnType(final ClauseArg arg)
{
if
(
path.equals(arg.symbol().path())
&&
nesting <= arg.nesting()
)
return true;
// Check for function matches
if
(
arg.symbol().name.contains("Function")
||
arg.symbol().name.contains("Constant")
)
{
if (arg.symbol().name.equals("MoveListFunction"))
{
if (name.equals("Move"))
return true;
}
if (arg.symbol().name.equals("BitSetFunction"))
{
if (name.equals("BitSet"))
return true;
}
// TODO: Should RegionFunction also be handled here?
}
return false;
}
/**
* @param clause
* @return Whether this symbol is a valid return type of the specified clause.
*/
public boolean validReturnType(final Clause clause)
{
//System.out.println("validReturnType for: " + clause.symbol().name());
return
path.equals(clause.symbol().path())
&&
nesting <= clause.symbol().nesting();
}
//-------------------------------------------------------------------------
/**
* @param other
* @return Whether this symbol is a collection of the specified one.
*/
public boolean isCollectionOf(final Symbol other)
{
return
path.equals(other.path())
&&
nesting > other.nesting;
}
//-------------------------------------------------------------------------
/**
* Extract name from classPath.
*/
void extractName()
{
// System.out.println("Source path: " + path);
// System.out.println("Source name: " + name);
// System.out.println("Source className: " + className + "\n");
// if (path.contains("java.util.List<") && path.contains(">"))
// {
// // Handle full List description
// isList = true;
// final int c = path.indexOf("java.util.List<");
// path = path.substring(c + 15);
// path = path.replace(">", "");
// }
// else if (path.contains("List<") && path.contains(">"))
// {
// // Handle short List description
// isList = true;
// final int c = path.indexOf("List<");
// path = path.substring(c + 5);
// path = path.replace(">", "");
// }
while (true)
{
final int c = path.indexOf("[]");
if (c == -1)
break;
nesting++;
path = path.substring(0, c) + path.substring(c+2);
}
name = new String(path);
name = name.replace('/', '.'); // handle absolute paths
name = name.replace('$', '.'); // handle inner classes
if (name.contains(".java"))
name = name.substring(0, name.length() - 5); // remove class extension
int c;
for (c = name.length() - 1; c >= 0; c--)
if (name.charAt(c) == '.')
break;
if (c >= 0)
name = name.substring(c);
if (name.length() > 0 && name.charAt(0) == '.')
name = name.substring(1); // remove leading dot
if (name.contains(">"))
name = name.replace('$', '.'); // remnant from list
}
//-------------------------------------------------------------------------
/**
* Extract name from classPath.
*/
void extractPackagePath()
{
notionalLocation = new String(path);
notionalLocation = notionalLocation.replace('/', '.'); // handle absolute paths
// name = name.replace('$', '.'); // Don't include inner classes!
if (notionalLocation.endsWith(".java"))
notionalLocation = notionalLocation.substring(0, name.length() - 5); // remove file extension
int c;
for (c = notionalLocation.length() - 1; c >= 0; c--)
if (notionalLocation.charAt(c) == '.')
break;
if (c >= 0)
notionalLocation = notionalLocation.substring(0, c);
}
//-------------------------------------------------------------------------
/**
* Derive keyword in lowerCamelCase from name.
*/
void deriveKeyword(final String alias)
{
if (alias != null)
{
// Take substring to right of last dot
int c;
for (c = alias.length() - 1; c >= 0; c--)
if (alias.charAt(c) == '.')
break;
token = (c < 0) ? new String(alias) : alias.substring(c+1);
//System.out.println("deriveKeyword from alias " + alias + ".");
return;
}
token = new String(name);
if (isClass())
{
// Make lowerCamelCase
for (int c = 0; c < token.length(); c++)
if (c == 0 || token.charAt(c - 1) == '.')
token =
token.substring(0, c)
+
token.substring(c, c + 1).toLowerCase()
+
token.substring(c + 1);
}
// System.out.println("derived keyword: " + keyword + "\n");
}
//-------------------------------------------------------------------------
/**
* @return Java description for later instantiation of this symbol.
*/
public String javaDescription()
{
String str = name;
for (int n = 0; n < nesting; n++)
str += "[]";
return str;
}
//-------------------------------------------------------------------------
/**
* @param forceLower Whether to use lowerCamelCase for all types.
* @return String description of symbol..
*/
public String toString(final boolean forceLower)
{
//final String safeKeyword = (grammarLabel == null) ? keyword : grammarLabel;
//String str = (forceLower || !terminal()) ? safeKeyword : name;
String str = (forceLower || !isTerminal()) ? grammarLabel : name;
if (ludemeType != LudemeType.Constant)
str = "<" + str + ">";
for (int n = 0; n < nesting; n++)
str += "{" + str + "}";
return str;
}
//-------------------------------------------------------------------------
@Override
public String toString()
{
return toString(false);
}
//-------------------------------------------------------------------------
public String info()
{
final StringBuilder sb = new StringBuilder();
sb.append
(
(usedInGrammar() ? "g" : "~") +
(usedInDescription() ? "d" : "~") +
(usedInMetadata() ? "m" : "~") +
(isAbstract() ? "*" : "~") +
" " + toString() +
" name=" + name +
" type=" + ludemeType +
" (" + path() + ") => " + returnType() +
//"\n pack=" + notionalLocation() +
", pack=" + notionalLocation() +
", label=" + grammarLabel() +
", cls=" + (cls() == null ? "null" : cls().getName()) +
", keyword=" + token +
", atomic=" + atomicLudeme.name() +
", atomic path=" + atomicLudeme.path()
// "\n depth=" + depth()
);
return sb.toString();
}
//-------------------------------------------------------------------------
}
| 24,281 | 21.175342 | 135 | java |
Ludii | Ludii-master/Common/src/main/grammar/Token.java | package main.grammar;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import main.StringRoutines;
//-----------------------------------------------------------------------------
/**
* Token from a game description in the Ludii grammar.
* @author cambolbro
*/
public class Token
{
public enum TokenType
{
Class,
Array,
Terminal
}
/** Name of this token. */
private String name = null;
/** Label for this element (if a named parameter). */
private String parameterLabel = null;
/** Open and closing brackets (if any). */
private char open = 0;
private char close = 0;
/** Arguments for the token. */
private final List<Token> arguments = new ArrayList<Token>();
// Formatting details.
// 78 chars should keep descriptions within page margin of Language Reference.
public static final int MAX_CHARS = 78; //80;
//public static final String TAB = " ";
private final int TAB_SIZE = 4;
//-------------------------------------------------------------------------
/**
* Constructor.
* Decomposes a string into a token tree.
*/
public Token(final String str, final Report report)
{
decompose(str, report);
}
//-------------------------------------------------------------------------
public String name()
{
return name;
}
public String parameterLabel()
{
return parameterLabel;
}
public char open()
{
return open;
}
public char close()
{
return close;
}
public List<Token> arguments()
{
return Collections.unmodifiableList(arguments);
}
//-------------------------------------------------------------------------
/**
* @return Type of token.
*/
public TokenType type()
{
if (open == '(' && close == ')' && name != null)
return TokenType.Class;
if (open == '{' && close == '}')
return TokenType.Array;
if (open == 0 && close == 0)
{
if (name != null)
return TokenType.Terminal;
}
// System.out.println("** Token.type(): Unidentified token: " + name);
// System.out.println(" in: " + toString());
return null;
}
public boolean isTerminal()
{
return open == 0 && close == 0;
}
public boolean isClass()
{
return open == '(' && close == ')' && name != null;
}
public boolean isArray()
{
return open == '{' && close == '}'; // && name == null;
}
//-------------------------------------------------------------------------
/**
* @return Number of tokens in the tree from this token down.
*/
public int count()
{
int count = 1;
for (final Token sub : arguments)
count += sub.count();
return count;
}
/**
* @return Number of tokens in the tree from this token down.
*/
public int countKeywords()
{
int count = type() == TokenType.Array ? 0 : 1;
for (final Token sub : arguments)
count += sub.countKeywords();
return count;
}
//-------------------------------------------------------------------------
/**
* @return Total length of this token and its arguments.
*/
int length()
{
int length = 0;
if (name != null)
length += name.length();
if (open != 0 && close != 0)
length += 2;
if (parameterLabel != null)
length += parameterLabel.length() + 1;
if (!arguments.isEmpty())
{
for (final Token sub : arguments)
length += sub.length();
length += arguments.size() - 1; // add separators
}
return length;
}
//-------------------------------------------------------------------------
public void decompose(final String strIn, final Report report)
{
String str = new String(strIn).trim();
//System.out.println("Decomposing: " + str);
if (str.isEmpty())
{
report.addError("Can't decompose token from empty string.");
return;
}
if (StringRoutines.isName(str))
str = consumeParameterName(str, 0, true);
String argsString = null;
final char ch = str.charAt(0);
if (ch == '"')
{
//System.out.println("Is string: " + str);
consumeString(str);
return;
}
else if (ch == '(')
{
//System.out.println("Is class: " + str);
open = '(';
final int cb = StringRoutines.matchingBracketAt(str, 0);
if (cb == -1)
{
// System.out.println("** Token.decompose(): No closing bracket ')' for clause:\n" + str);
// int numOpen = 0;
// int numClosed = 0;
// for (int n = 0; n < str.length(); n++)
// {
// if (str.charAt(n) == '(')
// numOpen++;
// else if (str.charAt(n) == ')')
// numClosed++;
// }
// System.out.println("numOpen=" + numOpen + ", numClosed=" + numClosed);
// System.out.println("strIn:\n" + strIn);
report.addError("No closing bracket ')' for clause '" + Report.clippedString(str, 20) + "'.");
return;
//close = '?';
//str = str.substring(1); // trim bracket
}
//else
{
close = ')';
str = str.substring(1, cb); // trim brackets
}
argsString = consumeToken(str);
}
else if (ch == '{')
{
//System.out.println("Is array: " + str);
open = '{';
final int cb = StringRoutines.matchingBracketAt(str, 0);
if (cb == -1)
{
// System.out.println("** Token.decompose(): No closing bracket '}' for clause: " + str);
// System.out.println("strIn:\n" + strIn);
report.addError("No closing bracket '}' for clause '" + Report.clippedString(str, 20) + "'.");
return;
}
close = '}';
str = str.substring(1, cb); // trim brackets
argsString = new String(str);
}
else if (ch != ' ')
{
//System.out.println("Is terminal: " + str);
consumeToken(str);
return;
}
else
{
//System.out.println("Unknown part type: " + str);
}
// System.out.println("Splitting args...");
if (argsString != null)
handleArgs(argsString, report);
}
//-------------------------------------------------------------------------
void handleArgs(final String strIn, final Report report)
{
String str = new String(strIn);
// String prevStr = strIn;
while (!str.isEmpty())
{
str = str.trim();
if (str.isEmpty())
break;
int c = 0;
if (StringRoutines.isName(str))
{
// Step past parameter name
while (c < str.length())
{
final char ch = str.charAt(c++);
if (ch == ':')
break;
}
}
if (c >= str.length())
{
final String msg = "Named arg with no value \"" + str + "\". Null arg to define?";
report.addWarning(msg);
//System.out.println(msg);
break;
}
// Don't strip named parameter names out here, they are
// passed on to subparts
// if (c > 0)
// {
// // Strip parameter name from front
// System.out.println("Stripping parameter name: " + str);
// str = str.substring(c);
// System.out.println("...new str is \"" + str + "\".");
// c = 0;
// }
final char ch = str.charAt(c);
// final int fromC = (c == 0) ? 0 : (c + 1);
// System.out.println("+ str before=\"" + str + "\".");
if (ch == '"')
{
// Arg is a string
//System.out.println("Handling arg as string: " + str);
int cc = c+1;
while (cc < str.length())
{
if (str.charAt(cc) == '"')
{
if (str.charAt(cc-1) != '\\') // step past embedded quotation mark "\""
break;
}
cc++;
}
//cc++;
if (cc >= str.length())
{
// System.out.println("** Token.handleArgs(): No closing quote '\"' for: " + str.substring(c));
// System.out.println("strIn:\n" + strIn);
report.addError("No closing quote '\"' for token arg '" +
Report.clippedString(str.substring(c), 20) + "'.");
return;
}
if (str.substring(0, cc+1).trim().isEmpty())
System.out.println("A - Empty substring.");
final Token sub = new Token(str.substring(0, cc+1), report); //, this);
arguments.add(sub);
// System.out.println("+ Created sub: " + sub.token);
// c = cc+1;
str = str.substring(cc+1);
}
else if (ch == '{')
{
// Arg is an array
//System.out.println("Handling arg as array: " + str);
final int cb = StringRoutines.matchingBracketAt(str, c);
if (cb == -1)
{
// System.out.println("** Token.handleArgs(): No closing bracket '}' for: " + str.substring(c));
// System.out.println("strIn:\n" + strIn);
report.addError("No closing bracket '}' for token arg '" + Report.clippedString(str.substring(c), 20) + "'.");
return;
}
if (str.substring(0, cb+1).trim().isEmpty())
System.out.println("B - Empty substring.");
final Token sub = new Token(str.substring(0, cb+1), report);
arguments.add(sub);
// System.out.println("+ Created sub: " + sub.token);
//c = cb + 1;
str = str.substring(cb+1);
}
else if (ch == '(')
{
// Arg is a class
//System.out.println("Handling arg as class: " + str);
final int cb = StringRoutines.matchingBracketAt(str, c);
if (cb == -1)
{
// System.out.println("** Token.handleArgs(): No closing bracket ')' for: " + str.substring(c));
report.addError("No closing bracket ')' for token arg '" +
Report.clippedString(str.substring(c), 20) + "'.");
return;
//str = str.substring(1);
}
//else
{
//System.out.println("+ Storing class subpart: " + str.substring(0, cb+1));
if (str.substring(0, cb+1).trim().isEmpty())
System.out.println("C - Empty substring.");
final Token sub = new Token(str.substring(0, cb+1), report);
arguments.add(sub);
// System.out.println("+ Created sub: " + sub.token);
// c = cb + 1;
str = str.substring(cb+1);
}
}
else if (ch != ' ')
{
// Arg is unknown
//System.out.println("** Handling arg as something unknown:\n" + str);
int cc = c;
while (cc < str.length() && StringRoutines.isTokenChar(str.charAt(cc)))
cc++;
if (cc == 0)
{
// System.out.println("** Can't handle empty arg substring (prevStr=\"" + prevStr + "\").");
// System.out.println("** strIn=" + strIn);
// System.out.println("** Maybe a wrong bracket type, or incorrect use of commas as list separators?");
str = str.substring(1);
report.addError("Empty substring from '" + Report.clippedString(strIn, 20) +
"'. Maybe a wrong bracket type '}'?");
return;
}
// if (str.substring(0, cc).trim().isEmpty())
// System.out.println("D - Empty substring.");
final Token sub = new Token(str.substring(0, cc), report);
arguments.add(sub);
// System.out.println("+ Created sub: " + sub.token);
// c = cc+1;
str = str.substring(cc);
}
else
{
// Not handling arg
System.out.println("** Token.handleArgs(): Not handling arg: " + str);
str = str.substring(1);
}
// System.out.println("+ str after =\"" + str + "\".\n");
// prevStr = str;
}
// Remove any null arguments, which can occur if the last line is a closing bracket.
// e.g. (ai
// "Go_ai"
// )
for (int a = arguments.size() - 1; a >= 0; a--)
if (arguments.get(a) == null || arguments.get(a).type() == null)
{
// System.out.println("Removing null arg " + a + "...");
arguments.remove(a);
}
}
//-------------------------------------------------------------------------
void consumeString(final String strIn)
{
final String str = new String(strIn);
// System.out.print("Consuming string: " + str);
if (str.isEmpty() || str.charAt(0) != '"')
{
System.out.println("Not a string: " + str);
return;
}
name = "\"";
int c = 1;
while (c < str.length())
{
final char ch = str.charAt(c);
final boolean isQuote = (ch == '"');
final boolean isEmbedded = (ch == '"' && str.charAt(c-1) == '\\');
if (isQuote && !isEmbedded)
break;
c++;
//if (ch != '\\')
if (isEmbedded)
name = name.substring(0, name.length()-1) + "'"; //"@#@"; //"\""; //'\\' + '"';
else
name += ch;
}
name += "\"";
// // Restore embedded substrings
// if (name != null)
// name = name.replaceAll("@#@", "'"); //"!");
//name = "\"" + str.substring(1, c-1) + "\"";
// System.out.println(" => String token name is: " + name);
}
String consumeToken(final String strIn)
{
final String str = new String(strIn);
// System.out.print("Consuming terminal: " + str);
if (str.isEmpty())
{
System.out.println("Not a token: \"" + str + "\"");
System.out.println("Check for empty clause \"()\".");
return null;
}
name = "";
int c = 0;
while (c < str.length())
{
final char ch = str.charAt(c++);
if (!StringRoutines.isTokenChar(ch))
break;
name += ch;
}
// System.out.println(" => token is: " + tokenName);
// System.out.println("consumeToken(): name=" + name + " => " + str.substring(c).trim());
return str.substring(c).trim();
}
String consumeParameterName(final String strIn, final int cIn, final boolean store)
{
final String str = new String(strIn);
// System.out.println("Consuming label: " + str);
if (str.isEmpty())
{
System.out.println("Not a parameter name: " + str);
return null;
}
if (store)
parameterLabel = "";
int c = cIn;
while (c < str.length())
{
final char ch = str.charAt(c++);
if (ch == ':')
break;
if (store)
parameterLabel += ch;
}
// System.out.println(" => parameter tokenName is: " + tokenName);
final String str2 = str.substring(0, cIn) + str.substring(c);
return str2.trim();
}
//-------------------------------------------------------------------------
@Override
public String toString()
{
return format();
}
//-------------------------------------------------------------------------
public String format()
{
final List<String> lines = new ArrayList<String>();
format(lines, 0, false);
// Combine line with "game" ludeme and name
for (int n = 0; n < lines.size()-1; n++)
if
(
lines.get(n).contains("(game")
||
lines.get(n).contains("(match")
||
lines.get(n).contains("(piece")
)
mergeNameLinesAt(lines, n);
compressNumberPairArrayElements(lines);
// Merge simple array elements into more compact format
mergeArrayLines(lines);
final StringBuilder sb = new StringBuilder();
for (final String line : lines)
sb.append(line + "\n"); //" [" + line.length() + ", " + line.trim().length() + "]\n");
return sb.toString();
}
public void format(final List<String> lines, final int depth, final boolean doSplit)
{
String line = StringRoutines.indent(TAB_SIZE, depth);
// Check if fits on one line
final String tokenLine = formatSingleLine();
// ...but always split (equipment ...) and (rules ...) ludemes
final boolean isEquipmentToken = tokenLine.indexOf("(equipment") == 0;
final boolean isRulesToken = tokenLine.indexOf("(rules") == 0;
// System.out.println("tokenLine is \"" + tokenLine.trim() + ", isEquipmentToken is " + isEquipmentToken + ".");
if (line.length() + tokenLine.length() <= MAX_CHARS && !doSplit && !isRulesToken && !isEquipmentToken)
{
// Print this token as a single line
lines.add(line + tokenLine);
return;
}
if (parameterLabel != null)
line += parameterLabel + ":"; // named parameter
if (isTerminal())
{
// Simple terminal token
lines.add(line + name);
return;
}
// Must split this token's arguments over several lines
// This token is a class constructor or array
line += open;
if (name != null)
line += name; // must be a class constructor
lines.add(line);
for (final Token arg : arguments)
{
final String argStr = arg.formatSingleLine();
final boolean isEquipmentArg = argStr.indexOf("(equipment") == 0;
final boolean isRulesArg = argStr.indexOf("(rules") == 0;
// System.out.println("argStr is \"" + argStr.trim() + ", isEquipmentArg is " + isEquipmentArg + ".");
if
(
StringRoutines.indent(TAB_SIZE, depth+1).length() + argStr.length() > MAX_CHARS
||
isEquipmentToken || isEquipmentArg
||
isRulesToken || isRulesArg
)
{
// Split arg over several lines
final List<String> subLines = new ArrayList<String>();
arg.format(subLines, depth+1, isEquipmentToken); // remember for next level of nesting
lines.addAll(subLines);
}
else
{
// Fit arg on one line
lines.add(StringRoutines.indent(TAB_SIZE, depth+1) + argStr);
}
}
lines.add(StringRoutines.indent(TAB_SIZE, depth) + close);
}
//-------------------------------------------------------------------------
static void mergeNameLinesAt(final List<String> lines, final int n)
{
if (n >= lines.size())
return; // no next line
final boolean isName = lines.get(n+1).trim().charAt(0) == '"';
if (isName)
mergeLinesAt(lines, n);
}
static void mergeLinesAt(final List<String> lines, final int n)
{
final String line = lines.get(n) + " " + lines.get(n+1).trim();
lines.remove(n);
lines.remove(n);
lines.add(n, line);
}
//-------------------------------------------------------------------------
static void mergeArrayLines(final List<String> lines)
{
int n = 0;
while (n < lines.size())
{
//final String line = lines.get(n);
if (isArrayOpen(lines.get(n)))
{
boolean containsClass = false;
int nn;
for (nn = n+1; nn < lines.size(); nn++)
{
if (isClass(lines.get(nn)))
containsClass = true;
if (isArrayClose(lines.get(nn)))
break;
}
final boolean isEquipment = n > 0 && lines.get(n-1).contains("(equipment");
// System.out.println("line is \"" + lines.get(n).trim() + ", prev is \"" + lines.get(n-1).trim() + ", isEquipment is " + isEquipment + ".");
if (nn < lines.size() && !containsClass && !isEquipment)
{
// Merge the lines of this array
n++; // move to next line
while (n < lines.size() - 1)
{
final String nextLine = lines.get(n + 1);
if (isArrayClose(nextLine))
break;
if (lines.get(n).length() + nextLine.trim().length() < MAX_CHARS)
mergeLinesAt(lines, n);
else
n++;
}
}
}
n++;
}
}
static boolean isArrayOpen(final String line)
{
final int numOpen = StringRoutines.numOpenBrackets(line);
final int numClose = StringRoutines.numCloseBrackets(line);
return line.contains("{") && numOpen == 1 && numClose == 0;
}
static boolean isArrayClose(final String line)
{
final int numOpen = StringRoutines.numOpenBrackets(line);
final int numClose = StringRoutines.numCloseBrackets(line);
return line.contains("}") && numOpen == 0 && numClose == 1;
}
static boolean isClass(final String line)
{
return line.contains("(");
}
//-------------------------------------------------------------------------
static void compressNumberPairArrayElements(final List<String> lines)
{
for (int n = 0; n < lines.size(); n++)
{
String line = lines.get(n);
if (!line.contains("{ ") || !line.contains(" }"))
continue;
int c = line.indexOf("{ ");
if (c >= 0)
{
final char ch = line.charAt(c + 2);
if (ch == '"' || StringRoutines.isNumeric(ch))
line = line.substring(0, c+1) + line.substring(c+2);
}
c = line.indexOf(" }");
if (c >= 0)
{
final char ch = line.charAt(c - 1);
if (ch == '"' || StringRoutines.isNumeric(ch))
line = line.substring(0, c) + line.substring(c+1);
}
lines.remove(n);
lines.add(n, line);
}
}
//-------------------------------------------------------------------------
public String formatSingleLine()
{
final StringBuilder sb = new StringBuilder();
if (parameterLabel != null)
sb.append(parameterLabel + ":"); // named parameter
if (isTerminal())
{
// Simple terminal token
sb.append(name);
return sb.toString();
}
sb.append(open);
if (isClass())
sb.append(name);
for (final Token sub : arguments)
sb.append(" " + sub.formatSingleLine());
if (isArray())
sb.append(" "); // pad past last array entry
sb.append(close);
return sb.toString();
}
//-------------------------------------------------------------------------
public String formatZhangShasha
(
final String indent, final int depth,
final boolean inline, final boolean zhangShasha
)
{
//System.out.println("Formatting:" + token + "\n-------------------------");
String str = "";
if (open == 0)
{
// Just print token (prepended with label, if given)
if (zhangShasha && StringRoutines.isInteger(name))
{
// Convert number to string
if (parameterLabel != null)
str += indent + "\"" + parameterLabel + ":" + name + "\"";
else
str += "\"" + name + "\"";
}
else
{
if (parameterLabel != null)
str += indent + parameterLabel + ":";
str += name;
}
return str;
}
// Is a named parameter
if (parameterLabel != null)
str += indent + parameterLabel + ":";
final String tab = StringRoutines.indent(TAB_SIZE, 1);
if (name != null)
{
// Token is a constructor
final int len = length();
if (name.equals("game"))
{
// Print name and model on one line
if (zhangShasha)
str += name + open;
else
str += open + name;
// Put name on same line
str += " " + arguments.get(0).formatZhangShasha("", depth+1, true, zhangShasha);
// Look for class and
for (final Token arg : arguments)
{
if (arg != null && arg.type() == TokenType.Class)
str += indent + tab + arg.formatZhangShasha(tab, depth+1, false, zhangShasha) + "\n";
}
str += close; // + "\n";
}
else if (len < MAX_CHARS && (depth > 1 || inline))
{
// Print on one line
//System.out.println("name=" + name + ", is number=" + StringRoutines.isInteger(name));
if (zhangShasha)
str += name + open;
else
str += open + name;
for (final Token sub : arguments)
str += " " + sub.formatZhangShasha("", depth+1, true, zhangShasha);
str += close; // + "\n";
}
else
{
// Print over multiple lines
if (zhangShasha)
str += name + open;
else
str += open + name;
str += "\n";
for (final Token sub : arguments)
str += indent + tab + sub.formatZhangShasha(indent+tab, depth+1, false, zhangShasha) + "\n";
str += indent + close; // + "\n";
}
}
else
{
// Token is an array
final int len = length();
if (len < MAX_CHARS || shortArguments()) // && arguments.size() < 15)
{
// Print on one line
if (zhangShasha)
str += "array(";
else
str += open;
if (name != null)
str += name;
for (final Token sub : arguments)
str += " " + sub.formatZhangShasha("", depth+1, true, zhangShasha);
if (zhangShasha)
str += " )";
else
str += " " + close; // + "\n";
}
else
{
// Print over multiple lines
if (zhangShasha)
str += "array(";
else
str += open;
if (name != null)
str += name + "\n";
for (final Token sub : arguments)
str += indent + tab + sub.formatZhangShasha(indent+tab, depth+1, false, zhangShasha) + "\n";
if (zhangShasha)
str += indent + ")";
else
str += indent + close; // + "\n";
}
}
return str;
}
//-------------------------------------------------------------------------
/**
* @return Whether arguments are relatively small, typically a list of cell coordinates.
*/
public boolean shortArguments()
{
int maxLen = 0;
for (final Token sub : arguments)
{
final int len = sub.length();
if (len > maxLen)
maxLen = len;
}
return maxLen < 6;
}
//-------------------------------------------------------------------------
public String dump(final String indent)
{
final String label = "" + type().name().charAt(0) + type().name().charAt(1) + ": ";
final StringBuilder sb = new StringBuilder();
sb.append(label + indent);
if (parameterLabel != null)
sb.append(parameterLabel + ":");
if (open != 0)
sb.append(open);
if (name != null)
sb.append(name);
// if (parameterLabel != null)
// sb.append(" (" + parameterLabel + ":)");
final String tab = StringRoutines.indent(TAB_SIZE, 1);
if (arguments.size() > 0)
{
sb.append("\n");
for (final Token arg : arguments)
sb.append(arg.dump(indent + tab));
if (close != 0)
sb.append(label + indent + close);
}
else
{
if (close != 0)
sb.append(close);
}
sb.append("\n");
return sb.toString();
}
//-------------------------------------------------------------------------
/**
* @return All tokens that are included in this token's tree.
*/
public Set<Token> getAllTokensInTree()
{
final Set<Token> allTokens = new HashSet<>();
allTokens.add(this);
for (final Token arg : arguments)
allTokens.addAll(arg.getAllTokensInTree());
return allTokens;
}
//-------------------------------------------------------------------------
}
| 25,179 | 23.026718 | 144 | java |
Ludii | Ludii-master/Common/src/main/grammar/TokenForest.java | package main.grammar;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import main.StringRoutines;
//-----------------------------------------------------------------------------
/**
* Game description with full details after expansion.
*
* @author cambolbro
*/
public class TokenForest
{
private List<Token> tokenTrees = new ArrayList<Token>();
//-------------------------------------------------------------------------
public List<Token> tokenTrees()
{
return Collections.unmodifiableList(tokenTrees);
}
public Token tokenTree()
{
// First token tree is the most important
return tokenTrees.isEmpty() ? null : tokenTrees.get(0);
}
public void clearTokenTrees()
{
tokenTrees.clear();
}
//-------------------------------------------------------------------------
public void populate(final String strIn, final Report report)
{
tokenTrees.clear();
if (strIn == null || strIn.isEmpty())
{
report.addError("Empty string in TokenForest.populate().");
return;
}
String str = new String(strIn).trim();
while (true)
{
final int c = str.indexOf("(");
if (c < 0)
break;
final int cc = StringRoutines.matchingBracketAt(str, c);
if (cc < 0)
{
report.addError("Couldn't close clause '" + Report.clippedString(str.substring(c), 20) + "'.");
return;
}
tokenTrees.add(new Token(str.substring(c), report));
str = str.substring(cc+1).trim();
}
}
//-------------------------------------------------------------------------
@Override
public String toString()
{
final StringBuilder sb = new StringBuilder();
for (final Token token : tokenTrees)
{
if (sb.length() > 0)
sb.append("\n");
sb.append(token.toString());
}
return sb.toString();
}
//-------------------------------------------------------------------------
}
| 1,893 | 20.044444 | 99 | java |
Ludii | Ludii-master/Common/src/main/grammar/ebnf/EBNF.java | package main.grammar.ebnf;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
//-----------------------------------------------------------------------------
/**
* EBNF style interpreter for grammar.
*
* @author cambolbro
*/
public class EBNF
{
private Map<String, EBNFRule> rules = new HashMap<String, EBNFRule>();
//-------------------------------------------------------------------------
public EBNF(final String grammar)
{
interpret(grammar);
}
//-------------------------------------------------------------------------
public Map<String, EBNFRule> rules()
{
return Collections.unmodifiableMap(rules);
}
//-------------------------------------------------------------------------
/**
* @return Whether the given string is a terminal symbol, typically int, boolean, float, string.
*/
public static boolean isTerminal(final String token)
{
return
token.charAt(0) != '<'
&&
token.charAt(token.length() - 1) != '>'
&&
!token.trim().contains(" ");
}
//-------------------------------------------------------------------------
public void interpret(final String grammar)
{
final String[] split = grammar.trim().split("\n");
// Remove comments
for (int n = 0; n < split.length; n++)
{
final int c = split[n].indexOf("//");
if (c >= 0)
split[n] = split[n].substring(0, c);
}
// Merge split lines
for (int n = split.length - 1; n >= 1; n--)
{
final int c = split[n].indexOf("::=");
if (c < 0)
{
split[n - 1] += " " + split[n].trim();
split[n] = "";
}
}
for (int n = 0; n < split.length; n++)
{
if (split[n].contains("::="))
{
String strRule = split[n];
while (strRule.contains(" "))
strRule = strRule.replaceAll(" ", " ");
final EBNFRule rule = new EBNFRule(strRule);
rules.put(rule.lhs(), rule);
}
}
// System.out.println(rules.size() + " EBNF rules found.");
// for (final EBNFRule rule : rules.values())
// System.out.println(rule);
}
//-------------------------------------------------------------------------
}
| 2,122 | 21.827957 | 97 | java |
Ludii | Ludii-master/Common/src/main/grammar/ebnf/EBNFClause.java | package main.grammar.ebnf;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
//-----------------------------------------------------------------------------
/**
* EBNF style clause for interpreting grammar.
*
* @author cambolbro
*/
public class EBNFClause
{
protected String token = "?";
private boolean isConstructor = false;
private boolean isRule = false;
private boolean isTerminal = false;
private List<EBNFClauseArg> args = null;
//-------------------------------------------------------------------------
public EBNFClause()
{
}
public EBNFClause(final String input)
{
decompose(input);
}
//-------------------------------------------------------------------------
public String token()
{
return token;
}
public boolean isConstructor()
{
return isConstructor;
}
public boolean isRule()
{
return isRule;
}
public boolean isTerminal()
{
return isTerminal;
}
public List<EBNFClauseArg> args()
{
if (args == null)
return null;
return Collections.unmodifiableList(args);
}
//-------------------------------------------------------------------------
void decompose(final String input)
{
String str = input.trim();
switch (str.charAt(0))
{
case '(':
isConstructor = true;
break;
case '<':
isRule = true;
token = str;
return;
default:
isTerminal = true;
token = str;
return;
}
// Must be constructor: strip opening and closing brackets
if (str.charAt(0) != '(' || str.charAt(str.length() - 1) != ')')
{
System.out.println("** Bad bracketing of constructor: " + str);
return;
}
str = str.substring(1, str.length() - 1);
// Extract leading token
int c = 0;
while (c < str.length() && str.charAt(c) != ' ')
c++;
token = str.substring(0, c).trim();
str = (c >= str.length()) ? "" : str.substring(c + 1).trim();
// Create args
args = new ArrayList<EBNFClauseArg>();
if (str == "")
return;
final String[] subs = str.split(" ");
final int[] orGroups = new int[subs.length];
final boolean [] optional = new boolean[subs.length];
// Determine 'or' groups
int orGroup = 0;
for (int n = 1; n < subs.length - 1; n++)
{
if (!subs[n].equals("|"))
continue;
if (n < 2 || !subs[n - 2].equals("|"))
orGroup++;
orGroups[n - 1] = orGroup;
orGroups[n + 1] = orGroup;
}
// Determine optional items
boolean on = false;
for (int n = 0; n < subs.length; n++)
{
final boolean isOpen = subs[n].contains("[");
final boolean isClose = subs[n].contains("]");
if (isOpen || isClose || on)
optional[n] = true;
if (isOpen)
on = true;
if (isClose)
on = false;
}
// Create args, stripping of optional '[' and ']' brackets and 'or' brackets '(' and ')'
for (int n = 0; n < subs.length; n++)
{
if (subs[n].equals("|"))
continue;
final String strArg = subs[n].replace("[", "").replace("]", "").replace("(", "").replace(")", "");
final EBNFClauseArg arg = new EBNFClauseArg(strArg, optional[n], orGroups[n]);
args.add(arg);
}
}
//-------------------------------------------------------------------------
@Override
public String toString()
{
final StringBuilder sb = new StringBuilder();
if (isConstructor)
sb.append("(");
sb.append(token);
if (args != null)
for (int a = 0; a < args.size(); a++)
{
final EBNFClauseArg arg = args.get(a);
sb.append(" ");
// Check opening bracket
if (arg.orGroup() != 0)
{
// Check if must show opening bracket
if (a == 0 || args.get(a - 1).orGroup() != arg.orGroup())
{
// Must show opening bracket, determine what type
if (arg.isOptional())
sb.append("[");
else
sb.append("(");
}
// Check if must show 'or' separator
if (a > 0 && args.get(a - 1).orGroup() == arg.orGroup())
sb.append("| ");
}
else
{
// Individual item
if (arg.isOptional())
sb.append("[");
}
sb.append(arg);
// Check closing bracket
if (arg.orGroup() != 0)
{
// Check if must show closing bracket
if (a == args.size() - 1 || args.get(a + 1).orGroup() != arg.orGroup())
{
// Must show closing bracket, determine what type
if (arg.isOptional())
sb.append("]");
else
sb.append(")");
}
}
else
{
// Individual item
if (arg.isOptional())
sb.append("]");
}
}
if (isConstructor)
sb.append(")");
return sb.toString();
}
//-------------------------------------------------------------------------
}
| 4,717 | 19.513043 | 101 | java |
Ludii | Ludii-master/Common/src/main/grammar/ebnf/EBNFClauseArg.java | package main.grammar.ebnf;
/**
* EBNF style clause argument for interpreting grammar.
*
* @author cambolbro
*/
public class EBNFClauseArg extends EBNFClause
{
private boolean isOptional = false;
private int orGroup = 0;
private String parameterName = null;
private int nesting = 0;
//-------------------------------------------------------------------------
public EBNFClauseArg
(
final String input, final boolean isOptional, final int orGroup
)
{
this.isOptional = isOptional;
this.orGroup = orGroup;
decompose(input);
}
//-------------------------------------------------------------------------
public boolean isOptional()
{
return isOptional;
}
public int orGroup()
{
return orGroup;
}
public String parameterName()
{
return parameterName;
}
public int nesting()
{
return nesting;
}
//-------------------------------------------------------------------------
void decompose(final String input)
{
String str = input.trim();
// Assume that optional status has already been set and brackets '[...]' removed
// Strip parameter name, if any
final int colonAt = str.indexOf(":");
if (colonAt >= 0)
{
parameterName = str.substring(0, colonAt).trim();
str = str.substring(colonAt + 1).trim();
}
// Strip array braces, if any
while (str.charAt(0) == '{')
{
if (str.charAt(str.length() - 1) != '}')
{
System.out.println("** No closing brace for array in: " + str);
return;
}
nesting++;
str = str.substring(1, str.length() - 1).trim();
}
token = str.trim();
}
//-------------------------------------------------------------------------
@Override
public String toString()
{
final StringBuilder sb = new StringBuilder();
// if (isOptional)
// sb.append("[");
if (parameterName != null)
sb.append(parameterName + ":");
for (int n = 0; n < nesting; n++)
sb.append("{");
sb.append(token);
for (int n = 0; n < nesting; n++)
sb.append("}");
// if (isOptional)
// sb.append("]");
// if (orGroup != 0)
// sb.append("=" + orGroup);
return sb.toString();
}
//-------------------------------------------------------------------------
}
| 2,214 | 18.429825 | 82 | java |
Ludii | Ludii-master/Common/src/main/grammar/ebnf/EBNFRule.java | package main.grammar.ebnf;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import main.StringRoutines;
//-----------------------------------------------------------------------------
/**
* EBNF style rule for interpreting grammar.
*
* @author cambolbro
*/
public class EBNFRule
{
private String lhs = "?";
private final List<EBNFClause> rhs = new ArrayList<EBNFClause>();
//private Class<?> cls = null;
//-------------------------------------------------------------------------
public EBNFRule(final String input)
{
decompose(input);
}
//-------------------------------------------------------------------------
public String lhs()
{
return lhs;
}
public List<EBNFClause> rhs()
{
return Collections.unmodifiableList(rhs);
}
// public Class<?> cls()
// {
// return cls;
// }
//
// public void setClass(final Class<?> c)
// {
// cls = c;
// }
//-------------------------------------------------------------------------
void decompose(final String input)
{
// Store and trim LHS
final String[] sides = input.split("::=");
lhs = sides[0].trim();
// Decompose RHS (sides[1])
String str = sides[1].trim();
// Avoid bad bracket interpretation in <boolean>: "<<> | <<=> | <=> | <>> | <>=>"
str = str.replaceAll("<<", "<#");
str = str.replaceAll("<>", "<@");
str = str.replaceAll("<>", "#>");
str = str.replaceAll(">>", "@>");
if (str.length() == 0)
{
System.out.println("** Empty RHS for rule: " + input);
return;
}
int c = 0;
int cc;
do
{
if (str.charAt(c) == '(' || str.charAt(c) == '<')
{
cc = StringRoutines.matchingBracketAt(str, c);
if (cc < 0)
{
System.out.println("** Failed to load clause from: " + str);
return;
}
}
else
{
cc = c + 1;
while (cc < str.length() && str.charAt(cc) != ' ')
cc++;
}
if (cc >= str.length())
cc--;
String strClause = str.substring(c, cc + 1).trim();
strClause = strClause.replaceAll("#", "<");
strClause = strClause.replaceAll("@", ">");
final EBNFClause clause = new EBNFClause(strClause);
rhs.add(clause);
// if (!StringRoutines.balancedBrackets(strClause))
// System.out.println("** Unbalanced brackets: " + strClause);
c = cc + 1;
while (c < str.length() && (str.charAt(c) == ' ' ||str.charAt(c) == '|'))
c++;
} while (c < str.length());
}
//-------------------------------------------------------------------------
@Override
public String toString()
{
final StringBuilder sb = new StringBuilder();
sb.append(lhs);
sb.append(" ::= ");
for (int c = 0; c < rhs.size(); c++)
{
final EBNFClause clause = rhs.get(c);
if (c > 0)
sb.append(" | ");
sb.append(clause);
}
return sb.toString();
}
//-------------------------------------------------------------------------
}
| 2,887 | 20.392593 | 83 | java |
Ludii | Ludii-master/Common/src/main/math/Bezier.java | package main.math;
import java.awt.Point;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.util.List;
//-----------------------------------------------------------------------------
/**
* Cubic Bezier segment.
*
* @author cambolbro
*/
public final class Bezier
{
private final Point2D[] cps = new Point2D[4];
//-------------------------------------------------------------------------
public Bezier()
{
}
public Bezier(final List<Point2D> pts)
{
cps[0] = pts.get(0);
cps[1] = pts.get(1);
cps[2] = pts.get(2);
cps[3] = pts.get(3);
}
public Bezier(final Point2D[] pts)
{
cps[0] = pts[0];
cps[1] = pts[1];
cps[2] = pts[2];
cps[3] = pts[3];
}
public Bezier(final Float[][] pts)
{
cps[0] = new Point2D.Double(pts[0][0].floatValue(), pts[0][1].floatValue());
cps[1] = new Point2D.Double(pts[1][0].floatValue(), pts[1][1].floatValue());
cps[2] = new Point2D.Double(pts[2][0].floatValue(), pts[2][1].floatValue());
cps[3] = new Point2D.Double(pts[3][0].floatValue(), pts[3][1].floatValue());
}
public Bezier(final Point2D ptA, final Point2D ptAperp, final Point2D ptB, final Point2D ptBperp)
{
cps[0] = ptA;
cps[3] = ptB;
final Vector vecA = new Vector(ptA, ptAperp);
final Vector vecB = new Vector(ptB, ptBperp);
vecA.normalise();
vecB.normalise();
final double distAB = MathRoutines.distance(ptA, ptB);
final double off = 0.333 * distAB;
final Point2D ptA1 = new Point2D.Double
(
ptA.getX() - off * vecA.y(),
ptA.getY() + off * vecA.x()
);
final Point2D ptA2 = new Point2D.Double
(
ptA.getX() + off * vecA.y(),
ptA.getY() - off * vecA.x()
);
final Point2D ptB1 = new Point2D.Double
(
ptB.getX() - off * vecB.y(),
ptB.getY() + off * vecB.x()
);
final Point2D ptB2 = new Point2D.Double
(
ptB.getX() + off * vecB.y(),
ptB.getY() - off * vecB.x()
);
if (MathRoutines.distance(ptA1, ptB) < MathRoutines.distance(ptA2, ptB))
cps[1] = ptA1;
else
cps[1] = ptA2;
if (MathRoutines.distance(ptB1, ptA) < MathRoutines.distance(ptB2, ptA))
cps[2] = ptB1;
else
cps[2] = ptB2;
}
public Bezier(final Point ptA, final Point ptAperp, final Point ptB, final Point ptBperp)
{
this
(
new Point2D.Double(ptA.x, ptA.y),
new Point2D.Double(ptAperp.x, ptAperp.y),
new Point2D.Double(ptB.x, ptB.y),
new Point2D.Double(ptBperp.x, ptBperp.y)
);
}
//-------------------------------------------------------------------------
public Point2D[] cps()
{
return cps;
}
//-------------------------------------------------------------------------
public double length()
{
return MathRoutines.distance(cps[0], cps[1])
+
MathRoutines.distance(cps[1], cps[2])
+
MathRoutines.distance(cps[2], cps[3]);
}
public Point2D midpoint()
{
//return sample(0.5);
final Point2D ab = new Point2D.Double((cps[0].getX() + cps[1].getX()) / 2, (cps[0].getY() + cps[1].getY()) / 2);
final Point2D bc = new Point2D.Double((cps[1].getX() + cps[2].getX()) / 2, (cps[1].getY() + cps[2].getY()) / 2);
final Point2D cd = new Point2D.Double((cps[2].getX() + cps[3].getX()) / 2, (cps[2].getY() + cps[3].getY()) / 2);
final Point2D abbc = new Point2D.Double((ab.getX() + bc.getX()) / 2, (ab.getY() + bc.getY()) / 2);
final Point2D bccd = new Point2D.Double((bc.getX() + cd.getX()) / 2, (bc.getY() + cd.getY()) / 2);
return new Point2D.Double((abbc.getX() + bccd.getX()) / 2, (abbc.getY() + bccd.getY()) / 2);
}
// De Casteljau algorithm
public Point2D sample(final double t)
{
final Point2D ab = MathRoutines.lerp(t, cps[0], cps[1]);
final Point2D bc = MathRoutines.lerp(t, cps[1], cps[2]);
final Point2D cd = MathRoutines.lerp(t, cps[2], cps[3]);
final Point2D abbc = MathRoutines.lerp(t, ab, bc);
final Point2D bccd = MathRoutines.lerp(t, bc, cd);
return MathRoutines.lerp(t, abbc, bccd);
}
//-------------------------------------------------------------------------
/**
* @return Bounding box of points.
*/
public Rectangle2D bounds()
{
double x0 = 1000000;
double y0 = 1000000;
double x1 = -1000000;
double y1 = -1000000;
for (final Point2D pt : cps)
{
final double x = pt.getX();
final double y = pt.getY();
if (x < x0) x0 = x;
if (x > x1) x1 = x;
if (y < y0) y0 = y;
if (y > y1) y1 = y;
}
return new Rectangle2D.Double(x0, y0, x1-x0, y1-y0);
}
//-------------------------------------------------------------------------
@Override
public String toString()
{
final StringBuilder sb = new StringBuilder();
sb.append("Bezier:");
for (final Point2D pt : cps)
sb.append(" (" + pt.getX() + "," + pt.getY() + ")");
return sb.toString();
}
//-------------------------------------------------------------------------
}
| 4,954 | 24.410256 | 115 | java |
Ludii | Ludii-master/Common/src/main/math/BitTwiddling.java | package main.math;
/**
* Static class with bit twiddling routines
* Many taken from the fantastic:
* https://graphics.stanford.edu/~seander/bithacks.html
* @author Stephen Tavener
*
*/
public final class BitTwiddling {
/**
* No, you can't... and I won't :P
*/
private BitTwiddling() {
// Go away
}
/**
* @param a
* @param b
* @return true if a and b have opposite signs
*/
public static final boolean oppositeSigns (final int a, final int b) {
return ((a ^ b) < 0);
}
/**
* @param a
* @param b
* @return true if a and b have opposite signs
*/
public static final boolean oppositeSigns (final long a, final long b) {
return ((a ^ b) < 0);
}
/**
* @param a
* @return true if a is a power of two (exactly one bit set)
*/
public static final boolean exactlyOneBitSet (final int a) {
if (a == 0) return false;
return (a & (a - 1))==0;
}
/**
* @param a
* @return true if a is a power of two (exactly one bit set)
*/
public static final boolean exactlyOneBitSet (final long a) {
if (a == 0) return false;
return (a & (a - 1))==0;
}
/**
* @param a
* @return true if a is a power of two (exactly one bit set) or zero
*/
public static final boolean leOneBitSet (final int a) {
return (a & (a - 1))==0;
}
/**
* @param a
* @return true if a is a power of two (exactly one bit set) or zero
*/
public static final boolean leOneBitSet (final long a) {
return (a & (a - 1))==0;
}
/**
* @param a Number to test
* @return position of top bit set in this int
*/
public static final int topBitPos (final int a)
{
return 31-Integer.numberOfLeadingZeros(a);
}
/**
* @param a Number to test
* @return position of top bit set in this int
*/
public static final int topBitPos (final long a)
{
return 63-Long.numberOfLeadingZeros(a);
}
/**
* @param v
* @return index of lowest bit, 0 if no bit set
*/
public static final int lowBitPos (int v)
{
return Integer.numberOfTrailingZeros(v);
}
/**
* @param v
* @return index of lowest bit, 0 if no bit set
*/
public static final int lowBitPos (long v)
{
return Long.numberOfTrailingZeros(v);
}
/**
* @param a Number to test
* @return bottom bit
*/
public static final int bottomBit (final int a)
{
return Integer.lowestOneBit(a);
}
/**
* @param a Number to test
* @return bottom bit
*/
public static final long bottomBit (final long a)
{
return Long.lowestOneBit(a);
}
/**
* @param v
* @return number of bits set
*/
public static final int countBits(final int v)
{
return Integer.bitCount(v);
}
/**
* A generalization of the best bit counting method to integers of bit-widths up to 128 (parameterized by type T) is this:
*
* v = v - ((v >> 1) & (T)~(T)0/3); // temp
* v = (v & (T)~(T)0/15*3) + ((v >> 2) & (T)~(T)0/15*3); // temp
* v = (v + (v >> 4)) & (T)~(T)0/255*15; // temp
* c = (T)(v * ((T)~(T)0/255)) >> (sizeof(T) - 1) * CHAR_BIT; // count
*
* @param v
* @return number of bits set
*/
public static final int countBits(final long v)
{
return Long.bitCount(v);
}
/**
* @param v
* @return next permutation in sequence
*/
public static final int nextPermutation (final int v)
{
final int t = (v | (v - 1)) + 1;
return t | ((((t & -t) / (v & -v)) >>> 1) - 1);
}
/**
* @param v
* @return next permutation in sequence
*/
public static final long nextPermutation (final long v)
{
final long t = (v | (v - 1)) + 1;
return t | ((((t & -t) / (v & -v)) >>> 1) - 1);
}
/**
* @param n
* @return 1 if value is non-zero, 0 if it is zero
*/
public static final int oneIfNonZero (int n)
{
return ((n | (~n + 1)) >>> 31);
}
/**
* @param n
* @return 1 if value is zero, 0 if it is non-zero
*/
public static final int oneIfZero (int n)
{
return oneIfNonZero(n)^1;
}
/**
* @param n
* @return 1 if value is non-zero, 0 if it is zero
*/
public static final long oneIfNonZero (long n)
{
return ((n | (~n + 1L)) >>> 63);
}
/**
* @param n
* @return 1 if value is zero, 0 if it is non-zero
*/
public static final long oneIfZero (long n)
{
return oneIfNonZero(n)^1L;
}
/**
* Reverses one byte of data
* 5 ops, no division
*
* The following shows the flow of the bit values with the boolean variables a, b, c, d, e, f, g, and h, which comprise an 8-bit byte.
* Notice how the first multiply fans out the bit pattern to multiple copies, while the last multiply combines them in the fifth byte from the right.
* abcd efgh (-> hgfe dcba)
*
* * 1000 0000 0010 0000 0000 1000 0000 0010 (0x80200802)
* -------------------------------------------------------------------------------------------------
* 0abc defg h00a bcde fgh0 0abc defg h00a bcde fgh0
* & 0000 1000 1000 0100 0100 0010 0010 0001 0001 0000 (0x0884422110)
* -------------------------------------------------------------------------------------------------
* 0000 d000 h000 0c00 0g00 00b0 00f0 000a 000e 0000
* * 0000 0001 0000 0001 0000 0001 0000 0001 0000 0001 (0x0101010101)
* -------------------------------------------------------------------------------------------------
* 0000 d000 h000 0c00 0g00 00b0 00f0 000a 000e 0000
* 0000 d000 h000 0c00 0g00 00b0 00f0 000a 000e 0000
* 0000 d000 h000 0c00 0g00 00b0 00f0 000a 000e 0000
* 0000 d000 h000 0c00 0g00 00b0 00f0 000a 000e 0000
* 0000 d000 h000 0c00 0g00 00b0 00f0 000a 000e 0000
* -------------------------------------------------------------------------------------------------
* 0000 d000 h000 dc00 hg00 dcb0 hgf0 dcba hgfe dcba hgfe 0cba 0gfe 00ba 00fe 000a 000e 0000
* >> 32
* -------------------------------------------------------------------------------------------------
* 0000 d000 h000 dc00 hg00 dcb0 hgf0 dcba hgfe dcba
* & 1111 1111
* -------------------------------------------------------------------------------------------------
* hgfe dcba
* Note that the last two steps can be combined on some processors because the registers can be accessed as bytes; just multiply so that a register stores the upper 32 bits of the result and the take the low byte. Thus, it may take only 6 operations.
*
* @param value
* @return 8 bits, order reversed
*/
public static int reverseByte (final int value)
{
return ((int)(((value * 0x80200802L) & 0x0884422110L) * 0x0101010101L >>> 32)) & 0xFF;
}
//-------------------------------------------------------------------------
/**
* @param value
* @return Number of bits required to cover integers from 0..value.
*/
public static int bitsRequired(final int value)
{
return (int) Math.ceil(Math.log(value + 1) / Math.log(2));
}
/**
* @param numBits
* @return Mask with specified number of bits [0..31] turned on.
*/
public static int maskI(final int numBits)
{
return (0x1 << numBits) - 1;
}
/**
* @param numBits
* @return Mask with specified number of bits [0..63] turned on.
*/
public static long maskL(final int numBits)
{
return (0x1L << numBits) - 1L;
}
/**
* @param n
* @return Lowest power of 2 >= n.
*/
public static int nextPowerOf2(final int n)
{
if (n <= 1) return 1; // n^0 == 1
return (int) Math.pow(2, Math.ceil(Math.log(n) / Math.log(2)));
}
/**
* @param n
* @return Whether the specified value is a positive power of 2.
*/
public static boolean isPowerOf2(final int n)
{
return n > 0 && ((n & (n - 1)) == 0);
}
//-------------------------------------------------------------------------
/**
* @param x
* @return Base-2 log of an integer x, rounded down
*/
public static int log2RoundDown(final int x)
{
return (Integer.SIZE - 1) - Integer.numberOfLeadingZeros(x);
}
/**
* @param x
* @return Base-2 log of an integer x, rounded up
*/
public static int log2RoundUp(final int x)
{
return Integer.SIZE - Integer.numberOfLeadingZeros(x - 1);
}
//-------------------------------------------------------------------------
}
| 8,591 | 26.104101 | 251 | java |
Ludii | Ludii-master/Common/src/main/math/LinearRegression.java | package main.math;
/**
* The {@code LinearRegression} class performs a simple linear regression
* on an set of <em>n</em> data points (<em>y<sub>i</sub></em>, <em>x<sub>i</sub></em>).
* That is, it fits a straight line <em>y</em> = α + β <em>x</em>,
* (where <em>y</em> is the response variable, <em>x</em> is the predictor variable,
* α is the <em>y-intercept</em>, and β is the <em>slope</em>)
* that minimizes the sum of squared residuals of the linear regression model.
* It also computes associated statistics, including the coefficient of
* determination <em>R</em><sup>2</sup> and the standard deviation of the
* estimates for the slope and <em>y</em>-intercept.
*
* @author Robert Sedgewick
* @author Kevin Wayne
*/
public class LinearRegression {
private final double intercept, slope;
private final double r2;
private final double svar0, svar1;
/**
* Performs a linear regression on the data points {@code (y[i], x[i])}.
*
* @param x the values of the predictor variable
* @param y the corresponding values of the response variable
* @throws IllegalArgumentException if the lengths of the two arrays are not equal
*/
public LinearRegression(double[] x, double[] y) {
if (x.length != y.length) {
throw new IllegalArgumentException("array lengths are not equal");
}
int n = x.length;
// first pass
double sumx = 0.0, sumy = 0.0;// sumx2 = 0.0;
for (int i = 0; i < n; i++) {
sumx += x[i];
//sumx2 += x[i]*x[i];
sumy += y[i];
}
double xbar = sumx / n;
double ybar = sumy / n;
// second pass: compute summary statistics
double xxbar = 0.0, yybar = 0.0, xybar = 0.0;
for (int i = 0; i < n; i++) {
xxbar += (x[i] - xbar) * (x[i] - xbar);
yybar += (y[i] - ybar) * (y[i] - ybar);
xybar += (x[i] - xbar) * (y[i] - ybar);
}
slope = xybar / xxbar;
intercept = ybar - slope * xbar;
// more statistical analysis
double rss = 0.0; // residual sum of squares
double ssr = 0.0; // regression sum of squares
for (int i = 0; i < n; i++) {
double fit = slope*x[i] + intercept;
rss += (fit - y[i]) * (fit - y[i]);
ssr += (fit - ybar) * (fit - ybar);
}
int degreesOfFreedom = n-2;
r2 = ssr / yybar;
double svar = rss / degreesOfFreedom;
svar1 = svar / xxbar;
svar0 = svar/n + xbar*xbar*svar1;
}
/**
* Returns the <em>y</em>-intercept α of the best of the best-fit line <em>y</em> = α + β <em>x</em>.
*
* @return the <em>y</em>-intercept α of the best-fit line <em>y = α + β x</em>
*/
public double intercept() {
return intercept;
}
/**
* Returns the slope β of the best of the best-fit line <em>y</em> = α + β <em>x</em>.
*
* @return the slope β of the best-fit line <em>y</em> = α + β <em>x</em>
*/
public double slope() {
return slope;
}
/**
* Returns the coefficient of determination <em>R</em><sup>2</sup>.
*
* @return the coefficient of determination <em>R</em><sup>2</sup>,
* which is a real number between 0 and 1
*/
public double R2() {
return r2;
}
/**
* Returns the standard error of the estimate for the intercept.
*
* @return the standard error of the estimate for the intercept
*/
public double interceptStdErr() {
return Math.sqrt(svar0);
}
/**
* Returns the standard error of the estimate for the slope.
*
* @return the standard error of the estimate for the slope
*/
public double slopeStdErr() {
return Math.sqrt(svar1);
}
/**
* Returns the expected response {@code y} given the value of the predictor
* variable {@code x}.
*
* @param x the value of the predictor variable
* @return the expected response {@code y} given the value of the predictor
* variable {@code x}
*/
public double predict(double x) {
return slope*x + intercept;
}
/**
* Returns a string representation of the simple linear regression model.
*
* @return a string representation of the simple linear regression model,
* including the best-fit line and the coefficient of determination
* <em>R</em><sup>2</sup>
*/
public String toString() {
StringBuilder s = new StringBuilder();
s.append(String.format("%.2f n + %.2f", slope(), intercept()));
s.append(" (R^2 = " + String.format("%.3f", R2()) + ")");
return s.toString();
}
}
/******************************************************************************
* Copyright 2002-2020, Robert Sedgewick and Kevin Wayne.
*
* This file is part of algs4.jar, which accompanies the textbook
*
* Algorithms, 4th edition by Robert Sedgewick and Kevin Wayne,
* Addison-Wesley Professional, 2011, ISBN 0-321-57351-X.
* http://algs4.cs.princeton.edu
*
*
* algs4.jar is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* algs4.jar is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with algs4.jar. If not, see http://www.gnu.org/licenses.
******************************************************************************/ | 5,993 | 34.892216 | 122 | java |
Ludii | Ludii-master/Common/src/main/math/MathRoutines.java | package main.math;
import java.awt.Color;
import java.awt.Point;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.util.ArrayList;
import java.util.List;
import gnu.trove.list.array.TFloatArrayList;
//-----------------------------------------------------------------------------
/**
* Useful math routines.
* @author cambolbro and Dennis Soemers
*/
public final class MathRoutines
{
public static final double EPSILON = 0.0000001;
public static final double MAX_RANGE = 1000000;
//-------------------------------------------------------------------------
// Numerical routines
// /**
// * @return Value normalised to range -1..1 (can overshoot).
// */
// public static double normalise(final int value)
// {
// double norm = 0;
// if (value > 0)
// norm = Math.log10( value) / Math.log10(MAX_RANGE);
// else if (value < 0)
// norm = -Math.log10(-value) / Math.log10(MAX_RANGE);
// return norm;
// }
/**
* @return Large value normalised to range -1..1 (clamped to range).
*/
public static double normaliseLarge(final double value)
{
double norm = 0;
if (value > 0)
norm = Math.min(1, Math.log10( value + 1) / Math.log10(MAX_RANGE));
else if (value < 0)
norm = Math.min(1, -Math.log10(-value + 1) / Math.log10(MAX_RANGE));
return norm;
}
/**
* @return Small value normalised to range -1..1.
*/
public static double normaliseSmall(final double value)
{
return Math.tanh(value);
}
/**
* @param a
* @param b
* @param epsilon
* @return True if and only if the absolute difference between a and b is less than epsilon
*/
public static boolean approxEquals(final double a, final double b, final double epsilon)
{
return (Math.abs(a - b) < epsilon);
}
/**
* @param x
* @return Base-2 logarithm of x: log_2 (x)
*/
public static double log2(final double x)
{
return Math.log(x) / Math.log(2);
}
//-------------------------------------------------------------------------
// Geometry routines
/**
* @return Linear interpolant between two values.
*/
public static double lerp(final double t, final double a, final double b)
{
return a + t * (b - a);
}
/**
* @return Linear interpolant between two points.
*/
public static Point2D lerp(final double t, final Point2D a, final Point2D b)
{
final double dx = b.getX() - a.getX();
final double dy = b.getY() - a.getY();
return new Point2D.Double(a.getX() + t * dx, a.getY() + t * dy);
}
/**
* @return Linear interpolant between two points.
*/
public static Point3D lerp(final double t, final Point3D a, final Point3D b)
{
final double dx = b.x() - a.x();
final double dy = b.y() - a.y();
final double dz = b.z() - a.z();
return new Point3D(a.x() + t * dx, a.y() + t * dy, a.z() + t * dz);
}
/**
* @return Distance between two points.
*/
public static double distance(final Point2D a, final Point2D b)
{
final double dx = b.getX() - a.getX();
final double dy = b.getY() - a.getY();
return Math.sqrt(dx * dx + dy * dy);
}
/**
* @return Distance between two 3D points.
*/
public static double distance(final Point3D a, final Point3D b)
{
final double dx = b.x() - a.x();
final double dy = b.y() - a.y();
final double dz = b.z() - a.z();
return Math.sqrt(dx * dx + dy * dy + dz * dz);
}
/**
* @return Distance between two points.
*/
public static double distanceSquared(final Point2D a, final Point2D b)
{
final double dx = b.getX() - a.getX();
final double dy = b.getY() - a.getY();
return dx * dx + dy * dy;
}
/**
* @return Distance between two points.
*/
public static double distance(final Point a, final Point b)
{
final double dx = b.x - a.x;
final double dy = b.y - a.y;
return Math.sqrt(dx * dx + dy * dy);
}
/**
* @return Distance between two points.
*/
public static double distance(final double ax, final double ay, final double bx, final double by)
{
final double dx = bx - ax;
final double dy = by - ay;
return Math.sqrt(dx * dx + dy * dy);
}
/**
* @return Distance between two points.
*/
public static double distance
(
final double ax, final double ay, final double az,
final double bx, final double by, final double bz
)
{
final double dx = bx - ax;
final double dy = by - ay;
final double dz = bz - az;
return Math.sqrt(dx * dx + dy * dy + dz * dz);
}
/**
* @param theta
* @param pt
* @return Given point, rotated counterclockwise by angle theta about the (0, 0) origin
*/
public static Point2D rotate(final double theta, final Point2D pt)
{
return new Point2D.Double
(
pt.getX() * Math.cos(theta) - pt.getY() * Math.sin(theta),
pt.getY() * Math.cos(theta) + pt.getX() * Math.sin(theta)
);
}
/**
* @param theta
* @param pt
* @param pivot
* @return Given point, rotated counterclockwise by angle theta about the given pivot
*/
public static Point2D rotate(final double theta, final Point2D pt, final Point2D pivot)
{
return new Point2D.Double
(
(pt.getX() - pivot.getX()) * Math.cos(theta) - (pt.getY() - pivot.getY()) * Math.sin(theta) + pivot.getX(),
(pt.getY() - pivot.getY()) * Math.cos(theta) + (pt.getX() - pivot.getX()) * Math.sin(theta) + pivot.getY()
);
}
//-------------------------------------------------------------------------
/**
* @return Whether a and b are coincident.
*/
public static boolean coincident(final Point2D a, final Point2D b)
{
return distance(a, b) < EPSILON;
}
//-------------------------------------------------------------------------
/**
* @return Angle between two points, in radians (-PI .. PI).
*/
public static double angle(final Point2D a, final Point2D b)
{
final double dx = b.getX() - a.getX();
final double dy = b.getY() - a.getY();
return Math.atan2(dy, dx);
}
/**
* @return Angle between two points, in radians (0 .. 2*PI).
*/
public static double positiveAngle(final double theta)
{
double angle = theta;
while (angle < 0)
angle += 2 * Math.PI;
while (angle > 2 * Math.PI)
angle -= 2 * Math.PI;
return angle;
}
/**
* @return Angle between two points, in radians (0 .. 2*PI).
*/
public static double positiveAngle(final Point2D a, final Point2D b)
{
final double dx = b.getX() - a.getX();
final double dy = b.getY() - a.getY();
return positiveAngle(Math.atan2(dy, dx));
}
/**
* @return Angle formed by points a, b and c.
*/
public static double angleDifference(final Point2D a, final Point2D b, final Point2D c)
{
// double difference = Math.atan2(c.getY() - b.getY(), c.getX() - b.getX())
// -
// Math.atan2(b.getY() - a.getY(), b.getX() - a.getX());
// // From: https://en.wikipedia.org/wiki/Atan2#Angle_sum_and_difference_identity
// final double x1 = a.getX() - b.getX();
// final double y1 = a.getY() - b.getY();
// final double x2 = c.getX() - b.getX();
// final double y2 = c.getY() - b.getY();
//
// double difference = Math.atan2(y1 * x2 - y2 * x1, x1 * x2 - y1 * y2);
// final Vector vecAB = new Vector(b.getX() - a.getX(), b.getY() - a.getY());
// final Vector vecBC = new Vector(c.getX() - b.getX(), c.getY() - b.getY());
//
// vecAB.normalise();
// vecBC.normalise();
//
// double difference = Math.acos(vecAB.dotProduct(vecBC));
// System.out.println("difference=" + difference + "difference2=" + difference2);
// Partially based on: https://stackoverflow.com/a/3487062/6735980
//
// Define two vectors:
// v = (b - a)
// u = (c - b)
//
// This rotation matrix makes v overlap with the x-axis:
//
// [ v.x v.y ]
// [ -v.y v.x ]
//
// Applying this rotation matrix to u gives the following vector u':
//
// u' = [u'.x] = [ u.x * v.x + u.y * v.y ]
// [u'.y] [ u.x * -v.y + u.y * v.x ]
//
// Now we just need the angle between u' and the x-axis:
//
// Difference = atan2(u'.y, u'.x)
// = atan2(u.x * -v.y + u.y * v.x, u.x * v.x + u.y * v.y)
final double vx = b.getX() - a.getX();
final double vy = b.getY() - a.getY();
final double ux = c.getX() - b.getX();
final double uy = c.getY() - b.getY();
final double difference = Math.atan2(ux * -vy + uy * vx, ux * vx + uy * vy);
// if (difference > Math.PI)
// difference -= 2 * Math.PI;
// else if (difference < -Math.PI)
// difference += 2 * Math.PI;
return difference;
}
/**
* Computes angle formed by points a, b, and c, using an optimised implementation
* that is only valid if the x coordinate of the vector (c - b) is positive.
* Informally, this restriction means that c must at least somewhat lie in
* the same direction a --> b.
*
* If the restriction is violated, we'll only know that the true angle difference
* will have a big absolute value: > 0.5pi or < - 0.5pi. We will mark this by
* returning a value of positive infinity.
*
* @return Angle formed by points a, b and c, or infinity if the x coordinate
* of the vector (c - b) is not positive.
*/
public static double angleDifferencePosX(final Point2D a, final Point2D b, final Point2D c)
{
final double vx = b.getX() - a.getX();
final double vy = b.getY() - a.getY();
final double ux = c.getX() - b.getX();
final double uy = c.getY() - b.getY();
final double x = ux * vx + uy * vy;
if (x <= 0.0)
return Double.POSITIVE_INFINITY;
return Math.atan((ux * -vy + uy * vx) / x);
}
/**
* Computes the absolute value of the tangent of the angle formed by the three
* points a, b, and c, using an optimised implementation that is only valid if
* the x coordinate of the vector (c - b) is positive. Informally, this
* restriction means that c must at least somewhat lie in the same direction
* a --> b.
*
* If the restriction is violated, we return infinity.
*
* @param a
* @param b
* @param c
* @return Absolute value of the tangent of angle formed by points a, b and c,
* or infinity if the x coordinate of the vector (c - b) is not positive.
*/
public static double absTanAngleDifferencePosX(final Point2D a, final Point2D b, final Point2D c)
{
final double vx = b.getX() - a.getX();
final double vy = b.getY() - a.getY();
final double ux = c.getX() - b.getX();
final double uy = c.getY() - b.getY();
final double x = ux * vx + uy * vy;
if (x <= 0.0)
return Double.POSITIVE_INFINITY;
return Math.abs((ux * -vy + uy * vx) / x);
}
//-------------------------------------------------------------------------
/**
* @param pts
* @return Whether the polygon is clockwise.
*/
public static boolean isClockwise(final List<Point2D> pts)
{
double sum = 0;
for (int n = 0, m = pts.size() - 1; n < pts.size(); m = n++)
{
final Point2D ptM = pts.get(m);
final Point2D ptN = pts.get(n);
sum += (ptN.getX() - ptM.getX()) * (ptN.getY() + ptM.getY());
}
return sum < 0;
}
public static Point2D.Double normalisedVector(final double x0, final double y0, final double x1, final double y1)
{
final double dx = x1 - x0;
final double dy = y1 - y0;
double len = Math.sqrt(dx * dx + dy * dy);
if (len == 0)
len = 1;
return new Point2D.Double(dx / len, dy / len);
}
//-------------------------------------------------------------------------
// Probability routines
/**
* Computes union of probabilities (using inclusion-exclusion principle)
* for all the probabilities stored in given list.
*
* @param probs
* @return Union of probabilities
*/
public static float unionOfProbabilities(final TFloatArrayList probs)
{
float union = 0.f;
for (int i = 0; i < probs.size(); ++i)
{
float baseEval = probs.getQuick(i);
for (int j = 0; j < i; ++j)
baseEval *= (1.f - probs.getQuick(j));
union += baseEval;
}
return union;
}
//-------------------------------------------------------------------------
// Colour routines
/**
* @param colour
* @param adjust
* @return Colour with shade adjusted by specified amount.
*/
public static Color shade(final Color colour, final double adjust)
{
final int r = Math.max(0, Math.min(255, (int)(colour.getRed() * adjust + 0.5)));
final int g = Math.max(0, Math.min(255, (int)(colour.getGreen() * adjust + 0.5)));
final int b = Math.max(0, Math.min(255, (int)(colour.getBlue() * adjust + 0.5)));
return new Color(r, g, b);
}
//-------------------------------------------------------------------------
// Auxiliary routines
/**
* @param val
* @param min
* @param max
* @return The given value, but clipped between min and max (both inclusive)
*/
public static int clip(final int val, final int min, final int max)
{
if (val <= min)
return min;
if (val >= max)
return max;
return val;
}
/**
* @param val
* @param min
* @param max
* @return The given value, but clipped between min and max (both inclusive)
*/
public static double clip(final double val, final double min, final double max)
{
if (val <= min)
return min;
if (val >= max)
return max;
return val;
}
//-------------------------------------------------------------------------
// /**
// * @return Degrees as radians.
// */
// public static double degToRad(final double d)
// {
// return d * Math.PI / 180.0;
// }
//
// /**
// * @return Radians to degrees.
// */
// public static double radToDeg(final double r)
// {
// return r * 180.0 / Math.PI;
// }
//-------------------------------------------------------------------------
/**
* @return Average position of two points.
*/
public static Point2D.Double average(final Point2D a, final Point2D b)
{
final double xx = b.getX() + a.getX();
final double yy = b.getY() + a.getY();
return new Point2D.Double(xx * 0.5, yy * 0.5);
}
//-------------------------------------------------------------------------
// Line routines
/**
* From Morrison "Graphics Gems III" (1991) p10.
* @return Distance from pt to infinite line through a and b.
*/
public static double distanceToLine(final Point2D pt, final Point2D a, final Point2D b)
{
final double dx = b.getX() - a.getX();
final double dy = b.getY() - a.getY();
if (Math.abs(dx) + Math.abs(dy) < EPSILON)
return distance(pt, a); // endpoints a and b are coincident
final double a2 = (pt.getY() - a.getY()) * dx - (pt.getX() - a.getX()) * dy;
return Math.sqrt(a2 * a2 / (dx * dx + dy * dy));
}
/**
* From Bowyer & Woodwark "A Programmer's Geometry" p47.
* @return Distance from pt to line segment ab (squared).
*/
public static double distanceToLineSegment(final Point2D pt, final Point2D a, final Point2D b)
{
if (Math.abs(a.getX() - b.getX()) + Math.abs(a.getY() - b.getY()) < EPSILON)
return distance(pt, a); // endpoints a and b are coincident
return Math.sqrt(distanceToLineSegmentSquared(pt, a, b));
}
/**
* From Bowyer & Woodwark "A Programmer's Geometry" p47.
* @return Distance from pt to line segment ab (squared).
*/
public static double distanceToLineSegmentSquared
(
final Point2D pt, final Point2D a, final Point2D b
)
{
final double xkj = a.getX() - pt.getX();
final double ykj = a.getY() - pt.getY();
final double xlk = b.getX() - a.getX();
final double ylk = b.getY() - a.getY();
final double denom = xlk * xlk + ylk * ylk;
if (Math.abs(denom) < EPSILON)
{
// Coincident ends
return (xkj * xkj + ykj * ykj);
}
final double t = -(xkj * xlk + ykj * ylk) / denom;
if (t <= 0.0)
{
// Beyond A
return (xkj * xkj + ykj * ykj);
}
else if (t >= 1.0)
{
// Beyond B
final double xlj = b.getX() - pt.getX();
final double ylj = b.getY() - pt.getY();
return (xlj * xlj + ylj * ylj);
}
else
{
final double xfac = xkj + t * xlk;
final double yfac = ykj + t * ylk;
return (xfac * xfac + yfac * yfac);
}
}
/**
* From Bowyer & Woodwark "A Programmer's Geometry" p47.
* @return Distance from pt to line segment ab (squared).
*/
public static double distanceToLineSegment(final Point3D pt, final Point3D a, final Point3D b)
{
if (Math.abs(a.x() - b.x()) + Math.abs(a.y() - b.y()) + Math.abs(a.z() - b.z()) < EPSILON)
return distance(pt, a); // endpoints a and b are coincident
return Math.sqrt(distanceToLineSegmentSquared(pt, a, b));
}
/**
* From Bowyer & Woodwark "A Programmer's Geometry" p47.
* @return Distance from pt to line segment ab (squared).
*/
public static double distanceToLineSegmentSquared
(
final Point3D pt, final Point3D a, final Point3D b
)
{
final double xkj = a.x() - pt.x();
final double ykj = a.y() - pt.y();
final double zkj = a.z() - pt.z();
final double xlk = b.x() - a.x();
final double ylk = b.y() - a.y();
final double zlk = b.z() - a.z();
final double denom = xlk * xlk + ylk * ylk + zlk * zlk;
if (Math.abs(denom) < EPSILON)
{
// Coincident ends
return (xkj * xkj + ykj * ykj + zkj * zkj);
}
final double t = -(xkj * xlk + ykj * ylk + zkj * zlk) / denom;
if (t <= 0.0)
{
// Beyond A
return (xkj * xkj + ykj * ykj + zkj * zkj);
}
else if (t >= 1.0)
{
// Beyond B
final double xlj = b.x() - pt.x();
final double ylj = b.y() - pt.y();
final double zlj = b.z() - pt.z();
return (xlj * xlj + ylj * ylj + zlj * zlj);
}
else
{
final double xfac = xkj + t * xlk;
final double yfac = ykj + t * ylk;
final double zfac = zkj + t * zlk;
return (xfac * xfac + yfac * yfac + zfac * zfac);
}
}
/**
* @return Intersection point of two infinite lines, else null if parallel.
*/
public static Point2D.Double intersectionPoint
(
final Point2D a, final Point2D b, final Point2D c, final Point2D d
)
{
final double dd = (a.getX() - b.getX()) * (c.getY() - d.getY())
-
(a.getY() - b.getY()) * (c.getX() - d.getX());
if (Math.abs(dd) < EPSILON) //dd == 0)
{
System.out.println("** MathRoutines.intersectionPoint(): Parallel lines.");
return null; // parallel lines
}
final double xi = (
(c.getX() - d.getX()) * (a.getX()*b.getY() - a.getY()*b.getX())
-
(a.getX() - b.getX()) * (c.getX()*d.getY() - c.getY()*d.getX())
) / dd;
final double yi = (
(c.getY() - d.getY()) * (a.getX()*b.getY() - a.getY()*b.getX())
-
(a.getY() - b.getY()) * (c.getX()*d.getY() - c.getY()*d.getX())
) / dd;
return new Point2D.Double(xi, yi);
}
// /**
// * From Klassen "Graphics Gems IV" (1994) p273, after Bowyer & Woodwark (1983).
// * @return Intersection point of two lines, else null if parallel.
// */
// public static Point2D.Double intersectionPoint
// (
// final Point2D.Double a0, final Point2D.Double a1,
// final Point2D.Double b0, final Point2D.Double b1
// )
// {
// final double xlk = a1.x - a0.x;
// final double ylk = a1.y - a0.y;
// final double xnm = b1.x - b0.x;
// final double ynm = b1.y - b0.y;
// final double xmk = b0.x - a0.x;
// final double ymk = b0.y - a0.y;
//
// final double det = xnm * ylk - ynm * xlk;
//
// if (Math.abs(det) < Geometry.EPSILON)
// {
// System.out.println("Geometry.intersection(): Parallel lines.");
// return null; // parallel lines
// }
//
// final double detinv = 1.0 / det;
// final double s = (xnm * ymk - ynm * xmk) * detinv;
// //final double t = (xlk * ymk - ylk * xmk) * detinv;
//
// return new Point2D.Double(a0.x + s*(a1.x-a0.x), a0.y + s*(a1.y-a0.y));
// }
/**
* @return Projection point of pt onto infinite line through a and b.
*/
public static Point2D.Double projectionPoint
(
final Point2D pt, final Point2D a, final Point2D b
)
{
final double dx = b.getX() - a.getX();
final double dy = b.getY() - a.getY();
final Vector v = new Vector(dx, dy);
v.normalise();
v.perpendicular();
final Point2D.Double pt2 = new Point2D.Double(pt.getX() + v.x(), pt.getY() + v.y());
return intersectionPoint(a, b, pt, pt2);
}
//-------------------------------------------------------------------------
/**
* From: Klassen p273 in Graphics Gems IV (1994), after Bowyer & Woodwark (1983).
* @return Whether line segments A and B intersect.
*/
public static boolean lineSegmentsIntersect
(
final double a0x, final double a0y, final double a1x, final double a1y,
final double b0x, final double b0y, final double b1x, final double b1y
)
{
final double xlk = a1x - a0x;
final double ylk = a1y - a0y;
final double xnm = b1x - b0x;
final double ynm = b1y - b0y;
final double xmk = b0x - a0x;
final double ymk = b0y - a0y;
final double det = xnm * ylk - ynm * xlk;
if (Math.abs(det) < EPSILON)
return false; // parallel lines
final double detinv = 1.0 / det;
final double s = (xnm * ymk - ynm * xmk) * detinv; // pt on A [0..1]
final double t = (xlk * ymk - ylk * xmk) * detinv; // pt on B [0..1]
return s >= -EPSILON && s <= 1 + EPSILON && t >= -EPSILON && t <= 1 + EPSILON;
}
/**
* @return Whether line segments A and B cross internally, i.e. not at the vertices.
*/
public static boolean isCrossing
(
final double a0x, final double a0y, final double a1x, final double a1y,
final double b0x, final double b0y, final double b1x, final double b1y
)
{
final double MARGIN = 0.01;
final double xlk = a1x - a0x;
final double ylk = a1y - a0y;
final double xnm = b1x - b0x;
final double ynm = b1y - b0y;
final double xmk = b0x - a0x;
final double ymk = b0y - a0y;
final double det = xnm * ylk - ynm * xlk;
if (Math.abs(det) < EPSILON)
return false; // parallel lines
final double detinv = 1.0 / det;
final double s = (xnm * ymk - ynm * xmk) * detinv; // pt on A [0..1]
final double t = (xlk * ymk - ylk * xmk) * detinv; // pt on B [0..1]
return s > MARGIN && s < 1 - MARGIN && t > MARGIN && t < 1 - MARGIN;
}
/**
* @return Whether line segments A and B cross internally, i.e. not at the vertices.
*/
public static Point2D crossingPoint
(
final double a0x, final double a0y, final double a1x, final double a1y,
final double b0x, final double b0y, final double b1x, final double b1y
)
{
final double MARGIN = 0.01;
final double xlk = a1x - a0x;
final double ylk = a1y - a0y;
final double xnm = b1x - b0x;
final double ynm = b1y - b0y;
final double xmk = b0x - a0x;
final double ymk = b0y - a0y;
final double det = xnm * ylk - ynm * xlk;
if (Math.abs(det) < EPSILON)
return null; // parallel lines
final double detinv = 1.0 / det;
final double s = (xnm * ymk - ynm * xmk) * detinv; // pt on A [0..1]
final double t = (xlk * ymk - ylk * xmk) * detinv; // pt on B [0..1]
if (s > MARGIN && s < 1 - MARGIN && t > MARGIN && t < 1 - MARGIN)
return new Point2D.Double(a0x + s * (a1x - a0x), a0y + s * (a1y - a0y));
return null; // no crossing
}
/**
* @return Whether point P touches line segment A, apart from at its vertices.
*/
public static Point3D touchingPoint
(
final Point3D pt, final Point3D a, final Point3D b
)
{
final double MARGIN = 0.001;
final double distToA = distance(pt, a);
final double distToB = distance(pt, b);
final double distToAB = distanceToLineSegment(pt, a, b);
if (distToA < MARGIN || distToB < MARGIN || distToAB > MARGIN)
return null; // not touching
final double distAB = distance(a, b);
return lerp(distToA/distAB, a, b);
}
//-------------------------------------------------------------------------
// Polygon routines
/**
* From Bowyer & Woodwark, p63.
* @return Whether three points are in clockwise order.
*/
public static boolean clockwise
(
double x0, double y0, double x1, double y1, double x2, double y2
)
{
final double result = (x1 - x0) * (y2 - y0) - (x2 - x0) * (y1 - y0);
return (result < EPSILON);
}
public static boolean clockwise
(
final Point2D a, final Point2D b, final Point2D c
)
{
return clockwise(a.getX(), a.getY(), b.getX(), b.getY(), c.getX(), c.getY());
}
public static boolean clockwise(final List<Point2D> poly)
{
// Use negative area, since Y goes down in screen coordinates
return polygonArea(poly) < 0;
}
// BOOL
// GEO_Geometry::PtInCorner
// (
// CPoint3 const& P, CPoint3 const& A,
// CPoint3 const& B, CPoint3 const& C
// )
// {
// return
// (
// WhichSide(P, B, A) == 1
// &&
// WhichSide(P, B, C) == -1
// );
// }
/**
* @return Which side of line AB point (x,y) lies on.
*/
public static int whichSide
(
final double x, final double y,
final double ax, final double ay,
final double bx, final double by
)
{
final double result = (bx - ax) * (y - ay) - (by - ay) * (x - ax);
if (result < -EPSILON)
return -1;
if (result > EPSILON)
return 1;
return 0;
}
public static int whichSide
(
final Point2D pt, final Point2D a, final Point2D b
)
{
return whichSide(pt.getX(), pt.getY(), a.getX(), a.getY(), b.getX(), b.getY());
}
public static boolean pointInTriangle
(
final Point2D pt, final Point2D a, final Point2D b, final Point2D c
)
{
return whichSide(pt, a, b) >= 0
&&
whichSide(pt, b, c) >= 0
&&
whichSide(pt, c, a) >= 0;
}
//-------------------------------------------------------------------------
/**
* @return Whether pt is inside convex counterclockwise polygon poly.
*/
public static boolean pointInConvexPolygon(final Point2D pt, final Point2D[] poly)
{
final int sz = poly.length;
for (int i = 0; i < sz; i++)
{
final Point2D a = poly[i];
final Point2D b = poly[(i + 1) % sz] ;
final double side = (pt.getX() - a.getX()) * (b.getY() - a.getY()) - (pt.getY() - a.getY()) * (b.getX() - a.getX());
if (side < -EPSILON)
return false;
}
return true;
}
/**
* From https://forum.processing.org/one/topic/how-do-i-find-if-a-point-is-inside-a-complex-polygon.html.
* @return Whether pt is inside complex polygon.
*/
public static boolean pointInPolygon(final Point2D pt, final Point2D[] poly)
{
final int sz = poly.length;
int j = sz - 1;
boolean odd = false;
for (int i = 0; i < sz; i++)
{
if
(
(
poly[i].getY() < pt.getY() && poly[j].getY() >= pt.getY()
||
poly[j].getY() < pt.getY() && poly[i].getY() >= pt.getY()
)
&&
(poly[i].getX() <= pt.getX() || poly[j].getX() <= pt.getX())
)
{
odd ^= (
poly[i].getX() + (pt.getY() - poly[i].getY())
/
(poly[j].getY() - poly[i].getY()) * (poly[j].getX() - poly[i].getX())
<
pt.getX()
);
}
j=i;
}
return odd;
}
/**
* From https://forum.processing.org/one/topic/how-do-i-find-if-a-point-is-inside-a-complex-polygon.html.
* @return Whether pt is inside complex polygon.
*/
public static boolean pointInPolygon(final Point2D pt, final List<Point2D> poly)
{
final int sz = poly.size();
int j = sz - 1;
boolean odd = false;
final double x = pt.getX();
final double y = pt.getY();
for (int i = 0; i < sz; i++)
{
final double ix = poly.get(i).getX();
final double iy = poly.get(i).getY();
final double jx = poly.get(j).getX();
final double jy = poly.get(j).getY();
if ((iy < y && jy >= y || jy < y && iy >= y) && (ix <= x || jx <= x))
{
odd ^= (ix + (y - iy) / (jy - iy) * (jx - ix) < x);
}
j = i;
}
return odd;
}
//-------------------------------------------------------------------------
/**
* From: https://stackoverflow.com/questions/1165647/how-to-determine-if-a-list-of-polygon-points-are-in-clockwise-order
* @return Signed area of polygon.
*/
public static double polygonArea(final List<Point2D> poly)
{
double area = 0;
for (int n = 0; n < poly.size(); n++)
{
final Point2D ptN = poly.get(n);
final Point2D ptO = poly.get((n + 1) % poly.size());
area += ptN.getX() * ptO.getY() - ptO.getX() * ptN.getY();
}
return area / 2.0;
}
//-------------------------------------------------------------------------
/**
* Inflates the polygon outwards by the specified amount.
* Useful for board shapes that need to be inflated so don't intersect
* cell position exactly.
*/
public static void inflatePolygon(final List<Point2D> polygon, final double amount)
{
final List<Point2D> adjustments = new ArrayList<Point2D>();
for (int n = 0; n < polygon.size(); n++)
{
final Point2D ptA = polygon.get(n);
final Point2D ptB = polygon.get((n + 1) % polygon.size());
final Point2D ptC = polygon.get((n + 2) % polygon.size());
final boolean clockwise = MathRoutines.clockwise(ptA, ptB, ptC);
Vector vecIn = null;
Vector vecOut = null;
if (clockwise)
{
vecIn = new Vector(ptA, ptB);
vecOut = new Vector(ptC, ptB);
}
else
{
vecIn = new Vector(ptB, ptA);
vecOut = new Vector(ptB, ptC);
}
vecIn.normalise();
vecOut.normalise();
vecIn.scale( amount, amount);
vecOut.scale(amount, amount);
final double xx = (vecIn.x() + vecOut.x()) * 0.5;
final double yy = (vecIn.y() + vecOut.y()) * 0.5;
adjustments.add(new Point2D.Double(xx, yy));
}
for (int n = 0; n < polygon.size(); n++)
{
final Point2D pt = polygon.get(n);
final Point2D adjustment = adjustments.get((n - 1 + polygon.size()) % polygon.size());
final double xx = pt.getX() + adjustment.getX();
final double yy = pt.getY() + adjustment.getY();
polygon.remove(n);
polygon.add(n, new Point2D.Double(xx, yy));
}
}
//-------------------------------------------------------------------------
/**
* @return Bounding box of points.
*/
public static Rectangle2D bounds(final List<Point2D> points)
{
double x0 = 1000000;
double y0 = 1000000;
double x1 = -1000000;
double y1 = -1000000;
for (final Point2D pt : points)
{
final double x = pt.getX();
final double y = pt.getY();
if (x < x0)
x0 = x;
if (x > x1)
x1 = x;
if (y < y0)
y0 = y;
if (y > y1)
y1 = y;
}
if (x0 == 1000000 || y0 == 1000000)
{
x0 = 0;
y0 = 0;
x1 = 0;
y1 = 0;
}
return new Rectangle2D.Double(x0, y0, x1-x0, y1-y0);
}
//-------------------------------------------------------------------------
}
| 30,388 | 25.288062 | 121 | java |
Ludii | Ludii-master/Common/src/main/math/Point2D.java | package main.math;
/**
* 2D point.
* @author Dennis Soemers and cambolbro
*/
public class Point2D
{
//-------------------------------------------------------------------------
/** X coordinate */
private double x;
/** Y coordinate */
private double y;
//-------------------------------------------------------------------------
/**
* Constructor
* @param x
* @param y
*/
public Point2D(final double x, final double y)
{
this.x = x;
this.y = y;
}
//-------------------------------------------------------------------------
/**
* @return X coordinate
*/
public double x()
{
return x;
}
/**
* @return Y coordinate
*/
public double y()
{
return y;
}
//-------------------------------------------------------------------------
/**
* Set coordinates
* @param newX
* @param newY
*/
public void set(final double newX, final double newY)
{
x = newX;
y = newY;
}
//-------------------------------------------------------------------------
/**
* @param other
* @return Euclidean distance to other point
*/
public double distance(final Point2D other)
{
final double dx = other.x - x;
final double dy = other.y - y;
return Math.sqrt(dx * dx + dy * dy);
}
//-------------------------------------------------------------------------
/**
* Translate the point
* @param dx
* @param dy
*/
public void translate(final double dx, final double dy)
{
x += dx;
y += dy;
}
/**
* Scale the point by one scalar
* @param s
*/
public void scale(final double s)
{
x *= s;
y *= s;
}
/**
* Scale the two coordinates by two scalars
* @param sx
* @param sy
*/
public void scale(final double sx, final double sy)
{
x *= sx;
y *= sy;
}
//-------------------------------------------------------------------------
@Override
public int hashCode()
{
final int prime = 31;
int result = 1;
long temp;
temp = Double.doubleToLongBits(x);
result = prime * result + (int) (temp ^ (temp >>> 32));
temp = Double.doubleToLongBits(y);
result = prime * result + (int) (temp ^ (temp >>> 32));
return result;
}
@Override
public boolean equals(final Object obj)
{
if (this == obj)
return true;
if (!(obj instanceof Point2D))
return false;
final Point2D other = (Point2D) obj;
if (Double.doubleToLongBits(x) != Double.doubleToLongBits(other.x))
return false;
if (Double.doubleToLongBits(y) != Double.doubleToLongBits(other.y))
return false;
return true;
}
//-------------------------------------------------------------------------
/**
* @param other
* @param tolerance
* @return Are we approximately equal (given tolerance level)?
*/
public boolean equalsApprox(final Point2D other, final double tolerance)
{
return (Math.abs(x - other.x) <= tolerance && Math.abs(y - other.y) <= tolerance);
}
//-------------------------------------------------------------------------
}
| 2,964 | 17.765823 | 84 | java |
Ludii | Ludii-master/Common/src/main/math/Point3D.java | package main.math;
import java.awt.geom.Point2D;
/**
* 3D point.
* @author cambolbro
*/
public class Point3D
{
private double x;
private double y;
private double z;
//-------------------------------------------------------------------------
public Point3D(final double x, final double y)
{
this.x = x;
this.y = y;
this.z = 0;
}
public Point3D(final double x, final double y, final double z)
{
this.x = x;
this.y = y;
this.z = z;
}
public Point3D(final Point3D other)
{
this.x = other.x;
this.y = other.y;
this.z = other.z;
}
public Point3D(final Point2D other)
{
this.x = other.getX();
this.y = other.getY();
this.z = 0;
}
//-------------------------------------------------------------------------
public double x()
{
return x;
}
public double y()
{
return y;
}
public double z()
{
return z;
}
//-------------------------------------------------------------------------
public void set(final double xx, final double yy)
{
x = xx;
y = yy;
}
public void set(final double xx, final double yy, final double zz)
{
x = xx;
y = yy;
z = zz;
}
public void set(final Point3D other)
{
x = other.x;
y = other.y;
z = other.z;
}
public void set(final Point2D other)
{
x = other.getX();
y = other.getY();
z = 0;
}
//-------------------------------------------------------------------------
public double distance(final Point3D other)
{
final double dx = other.x - x;
final double dy = other.y - y;
final double dz = other.z - z;
return Math.sqrt(dx * dx + dy * dy + dz * dz);
}
public double distance(final Point2D other)
{
final double dx = other.getX() - x;
final double dy = other.getY() - y;
return Math.sqrt(dx * dx + dy * dy);
}
//-------------------------------------------------------------------------
public void translate(final double dx, final double dy)
{
x += dx;
y += dy;
}
public void translate(final double dx, final double dy, final double dz)
{
x += dx;
y += dy;
z += dz;
}
public void scale(final double s)
{
x *= s;
y *= s;
z *= s;
}
public void scale(final double sx, final double sy)
{
x *= sx;
y *= sy;
}
public void scale(final double sx, final double sy, final double sz)
{
x *= sx;
y *= sy;
z *= sz;
}
//-------------------------------------------------------------------------
}
| 2,398 | 15.209459 | 76 | java |
Ludii | Ludii-master/Common/src/main/math/Polygon.java | package main.math;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import gnu.trove.list.array.TIntArrayList;
//-----------------------------------------------------------------------------
/**
* Polygon with floating point precision, can be concave.
*
* @author cambolbro
*/
public final class Polygon
{
private final List<Point2D> points = new ArrayList<Point2D>();
//-------------------------------------------------------------------------
public Polygon()
{
}
public Polygon(final List<Point2D> pts, final int numRotations)
{
for (final Point2D pt : pts)
points.add(new Point2D.Double(pt.getX(), pt.getY()));
if (numRotations != 0)
addRotations(numRotations);
}
public Polygon(final Point2D[] pts)
{
for (final Point2D pt : pts)
points.add(new Point2D.Double(pt.getX(), pt.getY()));
}
public Polygon(final Float[][] pts, final int numRotations)
{
for (final Float[] pair : pts)
{
if (pair.length < 2)
{
System.out.println("** Polygon: Two points expected.");
points.clear();
break;
}
points.add(new Point2D.Double(pair[0].floatValue(), pair[1].floatValue()));
}
if (numRotations != 0)
addRotations(numRotations);
}
public Polygon(final int numSides)
{
final double r = numSides / (2 * Math.PI);
for (int n = 0; n < numSides; n++)
{
final double theta = Math.PI / 2 + (double)n / numSides * 2 * Math.PI;
final double x = r * Math.cos(theta);
final double y = r * Math.sin(theta);
points.add(new Point2D.Double(x, y));
}
}
//-------------------------------------------------------------------------
public List<Point2D> points()
{
return Collections.unmodifiableList(points);
}
//-------------------------------------------------------------------------
public int size()
{
return points.size();
}
public boolean isEmpty()
{
return points.isEmpty();
}
public void clear()
{
points.clear();
}
public void add(final Point2D pt)
{
points.add(pt);
}
//-------------------------------------------------------------------------
public void setFrom(final Polygon other)
{
clear();
for (final Point2D pt : other.points())
add(new Point2D.Double(pt.getX(), pt.getY()));
}
//-------------------------------------------------------------------------
/**
* Add the existing points repeated by the specified number of rotations.
* @param numRotations
*/
void addRotations(final int numRotations)
{
if (numRotations < 0)
Collections.reverse(points);
final int P = points.size();
final double rotnAngle = 2.0 * Math.PI / numRotations;
double angle = rotnAngle;
for (int r = 1; r < Math.abs(numRotations); r++)
{
final double sinAngle = Math.sin(angle);
final double cosAngle = Math.cos(angle);
for (int p = 0; p < P; p++)
{
final double x = points.get(p).getX();
final double y = points.get(p).getY();
final double xx = x * cosAngle - y * sinAngle;
final double yy = x * sinAngle + y * cosAngle;
points.add(new Point2D.Double(xx, yy));
}
angle += rotnAngle;
}
}
//-------------------------------------------------------------------------
public double length()
{
double length = 0;
for (int n = 0; n < points.size(); n++)
length += MathRoutines.distance(points.get(n), points.get((n + 1) % points.size()));
return length;
}
public Point2D midpoint()
{
if (points.isEmpty())
return new Point2D.Double();
double avgX = 0;
double avgY = 0;
for (int n = 0; n < points.size(); n++)
{
avgX += points.get(n).getX();
avgY += points.get(n).getY();
}
avgX /= points.size();
avgY /= points.size();
return new Point2D.Double(avgX, avgY);
}
/**
* From: https://stackoverflow.com/questions/1165647/how-to-determine-if-a-list-of-polygon-points-are-in-clockwise-order
* @return Signed area of polygon.
*/
public double area()
{
double area = 0;
for (int n = 0; n < points.size(); n++)
{
final Point2D ptN = points.get(n);
final Point2D ptO = points.get((n + 1) % points.size());
area += ptN.getX() * ptO.getY() - ptO.getX() * ptN.getY();
}
return area / 2.0;
}
//-------------------------------------------------------------------------
public boolean isClockwise()
{
double sum = 0;
for (int n = 0, m = points.size() - 1; n < points.size(); m = n++)
{
final Point2D ptM = points.get(m);
final Point2D ptN = points.get(n);
sum += (ptN.getX() - ptM.getX()) * (ptN.getY() + ptM.getY());
}
return sum < 0;
}
public boolean clockwise()
{
// Use negative area, since Y goes down in screen coordinates
return area() < 0;
}
//-------------------------------------------------------------------------
public boolean contains(final double x, final double y)
{
return contains(new Point2D.Double(x, y));
}
/**
* From https://forum.processing.org/one/topic/how-do-i-find-if-a-point-is-inside-a-complex-polygon.html.
* @return Whether pt is inside complex polygon.
*/
public boolean contains(final Point2D pt)
{
final int numPoints = points.size();
int j = numPoints - 1;
boolean odd = false;
final double x = pt.getX();
final double y = pt.getY();
for (int i = 0; i < numPoints; i++)
{
final double ix = points.get(i).getX();
final double iy = points.get(i).getY();
final double jx = points.get(j).getX();
final double jy = points.get(j).getY();
if ((iy < y && jy >= y || jy < y && iy >= y) && (ix <= x || jx <= x))
{
odd ^= (ix + (y - iy) / (jy - iy) * (jx - ix) < x);
}
j = i;
}
return odd;
}
// /**
// * @return Whether pt is inside convex counterclockwise polygon poly.
// */
// public boolean containsConvex(final Point2D pt)
// {
// final int numPoints = points.size();
// for (int i = 0; i < numPoints; i++)
// {
// final Point2D a = points.get(i);
// final Point2D b = points.get((i + 1) % numPoints);
//
// if (MathRoutines.whichSide(pt, a, b) < 0)
// return false;
// }
// return true;
// }
//-------------------------------------------------------------------------
/**
* Generate polygon from the description of sides.
*
* Can't really distinguish Cell from Vertex versions here (-ve turns make
* ambiguous cases) so treat both the same.
*/
public void fromSides(final TIntArrayList sides, final int[][] steps)
{
int step = steps.length - 1;
int row = 0;
int col = 0;
clear();
points.add(new Point2D.Double(col, row));
for (int n = 0; n < sides.size(); n++)
{
final int nextStep = sides.get(n);
step = (step + (nextStep < 0 ? -1 : 1) + steps.length) % steps.length;
row += nextStep * steps[step][0];
col += nextStep * steps[step][1];
points.add(new Point2D.Double(col, row));
}
}
public void fromSides(final TIntArrayList sides, final double[][] steps)
{
int step = steps.length - 1;
double x = 0;
double y = 0;
clear();
points.add(new Point2D.Double(x, y));
for (int n = 0; n < sides.size(); n++)
{
final int nextStep = sides.get(n);
step = (step + (nextStep < 0 ? -1 : 1) + steps.length) % steps.length;
x += nextStep * steps[step][0];
y += nextStep * steps[step][1];
points.add(new Point2D.Double(x, y));
}
}
//-------------------------------------------------------------------------
/**
* Inflates the polygon outwards by the specified amount.
* Useful for board shapes that need to be inflated so don't intersect
* cell position exactly.
*/
public void inflate(final double amount)
{
final List<Point2D> adjustments = new ArrayList<Point2D>();
for (int n = 0; n < points.size(); n++)
{
final Point2D ptA = points.get(n);
final Point2D ptB = points.get((n + 1) % points.size());
final Point2D ptC = points.get((n + 2) % points.size());
final boolean clockwise = MathRoutines.clockwise(ptA, ptB, ptC);
Vector vecIn = null;
Vector vecOut = null;
if (clockwise)
{
vecIn = new Vector(ptA, ptB);
vecOut = new Vector(ptC, ptB);
}
else
{
vecIn = new Vector(ptB, ptA);
vecOut = new Vector(ptB, ptC);
}
vecIn.normalise();
vecOut.normalise();
vecIn.scale( amount, amount);
vecOut.scale(amount, amount);
final double xx = (vecIn.x() + vecOut.x()) * 0.5;
final double yy = (vecIn.y() + vecOut.y()) * 0.5;
adjustments.add(new Point2D.Double(xx, yy));
}
for (int n = 0; n < points.size(); n++)
{
final Point2D pt = points.get(n);
final Point2D adjustment = adjustments.get((n - 1 + points.size()) % points.size());
final double xx = pt.getX() + adjustment.getX();
final double yy = pt.getY() + adjustment.getY();
points.remove(n);
points.add(n, new Point2D.Double(xx, yy));
}
}
//-------------------------------------------------------------------------
/**
* @return Bounding box of points.
*/
public Rectangle2D bounds()
{
if (points.isEmpty())
return new Rectangle2D.Double();
double x0 = 1000000;
double y0 = 1000000;
double x1 = -1000000;
double y1 = -1000000;
for (final Point2D pt : points)
{
final double x = pt.getX();
final double y = pt.getY();
if (x < x0) x0 = x;
if (x > x1) x1 = x;
if (y < y0) y0 = y;
if (y > y1) y1 = y;
}
return new Rectangle2D.Double(x0, y0, x1-x0, y1-y0);
}
//-------------------------------------------------------------------------
@Override
public String toString()
{
final StringBuilder sb = new StringBuilder();
sb.append("Polygon:");
for (final Point2D pt : points)
sb.append(" (" + pt.getX() + "," + pt.getY() + ")");
return sb.toString();
}
//-------------------------------------------------------------------------
}
| 9,940 | 21.95843 | 121 | java |
Ludii | Ludii-master/Common/src/main/math/RCL.java | package main.math;
import java.io.Serializable;
//-----------------------------------------------------------------------------
/**
* [row,column,layer] coordinate.
*
* @author cambolbro and Eric.Piette
*/
public final class RCL implements Serializable
{
private static final long serialVersionUID = 1L;
/** Row. */
private int row = -1;
/** Column. */
private int column = -1;
/** Layer. */
private int layer = -1;
//-------------------------------------------------------------------------
/**
* Default constructor.
*/
public RCL()
{
}
/**
* Constructor 2D.
*/
public RCL(final int r, final int c)
{
row = r;
column = c;
layer = 0;
}
/**
* Constructor 2D.
*/
public RCL(final int r, final int c, final int l)
{
row = r;
column = c;
layer = l;
}
//-------------------------------------------------------------------------
public int row()
{
return row;
}
public void setRow(final int r)
{
row = r;
}
public int column()
{
return column;
}
public void setColumn(final int c)
{
column = c;
}
public int layer()
{
return layer;
}
public void setLayer(final int l)
{
layer = l;
}
//-------------------------------------------------------------------------
/**
* @param r Row.
* @param c Column.
* @param l Layer.
*/
public void set(final int r, final int c, final int l)
{
row = r;
column = c;
layer = l;
}
/**
*/
public void set(final RCL other)
{
row = other.row;
column = other.column;
layer = other.layer;
}
//-------------------------------------------------------------------------
@Override
public String toString()
{
return "row = " + row + ", column = " + column + ", layer = " + layer;
}
//-------------------------------------------------------------------------
}
| 1,834 | 14.291667 | 79 | java |
Ludii | Ludii-master/Common/src/main/math/RCLType.java | package main.math;
/**
* Dimension types in an RCL coordinate.
*
* @author cambolbro
*/
public enum RCLType
{
/** Row (typically based on Y coordinate). */
Row,
/** Column (typically based on X coordinate). */
Column,
/** Layer (typically based on Z coordinate). */
Layer,
}
| 292 | 13.65 | 49 | java |
Ludii | Ludii-master/Common/src/main/math/Vector.java | package main.math;
import java.awt.geom.Point2D;
import java.text.DecimalFormat;
/**
* 2D vector.
* @author cambolbro
*/
public class Vector
{
private double x = 0;
private double y = 0;
private double z = 0;
//-------------------------------------------------------------------------
public Vector(final double x, final double y)
{
this.x = x;
this.y = y;
}
public Vector(final double x, final double y, final double z)
{
this.x = x;
this.y = y;
this.z = z;
}
public Vector(final Point2D pt)
{
this.x = pt.getX();
this.y = pt.getY();
}
public Vector(final Point2D ptA, final Point2D ptB)
{
this.x = ptB.getX() - ptA.getX();
this.y = ptB.getY() - ptA.getY();
}
public Vector(final Point3D ptA, final Point3D ptB)
{
this.x = ptB.x() - ptA.x();
this.y = ptB.y() - ptA.y();
this.z = ptB.z() - ptA.z();
}
public Vector(final Vector other)
{
this.x = other.x;
this.y = other.y;
this.z = other.z;
}
//-------------------------------------------------------------------------
public double x()
{
return x;
}
public double y()
{
return y;
}
public double z()
{
return z;
}
public void set(final double xx, final double yy, final double zz)
{
x = xx;
y = yy;
z = zz;
}
//-------------------------------------------------------------------------
/**
* @return Magnitude of vector.
*/
public double magnitude()
{
return Math.sqrt(x * x + y * y + z * z);
}
/**
* Normalise to unit vector.
*/
public void normalise()
{
final double mag = magnitude();
if (mag < MathRoutines.EPSILON)
return; // too small
x /= mag;
y /= mag;
z /= mag;
}
public double direction()
{
return Math.atan2(y, x); // in radians, -PI .. PI
}
public void reverse()
{
x = -x;
y = -y;
z = -z;
}
/**
* Make perpendicular (to right?).
*/
public void perpendicular()
{
final double tmp = x;
x = -y;
y = tmp;
}
public void translate(final double dx, final double dy)
{
x += dx;
y += dy;
}
/**
* Translate.
*/
public void translate(final double dx, final double dy, final double dz)
{
x += dx;
y += dy;
z += dz;
}
public void scale(final double factor)
{
x *= factor;
y *= factor;
z *= factor;
}
public void scale(final double sx, final double sy)
{
x *= sx;
y *= sy;
}
public void scale(final double sx, final double sy, final double sz)
{
x *= sx;
y *= sy;
z *= sz;
}
/**
* @param theta Radians.
*/
public void rotate(final double theta)
{
final double xx = x * Math.cos(theta) - y * Math.sin(theta);
final double yy = y * Math.cos(theta) + x * Math.sin(theta);
x = xx;
y = yy;
}
/**
* @return Dot product of this vector and another.
*/
public double dotProduct(final Vector other)
{
return x * other.x + y * other.y + z * other.z;
}
/**
* @return Determinant of this vector and another.
*/
public double determinant(final Vector other)
{
return x * other.y - y * other.x;
}
//-------------------------------------------------------------------------
@Override
public String toString()
{
final DecimalFormat df = new DecimalFormat("#.###");
return "<" + df.format(x) + "," + df.format(y) + "," + df.format(z) + ">";
}
//-------------------------------------------------------------------------
}
| 3,346 | 15.569307 | 77 | java |
Ludii | Ludii-master/Common/src/main/math/statistics/IncrementalStats.java | package main.math.statistics;
import main.Constants;
/**
* Object that can compute some statistics of data incrementally (online). In
* contrast to our Stats class, this one does not have to retain all observations
* in memory (and can more quickly return aggregates because it no longer requires
* any loops through all observations).
*
* Uses algorithm found by Welford, as described here:
* https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance#Welford's_online_algorithm
*
* @author Dennis Soemers
*
*/
public class IncrementalStats
{
//-------------------------------------------------------------------------
/** Number of observations */
private int n;
/** Mean of observations */
private double mean;
/** Sum of squared differences from mean */
private double sumSquaredDifferences;
//-------------------------------------------------------------------------
/**
* Constructor
*/
public IncrementalStats()
{
n = 0;
mean = 0.0;
sumSquaredDifferences = 0.0;
}
/**
* Copy constructor
*
* @param other
*/
public IncrementalStats(final IncrementalStats other)
{
n = other.getNumObservations();
mean = other.getMean();
sumSquaredDifferences = other.getSumSquaredDifferences();
}
//-------------------------------------------------------------------------
/**
* Returns the mean of all observations so far
*/
public double getMean()
{
return mean;
}
/**
* Returns the number of observations processed so far
*/
public int getNumObservations()
{
return n;
}
/**
* @return Sample standard deviation (biased if n = 1)
*/
public double getStd()
{
return Math.sqrt(getVariance());
}
/**
* @return Sum of squared differences
*/
public double getSumSquaredDifferences()
{
return sumSquaredDifferences;
}
/**
* Returns the sample variance, except for the case where that would be exactly 0.0.
*
* In that case, it instead returns a value that decreases as we get more observations
*/
public double getNonZeroVariance()
{
if (sumSquaredDifferences == 0.0)
{
// We probably don't really want a variance of 0, so instead return something
// that decreases as we get more observations
//System.out.println("returning 1 / (n + epsilon) = " + (1.0 / (n + Globals.EPSILON)));
return 1.0 / (n + Constants.EPSILON);
}
return getVariance();
}
/**
* Returns the sample variance of all observations so far (biased if n = 1)
*/
public double getVariance()
{
if (n > 1)
return (sumSquaredDifferences / (n - 1));
return (sumSquaredDifferences / (n));
}
/**
* Initialises the data with some initial values (useful for simulating
* prior distribution / knowledge)
*
* @param newN
* @param newMean
* @param newSumSquaredDifferences
*/
public void init(final int newN, final double newMean, final double newSumSquaredDifferences)
{
this.n = newN;
this.mean = newMean;
this.sumSquaredDifferences = newSumSquaredDifferences;
}
/**
* Initialise from another object
* @param other
*/
public void initFrom(final IncrementalStats other)
{
this.n = other.getNumObservations();
this.mean = other.getMean();
this.sumSquaredDifferences = other.getSumSquaredDifferences();
}
/**
* Add a new observation
*
* @param observation
*/
public void observe(final double observation)
{
++n;
double delta = observation - mean;
mean += delta / n;
sumSquaredDifferences += delta * (observation - mean);
}
/**
* Opposite of observing, we'll forget about a previously made observation
*
* @param observation
*/
public void unobserve(final double observation)
{
final int wrongN = n;
final double wrongMean = mean;
final double wrongSsd = sumSquaredDifferences;
--n;
mean = (wrongN * wrongMean - observation) / n;
final double delta = observation - mean;
sumSquaredDifferences = wrongSsd - delta * (observation - wrongMean);
}
/**
* Merges two sets of incrementally collected stats, using Chan et al.'s method as described on
* https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance#Parallel_algorithm
*
* @param a
* @param b
*/
public static IncrementalStats merge(final IncrementalStats a, final IncrementalStats b)
{
final double meanA = a.getMean();
final double meanB = b.getMean();
final int nA = a.getNumObservations();
final int nB = b.getNumObservations();
final double delta = meanA - meanB;
final int sumN = nA + nB;
// Two different methods of computing mean, not sure which is safer / more stable
double newMean = meanA + delta * ((double)nB / sumN);
//double newMean = (nA * meanA + nB * meanB) / (sumN);
final double newSumSquaredDifferences = (sumN == 0) ? 0.0 :
a.getSumSquaredDifferences() + b.getSumSquaredDifferences() +
delta * delta * ((nA * nB) / sumN);
final IncrementalStats mergedStats = new IncrementalStats();
mergedStats.init(sumN, newMean, newSumSquaredDifferences);
return mergedStats;
}
@Override
public String toString()
{
return "[n = " + n + ", mean = " + mean + ", std = " + getStd() + "]";
}
//-------------------------------------------------------------------------
} | 5,240 | 23.721698 | 96 | java |
Ludii | Ludii-master/Common/src/main/math/statistics/KolmogorovSmirnov.java | package main.math.statistics;
import gnu.trove.list.array.TDoubleArrayList;
/**
* Code to compute Kolmogorov-Smirnov statistics for pairs of
* empirical distributions.
*
* @author Dennis Soemers
*/
public class KolmogorovSmirnov
{
//-------------------------------------------------------------------------
/**
* Constructor
*/
private KolmogorovSmirnov()
{
// Don't need constructor
}
//-------------------------------------------------------------------------
/**
* @param distA
* @param distB
* @return Kolmogorov-Smirnov statistic (or "distance") for two given empirical distributions
*/
public static double kolmogorovSmirnovStatistic(final TDoubleArrayList distA, final TDoubleArrayList distB)
{
// Sort both distributions
final TDoubleArrayList sortedA = new TDoubleArrayList(distA);
sortedA.sort();
final TDoubleArrayList sortedB = new TDoubleArrayList(distB);
sortedB.sort();
// Loop through both distribution simultaneously and find point of maximum deviation
final int sampleSizeA = sortedA.size();
final int sampleSizeB = sortedB.size();
int currIdxA = 0;
int currIdxB = 0;
double cumulProbA = 0.0;
double cumulProbB = 0.0;
double maxDeviation = 0.0;
while (currIdxA < sampleSizeA || currIdxB < sampleSizeB)
{
double valA = (currIdxA == sampleSizeA) ? Double.POSITIVE_INFINITY : sortedA.getQuick(currIdxA);
double valB = (currIdxB == sampleSizeB) ? Double.POSITIVE_INFINITY : sortedB.getQuick(currIdxB);
final double currVal = Math.min(valA, valB);
if (Double.isInfinite(currVal))
{
// Should never happen
System.err.println("ERROR: currVal is infinite!");
break;
}
while (valA <= currVal)
{
cumulProbA += 1.0 / sampleSizeA;
++currIdxA;
valA = (currIdxA == sampleSizeA) ? Double.POSITIVE_INFINITY : sortedA.getQuick(currIdxA);
}
while (valB <= currVal)
{
cumulProbB += 1.0 / sampleSizeB;
++currIdxB;
valB = (currIdxB == sampleSizeB) ? Double.POSITIVE_INFINITY : sortedB.getQuick(currIdxB);
}
final double deviation = Math.abs(cumulProbA - cumulProbB);
if (deviation > maxDeviation)
maxDeviation = deviation;
}
// System.out.println();
// System.out.println("Max deviation = " + maxDeviation);
// System.out.println("A = " + sortedA);
// System.out.println("B = " + sortedB);
return maxDeviation;
}
//-------------------------------------------------------------------------
}
| 2,487 | 25.752688 | 108 | java |
Ludii | Ludii-master/Common/src/main/math/statistics/Sampling.java | package main.math.statistics;
import java.util.concurrent.ThreadLocalRandom;
import gnu.trove.list.array.TDoubleArrayList;
/**
* Some utilities for sampling.
*
* @author Dennis Soemers
*/
public class Sampling
{
//-------------------------------------------------------------------------
/**
* Constructor
*/
private Sampling()
{
// Don't need constructor
}
//-------------------------------------------------------------------------
/**
* @param sampleSize Number of samples to take
* @param list List to sample from
* @return New list of samples, sampled from given list with replacement
*/
public static TDoubleArrayList sampleWithReplacement(final int sampleSize, final TDoubleArrayList list)
{
final TDoubleArrayList samples = new TDoubleArrayList(sampleSize);
for (int i = 0; i < sampleSize; ++i)
{
samples.add(list.getQuick(ThreadLocalRandom.current().nextInt(list.size())));
}
return samples;
}
//-------------------------------------------------------------------------
}
| 1,044 | 21.234043 | 104 | java |
Ludii | Ludii-master/Common/src/main/math/statistics/Stats.java | package main.math.statistics;
import java.text.DecimalFormat;
import java.util.Locale;
import gnu.trove.list.array.TDoubleArrayList;
//------------------------------------------------------------------------
/**
* Basic statistics of a list of (double) samples.
* @author Cameron Browne, Dennis Soemers
*/
public class Stats
{
/** Description of what these statistics describe. */
protected String label = "?";
/** Samples. */
protected TDoubleArrayList samples = new TDoubleArrayList();
/** CI constant, from: http://mathworld.wolfram.com/StandardDeviation.html */
//private final double ci = 1.64485; // for 90%
protected final double ci = 1.95996; // for 95%
/** Minimum value. */
protected double min;
/** Maximum value. */
protected double max;
/** Sum. */
protected double sum;
/** Mean. */
protected double mean;
/** Sample variance. */
protected double varn;
/** Sample standard deviation. */
protected double stdDevn;
/** Standard error. */
protected double stdError;
/** Confidence interval. */
protected double confInterval;
/** Decimal format for printing. */
private final static DecimalFormat df3 = new DecimalFormat("#.###");
private final static DecimalFormat df6 = new DecimalFormat("#.######");
//---------------------------------------------
/**
* Default constructor
*/
public Stats()
{
label = "Unnamed";
}
/**
* Constructor
* @param str Label.
*/
public Stats(final String str)
{
label = str;
}
//---------------------------------------------
/**
* @return What these statistics describe.
*/
public String label()
{
return label;
}
/**
* @param lbl Description of these statistics.
*/
public void setLabel(final String lbl)
{
label = lbl;
}
/**
* Add a sample.
* @param val Sample to add.
*/
public void addSample(final double val)
{
samples.add(val);
}
/**
* @param index Sample to get.
* @return Specified sample.
*/
public double get(final int index)
{
return samples.get(index);
}
/**
* @return Number of samples.
*/
public int n()
{
return samples.size();
}
/**
* @return Sum.
*/
public double sum()
{
return sum;
}
/**
* @return Mean.
*/
public double mean()
{
return mean;
}
/**
* @return Sample variance.
*/
public double varn()
{
return varn;
}
/**
* @return Standard deviation.
*/
public double sd()
{
return stdDevn;
}
/**
* @return Standard error.
*/
public double se()
{
return stdError;
}
/**
* @return Confidence interval (95%).
*/
public double ci()
{
return confInterval;
}
/**
* @return Minimum value.
*/
public double min()
{
return min;
}
/**
* @return Maximum value.
*/
public double max()
{
return max;
}
/**
* @return Range of values.
*/
public double range()
{
return max() - min();
}
/**
* @param list Sample list.
*/
public void set(final TDoubleArrayList list)
{
samples = list;
}
//---------------------------------------------
/**
* Clears this set of statistics.
*/
public void clear()
{
samples.clear();
sum = 0.0;
mean = 0.0;
varn = 0.0;
stdDevn = 0.0;
stdError = 0.0;
confInterval = 0.0;
min = 0.0;
max = 0.0;
}
//---------------------------------------------
/**
* Measures stats from samples.
*/
public void measure()
{
sum = 0.0;
mean = 0.0;
varn = 0.0;
stdDevn = 0.0;
stdError = 0.0;
confInterval = 0.0;
min = 0.0;
max = 0.0;
final int n = samples.size();
if (n == 0)
return;
min = Double.POSITIVE_INFINITY;
max = Double.NEGATIVE_INFINITY;
// Calculate mean
for (int i = 0; i < n; ++i)
{
final double val = samples.getQuick(i);
sum += val;
if (val < min)
min = val;
else if (val > max)
max = val;
}
mean = sum / n;
// We require sample size of at least 2 for sample variance, sample STD, CIs, etc.
if (n > 1)
{
// Variance
for (int i = 0; i < n; ++i)
{
final double val = samples.getQuick(i);
final double diff = val - mean;
varn += diff * diff;
}
// N - 1 for sample variance instead of population variance
varn /= (n - 1);
// Standard deviation
stdDevn = Math.sqrt(varn);
// Standard error
stdError = stdDevn / Math.sqrt(n);
// Confidence interval
//conf = 2 * ci * devn / Math.sqrt(samples.size());
confInterval = ci * stdDevn / Math.sqrt(n);
}
}
/**
* Shows stats.
*/
public void show()
{
System.out.printf(toString());
}
/**
* Shows stats.
*/
public void showFull()
{
// String str = String.format(
// Locale.ROOT,
// "%s: N=%d, mean=%.6f (+/-%.6f), sd=%.6f, min=%.6f, max=%.6f.",
// label, samples.size(), mean, conf, devn, min, max);
final String str =
"" + Locale.ROOT + ": " +
"N=" + samples.size() + ", " +
"mean=" + df6.format(mean) + " " +
"(+/-" + df6.format(confInterval) + "), " +
"sd=" + df6.format(stdDevn) + ", " +
"se=" + df6.format(stdError) + ", " +
"min=" + df6.format(min) + ", " +
"max=" + df6.format(max) + ".";
System.out.println(str);
}
@Override
public String toString()
{
// String str = String.format(
// Locale.ROOT,
// "%s: N=%d, mean=%.6f (+/-%.6f).",
// label, samples.size(), mean, conf);
final String str =
"" + Locale.ROOT + ": " +
"N=" + samples.size() + ", " +
"mean=" + df6.format(mean) + " " +
"(+/-" + df6.format(confInterval) + ").";
return str;
}
public String exportPS()
{
return
"[ (" + label + ") " + samples.size() + " " + df3.format(mean)
+
" " + df3.format(min) + " " + df3.format(max)
+
" " + df3.format(stdDevn) + " " + df3.format(stdError) + " " + df3.format(ci)
+
" ]";
}
}
| 5,862 | 16.294985 | 84 | java |
Ludii | Ludii-master/Common/src/main/options/GameOptions.java | package main.options;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import exception.DuplicateOptionUseException;
import exception.UnusedOptionException;
import main.Constants;
import main.StringRoutines;
/**
* Maintains a list of game option categories, with the current user selection for each.
*
* @author cambolbro and mrraow
*/
public class GameOptions
{
/** Maximum number of option categories. */
public static final int MAX_OPTION_CATEGORIES = 10;
/** List of option categories. */
private final List<OptionCategory> categories = new ArrayList<OptionCategory>();
/** Whether options have been loaded for this Game instance. */
private boolean optionsLoaded = false;
//-------------------------------------------------------------------------
public List<OptionCategory> categories()
{
return Collections.unmodifiableList(categories);
}
// public int currentOption(final int category)
// {
// return categories.get(category).selection();
// }
//
// public void setCurrentOptions(final int[] selections)
// {
// for (int n = 0; n < Math.min(selections.length, categories.size()); n++)
// categories.get(n).setSelection(selections[n]);
// optionsLoaded = true;
// }
//
// public void setCurrentOption(final int category, final int selection)
// {
// categories.get(category).setSelection(selection);
// }
public boolean optionsLoaded()
{
return optionsLoaded;
}
public void setOptionsLoaded(final boolean set)
{
optionsLoaded = set;
}
public void setOptionCategories(final List<Option>[] optionsAvList)
{
categories.clear();
for (int n = 0; n < optionsAvList.length; n++)
categories.add(new OptionCategory(optionsAvList[n]));
optionsLoaded = true;
}
// public String currentSelectionsAsString()
// {
// final StringBuilder sb = new StringBuilder();
// sb.append("[");
// for (int n = 0; n < categories.size(); n++)
// {
// if (n > 0)
// sb.append(", ");
// sb.append(categories.get(n).selection());
// }
// sb.append("]");
// return sb.toString();
// }
//
// public List<Integer> currentSelectionsAsList()
// {
// final List<Integer> list = new ArrayList<Integer>();
// for (final OptionCategory category : categories)
// list.add(new Integer(category.selection()));
// return list;
// }
// public List<Integer> currentSelectionsAsList(final int[] optionSelections)
// {
// final List<Integer> list = new ArrayList<Integer>();
// for (int cat = 0; cat < categories.size(); cat++)
// //for (final OptionCategory category : categories)
// list.add(new Integer(optionSelections[cat])); //category.selection()));
// return list;
// }
//-------------------------------------------------------------------------
public void clear()
{
categories.clear();
optionsLoaded = false;
}
//-------------------------------------------------------------------------
/**
* @return The number of option categories we have
*/
public int numCategories()
{
return categories.size();
}
//-------------------------------------------------------------------------
/**
* Add this option to the relevant option category, else create a new option category.
*/
public void add(final Option option)
{
// Search for existing option category with this option's tag
for (final OptionCategory category : categories)
if (option.tag().equals(category.tag()))
{
category.add(option);
return;
}
// Start a new option category
final OptionCategory category = new OptionCategory(option);
categories.add(category);
}
public void add(final OptionCategory category)
{
categories.add(category);
}
//-------------------------------------------------------------------------
/**
* @param selectedOptionStrings Strings for current option string selections.
* We assume default options for any categories without explicit selections.
* @return An int array with for each option category, the index of the
* current option within that category.
*/
public int[] computeOptionSelections(final List<String> selectedOptionStrings)
{
final int[] optionSelections = new int[numCategories()];
final boolean[] usedOptionStrings = new boolean[selectedOptionStrings.size()];
for (int cat = 0; cat < categories.size(); cat++)
{
final OptionCategory category = categories.get(cat);
int maxPriority = Integer.MIN_VALUE;
int activeOptionIdx = Constants.UNDEFINED;
for (int i = 0; i < category.options().size(); i++)
{
final Option option = category.options().get(i);
final String optionStr = StringRoutines.join("/", option.menuHeadings());
final int optionStrIndex = selectedOptionStrings.indexOf(optionStr);
if (optionStrIndex >= 0)
{
// This option was explicitly selected, so we take it and we break
if (usedOptionStrings[optionStrIndex])
throw new DuplicateOptionUseException(optionStr);
usedOptionStrings[optionStrIndex] = true;
activeOptionIdx = i;
break;
}
if (option.priority() > maxPriority)
{
// New max priority option; this is what we'll take if we don't find an explicitly selected option
activeOptionIdx = i;
maxPriority = option.priority();
}
}
optionSelections[cat] = activeOptionIdx;
}
for (int i = 0; i < usedOptionStrings.length; ++i)
{
if (!usedOptionStrings[i])
throw new UnusedOptionException(selectedOptionStrings.get(i));
}
return optionSelections;
}
/**
* @param selectedOptionStrings Strings of explicitly selected options. May
* not contain any Strings for categories left at defaults
* @return A list of strings for ALL active options (including Strings for
* default options if no non-defaults were selected in their categories)
*/
public List<String> allOptionStrings(final List<String> selectedOptionStrings)
{
final List<String> strings = new ArrayList<String>();
final boolean[] usedOptionStrings = new boolean[selectedOptionStrings.size()];
for (int cat = 0; cat < categories.size(); cat++)
{
final OptionCategory category = categories.get(cat);
int maxPriority = Integer.MIN_VALUE;
String activeOptionStr = null;
for (int i = 0; i < category.options().size(); i++)
{
final Option option = category.options().get(i);
final String optionStr = StringRoutines.join("/", option.menuHeadings());
final int optionStrIndex = selectedOptionStrings.indexOf(optionStr);
if (optionStrIndex >= 0)
{
// This option was explicitly selected, so we take it and we break
if (usedOptionStrings[optionStrIndex])
throw new DuplicateOptionUseException(optionStr);
usedOptionStrings[optionStrIndex] = true;
activeOptionStr = optionStr;
break;
}
if (option.priority() > maxPriority)
{
// New max priority option; this is what we'll take if we don't find an explicitly selected option
activeOptionStr = optionStr;
maxPriority = option.priority();
}
}
strings.add(activeOptionStr);
}
for (int i = 0; i < usedOptionStrings.length; ++i)
{
if (!usedOptionStrings[i])
throw new UnusedOptionException(selectedOptionStrings.get(i));
}
return strings;
}
/**
* @param optionString
* @return True if an option described by the given String exists, false otherwise
*/
public boolean optionExists(final String optionString)
{
for (int cat = 0; cat < categories.size(); cat++)
{
final OptionCategory category = categories.get(cat);
for (int i = 0; i < category.options().size(); i++)
{
final Option option = category.options().get(i);
final String optionStr = StringRoutines.join("/", option.menuHeadings());
if (optionString.equals(optionStr))
return true;
}
}
return false;
}
/**
* @param optionSelections
* @return List of strings describing selected options in int-array format
*/
public List<String> toStrings(final int[] optionSelections)
{
final List<String> strings = new ArrayList<String>();
for (int cat = 0; cat < categories.size(); cat++)
{
final OptionCategory category = categories.get(cat);
final int selection = optionSelections[cat];
final Option option = category.options().get(selection);
final List<String> headings = option.menuHeadings();
strings.add(StringRoutines.join("/", headings));
}
return strings;
}
/**
* @param selectedOptionStrings List of Strings describing explicitly-selected options
* @return List of Option objects for all active objects
*/
public List<Option> activeOptionObjects(final List<String> selectedOptionStrings)
{
final List<Option> options = new ArrayList<Option>(numCategories());
final int[] selections = computeOptionSelections(selectedOptionStrings);
for (int i = 0; i < categories.size(); ++i)
{
final OptionCategory category = categories.get(i);
options.add(category.options().get(selections[i]));
}
return options;
}
//-------------------------------------------------------------------------
@Override
public String toString()
{
final StringBuilder sb = new StringBuilder();
for (final OptionCategory category : categories)
sb.append(category.toString() + "\n");
return sb.toString();
}
//-------------------------------------------------------------------------
}
| 9,399 | 27.228228 | 103 | java |
Ludii | Ludii-master/Common/src/main/options/Option.java | package main.options;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import main.StringRoutines;
//-----------------------------------------------------------------------------
/**
* Record of an "(option ...)" instance.
* @author cambolbro
*/
public class Option
{
/** Tag for this option used to identify it in the game description, e.g. "1" or "BoardSize". */
private String tag = "";
/** Description for showing in help etc. */
private String description = "";
/** List of arguments for this option, to be instantiated when option is expanded. */
private final List<OptionArgument> arguments = new ArrayList<OptionArgument>();
/**
* Headings to be shown in the menu, split by level of nesting:
* - headings[0] is main menu item heading (e.g. "Board Size")
* - headings[1] is child menu item heading (e.g. "7x7")
*/
private List<String> headings = new ArrayList<String>();
/** Option's priority within its category. */
private int priority = 0;
//------------------------------------------------------------------------
// public Option(final String str)
// {
// interpret(str);
// }
public Option(final String str, final OptionCategory category)
{
try { interpret(str, category); }
catch (Exception e) { e.printStackTrace(); }
}
public Option()
{
}
//------------------------------------------------------------------------
public String tag()
{
return tag;
}
public String description()
{
return description;
}
public List<String> menuHeadings()
{
return Collections.unmodifiableList(headings);
}
public void setHeadings(final List<String> headings)
{
this.headings = headings;
}
public List<OptionArgument> arguments()
{
return Collections.unmodifiableList(arguments);
}
public int priority()
{
return priority;
}
//------------------------------------------------------------------------
// /**
// * @return Whether any option arguments are named.
// */
// public boolean argumentsAreNamed()
// {
// for (final OptionArgument arg : arguments)
// if (arg.name() != null)
// return true;
// return false;
// }
//------------------------------------------------------------------------
/**
* Interprets options from a given string in the new format, based on its category.
*/
void interpret(final String strIn, final OptionCategory category) throws Exception
{
// New format: ("2x2" <2 2> <4> <2> "Played on a square 2x2 board.")
String str = strIn.trim();
if (!str.contains("(item ") || !str.contains(")"))
throw new Exception("Option not bracketed properly: " + str);
tag = category.tag();
// Extract priority (number of asterisks appended)
priority = 0;
while (str.charAt(str.length()-1) == '*')
{
priority++;
str = str.substring(0, str.length()-1); // strip of rightmost asterisk
}
str = str.substring(1, str.length()-1).trim();
// System.out.println("priority: " + priority);
// System.out.println("Reduced option string: " + str);
// Extract option heading
int c = str.indexOf('"');
if (c < 0)
throw new Exception("Failed to find option heading: " + str);
int cc = c+1;
while (cc < str.length() && str.charAt(cc) != '"')
cc++;
if (cc < 0 || cc >= str.length())
throw new Exception("Failed to find option heading: " + str);
final String heading = str.substring(c+1, cc);
headings.add(new String(category.heading()));
headings.add(heading);
// System.out.println("Options headings are: " + headings);
str = str.substring(cc+1).trim();
// System.out.println("Reduced option string: " + str);
// Extract option description (search backwards from end)
cc = str.length()-1;
while (cc >= 0 && str.charAt(cc) != '"')
cc--;
if (cc < 0)
throw new Exception("Failed to find option description: " + str);
c = cc-1;
while (c >= 0 && str.charAt(c) != '"')
c--;
if (c < 0)
throw new Exception("Failed to find option description: " + str);
description = str.substring(c+1, cc);
// System.out.println("Option description is: " + description);
str = str.substring(0, c).trim();
// System.out.println("Option arguments are: " + str);
// Extract option arguments
final List<String> argTags = category.argTags();
while (true)
{
c = str.indexOf("<");
if (c < 0)
break; // no more options
// System.out.println("c=" + c);
if (c > 0 && str.charAt(c-1) == '(')
{
// Is an embedded alias "(< a b)" or "(<= a b)"
str = str.substring(c+1).trim();
continue;
}
cc = StringRoutines.matchingBracketAt(str, c, false);
if (cc < 0 || cc >= str.length())
throw new Exception("No closing bracket '>' for option argument: " + str);
cc++;
final String arg = (c+1 >= cc-1) ? "" : str.substring(c+1, cc-1);
// System.out.println("-- arg is: " + arg);
// final Option option = new Option(optionString, this);
// options.add(option);
//
// System.out.println("Option is: " + option);
if (arguments.size() >= argTags.size())
{
// System.out.println("arguments.size() is " + arguments.size() + ", argTags.size() is " + argTags.size() + ".");
throw new Exception("Not enough tags for option arguments: " + strIn);
}
final String name = argTags.get(arguments.size());
final OptionArgument optArg = new OptionArgument(name, arg);
arguments.add(optArg);
// System.out.println("-- optArg: " + optArg);
// System.out.println("cc=" + cc);
//str = str.substring(c+1).trim();
str = str.substring(cc).trim();
}
}
//------------------------------------------------------------------------
@Override
public String toString()
{
final StringBuilder sb = new StringBuilder();
sb.append("[" + tag + ", \"");
for (int n = 0; n < headings.size(); n++)
{
if (n > 0)
sb.append("/"); //" > ");
sb.append(headings.get(n));
}
sb.append("\",");
for (final OptionArgument arg : arguments)
{
//sb.append(" " + (arg.name() == null ? "" : (arg.name() + ":")) + "<" + arg.expression() + ">");
sb.append(" ");
if (arg.name() != null)
sb.append(arg.name() + ":");
sb.append("<" + arg.expression() + ">");
}
sb.append(", priority " + priority + "]");
return sb.toString();
}
//------------------------------------------------------------------------
}
| 6,414 | 24.866935 | 116 | java |
Ludii | Ludii-master/Common/src/main/options/OptionArgument.java | package main.options;
//-----------------------------------------------------------------------------
/**
* Record of an option argument, which may be named.
* @author cambolbro
*/
public class OptionArgument
{
/** Optional name in definition. Format is: name:<expression>. */
private final String name;
/** This argument's expression to expand in the game description. */
private final String expression;
//------------------------------------------------------------------------
public OptionArgument(final String name, final String expression)
{
this.name = (name == null) ? null : new String(name);
this.expression = new String(expression);
}
//------------------------------------------------------------------------
public String name()
{
return name;
}
public String expression()
{
return expression;
}
//------------------------------------------------------------------------
@Override
public String toString()
{
final StringBuilder sb = new StringBuilder();
if (name != null)
sb.append(name + ":");
sb.append("<" + expression + ">");
return sb.toString();
}
//------------------------------------------------------------------------
}
| 1,214 | 22.365385 | 79 | java |
Ludii | Ludii-master/Common/src/main/options/OptionCategory.java | package main.options;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import main.StringRoutines;
//-----------------------------------------------------------------------------
/**
* Maintains a named category of game options.
* @author cambolbro
*/
public class OptionCategory
{
/** Tag for this option category used to identify it in the game description, e.g. "1" or "BoardSize". */
private String tag;
/** Heading for this category in the memu. This is not necessary, but provided for completeness. */
private String heading;
/**
* List of argument tags for each option in this category. Theses are already stored in
* the argument of each option, but also kept here in a single list for convenience.
*/
private final List<String> argTags;
/** The list of actual options for this category. */
private List<Option> options;
// **
// ** TODO: Move the selection elsewhere!
// ** These values need to be decoupled from the Game and kept e.g. in user preferences.
// **
/** User selection for this option category. */
// private int selection = 0;
//-------------------------------------------------------------------------
public OptionCategory(final String description)
{
this.argTags = new ArrayList<String>();
this.options = new ArrayList<Option>();
try { extractOptions(description); }
catch (Exception e) { e.printStackTrace(); }
}
public OptionCategory(final Option option)
{
this.tag = new String(option.tag());
this.heading = new String(option.menuHeadings().get(0));
this.argTags = null;
this.options = new ArrayList<Option>();
this.options.add(option);
// System.out.println("Tag=" + tag + ", menuHeading=" + menuHeading);
}
public OptionCategory(final List<Option> options)
{
this.tag = new String(options.get(0).tag());
this.heading = new String(options.get(0).menuHeadings().get(0));
this.argTags = null;
this.options = options;
}
//-------------------------------------------------------------------------
public String tag()
{
return tag;
}
public String heading()
{
return heading;
}
public List<Option> options()
{
return Collections.unmodifiableList(options);
}
public List<String> argTags()
{
if (argTags == null)
return argTags;
return Collections.unmodifiableList(argTags);
}
// public int selection()
// {
// return selection;
// }
//
// public void setSelection(final int value)
// {
// selection = value;
// }
//
// public Option selectedOption()
// {
// return options.get(selection);
// }
//-------------------------------------------------------------------------
public void add(final Option option)
{
if (!tag.equals(option.tag()))
{
System.out.println("** Option label does not match option category label.");
}
options.add(option);
}
//-------------------------------------------------------------------------
void extractOptions(final String strIn) throws Exception
{
// Extract an option set in this format:
//
// (options "Board Size" <Size> args:{ <dim> <start> <end> }
// {
// ("2x2" <2 2> <4> <2> "Played on a square 2x2 board.")
// ("3x3" <3 3> <9> <4> "Played on a square 3x3 board.")
// ("4x4" <4 4> <16> <8> "Played on a square 4x4 board.")*
// ("5x5" <5 5> <25> <12> "Played on a square 5x5 board.")**
// ("6x6" <6 6> <36> <18> "Played on a square 6x6 board.")
// }
// )
//
// (options "End Rule" <End> args:{ <result> }
// {
// ("Standard" <Win> "Win by making a line of four pieces.")*
// ("Misere" <Lose> "Lose by making a line of four pieces.")
// }
String str = new String(strIn);
str = extractHeading(str);
str = extractTag(str);
str = extractArgTags(str);
// System.out.println("Option category so far: " + toString());
// System.out.println("Now processing:\n" + str);
// Extract list of options
int c = str.indexOf('{');
if (c < 0)
throw new Exception("Couldn't find opening bracket '{' for option list " + str.substring(c));
int cc = StringRoutines.matchingBracketAt(str, c);
if (cc < 0 || cc >= str.length())
throw new Exception("Couldn't close option bracket '>' in " + str.substring(c));
String optionList = str.substring(c+1, cc);
// System.out.println("Option list: " + optionList);
while (true)
{
c = optionList.indexOf("(item ");
if (c < 0)
break; // no more options
cc = StringRoutines.matchingBracketAt(optionList, c);
if (cc < 0 || cc >= optionList.length())
throw new Exception("No closing bracket ')' for option: " + optionList.substring(c));
cc++;
while (cc < optionList.length() && optionList.charAt(cc) == '*')
cc++;
final String optionString = optionList.substring(c, cc);
// System.out.println("Option string is: " + optionString);
final Option option = new Option(optionString, this);
options.add(option);
// System.out.println("Option is: " + option);
optionList = optionList.substring(c+1).trim();
}
}
String extractHeading(final String str) throws Exception
{
// Extract category heading
int c = 0;
while (c < str.length() && str.charAt(c) != '"')
c++;
if (c >= str.length())
throw new Exception("Failed to find option category heading: " + str);
int cc = c+1;
while (cc < str.length() && str.charAt(cc) != '"')
cc++;
if (cc < 0 || cc >= str.length())
throw new Exception("Failed to find option category heading: " + str);
heading = str.substring(c+1, cc);
//System.out.println("Category heading is: " + heading);
return str.substring(cc+1);
}
String extractTag(final String str) throws Exception
{
// Extract category tag
int c = str.indexOf('<');
if (c < 0)
throw new Exception("Failed to find option category tag: " + str);
int cc = StringRoutines.matchingBracketAt(str, c);
if (cc < 0 || cc >= str.length())
throw new Exception("Couldn't close option bracket '>' in " + str.substring(c));
cc++;
tag = str.substring(c+1, cc-1);
//System.out.println("Category tag is: " + primaryTag);
return str.substring(cc+1);
}
String extractArgTags(final String strIn) throws Exception
{
// Extract arg names
if (!strIn.contains("args:"))
throw new Exception("Option category must define args:{...}." + strIn);
int c = strIn.indexOf("args:");
if (c < 0)
throw new Exception("No option argument tags of form args:{...}: " + strIn);
c = strIn.indexOf("{");
if (c < 0)
throw new Exception("Couldn't find opening bracket '{' in option category " + strIn.substring(c));
int cc = StringRoutines.matchingBracketAt(strIn, c);
if (cc < 0 || cc >= strIn.length())
throw new Exception("Couldn't find closing bracket '}' in option category " + strIn.substring(c));
String str = strIn.substring(c, cc).trim();
// Extract each arg, denoted <expression>
while (true)
{
// System.out.println("str is: " + str);
int a = str.indexOf("<");
if (a < 0)
break; // no more options
int aa = StringRoutines.matchingBracketAt(str, a);
if (aa < 0 || aa >= str.length())
throw new Exception("No closing bracket '>' for option argument: " + str);
final String arg = str.substring(a+1, aa);
argTags.add(arg);
// System.out.println("-- arg is: " + arg);
str = str.substring(aa+1).trim();
}
// System.out.println(argTags.size() + " argTags: " + argTags);
return strIn.substring(cc+1);
}
//-------------------------------------------------------------------------
@Override
public String toString()
{
final StringBuilder sb = new StringBuilder();
sb.append("<" + tag + "> \"" + heading + "\"");
if (argTags != null)
{
sb.append(" [ ");
for (final String arg : argTags)
sb.append(arg + " ");
sb.append("]");
}
return sb.toString();
}
//-------------------------------------------------------------------------
}
| 8,008 | 26.057432 | 106 | java |
Ludii | Ludii-master/Common/src/main/options/Ruleset.java | package main.options;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import main.StringRoutines;
//-----------------------------------------------------------------------------
/**
* Record of an "(option ...)" instance.
*
* @author cambolbro and Dennis Soemers and Eric.Piette and Matthew.Stephenson
*/
public class Ruleset
{
/** Heading for this ruleset as it appears in the menu, e.g. "Standard Rules (Known)". */
private String heading = null;
/** List of option selections for this rule set. */
private final List<String> optionSettings = new ArrayList<String>();
/** Map between option header and option tags. */
private final Map<String, List<String>> variations = new HashMap<String, List<String>>();
/** Ruleset's priority. */
private int priority = 0;
//------------------------------------------------------------------------
public Ruleset(final String str)
{
try { interpret(str); }
catch (final Exception e) { e.printStackTrace(); }
}
//------------------------------------------------------------------------
public String heading()
{
return heading;
}
/**
* @return List of options that this ruleset selects.
*/
public List<String> optionSettings()
{
return Collections.unmodifiableList(optionSettings);
}
/**
* @return Map of allowed option variations within this ruleset for each option
* header.
*/
public Map<String, List<String>> variations()
{
return variations;
}
/**
* @return The priority.
*/
public int priority()
{
return priority;
}
//------------------------------------------------------------------------
/**
* Interprets ruleset from a given string.
*/
void interpret(final String strIn)
{
// Ruleset format:
//
// (ruleset “Standard Game (Known)” { "Board Size/6x6” "End Rule/Standard" })
//
// (ruleset false “Not in Database” { "Board Size/5x5” "End Rule/Standard" })
// System.out.println("Interpreting ruleset:\n" + strIn);
String str = new String(strIn).trim();
// Extract priority (number of asterisks appended)
priority = 0;
while (str.charAt(str.length()-1) == '*')
{
priority++;
str = str.substring(0, str.length()-1); // strip of rightmost asterisk
}
// System.out.println("ruleset priority: " + priority);
// Strip off opening and closing chars
int c = str.indexOf("(ruleset ");
if (c < 0)
throw new RuntimeException("Ruleset not found: " + str);
int cc = StringRoutines.matchingBracketAt(str, c);
if (cc < 0)
throw new RuntimeException("No closing bracket ')' in ruleset: " + str);
str = extractVariations(str);
// Extract menu heading
c = str.indexOf('"');
if (c < 0)
throw new RuntimeException("Ruleset heading not found: " + str);
cc = c + 1;
while (cc < str.length() && (str.charAt(cc) != '"' || str.charAt(cc - 1) == '\\'))
cc++;
if (cc < 0)
throw new RuntimeException("No closing quote for ruleset heading: " + str);
heading = str.substring(c+1, cc);
// System.out.println("Heading: " + heading);
// Move past heading string
str = str.substring(cc+1).trim();
// System.out.println("Reduced ruleset is: " + str);
// Extract option settings
while (true)
{
c = str.indexOf('"');
if (c < 0)
break; // no more option settings
cc = c + 1;
while (cc < str.length() && str.charAt(cc) != '"')
cc++;
if (cc < 0)
throw new RuntimeException("No closing quote for option setting: " + str);
final String option = str.substring(c+1, cc);
optionSettings.add(option);
// System.out.println("-- option: " + option);
str = str.substring(cc+1).trim(); // move past option string
}
// Add the default tags to the possible variations tags.
for (final String variation : optionSettings)
{
final String header = variation.substring(0, variation.indexOf('/'));
final String tag = variation.substring(variation.indexOf('/') + 1, variation.length());
if (variations.containsKey(header))
variations.get(header).add(0, tag);
}
}
//------------------------------------------------------------------------
/**
* Interprets ruleset from a given string.
*/
private String extractVariations(final String strIn)
{
final List<String> vars = new ArrayList<String>();
vars.clear();
final int varAt = strIn.indexOf("variations:");
if (varAt == -1)
return strIn; // no variations
int openAt = varAt + 11;
while (openAt < strIn.length() && strIn.charAt(openAt) != '{')
openAt++;
if (openAt >= strIn.length())
throw new RuntimeException("No opening bracket for ruleset variations: " + strIn);
final int closeAt = StringRoutines.matchingBracketAt(strIn, openAt);
if (closeAt == -1)
throw new RuntimeException("No closing bracket for ruleset variations: " + strIn);
// Extract menu heading
int c = openAt + 1;
// Extract ruleset variations
while (true)
{
c = strIn.indexOf('"', c);
if (c < 0)
break; // no more option settings
int cc = c + 1;
while (cc < strIn.length() && strIn.charAt(cc) != '"')
cc++;
if (cc < 0)
throw new RuntimeException("No closing quote for option variation: " + strIn.substring(c));
final String varn = strIn.substring(c+1, cc);
vars.add(varn);
c = cc + 1;
}
// Get the map of variations according to each header.
for (final String variation : vars)
{
final String header = variation.substring(0, variation.indexOf('/'));
final String tag = variation.substring(variation.indexOf('/') + 1, variation.length());
if (!variations.containsKey(header))
variations.put(header, new ArrayList<String>());
variations.get(header).add(tag);
}
// Return string with variations section removed
return strIn.substring(0, varAt) + strIn.substring(closeAt + 1);
}
//------------------------------------------------------------------------
/**
* @return List of all option string lists (optionSettings) that this ruleset can have.
*/
public List<List<String>> allOptionSettings()
{
List<List<String>> allOptionSettings = new ArrayList<>();
if (variations.isEmpty())
{
allOptionSettings.add(optionSettings());
}
else
{
allOptionSettings.add(new ArrayList<>());
for (final String OptionHeader : variations.keySet())
{
final List<List<String>> nextOptionSettings = new ArrayList<>();
for (final List<String> optionSetting : allOptionSettings)
{
for (int i = 0; i < variations.get(OptionHeader).size(); i++)
{
final List<String> newOptionSetting = new ArrayList<>(optionSetting);
newOptionSetting.add(OptionHeader + "/" + variations.get(OptionHeader).get(i));
nextOptionSettings.add(newOptionSetting);
}
}
allOptionSettings = new ArrayList<>(nextOptionSettings);
}
}
return allOptionSettings;
}
//------------------------------------------------------------------------
// /**
// * Set option selections based on this ruleset.
// */
// @Deprecated
// public void setOptionSelections(final GameOptions gameOptions, final int[] selections)
// {
// final BitSet used = new BitSet();
//
// final int numCategories = gameOptions.categories().size();
//
// for (final String optionSetting : optionSettings)
// {
//// System.out.println("Handling optionSetting: " + optionSetting);
//
// final String[] subs = optionSetting.split("/");
//
// if (subs.length < 2)
// throw new RuntimeException("Badly formed option heading: " + optionSetting);
//
// for (int cat = 0; cat < numCategories; cat++)
// {
// final OptionCategory category = gameOptions.categories().get(cat);
// if (category.heading().equals(subs[0]))
// {
// // Found the category
//// System.out.println("+ matches category: " + category);
//
// for (int o = 0; o < category.options().size(); o++)
// {
// final Option option = category.options().get(o);
// if (option.menuHeadings().get(1).equals(subs[1]))
// {
// // Found the options
//// System.out.println("+ + and matches option: " + option);
//
// if (used.get(cat))
// throw new RuntimeException("Option category already set in ruleset: " + optionSetting);
//
// selections[cat] = o;
// used.set(cat, true);
// }
// }
// }
// }
// }
//
// if (used.cardinality() != numCategories)
// throw new RuntimeException("Not all options are specified in ruleset: " + toString());
// }
//------------------------------------------------------------------------
@Override
public String toString()
{
final StringBuilder sb = new StringBuilder();
sb.append("[\"" + heading + "\" {");
for (final String option : optionSettings)
sb.append(" \"" + option + "\"");
sb.append(" }]");
return sb.toString();
}
//------------------------------------------------------------------------
}
| 9,026 | 26.775385 | 97 | java |
Ludii | Ludii-master/Common/src/main/options/UserSelections.java | package main.options;
import java.util.ArrayList;
import java.util.List;
import main.Constants;
/**
* Record of the user's option and ruleset selections.
*
* @author cambolbro and Dennis Soemers
*/
public class UserSelections
{
/** Record of user's current option selections. */
private List<String> selectedOptionStrings = new ArrayList<String>();
/** Record of user's current ruleset selection. */
private int ruleset = Constants.UNDEFINED;
//-------------------------------------------------------------------------
public UserSelections(final List<String> selectedOptionStrings)
{
this.selectedOptionStrings = selectedOptionStrings;
}
//-------------------------------------------------------------------------
/**
* @return List of Strings describing option selections
*/
public List<String> selectedOptionStrings()
{
return selectedOptionStrings;
}
/**
* Sets the array of user option selections
* @param optionSelections
*/
public void setSelectOptionStrings(final List<String> optionSelections)
{
this.selectedOptionStrings = optionSelections;
}
public int ruleset()
{
return ruleset;
}
public void setRuleset(final int set)
{
ruleset = set;
}
//-------------------------------------------------------------------------
}
| 1,301 | 20.344262 | 76 | java |
Ludii | Ludii-master/Core/src/game/API.java | package game;
import java.util.List;
import java.util.Random;
import game.rules.play.moves.Moves;
import other.AI;
import other.context.Context;
import other.move.Move;
import other.playout.PlayoutMoveSelector;
import other.trial.Trial;
/**
* Game API.
*
* @author cambolbro
*/
public interface API
{
/** Initialise the game graph and other relevant items. */
public void create();
//-------------------------------------------------------------------------
/**
* Start new instance of the game.
*
* @param context
*/
public void start(final Context context);
//-------------------------------------------------------------------------
/**
* @param context
* @return Legal turns from the current state.
*/
public Moves moves(final Context context);
//-------------------------------------------------------------------------
/**
* Apply the specified instructions (i.e. game turn).
*
* @param context
* @param move
* @return Move object as applied, possibly with additional Actions from consequents
*/
public Move apply(final Context context, final Move move);
//-------------------------------------------------------------------------
/**
* Play out game to conclusion from current state.
*
* @param context
* @param ais List of AI move planners for each player.
* @param thinkingTime The maximum number of seconds that AIs are allowed
* to spend per turn
* @param playoutMoveSelector Playout move selector to select moves non-uniformly
* @param maxNumBiasedActions Maximum number of actions for which to bias
* selection using features (-1 for no limit)
* @param maxNumPlayoutActions Maximum number of actions to be applied,
* after which we will simply return a null result (-1 for no limit)
* @param random RNG for selecting actions
* @return A fully played-out Trial object.
*/
public Trial playout
(
final Context context,
final List<AI> ais,
final double thinkingTime,
final PlayoutMoveSelector playoutMoveSelector,
final int maxNumBiasedActions,
final int maxNumPlayoutActions,
final Random random
);
}
| 2,122 | 25.873418 | 85 | java |
Ludii | Ludii-master/Core/src/game/Game.java | package game;
import java.io.Serializable;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.ThreadLocalRandom;
import org.apache.commons.rng.RandomProviderState;
import annotations.Hide;
import annotations.Opt;
import game.equipment.Equipment;
import game.equipment.Item;
import game.equipment.component.Component;
import game.equipment.container.Container;
import game.equipment.container.board.Board;
import game.equipment.container.board.Track;
import game.equipment.container.other.Deck;
import game.equipment.container.other.Dice;
import game.equipment.other.Regions;
import game.functions.booleans.BooleanFunction;
import game.functions.booleans.deductionPuzzle.ForAll;
import game.functions.booleans.is.Is;
import game.functions.booleans.is.IsLineType;
import game.functions.dim.DimConstant;
import game.functions.graph.generators.basis.square.RectangleOnSquare;
import game.functions.ints.IntConstant;
import game.functions.ints.IntFunction;
import game.functions.ints.state.Mover;
import game.functions.region.RegionFunction;
import game.functions.region.sites.index.SitesEmpty;
import game.match.Subgame;
import game.mode.Mode;
import game.players.Player;
import game.players.Players;
import game.rules.Rules;
import game.rules.end.End;
import game.rules.end.Result;
import game.rules.meta.Automove;
import game.rules.meta.Gravity;
import game.rules.meta.MetaRule;
import game.rules.meta.Pin;
import game.rules.meta.Swap;
import game.rules.phase.NextPhase;
import game.rules.phase.Phase;
import game.rules.play.Play;
import game.rules.play.moves.BaseMoves;
import game.rules.play.moves.Moves;
import game.rules.play.moves.decision.MoveSiteType;
import game.rules.play.moves.nonDecision.effect.Add;
import game.rules.play.moves.nonDecision.effect.Pass;
import game.rules.play.moves.nonDecision.effect.Satisfy;
import game.rules.play.moves.nonDecision.effect.Then;
import game.rules.play.moves.nonDecision.effect.requirement.Do;
import game.rules.start.StartRule;
import game.rules.start.place.item.PlaceItem;
import game.rules.start.place.stack.PlaceCustomStack;
import game.types.board.RegionTypeStatic;
import game.types.board.RelationType;
import game.types.board.SiteType;
import game.types.play.ModeType;
import game.types.play.ResultType;
import game.types.play.RoleType;
import game.types.state.GameType;
import game.util.directions.AbsoluteDirection;
import game.util.directions.DirectionFacing;
import game.util.equipment.Region;
import game.util.moves.To;
import gnu.trove.list.array.TIntArrayList;
import graphics.ImageUtil;
import main.Constants;
import main.ReflectionUtils;
import main.Status;
import main.Status.EndType;
import main.collections.FastArrayList;
import main.grammar.Description;
import main.options.Ruleset;
import metadata.Metadata;
import metadata.recon.ReconItem;
import other.AI;
import other.BaseLudeme;
import other.Ludeme;
import other.MetaRules;
import other.action.Action;
import other.action.others.ActionPass;
import other.concept.Concept;
import other.concept.ConceptDataType;
import other.context.Context;
import other.context.TempContext;
import other.model.Model;
import other.move.Move;
import other.playout.PlayoutAddToEmpty;
import other.playout.PlayoutFilter;
import other.playout.PlayoutMoveSelector;
import other.playout.PlayoutNoRepetition;
import other.state.State;
import other.state.container.ContainerState;
import other.topology.SiteFinder;
import other.topology.Topology;
import other.topology.TopologyElement;
import other.translation.LanguageUtils;
import other.trial.Trial;
/**
* Defines the main ludeme that describes the players, mode, equipment and rules of a game.
*
* @author Eric.Piette and cambolbro
*/
public class Game extends BaseLudeme implements API, Serializable
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/** Game name. */
protected final String name;
/** Selected options. */
private List<String> options = new ArrayList<>();
/** Game control. */
protected final Mode mode;
/** The players of the game. */
protected final Players players;
/** Game's equipment. */
protected Equipment equipment;
/** Game's rules. */
private Rules rules;
/** Store which meta rule is activated or not. */
private final MetaRules metaRules = new MetaRules();
/** Table of Strings that can be used for voting mechanisms. Populated by preprocess() calls */
private final List<String> voteStringsTable = new ArrayList<String>();
/** Current game description. */
private Description description = new Description("Unprocessed");
/** Maximum number of turns for this game */
protected int maxTurnLimit = Constants.DEFAULT_TURN_LIMIT;
/** Maximum number of moves for this game */
protected int maxMovesLimit = Constants.DEFAULT_MOVES_LIMIT;
//-----------------------------State/Context-------------------------------
/** The number of starting actions done during the initialisation of the game. */
private int numStartingAction = 0;
/** Flags corresponding to the gameType of this game. */
private long gameFlags;
/** Flags corresponding to the boolean concepts of this game. */
protected BitSet booleanConcepts;
/** Map corresponding to the non boolean concepts of this game. */
protected Map<Integer, String> conceptsNonBoolean;
/** Reference state type, for creating new versions of appropriate type. */
protected State stateReference;
/** Set to true once we've finished preprocessing */
protected boolean finishedPreprocessing = false;
/** Copy of the starting context for games with no stochastic element in the starting rules. */
private Context startContext;
/** True if some stochastic elements are in the starting rules. */
private boolean stochasticStartingRules = false;
//-----------------------------Shortcuts-----------------------------------
/** Access container by label. */
private final Map<String, Container> mapContainer = new HashMap<>();
/** Access component by label. */
private final Map<String, Component> mapComponent = new HashMap<>();
/** The list of the different sets of dice. */
private final List<Dice> handDice = new ArrayList<>();
/** The list of the different decks. */
private final List<Deck> handDeck = new ArrayList<>();
/** All variables constraint by the puzzle.*/
private final TIntArrayList constraintVariables = new TIntArrayList();
//-----------------------Metadata-------------------------------------------
/** The game's metadata */
protected Metadata metadata = null;
/** The expected concepts values for reconstruction. */
protected ArrayList<metadata.recon.concept.Concept> expectedConcepts = new ArrayList<metadata.recon.concept.Concept>();
// -----------------------Warning/Crash reports-----------------------------
/** The report with all the warning due of some missing required ludemes. */
private final List<String> requirementReport = new ArrayList<String>();
/** True if any required ludeme is missing. */
protected boolean hasMissingRequirement;
/** The report with all the crashes due of some ludemes used badly. */
private final List<String> crashReport = new ArrayList<String>();
/** True if any ludeme can crash the game. */
protected boolean willCrash;
//---------------------------------AI--------------------------------------
/**
* Simply counts how often we've called start() on this game object.
* Used to avoid unnecessary re-initialisations of AIs.
*/
private int gameStartCount = 0;
//-------------------------------------------------------------------------
/**
* @param name The name of the game.
* @param players The players of the game.
* @param mode The mode of the game [Alternating].
* @param equipment The equipment of the game.
* @param rules The rules of the game.
* @example (game "Tic-Tac-Toe" (players 2) (equipment { (board (square 3))
* (piece "Disc" P1) (piece "Cross" P2) }) (rules (play (move Add (to
* (sites Empty)))) (end (if (is Line 3) (result Mover Win))) ) )
*
*/
public Game
(
final String name,
final Players players,
@Opt final Mode mode,
final Equipment equipment,
final Rules rules
)
{
this.name = new String(name);
this.players = (players == null) ? new Players(Integer.valueOf(Constants.DEFAULT_NUM_PLAYERS)) : players;
if (this.players.count() == 0)
this.mode = new Mode(ModeType.Simulation);
else if (this.players.count() == 1)
this.mode = new Mode(ModeType.Alternating);
else if (mode != null)
this.mode = mode;
else
this.mode = new Mode(ModeType.Alternating);
this.equipment = equipment;
this.rules = rules;
}
/**
* Bare skeleton loader for distance metric tests.
*
* @param name The name of the game.
* @param gameDescription The game description.
*/
@Hide
public Game(final String name, final Description gameDescription)
{
this.name = new String(name);
description = gameDescription;
mode = null;
players = null;
equipment = null;
rules = null;
}
//-------------------------------------------------------------------------
@Override
public String toEnglish(final Game game)
{
if (game.hasSubgames())
return "Sorry! Matches are not yet supported.";
String playersString = players.toEnglish(game);
playersString = LanguageUtils.NumberAsText(players.count(), "player", "players") + (playersString.isEmpty() ? "" : ": (" + playersString + ")");
final String equipmentString = equipment.toEnglish(game);
final String rulesString = rules.toEnglish(game);
String turnFormatString = "Players take turns moving.";
if (game.isSimultaneousMoveGame())
turnFormatString = "Players moves at the same time.";
return String.format("The game \"%s\" is played by %s %s\n%s\n%s\n\n",
name,
playersString,
equipmentString,
turnFormatString,
rulesString);
}
//----------------------------Getter and Shortcuts-----------------------------------
/**
* @return Game name.
*/
public String name()
{
return name;
}
/**
* @return The game's metadata
*/
public Metadata metadata()
{
return metadata;
}
/**
* @return The game's expected concepts used for reconstruction.
*/
public ArrayList<metadata.recon.concept.Concept> expectedConcepts()
{
return expectedConcepts;
}
/**
* Sets the game's metadata and update the concepts.
* @param md The metadata.
*/
public void setMetadata(final Object md)
{
metadata = (Metadata)md;
// We add the concepts of the metadata to the game.
if (metadata != null)
{
final BitSet metadataConcept = metadata.concepts(this);
booleanConcepts.or(metadata.concepts(this));
final boolean stackTypeUsed = booleanConcepts.get(Concept.StackType.id());
if
(
stackTypeUsed
&&
!metadataConcept.get(Concept.Stack.id())
&&
booleanConcepts.get(Concept.StackState.id())
)
booleanConcepts.set(Concept.Stack.id(), false);
if
(
booleanConcepts.get(Concept.MancalaBoard.id())
&&
booleanConcepts.get(Concept.Track.id())
)
{
final Container board = equipment.containers()[0];
final Topology topology = board.topology();
for (final Track track : board.tracks())
{
final int firstSite = track.elems()[0].site;
final int nextSite = track.elems()[0].next;
final List<DirectionFacing> directionsSupported = topology.supportedDirections(RelationType.All, SiteType.Vertex);
for (final DirectionFacing facingDirection : directionsSupported)
{
final AbsoluteDirection absDirection = facingDirection.toAbsolute();
final List<game.util.graph.Step> steps = topology.trajectories().steps(SiteType.Vertex, firstSite, SiteType.Vertex, absDirection);
for (final game.util.graph.Step step : steps)
{
final int to = step.to().id();
if (nextSite == to)
{
if
(
absDirection.equals(AbsoluteDirection.N)
||
absDirection.equals(AbsoluteDirection.E)
||
absDirection.equals(AbsoluteDirection.CCW)
)
booleanConcepts.set(Concept.SowCCW.id(), true);
else if
(
absDirection.equals(AbsoluteDirection.S)
||
absDirection.equals(AbsoluteDirection.W)
||
absDirection.equals(AbsoluteDirection.CW)
)
booleanConcepts.set(Concept.SowCW.id(), true);
}
}
}
}
}
final long gameFlagsWithMetadata = computeGameFlags(); // NOTE: need compute here!
for (final SiteType type : SiteType.values())
{
// We compute the step distance only if needed by the game.
if
(
(gameFlagsWithMetadata & GameType.StepAdjacentDistance) != 0L
&&
board().topology().distancesToOtherSite(type) == null
)
board().topology().preGenerateDistanceToEachElementToEachOther(type, RelationType.Adjacent);
else if
(
(gameFlagsWithMetadata & GameType.StepAllDistance) != 0L
&&
board().topology().distancesToOtherSite(type) == null
)
board().topology().preGenerateDistanceToEachElementToEachOther(type, RelationType.All);
else if
(
(gameFlagsWithMetadata & GameType.StepOffDistance) != 0L
&&
board().topology().distancesToOtherSite(type) == null
)
board().topology().preGenerateDistanceToEachElementToEachOther(type, RelationType.OffDiagonal);
else if
(
(gameFlagsWithMetadata & GameType.StepDiagonalDistance) != 0L
&&
board().topology().distancesToOtherSite(type) == null
)
board().topology().preGenerateDistanceToEachElementToEachOther(type, RelationType.Diagonal);
else if
(
(gameFlagsWithMetadata & GameType.StepOrthogonalDistance) != 0L
&&
board().topology().distancesToOtherSite(type) == null
)
board().topology().preGenerateDistanceToEachElementToEachOther(type, RelationType.Orthogonal);
}
if (metadata.graphics() != null)
metadata.graphics().computeNeedRedraw(this);
if(metadata.recon() != null)
{
final List<ReconItem> reconItems = metadata.recon().getItem();
for(ReconItem item : reconItems)
expectedConcepts.add((metadata.recon.concept.Concept) item);
}
}
else
{
metadata = new Metadata(null, null, null, null);
}
}
/**
* @return Game control.
*/
public Mode mode()
{
return mode;
}
/**
* @return Players record.
*/
public Players players()
{
return players;
}
/**
* @return Game's equipment.
*/
public Equipment equipment()
{
return equipment;
}
/**
* @return Game's rules.
*/
public Rules rules()
{
return rules;
}
/**
* @return The meta rules of the game which are activated.
*/
public MetaRules metaRules()
{
return metaRules;
}
/**
* @return The different instances of a match.
*/
@SuppressWarnings("static-method")
public Subgame[] instances()
{
return null;
}
/**
* @return Master Container map.
*/
public Map<String, Container> mapContainer()
{
return Collections.unmodifiableMap(mapContainer);
}
/**
* @return Number of distinct containers.
*/
public int numContainers()
{
return equipment().containers().length;
}
/**
* @return Number of distinct components.
*/
public int numComponents()
{
return equipment().components().length - 1;
}
/**
* @param nameC
* @return A component object from its name.
*/
public Component getComponent(final String nameC)
{
return mapComponent.get(nameC);
}
/**
* @return Reference to main board object.
*/
public Board board()
{
// Assume board is always at position 0
return (Board) equipment().containers()[0];
}
/**
* @return constraintVariables
*/
public TIntArrayList constraintVariables()
{
return constraintVariables;
}
/**
* @return The dice hands the game.
*/
public List<Dice> handDice()
{
return Collections.unmodifiableList(handDice);
}
/**
* @return The hand decks of the game.
*/
public List<Deck> handDeck()
{
return Collections.unmodifiableList(handDeck);
}
/**
* @param index
* @return To get a specific hand dice.
*/
public Dice getHandDice(final int index)
{
return handDice.get(index);
}
/**
* @return The description of the game.
*/
public Description description()
{
return description;
}
/**
* Set the description of the game.
*
* @param gd The description.
*/
public void setDescription(final Description gd)
{
description = gd;
}
/**
* @param trackName Name of a track.
* @return Unique index of the track with given name (-1 if no such track
* exists)
*/
public int trackNameToIndex(final String trackName)
{
final List<Track> tracks = board().tracks();
for (int i = 0; i < tracks.size(); ++i)
if (tracks.get(i).name().equals(trackName))
return i;
return Constants.UNDEFINED;
}
/**
* @param voteInt The index of the vote.
* @return String representation of vote for given int
*/
public String voteString(final int voteInt)
{
// NOTE: if we receive a -1 index here, that means that preprocess()
// was not properly called on some vote-related ludeme!
return voteStringsTable.get(voteInt);
}
/**
* Registers a given String as something that players can vote on.
*
* @param voteString The vote.
* @return int representation of the corresponding vote
*/
public int registerVoteString(final String voteString)
{
for (int i = 0; i < voteStringsTable.size(); ++i)
if (voteString.equals(voteStringsTable.get(i)))
return i; // Already registered
voteStringsTable.add(voteString);
return voteStringsTable.size() - 1;
}
/**
* @return Number of different vote strings we have in this game
*/
public int numVoteStrings()
{
return voteStringsTable.size();
}
//---------------------Properties of the game------------------------------
/**
* @return True is the game uses instance.
*/
@SuppressWarnings("static-method")
public boolean hasSubgames()
{
return false;
}
/**
* @return True if we're an alternating-move game.
*/
public boolean isAlternatingMoveGame()
{
return mode.mode().equals(ModeType.Alternating);
}
/**
* @return True if we're a simultaneous-move game.
*/
public boolean isSimultaneousMoveGame()
{
return mode.mode().equals(ModeType.Simultaneous);
}
/**
* @return True if we're a simulation-move game.
*/
public boolean isSimulationMoveGame()
{
return mode.mode().equals(ModeType.Simulation);
}
/**
* @return True if we're a stochastic (i.e. not deterministic) game.
*/
public boolean isStochasticGame()
{
return ((gameFlags & GameType.Stochastic) != 0L);
}
/**
* @return True if the game uses some piece values.
*/
public boolean requiresPieceValue()
{
return ((gameFlags & GameType.Value) != 0L) || ((gameFlags & GameType.Dominoes) != 0L);
}
/**
* @return True if the game involves some moves applied to vertices or edges.
*/
public boolean isGraphGame()
{
return ((gameFlags & GameType.Graph) != 0L);
}
/**
* @return True if the game involves some vertices moves.
*/
public boolean isVertexGame()
{
return ((gameFlags & GameType.Vertex) != 0L);
}
/**
* @return True if the game involves some edges moves.
*/
public boolean isEdgeGame()
{
return ((gameFlags & GameType.Edge) != 0L);
}
/**
* @return True if the game involves some faces moves.
*/
public boolean isCellGame()
{
return ((gameFlags & GameType.Cell) != 0L);
}
/**
* @return True if this is a puzzle.
*/
public boolean isDeductionPuzzle()
{
return ((gameFlags() & GameType.DeductionPuzzle) != 0L);
}
/**
* @return True if this is game using a vote system.
*/
public boolean usesVote()
{
return ((gameFlags() & GameType.Vote) != 0L);
}
/**
* @return True if this is game using a note system.
*/
public boolean usesNote()
{
return ((gameFlags() & GameType.Note) != 0L);
}
/**
* @return True if this game used a ludeme in relation with visited.
*/
public boolean requiresVisited()
{
return ((gameFlags() & GameType.Visited) != 0L);
}
/**
* @return True if this game uses a score.
*/
public boolean requiresScore()
{
return ((gameFlags() & GameType.Score) != 0L);
}
/**
* @return True if this game uses a payoff.
*/
public boolean requiresPayoff()
{
return ((gameFlags() & GameType.Payoff) != 0L);
}
/**
* @return True if this game used an amount.
*/
public boolean requiresBet()
{
return ((gameFlags() & GameType.Bet) != 0L);
}
/**
* @return True if this game uses a local state.
*/
public boolean requiresLocalState()
{
return ((gameFlags() & GameType.SiteState) != 0L) || hasLargePiece();
}
/**
* @return True if this game uses a rotation state.
*/
public boolean requiresRotation()
{
return ((gameFlags() & GameType.Rotation) != 0L);
}
/**
* @return True if this game uses some teams.
*/
public boolean requiresTeams()
{
return ((gameFlags() & GameType.Team) != 0L);
}
/**
* @return True if this game needs a track cache.
*/
public boolean needTrackCache()
{
return ((gameFlags() & GameType.Track) != 0L);
}
/**
* @return True if this game uses a comparison of positional states
*/
public boolean usesNoRepeatPositionalInGame()
{
return ((gameFlags() & GameType.RepeatPositionalInGame) != 0L);
}
/**
* @return True if this game uses a comparison of positionalstates within a turn
*/
public boolean usesNoRepeatPositionalInTurn()
{
return ((gameFlags() & GameType.RepeatPositionalInTurn) != 0L);
}
/**
* @return True if this game uses a comparison of situational states
*/
public boolean usesNoRepeatSituationalInGame()
{
return ((gameFlags() & GameType.RepeatSituationalInGame) != 0L);
}
/**
* @return True if this game uses a comparison of situational states within a
* turn
*/
public boolean usesNoRepeatSituationalInTurn()
{
return ((gameFlags() & GameType.RepeatSituationalInTurn) != 0L);
}
/**
* @return True if the game involved a sequence of capture.
*/
public boolean hasSequenceCapture()
{
return ((gameFlags & GameType.SequenceCapture) != 0L);
}
/**
* @return True if the game involved a cycle detection.
*/
public boolean hasCycleDetection()
{
return ((gameFlags & GameType.CycleDetection) != 0L);
}
/**
* @return True if the game involved a sequence of capture.
*/
public boolean hasLargeStack()
{
return board().largeStack();
}
/**
* @return True if this game uses a local state.
*/
public boolean requiresCount()
{
if(isStacking())
return false;
for (final Container c : equipment.containers())
if (c.isHand())
return true;
return ((gameFlags() & GameType.Count) != 0L);
}
/**
* @return True if some information is hidden.
*/
public boolean hiddenInformation()
{
return ((gameFlags() & GameType.HiddenInfo) != 0L);
}
/**
* @return Whether we don't need to check all pass.
*/
public boolean requiresAllPass()
{
return ((gameFlags() & GameType.NotAllPass) == 0L) && mode.mode() != ModeType.Simulation;
}
/**
* @return True if any component is a card.
*/
public boolean hasCard()
{
return ((gameFlags & GameType.Card) != 0L);
}
/**
* @return True if any track has an internal loop in a track.
*/
public boolean hasInternalLoopInTrack()
{
return ((gameFlags & GameType.InternalLoopInTrack) != 0L);
}
/**
* @return True if any component is a large piece.
*/
public boolean hasLargePiece()
{
return ((gameFlags & GameType.LargePiece) != 0L);
}
/**
* @return true if the game is a stacking game
*/
public boolean isStacking()
{
return (gameFlags() & GameType.Stacking) != 0L || hasCard() || board().largeStack();
}
/**
* @return true if the game uses a line of Play
*/
public boolean usesLineOfPlay()
{
return (gameFlags() & GameType.LineOfPlay) != 0L;
}
/**
* @return true if the game uses (moveAgain) ludeme.
*/
public boolean usesMoveAgain()
{
return (gameFlags() & GameType.MoveAgain) != 0L;
}
/**
* @return true if the game uses some pending values/states.
*/
public boolean usesPendingValues()
{
return (gameFlags() & GameType.PendingValues) != 0L;
}
/**
* @return true if the game uses some values mapped.
*/
public boolean usesValueMap()
{
return (gameFlags() & GameType.MapValue) != 0L;
}
/**
* @return true if the game uses some remembering values.
*/
public boolean usesRememberingValues()
{
return (gameFlags() & GameType.RememberingValues) != 0L;
}
/**
* @return True if the game is boardless.
*/
public boolean isBoardless()
{
return board().isBoardless();
}
/**
* @return True if the game involved some dice hands.
*/
public boolean hasHandDice()
{
return !handDice.isEmpty();
}
/**
* @return True if the game involved some tracks.
*/
public boolean hasTrack()
{
return !board().tracks().isEmpty();
}
/**
* @return True if the game has dominoes
*/
public boolean hasDominoes()
{
for (int i = 1; i < equipment.components().length; i++)
if (equipment.components()[i].name().contains("Domino"))
return true;
return false;
}
/**
* @return True if the game uses somes decks.
*/
public boolean hasHandDeck()
{
return !handDeck.isEmpty();
}
/**
* @return True if the game requires a hand.
*/
public boolean requiresHand()
{
for (final Container c : equipment.containers())
if (c.isHand())
return true;
return false;
}
/**
* @return True if this game uses at least one custom playout strategy in any of
* its phases.
*/
public boolean hasCustomPlayouts()
{
if (mode().playout() != null)
return true;
for (final Phase phase : rules().phases())
if (phase.playout() != null)
return true;
return false;
}
//-------------------------State and Context-------------------------------
/**
* @return Reference copy of initial state.
*/
public State stateReference()
{
return stateReference;
}
/**
* @return Whether game state requires item indices to be stored. e.g. for ko or
* superko testing.
*/
public boolean requiresItemIndices()
{
if ((players.count() + 1) < equipment().components().length)
return true;
for (int numPlayer = 0; numPlayer < players.count() + 1; numPlayer++)
{
int nbComponent = 0;
for (int i = 1; i < equipment().components().length; i++)
{
final Component c = equipment().components()[i];
if (c.owner() == numPlayer)
nbComponent++;
if (nbComponent > 1)
return true;
}
}
return false;
}
/**
* @return The maximum count we need for sites with count.
*/
public int maxCount()
{
if(isStacking())
return 1;
if (hasDominoes())
return equipment.components().length;
int counter = 0;
if (rules != null && rules.start() != null)
for (final StartRule s : rules.start().rules())
counter += s.count(this) * s.howManyPlace(this);
int maxCountFromComponent = 0;
for (int i = 1; i < equipment.components().length; i++)
{
final Component component = equipment.components()[i];
if (component.maxCount() > maxCountFromComponent)
maxCountFromComponent = component.maxCount();
}
return Math.max(maxCountFromComponent, Math.max(counter, equipment.totalDefaultSites()));
}
/**
* @return The maximum local states possible for all the items.
*/
public int maximalLocalStates()
{
int maxLocalState = 2;
boolean localStateToCompute = true;
if (rules != null && rules.start() != null)
{
for (final StartRule s : rules.start().rules())
{
final int state = s.state(this);
if (maxLocalState < state)
{
maxLocalState = state;
localStateToCompute = false;
}
}
}
for (int i = 1; i < equipment.components().length; i++)
{
final Component c = equipment.components()[i];
if (c.isDie())
{
if (c.getNumFaces() > maxLocalState)
{
maxLocalState = c.getNumFaces();
localStateToCompute = false;
}
}
else if (c.isLargePiece())
{
final int numSteps = c.walk().length * 4;
if (numSteps > maxLocalState)
{
maxLocalState = numSteps;
localStateToCompute = false;
}
}
}
int maxLocalStateFromComponent = 0;
for (int i = 1; i < equipment.components().length; i++)
{
final Component component = equipment.components()[i];
if (component.maxState() > maxLocalStateFromComponent)
maxLocalStateFromComponent = component.maxState();
}
if (localStateToCompute)
return Math.max(maxLocalStateFromComponent, players().size());
return Math.max(maxLocalStateFromComponent, maxLocalState);
}
/**
* @return The maximum possible values for all the items.
*/
public int maximalValue()
{
int maxValueFromComponent = 0;
for (int i = 1; i < equipment.components().length; i++)
{
final Component component = equipment.components()[i];
if (component.maxValue() > maxValueFromComponent)
maxValueFromComponent = component.maxValue();
}
return Math.max(Constants.MAX_VALUE_PIECE, maxValueFromComponent);
}
/**
* @return The rotation states possible for all the items.
*/
public int maximalRotationStates()
{
return Math.max(
equipment().containers()[0].topology().supportedDirections(SiteType.Cell).size(),
equipment().containers()[0].topology().supportedDirections(SiteType.Vertex).size()
);
}
/**
* @return True if the game uses automove.
*/
public boolean automove()
{
return metaRules.automove();
}
/**
* @return List of all the elements that we play on in this game's
* graph (currently returns vertices if we play on vertices, or cells
* otherwise).
*/
public List<? extends TopologyElement> graphPlayElements()
{
switch (board().defaultSite())
{
case Cell:
return board().topology().cells();
case Edge:
return board().topology().edges();
case Vertex:
return board().topology().vertices();
}
return null;
}
/**
* @return Precomputed table of distances to centre; automatically picks
* either the table for vertices, or the table for cells, based on whether
* or not the game is played on intersections
*/
public int[] distancesToCentre()
{
if (board().defaultSite() == SiteType.Vertex)
return board().topology().distancesToCentre(SiteType.Vertex);
else
return board().topology().distancesToCentre(SiteType.Cell);
}
/**
* @return Precomputed table of distances to corners; automatically picks
* either the table for vertices, or the table for cells, based on whether
* or not the game is played on intersections
*/
public int[] distancesToCorners()
{
if (board().defaultSite() == SiteType.Vertex)
return board().topology().distancesToCorners(SiteType.Vertex);
else
return board().topology().distancesToCorners(SiteType.Cell);
}
/**
* @return Precomputed tables of distances to regions; automatically picks
* either the table for vertices, or the table for cells, based on whether
* or not the game is played on intersections
*/
public int[][] distancesToRegions()
{
if (board().defaultSite() == SiteType.Vertex)
return board().topology().distancesToRegions(SiteType.Vertex);
else
return board().topology().distancesToRegions(SiteType.Cell);
}
/**
* @return Precomputed table of distances to sides; automatically picks
* either the table for vertices, or the table for cells, based on whether
* or not the game is played on intersections
*/
public int[] distancesToSides()
{
if (board().defaultSite() == SiteType.Vertex)
return board().topology().distancesToSides(SiteType.Vertex);
else
return board().topology().distancesToSides(SiteType.Cell);
}
//-----------------------------------AI------------------------------------
/**
* @return How often have we called start() on this Game object?
*/
public int gameStartCount()
{
return gameStartCount;
}
/**
* To increment the game start counter.
*/
public void incrementGameStartCount()
{
gameStartCount += 1;
}
//----------------------------------Flags----------------------------------
/**
* To remove a flag. Only used in case of special computation (e.g. sequence of
* capture).
*
* @param flag
*/
public void removeFlag(final long flag)
{
gameFlags -= flag;
}
/**
* To add a flag. Only used in case of special computation (e.g. sequence of
* capture).
*
* @param flag
*/
public void addFlag(final long flag)
{
gameFlags |= flag;
}
/**
* @return Game flags (computed based on rules).
*/
public long computeGameFlags()
{
long flags = 0L;
try
{
flags |= SiteType.gameFlags(board().defaultSite());
// If any hand, dice or deck, we also need the cells.
if (equipment().containers().length > 1)
flags |= GameType.Cell;
// Accumulate flags for all the containers.
for (int i = 0; i < equipment().containers().length; i++)
flags |= equipment().containers()[i].gameFlags(this);
// Accumulate flags for all the components.
for (int i = 1; i < equipment().components().length; i++)
flags |= equipment().components()[i].gameFlags(this);
// Accumulate flags for all the regions.
for (int i = 0; i < equipment().regions().length; i++)
flags |= equipment().regions()[i].gameFlags(this);
// Accumulate flags for all the maps.
for (int i = 0; i < equipment().maps().length; i++)
flags |= equipment().maps()[i].gameFlags(this);
// Accumulate flags over all rules
if (rules.meta() != null)
for (final MetaRule meta : rules.meta().rules())
flags |= meta.gameFlags(this);
// Accumulate flags over all rules
if (rules.start() != null)
for (final StartRule start : rules.start().rules())
{
final long startGameFlags = start.gameFlags(this);
flags |= startGameFlags;
if((startGameFlags & GameType.Stochastic) != 0L )
stochasticStartingRules = true;
}
if (rules.end() != null)
flags |= rules.end().gameFlags(this);
for (final Phase phase : rules.phases())
flags |= phase.gameFlags(this);
for (int e = 1; e < equipment.components().length; ++e)
{
if (((gameFlags & GameType.Stochastic) == 0L) && equipment.components()[e].isDie())
flags |= GameType.Stochastic;
if (((gameFlags & GameType.LargePiece) == 0L) && equipment.components()[e].isLargePiece())
flags |= GameType.LargePiece;
}
// set model flags
if (mode.mode() == ModeType.Simultaneous)
flags |= GameType.Simultaneous;
if (hasHandDice())
flags |= GameType.NotAllPass;
if (hasTrack())
{
flags |= GameType.Track;
for (final Track track : board().tracks())
{
if (track.hasInternalLoop())
{
flags |= GameType.InternalLoopInTrack;
break;
}
}
}
}
catch (final Exception e)
{
e.printStackTrace();
}
if (metadata() != null)
flags |= metadata().gameFlags(this);
return flags;
}
/**
* Methods computing the warning report in looking if all the ludemes have the
* right requirement. Example: using the ludeme (roll) needs dice to be defined.
*
* @return True if any required ludeme is missing.
*/
public boolean computeRequirementReport()
{
boolean missingRequirement = false;
// Accumulate missing requirements for all the players.
missingRequirement |= players.missingRequirement(this);
// Accumulate missing requirements for all the components.
for (int i = 0; i < equipment().containers().length; i++)
missingRequirement |= equipment().containers()[i].missingRequirement(this);
// Accumulate missing requirements for all the components.
for (int i = 1; i < equipment().components().length; i++)
missingRequirement |= equipment().components()[i].missingRequirement(this);
// Accumulate crashes for all the regions.
for (int i = 0; i < equipment().regions().length; i++)
missingRequirement |= equipment().regions()[i].missingRequirement(this);
// Accumulate crashes for all the maps.
for (int i = 0; i < equipment().maps().length; i++)
missingRequirement |= equipment().maps()[i].missingRequirement(this);
// Accumulate missing requirements over meta rules
if (rules.meta() != null)
for (final MetaRule meta : rules.meta().rules())
missingRequirement |= meta.missingRequirement(this);
// Accumulate missing requirements over starting rules
if (rules.start() != null)
for (final StartRule start : rules.start().rules())
missingRequirement |= start.missingRequirement(this);
// Accumulate missing requirements over the playing rules.
for (final Phase phase : rules.phases())
missingRequirement |= phase.missingRequirement(this);
// Accumulate missing requirements over the ending rules.
if (rules.end() != null)
missingRequirement |= rules.end().missingRequirement(this);
// We check if two identical meta rules are used.
if (rules.meta() != null)
{
boolean twiceSameMetaRule = false;
for (int i = 0; i < rules.meta().rules().length; i++)
{
final MetaRule meta = rules.meta().rules()[i];
for (int j = i + 1; j < rules.meta().rules().length; j++)
{
final MetaRule metaToCompare = rules.meta().rules()[j];
if (meta.equals(metaToCompare))
{
twiceSameMetaRule = true;
break;
}
}
if (twiceSameMetaRule)
break;
}
if (twiceSameMetaRule)
{
addRequirementToReport("The same meta rule is used twice or more.");
missingRequirement = true;
}
}
return missingRequirement;
}
/**
* Add a new missing requirement even to the report.
*
* @param requirementEvent The requirement event to add.
*/
public void addRequirementToReport(final String requirementEvent)
{
requirementReport.add(requirementEvent);
}
/**
* @return The report of the missing requirements.
*/
public List<String> requirementReport()
{
return requirementReport;
}
/**
* @return True if any required ludeme is missing.
*/
public boolean hasMissingRequirement()
{
return hasMissingRequirement;
}
/**
* Methods computing the crash report in looking if any used ludeme can create a
* crash. Example: using some deduction puzzle ludeme in a game with more or
* less than one player.
*
* @return True if any ludeme can crash the game during its play.
*/
public boolean computeCrashReport()
{
boolean crash = false;
// Accumulate crashes for all the players.
crash |= players.willCrash(this);
// Accumulate crashes for all the components.
for (int i = 0; i < equipment().containers().length; i++)
crash |= equipment().containers()[i].willCrash(this);
// Accumulate crashes for all the components.
for (int i = 1; i < equipment().components().length; i++)
crash |= equipment().components()[i].willCrash(this);
// Accumulate crashes for all the regions.
for (int i = 0; i < equipment().regions().length; i++)
crash |= equipment().regions()[i].willCrash(this);
// Accumulate crashes for all the maps.
for (int i = 0; i < equipment().maps().length; i++)
crash |= equipment().maps()[i].willCrash(this);
if (players().count() != 1)
if (equipment().vertexHints().length != 0 || equipment().cellsWithHints().length != 0
|| equipment().edgesWithHints().length != 0)
{
crash = true;
addCrashToReport("The game uses some hints but the number of players is not 1");
}
// Accumulate crashes over meta rules
if (rules.meta() != null)
for (final MetaRule meta : rules.meta().rules())
crash |= meta.willCrash(this);
// Accumulate crashes over starting rules
if (rules.start() != null)
for (final StartRule start : rules.start().rules())
crash |= start.willCrash(this);
// Accumulate crashes over the playing rules.
for (final Phase phase : rules.phases())
crash |= phase.willCrash(this);
// Accumulate crashes over the ending rules.
if (rules.end() != null)
crash |= rules.end().willCrash(this);
return crash;
}
/**
* Add a new crash event to the report.
*
* @param crashEvent The crash event to add.
*/
public void addCrashToReport(final String crashEvent)
{
crashReport.add(crashEvent);
}
/**
* @return The report of the crashes.
*/
public List<String> crashReport()
{
return crashReport;
}
/**
* @return True if the game will crash.
*/
public boolean willCrash()
{
return willCrash;
}
/**
* @return BitSet corresponding to ludeme modifying data in EvalContext.
*/
public BitSet computeWritingEvalContextFlag()
{
final BitSet writingEvalContextFlags = new BitSet();
try
{
// Accumulate writeEvalContext over the players.
writingEvalContextFlags.or(players.writesEvalContextRecursive());
// Accumulate writeEvalContext for all the containers.
for (int i = 0; i < equipment().containers().length; i++)
writingEvalContextFlags.or(equipment().containers()[i].writesEvalContextRecursive());
// Accumulate concepts for all the components.
for (int i = 1; i < equipment().components().length; i++)
writingEvalContextFlags.or(equipment().components()[i].writesEvalContextRecursive());
// Accumulate concepts for all the regions.
for (int i = 0; i < equipment().regions().length; i++)
writingEvalContextFlags.or(equipment().regions()[i].writesEvalContextRecursive());
// Accumulate concepts for all the maps.
for (int i = 0; i < equipment().maps().length; i++)
writingEvalContextFlags.or(equipment().maps()[i].writesEvalContextRecursive());
// Accumulate concepts over meta rules
if (rules.meta() != null)
for (final MetaRule meta : rules.meta().rules())
writingEvalContextFlags.or(meta.writesEvalContextRecursive());
// Accumulate concepts over starting rules
if (rules.start() != null)
for (final StartRule start : rules.start().rules())
writingEvalContextFlags.or(start.writesEvalContextRecursive());
// Accumulate concepts over the playing rules.
for (final Phase phase : rules.phases())
writingEvalContextFlags.or(phase.writesEvalContextRecursive());
// Accumulate concepts over the ending rules.
if (rules.end() != null)
writingEvalContextFlags.or(rules.end().writesEvalContextRecursive());
}
catch (final Exception e)
{
e.printStackTrace();
}
// TO PRINT RESULTS
// final List<String> dataEvalContext = new ArrayList<String>();
// if (writingEvalContextFlags.get(EvalContextData.From.id()))
// dataEvalContext.add("From");
// if (writingEvalContextFlags.get(EvalContextData.Level.id()))
// dataEvalContext.add("Level");
// if (writingEvalContextFlags.get(EvalContextData.To.id()))
// dataEvalContext.add("To");
// if (writingEvalContextFlags.get(EvalContextData.Between.id()))
// dataEvalContext.add("Between");
// if (writingEvalContextFlags.get(EvalContextData.PipCount.id()))
// dataEvalContext.add("PipCount");
// if (writingEvalContextFlags.get(EvalContextData.Player.id()))
// dataEvalContext.add("Player");
// if (writingEvalContextFlags.get(EvalContextData.Track.id()))
// dataEvalContext.add("Track");
// if (writingEvalContextFlags.get(EvalContextData.Site.id()))
// dataEvalContext.add("Site");
// if (writingEvalContextFlags.get(EvalContextData.Value.id()))
// dataEvalContext.add("Value");
// if (writingEvalContextFlags.get(EvalContextData.Region.id()))
// dataEvalContext.add("Region");
// if (writingEvalContextFlags.get(EvalContextData.HintRegion.id()))
// dataEvalContext.add("HintRegion");
// if (writingEvalContextFlags.get(EvalContextData.Hint.id()))
// dataEvalContext.add("Hint");
// if (writingEvalContextFlags.get(EvalContextData.Edge.id()))
// dataEvalContext.add("Edge");
//
// System.out.println("WRITING:");
// for (final String data : dataEvalContext)
// System.out.print(data + " ");
// System.out.println();
return writingEvalContextFlags;
}
/**
* @return BitSet corresponding to ludeme reading data in EvalContext.
*/
public BitSet computeReadingEvalContextFlag()
{
final BitSet readingEvalContextFlags = new BitSet();
try
{
// Accumulate writeEvalContext over the players.
readingEvalContextFlags.or(players.readsEvalContextRecursive());
// Accumulate writeEvalContext for all the containers.
for (int i = 0; i < equipment().containers().length; i++)
readingEvalContextFlags.or(equipment().containers()[i].readsEvalContextRecursive());
// Accumulate concepts for all the components.
for (int i = 1; i < equipment().components().length; i++)
readingEvalContextFlags.or(equipment().components()[i].readsEvalContextRecursive());
// Accumulate concepts for all the regions.
for (int i = 0; i < equipment().regions().length; i++)
readingEvalContextFlags.or(equipment().regions()[i].readsEvalContextRecursive());
// Accumulate concepts for all the maps.
for (int i = 0; i < equipment().maps().length; i++)
readingEvalContextFlags.or(equipment().maps()[i].readsEvalContextRecursive());
// Accumulate concepts over meta rules
if (rules.meta() != null)
for (final MetaRule meta : rules.meta().rules())
readingEvalContextFlags.or(meta.readsEvalContextRecursive());
// Accumulate concepts over starting rules
if (rules.start() != null)
for (final StartRule start : rules.start().rules())
readingEvalContextFlags.or(start.readsEvalContextRecursive());
// Accumulate concepts over the playing rules.
for (final Phase phase : rules.phases())
readingEvalContextFlags.or(phase.readsEvalContextRecursive());
// Accumulate concepts over the ending rules.
if (rules.end() != null)
readingEvalContextFlags.or(rules.end().readsEvalContextRecursive());
}
catch (final Exception e)
{
e.printStackTrace();
}
// TO PRINT RESULTS
// final List<String> dataEvalContext = new ArrayList<String>();
// if (readingEvalContextFlags.get(EvalContextData.From.id()))
// dataEvalContext.add("From");
// if (readingEvalContextFlags.get(EvalContextData.Level.id()))
// dataEvalContext.add("Level");
// if (readingEvalContextFlags.get(EvalContextData.To.id()))
// dataEvalContext.add("To");
// if (readingEvalContextFlags.get(EvalContextData.Between.id()))
// dataEvalContext.add("Between");
// if (readingEvalContextFlags.get(EvalContextData.PipCount.id()))
// dataEvalContext.add("PipCount");
// if (readingEvalContextFlags.get(EvalContextData.Player.id()))
// dataEvalContext.add("Player");
// if (readingEvalContextFlags.get(EvalContextData.Track.id()))
// dataEvalContext.add("Track");
// if (readingEvalContextFlags.get(EvalContextData.Site.id()))
// dataEvalContext.add("Site");
// if (readingEvalContextFlags.get(EvalContextData.Value.id()))
// dataEvalContext.add("Value");
// if (readingEvalContextFlags.get(EvalContextData.Region.id()))
// dataEvalContext.add("Region");
// if (readingEvalContextFlags.get(EvalContextData.HintRegion.id()))
// dataEvalContext.add("HintRegion");
// if (readingEvalContextFlags.get(EvalContextData.Hint.id()))
// dataEvalContext.add("Hint");
// if (readingEvalContextFlags.get(EvalContextData.Edge.id()))
// dataEvalContext.add("Edge");
//
// System.out.println("READING:");
// for (final String data : dataEvalContext)
// System.out.print(data + " ");
// System.out.println();
return readingEvalContextFlags;
}
/**
* @return True if the equipment has some stochastic ludeme involved.
*
* @remark Currently checking only the regions in the equipment.
*/
public boolean equipmentWithStochastic()
{
final BitSet regionConcept = new BitSet();
for (int i = 0; i < equipment().regions().length; i++)
regionConcept.or(equipment().regions()[i].concepts(this));
return regionConcept.get(Concept.Stochastic.id());
}
/**
* @return BitSet corresponding to the boolean concepts.
*/
public BitSet computeBooleanConcepts()
{
final BitSet concept = new BitSet();
try
{
// Accumulate concepts over the players.
concept.or(players.concepts(this));
// Accumulate concepts for all the containers.
for (int i = 0; i < equipment().containers().length; i++)
concept.or(equipment().containers()[i].concepts(this));
// Accumulate concepts for all the components.
for (int i = 1; i < equipment().components().length; i++)
concept.or(equipment().components()[i].concepts(this));
// Accumulate concepts for all the regions.
for (int i = 0; i < equipment().regions().length; i++)
concept.or(equipment().regions()[i].concepts(this));
// Accumulate concepts for all the maps.
for (int i = 0; i < equipment().maps().length; i++)
concept.or(equipment().maps()[i].concepts(this));
// Look if the game uses hints.
if (equipment().vertexHints().length != 0 || equipment().cellsWithHints().length != 0
|| equipment().edgesWithHints().length != 0)
concept.set(Concept.Hints.id(), true);
// Check if some regions are defined.
if (equipment().regions().length != 0)
concept.set(Concept.Region.id(), true);
// We check if the owned pieces are asymmetric or not.
final List<List<Component>> ownedPieces = new ArrayList<List<Component>>();
for (int i = 0; i < players.count(); i++)
ownedPieces.add(new ArrayList<Component>());
// Check if the game has some asymmetric owned pieces.
for (int i = 1; i < equipment().components().length; i++)
{
final Component component = equipment().components()[i];
if (component.owner() > 0 && component.owner() <= players.count())
ownedPieces.get(component.owner() - 1).add(component);
}
if (!ownedPieces.isEmpty())
for (final Component component : ownedPieces.get(0))
{
final String nameComponent = component.getNameWithoutNumber();
final int owner = component.owner();
for (int i = 1; i < ownedPieces.size(); i++)
{
boolean found = false;
for (final Component otherComponent : ownedPieces.get(i))
{
if (otherComponent.owner() != owner
&& otherComponent.getNameWithoutNumber().equals(nameComponent))
{
found = true;
break;
}
}
if (!found)
{
concept.set(Concept.AsymmetricPiecesType.id(), true);
break;
}
}
}
// Accumulate concepts over meta rules
if (rules.meta() != null)
for (final MetaRule meta : rules.meta().rules())
concept.or(meta.concepts(this));
// Accumulate concepts over starting rules
if (rules.start() != null)
for (final StartRule start : rules.start().rules())
concept.or(start.concepts(this));
// Accumulate concepts over the playing rules.
for (final Phase phase : rules.phases())
concept.or(phase.concepts(this));
// We check if the game has more than one phase.
if (rules().phases().length > 1)
concept.set(Concept.Phase.id(), true);
// Accumulate concepts over the ending rules.
if (rules.end() != null)
concept.or(rules.end().concepts(this));
concept.set(Concept.End.id(), true);
// Look if the game uses a stack state.
if (isStacking())
{
concept.set(Concept.StackState.id(), true);
concept.set(Concept.Stack.id(), true);
}
// Look the graph element types used.
concept.or(SiteType.concepts(board().defaultSite()));
// Accumulate the stochastic concepts.
if (concept.get(Concept.Dice.id()))
concept.set(Concept.Stochastic.id(), true);
if (concept.get(Concept.Domino.id()))
concept.set(Concept.Stochastic.id(), true);
if (concept.get(Concept.Card.id()))
concept.set(Concept.Stochastic.id(), true);
if (concept.get(Concept.Dice.id()) || concept.get(Concept.LargePiece.id()))
concept.set(Concept.SiteState.id(), true);
if (concept.get(Concept.LargePiece.id()))
concept.set(Concept.SiteState.id(), true);
if (concept.get(Concept.Domino.id()))
concept.set(Concept.PieceCount.id(), true);
for (int i = 1; i < equipment().components().length; i++)
{
final Component component = equipment().components()[i];
if (component.getNameWithoutNumber() == null)
continue;
final String componentName = component.getNameWithoutNumber().toLowerCase();
if (componentName.equals("ball"))
concept.set(Concept.BallComponent.id(), true);
else if (componentName.equals("disc"))
concept.set(Concept.DiscComponent.id(), true);
else if (componentName.equals("marker"))
concept.set(Concept.MarkerComponent.id(), true);
else if (componentName.equals("king") || componentName.equals("king_nocross"))
concept.set(Concept.KingComponent.id(), true);
else if (componentName.equals("knight"))
concept.set(Concept.KnightComponent.id(), true);
else if (componentName.equals("queen"))
concept.set(Concept.QueenComponent.id(), true);
else if (componentName.equals("bishop") || componentName.equals("bishop_nocross"))
concept.set(Concept.BishopComponent.id(), true);
else if (componentName.equals("rook"))
concept.set(Concept.RookComponent.id(), true);
else if (componentName.equals("pawn"))
concept.set(Concept.PawnComponent.id(), true);
else
{
final String svgPath = ImageUtil.getImageFullPath(componentName);
if (svgPath == null) // The SVG can not be find.
continue;
if (svgPath.contains("tafl"))
concept.set(Concept.TaflComponent.id(), true);
else if (svgPath.contains("animal"))
concept.set(Concept.AnimalComponent.id(), true);
else if (svgPath.contains("fairyChess"))
concept.set(Concept.FairyChessComponent.id(), true);
else if (svgPath.contains("chess"))
concept.set(Concept.ChessComponent.id(), true);
else if (svgPath.contains("ploy"))
concept.set(Concept.PloyComponent.id(), true);
else if (svgPath.contains("shogi"))
concept.set(Concept.ShogiComponent.id(), true);
else if (svgPath.contains("xiangqi"))
concept.set(Concept.XiangqiComponent.id(), true);
else if (svgPath.contains("stratego"))
concept.set(Concept.StrategoComponent.id(), true);
else if (svgPath.contains("Janggi"))
concept.set(Concept.JanggiComponent.id(), true);
else if (svgPath.contains("hand"))
concept.set(Concept.HandComponent.id(), true);
else if (svgPath.contains("checkers"))
concept.set(Concept.CheckersComponent.id(), true);
}
}
// Check the time model.
if (mode.mode().equals(ModeType.Simulation))
concept.set(Concept.Realtime.id(), true);
else
concept.set(Concept.Discrete.id(), true);
// Check the mode.
if (mode.mode().equals(ModeType.Alternating))
concept.set(Concept.Alternating.id(), true);
else if (mode.mode().equals(ModeType.Simultaneous))
concept.set(Concept.Simultaneous.id(), true);
else if (mode.mode().equals(ModeType.Simulation))
concept.set(Concept.Simulation.id(), true);
// Check the number of players.
if (players.count() == 1)
{
concept.set(Concept.Solitaire.id(), true);
if (!concept.get(Concept.DeductionPuzzle.id()))
concept.set(Concept.PlanningPuzzle.id(), true);
}
else if (players.count() == 2)
concept.set(Concept.TwoPlayer.id(), true);
else if (players.count() > 2)
concept.set(Concept.Multiplayer.id(), true);
// We put to true all the parents of concept which are true.
for (final Concept possibleConcept : Concept.values())
if (concept.get(possibleConcept.id()))
{
Concept conceptToCheck = possibleConcept;
while (conceptToCheck != null)
{
if (conceptToCheck.dataType().equals(ConceptDataType.BooleanData))
concept.set(conceptToCheck.id(), true);
conceptToCheck = conceptToCheck.parent();
}
}
// Detection of some concepts based on the ludemeplexes used.
for (String key: description().defineInstances().keySet()) {
final String define = key.substring(1, key.length()-1);
if(define.equals("AlquerqueBoard") && description().defineInstances().get(key).define().isKnown())
concept.set(Concept.AlquerqueBoard.id(), true);
if(define.equals("AlquerqueGraph") && description().defineInstances().get(key).define().isKnown())
concept.set(Concept.AlquerqueBoard.id(), true);
if(define.equals("AlquerqueBoardWithBottomAndTopTriangles") && description().defineInstances().get(key).define().isKnown())
{
concept.set(Concept.AlquerqueBoard.id(), true);
concept.set(Concept.AlquerqueBoardWithTwoTriangles.id(), true);
}
if(define.equals("AlquerqueGraphWithBottomAndTopTriangles") && description().defineInstances().get(key).define().isKnown())
{
concept.set(Concept.AlquerqueBoard.id(), true);
concept.set(Concept.AlquerqueBoardWithTwoTriangles.id(), true);
}
if(define.equals("AlquerqueBoardWithBottomTriangle") && description().defineInstances().get(key).define().isKnown())
{
concept.set(Concept.AlquerqueBoard.id(), true);
concept.set(Concept.AlquerqueBoardWithOneTriangle.id(), true);
}
if(define.equals("AlquerqueGraphWithBottomTriangle") && description().defineInstances().get(key).define().isKnown())
{
concept.set(Concept.AlquerqueBoard.id(), true);
concept.set(Concept.AlquerqueBoardWithOneTriangle.id(), true);
}
if(define.equals("AlquerqueBoardWithFourTriangles") && description().defineInstances().get(key).define().isKnown())
{
concept.set(Concept.AlquerqueBoard.id(), true);
concept.set(Concept.AlquerqueBoardWithFourTriangles.id(), true);
}
if(define.equals("AlquerqueGraphWithFourTriangles") && description().defineInstances().get(key).define().isKnown())
{
concept.set(Concept.AlquerqueBoard.id(), true);
concept.set(Concept.AlquerqueBoardWithFourTriangles.id(), true);
}
if(define.equals("AlquerqueBoardWithEightTriangles") && description().defineInstances().get(key).define().isKnown())
{
concept.set(Concept.AlquerqueBoard.id(), true);
concept.set(Concept.AlquerqueBoardWithEightTriangles.id(), true);
}
if(define.equals("ThreeMensMorrisBoard") && description().defineInstances().get(key).define().isKnown())
concept.set(Concept.ThreeMensMorrisBoard.id(), true);
if(define.equals("ThreeMensMorrisBoardWithLeftAndRightTriangles") && description().defineInstances().get(key).define().isKnown())
{
concept.set(Concept.ThreeMensMorrisBoard.id(), true);
concept.set(Concept.ThreeMensMorrisBoardWithTwoTriangles.id(), true);
}
if(define.equals("ThreeMensMorrisGraphWithLeftAndRightTriangles") && description().defineInstances().get(key).define().isKnown())
{
concept.set(Concept.ThreeMensMorrisBoard.id(), true);
concept.set(Concept.ThreeMensMorrisBoardWithTwoTriangles.id(), true);
}
if(define.equals("NineMensMorrisBoard") && description().defineInstances().get(key).define().isKnown())
concept.set(Concept.NineMensMorrisBoard.id(), true);
if(define.equals("StarBoard") && description().defineInstances().get(key).define().isKnown())
concept.set(Concept.StarBoard.id(), true);
if(define.equals("CrossBoard") && description().defineInstances().get(key).define().isKnown())
concept.set(Concept.CrossBoard.id(), true);
if(define.equals("CrossGraph") && description().defineInstances().get(key).define().isKnown())
concept.set(Concept.CrossBoard.id(), true);
if(define.equals("KintsBoard") && description().defineInstances().get(key).define().isKnown())
concept.set(Concept.KintsBoard.id(), true);
if(define.equals("PachisiBoard") && description().defineInstances().get(key).define().isKnown())
concept.set(Concept.PachisiBoard.id(), true);
if(define.equals("FortyStonesWithFourGapsBoard") && description().defineInstances().get(key).define().isKnown())
concept.set(Concept.FortyStonesWithFourGapsBoard.id(), true);
}
}
catch (final Exception e)
{
e.printStackTrace();
}
return concept;
}
/**
* @return The game flags.
*/
public long gameFlags()
{
return gameFlags;
}
/**
* @return The boolean concepts.
*/
public BitSet booleanConcepts()
{
return booleanConcepts;
}
/**
* @return The non boolean concepts.
*/
public Map<Integer, String> computeNonBooleanConcepts()
{
final Map<Integer, String> nonBooleanConcepts = new HashMap<Integer, String>();
// Compute the average number of each absolute direction.
final SiteType defaultSiteType = board().defaultSite();
final List<? extends TopologyElement> elements = board().topology().getGraphElements(defaultSiteType);
final int numDefaultElements = elements.size();
int totalNumDirections = 0;
int totalNumOrthogonalDirections = 0;
int totalNumDiagonalDirections = 0;
int totalNumAdjacentDirections = 0;
int totalNumOffDiagonalDirections = 0;
for (final TopologyElement element : elements)
{
totalNumDirections += element.neighbours().size();
totalNumOrthogonalDirections += element.orthogonal().size();
totalNumDiagonalDirections += element.diagonal().size();
totalNumAdjacentDirections += element.adjacent().size();
totalNumOffDiagonalDirections += element.off().size();
}
String avgNumDirection = new DecimalFormat("##.##").format((double) totalNumDirections / (double) numDefaultElements) + "";
avgNumDirection = avgNumDirection.replaceAll(",", ".");
String avgNumOrthogonalDirection = new DecimalFormat("##.##").format((double) totalNumOrthogonalDirections / (double) numDefaultElements) + "";
avgNumOrthogonalDirection = avgNumOrthogonalDirection.replaceAll(",", ".");
String avgNumDiagonalDirection = new DecimalFormat("##.##").format((double) totalNumDiagonalDirections / (double) numDefaultElements) + "";
avgNumDiagonalDirection = avgNumDiagonalDirection.replaceAll(",", ".");
String avgNumAdjacentlDirection = new DecimalFormat("##.##").format((double) totalNumAdjacentDirections / (double) numDefaultElements) + "";
avgNumAdjacentlDirection = avgNumAdjacentlDirection.replaceAll(",", ".");
String avgNumOffDiagonalDirection = new DecimalFormat("##.##").format((double) totalNumOffDiagonalDirections / (double) numDefaultElements) + "";
avgNumOffDiagonalDirection = avgNumOffDiagonalDirection.replaceAll(",", ".");
for (final Concept concept : Concept.values())
if (!concept.dataType().equals(ConceptDataType.BooleanData))
{
switch (concept)
{
case NumPlayableSites:
int countPlayableSites = 0;
for (int cid = 0; cid < equipment.containers().length; cid++)
{
final Container container = equipment.containers()[cid];
if (cid != 0)
countPlayableSites += container.numSites();
else
{
if (booleanConcepts.get(Concept.Cell.id()))
countPlayableSites += container.topology().cells().size();
if (booleanConcepts.get(Concept.Vertex.id()))
countPlayableSites += container.topology().vertices().size();
if (booleanConcepts.get(Concept.Edge.id()))
countPlayableSites += container.topology().edges().size();
}
}
nonBooleanConcepts.put(Integer.valueOf(concept.id()), countPlayableSites + "");
break;
case NumPlayableSitesOnBoard:
int countPlayableSitesOnBoard = 0;
final Container container = equipment.containers()[0];
if (booleanConcepts.get(Concept.Cell.id()))
countPlayableSitesOnBoard += container.topology().cells().size();
if (booleanConcepts.get(Concept.Vertex.id()))
countPlayableSitesOnBoard += container.topology().vertices().size();
if (booleanConcepts.get(Concept.Edge.id()))
countPlayableSitesOnBoard += container.topology().edges().size();
nonBooleanConcepts.put(Integer.valueOf(concept.id()), countPlayableSitesOnBoard + "");
break;
case NumPlayers:
nonBooleanConcepts.put(Integer.valueOf(concept.id()),
players.count() + "");
break;
case NumColumns:
nonBooleanConcepts.put(Integer.valueOf(concept.id()),
board().topology().columns(defaultSiteType).size() + "");
break;
case NumRows:
nonBooleanConcepts.put(Integer.valueOf(concept.id()),
board().topology().rows(defaultSiteType).size() + "");
break;
case NumCorners:
nonBooleanConcepts.put(Integer.valueOf(concept.id()),
board().topology().corners(defaultSiteType).size() + "");
break;
case NumDirections:
nonBooleanConcepts.put(Integer.valueOf(concept.id()), avgNumDirection);
break;
case NumOrthogonalDirections:
nonBooleanConcepts.put(Integer.valueOf(concept.id()), avgNumOrthogonalDirection);
break;
case NumDiagonalDirections:
nonBooleanConcepts.put(Integer.valueOf(concept.id()), avgNumDiagonalDirection);
break;
case NumAdjacentDirections:
nonBooleanConcepts.put(Integer.valueOf(concept.id()), avgNumAdjacentlDirection);
break;
case NumOffDiagonalDirections:
nonBooleanConcepts.put(Integer.valueOf(concept.id()), avgNumOffDiagonalDirection);
break;
case NumOuterSites:
nonBooleanConcepts.put(Integer.valueOf(concept.id()),
board().topology().outer(defaultSiteType).size() + "");
break;
case NumInnerSites:
nonBooleanConcepts.put(Integer.valueOf(concept.id()),
board().topology().inner(defaultSiteType).size() + "");
break;
case NumLayers:
nonBooleanConcepts.put(Integer.valueOf(concept.id()),
board().topology().layers(defaultSiteType).size() + "");
break;
case NumEdges:
nonBooleanConcepts.put(Integer.valueOf(concept.id()), board().topology().edges().size() + "");
break;
case NumCells:
nonBooleanConcepts.put(Integer.valueOf(concept.id()), board().topology().cells().size() + "");
break;
case NumVertices:
nonBooleanConcepts.put(Integer.valueOf(concept.id()), board().topology().vertices().size() + "");
break;
case NumPerimeterSites:
nonBooleanConcepts.put(Integer.valueOf(concept.id()),
board().topology().perimeter(defaultSiteType).size() + "");
break;
case NumTopSites:
nonBooleanConcepts.put(Integer.valueOf(concept.id()),
board().topology().top(defaultSiteType).size() + "");
break;
case NumBottomSites:
nonBooleanConcepts.put(Integer.valueOf(concept.id()),
board().topology().bottom(defaultSiteType).size() + "");
break;
case NumRightSites:
nonBooleanConcepts.put(Integer.valueOf(concept.id()),
board().topology().right(defaultSiteType).size() + "");
break;
case NumLeftSites:
nonBooleanConcepts.put(Integer.valueOf(concept.id()),
board().topology().left(defaultSiteType).size() + "");
break;
case NumCentreSites:
nonBooleanConcepts.put(Integer.valueOf(concept.id()),
board().topology().centre(defaultSiteType).size() + "");
break;
case NumConvexCorners:
nonBooleanConcepts.put(Integer.valueOf(concept.id()),
board().topology().cornersConvex(defaultSiteType).size() + "");
break;
case NumConcaveCorners:
nonBooleanConcepts.put(Integer.valueOf(concept.id()),
board().topology().cornersConcave(defaultSiteType).size() + "");
break;
case NumPhasesBoard:
int numPhases = 0;
final List<List<TopologyElement>> phaseElements = board().topology().phases(defaultSiteType);
for (final List<TopologyElement> topoElements : phaseElements)
if (topoElements.size() != 0)
numPhases++;
nonBooleanConcepts.put(Integer.valueOf(concept.id()), numPhases + "");
break;
case NumComponentsType:
nonBooleanConcepts.put(Integer.valueOf(concept.id()), equipment().components().length - 1 + "");
break;
case NumComponentsTypePerPlayer:
final int[] componentsPerPlayer = new int[players.size()];
for (int i = 1; i < equipment().components().length; i++)
{
final Component component = equipment().components()[i];
if (component.owner() > 0 && component.owner() < players().size())
componentsPerPlayer[component.owner()]++;
}
int numOwnerComponent = 0;
for (int i = 1; i < componentsPerPlayer.length; i++)
numOwnerComponent += componentsPerPlayer[i];
String avgNumComponentPerPlayer = players.count() <= 0 ? "0" : new DecimalFormat("##.##")
.format((double) numOwnerComponent / (double) players.count()) + "";
avgNumComponentPerPlayer = avgNumComponentPerPlayer.replaceAll(",", ".");
nonBooleanConcepts.put(Integer.valueOf(concept.id()), avgNumComponentPerPlayer);
break;
case NumPlayPhase:
nonBooleanConcepts.put(Integer.valueOf(concept.id()), rules().phases().length + "");
break;
case NumDice:
int numDice = 0;
for (int i = 1; i < equipment().components().length; i++)
if (equipment().components()[i].isDie())
numDice++;
nonBooleanConcepts.put(Integer.valueOf(concept.id()), numDice + "");
break;
case NumContainers:
nonBooleanConcepts.put(Integer.valueOf(concept.id()), equipment().containers().length + "");
break;
default:
break;
}
}
return nonBooleanConcepts;
}
/**
* @return The starting concepts. To use only for recons purposes because this is not taking in account the RNG.
*/
public Map<String, Double> startsConceptsWithoutRNG()
{
final Map<String, Double> mapStarting = new HashMap<String, Double>();
double numStartComponents = 0.0;
double numStartComponentsHands = 0.0;
double numStartComponentsBoard = 0.0;
// Setup a new instance of the game
final BitSet concepts = computeBooleanConcepts();
final Context context = new Context(this, new Trial(this));
this.start(context);
for (int cid = 0; cid < context.containers().length; cid++)
{
final Container cont = context.containers()[cid];
final ContainerState cs = context.containerState(cid);
if (cid == 0)
{
if (concepts.get(Concept.Cell.id()))
for (int cell = 0; cell < cont.topology().cells().size(); cell++)
{
final int count = isStacking() ? cs.sizeStack(cell, SiteType.Cell) : cs.count(cell, SiteType.Cell);
numStartComponents += count;
numStartComponentsBoard += count;
}
if (concepts.get(Concept.Vertex.id()))
for (int vertex = 0; vertex < cont.topology().vertices().size(); vertex++)
{
final int count = isStacking() ? cs.sizeStack(vertex, SiteType.Vertex) : cs.count(vertex, SiteType.Vertex);
numStartComponents += count;
numStartComponentsBoard += count;
}
if (concepts.get(Concept.Edge.id()))
for (int edge = 0; edge < cont.topology().edges().size(); edge++)
{
final int count = isStacking() ? cs.sizeStack(edge, SiteType.Edge) : cs.count(edge, SiteType.Edge);
numStartComponents += count;
numStartComponentsBoard += count;
}
}
else
{
if (concepts.get(Concept.Cell.id()))
for (int cell = context.sitesFrom()[cid]; cell < context.sitesFrom()[cid]
+ cont.topology().cells().size(); cell++)
{
final int count = isStacking() ? cs.sizeStack(cell, SiteType.Cell) : cs.count(cell, SiteType.Cell);
numStartComponents += count;
numStartComponentsHands += count;
}
}
}
mapStarting.put(Concept.NumStartComponents.name(), Double.valueOf(numStartComponents));
mapStarting.put(Concept.NumStartComponentsHand.name(), Double.valueOf(numStartComponentsHands));
mapStarting.put(Concept.NumStartComponentsBoard.name(), Double.valueOf(numStartComponentsBoard));
mapStarting.put(Concept.NumStartComponentsPerPlayer.name(), Double.valueOf(numStartComponents / (players().count() == 0 ? 1 : players().count())));
mapStarting.put(Concept.NumStartComponentsHandPerPlayer.name(), Double.valueOf(numStartComponentsHands / (players().count() == 0 ? 1 : players().count())));
mapStarting.put(Concept.NumStartComponentsBoardPerPlayer.name(), Double.valueOf(numStartComponentsBoard / (players().count() == 0 ? 1 : players().count())));
return mapStarting;
}
/**
* @return The non boolean concepts.
*/
public Map<Integer, String> nonBooleanConcepts()
{
return conceptsNonBoolean;
}
//-------------------------Game related methods----------------------------
/**
* @param context The context.
* @param forced True if the pass move is forced
* @return A pass move created to be applied in given context.
*/
public static Move createPassMove(final Context context, final boolean forced)
{
return createPassMove(context.state().mover(),forced);
}
/**
* @param player The player who is expected to make this move.
* @param forced True if the pass move is forced
* @return A pass move created to be applied in given context (with given player
* as mover.
*/
public static Move createPassMove(final int player, final boolean forced)
{
final ActionPass actionPass = new ActionPass(forced);
actionPass.setDecision(true);
final Move passMove = new Move(actionPass);
passMove.setMover(player);
passMove.setMovesLudeme(new Pass(null));
return passMove;
}
/**
* Initialise the game graph and other variables.
*/
@Override
public void create()
{
if (finishedPreprocessing)
System.err.println("Warning! Game.create() has already previously been called on " + name());
if (equipment == null) // If no equipment defined we use the default one.
equipment = new Equipment
(
new Item[]
{
new Board
(
new RectangleOnSquare
(
new DimConstant(3),
null,
null,
null
),
null,
null,
null,
null,
null,
Boolean.FALSE
)
}
);
if (rules == null) // If no rules defined we use the default ones.
{
rules = new Rules
(
null, // no metarules
null, // empty board
new Play
(
game.rules.play.moves.decision.Move.construct
(
MoveSiteType.Add,
null,
new To
(
null,
SitesEmpty.construct(null, null),
null,
null,
null,
null,
null
),
null,
null,
null
)
),
new End
(
new game.rules.end.If
(
Is.construct
(
IsLineType.Line, null, new IntConstant(3),
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null
),
null,
null,
new Result(RoleType.Mover, ResultType.Win)
),
null
)
);
}
// Create the times of the equipment.
equipment.createItems(this);
// We add the index of the owner at the end of the name of each component.
for (int i = 1; i < equipment.components().length; i++)
{
final Component component = equipment.components()[i];
if (component.isTile() && component.numSides() == Constants.OFF)
component.setNumSides(board().topology().cells().get(0).edges().size());
final String componentName = component.name();
final RoleType role = component.role();
// Not for the puzzle, not for a domino or a die
if (players.count() != 1 && !componentName.contains("Domino") && !componentName.contains("Die"))
if (role == RoleType.Neutral || (role.owner() > 0 && role.owner() <= Constants.MAX_PLAYERS))
component.setName(componentName + role.owner());
// For puzzle we modify the name only if the role is equal to Neutral
if (players.count() == 1 && !componentName.contains("Domino") && !componentName.contains("Die"))
if (role == RoleType.Neutral)
component.setName(componentName + role.owner());
}
// We build the tracks and compute the maps
for (final Track track : board().tracks())
track.buildTrack(this);
for (final game.equipment.other.Map map : equipment.maps())
map.computeMap(this);
// In case of direction for a player, all the pieces of this player will use it.
for (int j = 1; j < players.players().size(); j++)
{
final Player p = players.players().get(j);
final DirectionFacing direction = p.direction();
final int pid = p.index();
if (direction != null)
{
for (int i = 1; i < equipment.components().length; i++)
{
final Component component = equipment.components()[i];
if (pid == component.owner())
component.setDirection(direction);
}
}
}
for (final Container c : equipment.containers())
if (c.isDice())
handDice.add((Dice) c);
else if (c.isDeck())
handDeck.add((Deck) c);
gameFlags = computeGameFlags();
if ((gameFlags & GameType.UsesSwapRule) != 0L)
metaRules.setUsesSwapRule(true);
stateReference = new State(this, StateConstructorLock.INSTANCE);
// No component for the deduction puzzle (for sandbox)
if (isDeductionPuzzle())
equipment.clearComponents();
mapContainer.clear();
mapComponent.clear();
for (int e = 0; e < equipment.containers().length; e++)
{
final Container equip = equipment.containers()[e];
mapContainer.put(equip.name(), equip);
}
// e = 0 is the empty component
for (int e = 1; e < equipment.components().length; e++)
{
final Component equip = equipment.components()[e];
equip.setIndex(e);
mapComponent.put(equip.name(), equip);
}
// System.out.println(map.size() + " items mapped.");
// Initialise control: state, number of players, etc.
stateReference.initialise(this);
// preprocess regions
final game.equipment.other.Regions[] regions = equipment().regions();
for (final game.equipment.other.Regions region : regions)
region.preprocess(this);
// preprocessing step for any static ludemes and check if the items name exist.
if (rules.start() != null)
for (final StartRule start : rules.start().rules())
start.preprocess(this);
if (rules.end() != null)
rules.end().preprocess(this);
for (final Phase phase : rules.phases())
phase.preprocess(this);
booleanConcepts = computeBooleanConcepts();
conceptsNonBoolean = computeNonBooleanConcepts();
hasMissingRequirement = computeRequirementReport();
willCrash = computeCrashReport();
// System.out.println("Game.create(): numPlayers=" +
// stateReference.numPlayers()
// + ", active=" + stateReference.active());
// Create mappings between ints and moves
// for (final Phase phase : rules.phases())
// phase.play().moves().updateMoveIntMapper(this, Integer.MAX_VALUE, Integer.MIN_VALUE, Integer.MAX_VALUE,
// Integer.MIN_VALUE);
// Precompute distance tables which rely on preprocessing done above
// (e.g. regions)
if (board().defaultSite() == SiteType.Cell)
equipment.containers()[0].topology().preGenerateDistanceToRegionsCells(this, regions);
else
equipment.containers()[0].topology().preGenerateDistanceToRegionsVertices(this, regions);
postCreation();
// Create custom, optimised playout strategies
addCustomPlayouts();
finishedPreprocessing = true;
}
/**
* @return End rules for this game
*/
public End endRules()
{
return rules.end();
}
//-------------------------------------------------------------------------
/**
* Init the state and start the game.
*/
@Override
public void start(final Context context)
{
context.getLock().lock();
//System.out.println("Starting game with RNG internal state: " + Arrays.toString(((RandomProviderDefaultState)context.rng().saveState()).getState()));
try
{
if (startContext != null)
{
context.resetToContext(startContext);
}
else
{
// Normal case for single-trial games
context.reset();
// We keep a trace on all the remaining dominoes
if (hasDominoes())
for (int componentId = 1; componentId < equipment().components().length; componentId++)
context.state().remainingDominoes().add(componentId);
// Place the dice in a hand dice.
for (final Dice c : context.game().handDice())
for (int i = 1; i <= c.numLocs(); i++)
{
final StartRule rule = new PlaceItem("Die" + i, c.name(), SiteType.Cell, null, null, null, null,
null, null);
rule.eval(context);
}
// Place randomly the cards of the deck in the game.
for (final Deck d : context.game().handDeck())
{
final TIntArrayList components = new TIntArrayList(d.indexComponent());
final int nbCards = components.size();
for (int i = 0; i < nbCards; i++)
{
final int j = (context.rng().nextInt(components.size()));
final int index = components.getQuick(j);
final StartRule rule = new PlaceCustomStack("Card" + index, null, d.name(), SiteType.Cell, null,
null, null, null, null, null);
components.remove(index);
rule.eval(context);
}
}
if (rules.start() != null)
rules.start().eval(context);
// Apply the metarule
if (rules.meta() != null)
for (final MetaRule meta : rules.meta().rules())
meta.eval(context);
// We store the starting positions of each component.
for (int i = 0; i < context.components().length; i++)
context.trial().startingPos().add(new Region());
if (!isDeductionPuzzle())
{
final ContainerState cs = context.containerState(0);
for (int site = 0; site < board().topology().getGraphElements(board().defaultSite()).size(); site++)
{
final int what = cs.what(site, board().defaultSite());
context.trial().startingPos().get(what).add(site);
}
}
else
{
final Satisfy set = (Satisfy) rules().phases()[0].play().moves();
initConstraintVariables(set.constraints(), context);
}
// for (int what = 1; what < context.components().size(); what++)
// {
// final String nameCompo = context.components().get(what).name();
// System.out.println("Component " + nameCompo + " starting pos = " + context.trial().startingPos(what));
// }
// To update the sum of the dice container.
if (hasHandDice())
{
for (int i = 0; i < handDice().size(); i++)
{
final Dice dice = handDice().get(i);
final ContainerState cs = context.containerState(dice.index());
final int siteFrom = context.sitesFrom()[dice.index()];
final int siteTo = context.sitesFrom()[dice.index()] + dice.numSites();
int sum = 0;
for (int site = siteFrom; site < siteTo; site++)
{
sum += context.components()[cs.whatCell(site)].getFaces()[cs.stateCell(site)];
context.state().currentDice()[i][site - siteFrom] = context.components()[cs.whatCell(site)]
.getFaces()[cs.stateCell(site)];
}
context.state().sumDice()[i] = sum;
}
}
if (usesNoRepeatPositionalInGame() && context.state().mover() != context.state().prev())
context.trial().previousState().add(context.state().stateHash());
if (usesNoRepeatPositionalInTurn())
{
if (context.state().mover() == context.state().prev())
{
context.trial().previousStateWithinATurn().add(context.state().stateHash());
}
else
{
context.trial().previousStateWithinATurn().clear();
context.trial().previousStateWithinATurn().add(context.state().stateHash());
}
}
// only save the first state in trial after applying start rules
context.trial().saveState(context.state());
numStartingAction = context.trial().numMoves(); // FIXME should not be Game property if it can be variable with stochastic start rules
if (!stochasticStartingRules)
startContext = new Context(context);
}
// Important for AIs
//incrementGameStartCount();
// Make sure our "real" context's RNG actually gets used and progresses
if (!context.trial().over() && context.game().isStochasticGame())
context.game().moves(context);
}
finally
{
context.getLock().unlock();
}
}
/**
* Compute the legal moves of the game according to the context.
*/
@Override
public Moves moves(final Context context)
{
context.getLock().lock();
try
{
final Trial trial = context.trial();
if (trial.cachedLegalMoves() == null || trial.cachedLegalMoves().moves().isEmpty())
{
final Moves legalMoves;
if (trial.over())
{
legalMoves = new BaseMoves(null);
}
else if (isAlternatingMoveGame())
{
final int mover = context.state().mover();
final int indexPhase = context.state().currentPhase(mover);
final Phase phase = context.game().rules.phases()[indexPhase];
legalMoves = phase.play().moves().eval(context);
// Meta-rule: we apply the meta rule if existing.
Swap.apply(context, legalMoves);
// Meta-rule: We apply the Pin meta-rule if existing.
Pin.apply(context,legalMoves);
}
else if (isSimulationMoveGame())
{
final Phase phase = context.game().rules.phases()[0];
final Moves moves = phase.play().moves().eval(context);
legalMoves = new BaseMoves(null);
if (!moves.moves().isEmpty())
{
final Move singleMove = new Move(moves.get(0));
for (int i = 1; i < moves.moves().size(); i++)
for (final Action action : moves.get(i).actions())
singleMove.actions().add(action);
legalMoves.moves().add(singleMove);
}
}
else
{
legalMoves = new BaseMoves(null);
for (int p = 1; p <= players.count(); ++p)
{
// TODO: In the (probably very common) case where multiple players are in same
// phase, this implementation seems really inefficient? Always computing the same
// moves?
final int indexPhase = context.state().currentPhase(p);
final Phase phase = context.game().rules.phases()[indexPhase];
final FastArrayList<Move> phaseMoves = phase.play().moves().eval(context).moves();
boolean addedMove = false;
for (final Move move : phaseMoves)
{
if (move.mover() == p)
{
legalMoves.moves().add(move);
addedMove = true;
}
}
if (!addedMove && context.active(p))
{
// Need to add forced pass for p
legalMoves.moves().add(createPassMove(p,true));
}
}
for (final Move move : legalMoves.moves())
{
if (move.then().isEmpty())
if (legalMoves.then() != null)
move.then().add(legalMoves.then().moves());
}
}
// System.out.println("LEGAL MOVES ARE");
// for (final Move m : legalMoves.moves())
// {
// System.out.println(m);
// final BitSet moveConcepts = m.concepts(context);
// for (int indexConcept = 0; indexConcept < Concept.values().length; indexConcept++)
// {
// final Concept concept = Concept.values()[indexConcept];
// if (moveConcepts.get(concept.id()))
// System.out.println(concept.name());
// }
// }
trial.setLegalMoves(legalMoves, context);
if (context.active())
{
// empty <=> stalemated
context.state().setStalemated(context.state().mover(), legalMoves.moves().isEmpty());
}
}
return trial.cachedLegalMoves();
}
finally
{
context.getLock().unlock();
}
}
/**
* Apply a move to the current context.
*/
@Override
public Move apply(final Context context, final Move move)
{
return apply(context, move, false); // By default false --> don't skip computing end rules
}
/**
* Get matching move from the legal moves.
* @param context
* @param move
* @return Matching move from the legal moves.
*/
public Move getMatchingLegalMove(final Context context, final Move move)
{
Move realMoveToApply = null;
final Moves legal = moves(context);
final List<Action> moveActions = move.getActionsWithConsequences(context);
for (final Move m : legal.moves())
{
if (Model.movesEqual(move, moveActions, m, context))
{
realMoveToApply = m;
break;
}
}
return realMoveToApply;
}
/**
* Apply a move to the current context
*
* @param context The context.
* @param move The move to apply.
* @param skipEndRules If true, we do not spend any time computing end rules.
* Note that this can make the resulting context unsuitable
* for further use.
* @return Applied move (with consequents resolved etc.
*/
public Move apply(final Context context, final Move move, final boolean skipEndRules)
{
context.getLock().lock();
try
{
// Save data before applying end rules (for undo).
context.storeCurrentData();
// Meta-rule: We apply the auto move rules if existing.
Automove.apply(context, move);
// Meta-rule: We apply the gravity rules if existing.
Gravity.apply(context,move);
// If a decision was done previously we reset it.
if (context.state().isDecided() != Constants.UNDEFINED)
context.state().setIsDecided(Constants.UNDEFINED);
return applyInternal(context, move, skipEndRules);
}
finally
{
context.getLock().unlock();
}
}
/**
* @param context The context.
* @param move The move to apply.
* @param skipEndRules If true, we do not spend any time computing end rules.
* Note that this can make the resulting context unsuitable
* for further use.
*
* @return The move applied without forced play.
*/
public Move applyInternal(final Context context, final Move move, final boolean skipEndRules)
{
final Trial trial = context.trial();
final State state = context.state();
final Game game = context.game();
final int mover = state.mover();
if (move.isPass() && !state.isStalemated(mover))
{
// probably means our stalemated flag was incorrectly not set to true,
// make sure it's correct
computeStalemated(context);
}
state.rebootPending();
final Move returnMove = (Move) move.apply(context, true); // update the game state
if (skipEndRules) // We'll leave the state in a half-finished state and just return directly
return returnMove;
// System.out.println("Last move: " + context.trial().lastMove());
// System.out.println("lastTo=" + context.trial().lastMove().getTo());
// Check game status here
if (trial.numMoves() > game.numStartingAction)
{
// Only check if action not part of setup
if (context.active() && game.rules.phases() != null)
{
final End endPhase = game.rules.phases()[state.currentPhase(state.mover())].end();
if (endPhase != null)
endPhase.eval(context);
}
if (!trial.over())
{
final End endRule = game.rules.end();
if (endRule != null)
endRule.eval(context);
}
if (context.active() && checkMaxTurns(context))
{
int winner = 0;
if (game.players().count() > 1)
{
final double score = context.computeNextDrawRank();
assert(score >= 1.0 && score <= trial.ranking().length);
for (int player = 1; player < trial.ranking().length; player++)
{
if (trial.ranking()[player] == 0.0)
{
trial.ranking()[player] = score;
}
else if (context.trial().ranking()[player] == 1.0)
{
winner = player;
}
}
}
else
{
trial.ranking()[1] = 0.0;
}
context.setAllInactive();
EndType endType = EndType.NaturalEnd;
if (state.numTurn() >= getMaxTurnLimit() * players.count())
endType = EndType.TurnLimit;
else if ((trial.numMoves() - trial.numInitialPlacementMoves()) >= getMaxMoveLimit())
endType = EndType.MoveLimit;
trial.setStatus(new Status(winner, endType));
}
if (!context.active())
{
state.setPrev(mover);
// break;
}
else // We update the current Phase for each player if this is a game with phases.
{
if (game.rules.phases() != null)
{
for (int pid = 1; pid <= game.players().count(); pid++)
{
final Phase phase = game.rules.phases()[state.currentPhase(pid)];
for (int i = 0; i < phase.nextPhase().length; i++)
{
final NextPhase cond = phase.nextPhase()[i];
final int who = cond.who().eval(context);
if (who == game.players.count() + 1 || pid == who)
{
final int nextPhase = cond.eval(context);
if (nextPhase != Constants.UNDEFINED)
{
state.setPhase(pid, nextPhase);
break;
}
}
}
}
}
}
state.incrCounter();
}
if (usesNoRepeatPositionalInGame() && state.mover() != context.state().prev())
trial.previousState().add(state.stateHash());
else
if (hasCycleDetection())
trial.previousState().add(state.stateHash());
if (usesNoRepeatPositionalInTurn())
{
if (state.mover() == state.prev())
{
trial.previousStateWithinATurn().add(state.stateHash());
}
else
{
trial.previousStateWithinATurn().clear();
trial.previousStateWithinATurn().add(state.stateHash());
}
}
if (usesNoRepeatSituationalInGame() && state.mover() != state.prev())
trial.previousState().add(state.fullHash());
if (usesNoRepeatSituationalInTurn())
{
if (state.mover() == state.prev())
{
trial.previousStateWithinATurn().add(state.fullHash());
}
else
{
trial.previousStateWithinATurn().clear();
trial.previousStateWithinATurn().add(state.fullHash());
}
}
if (context.active())
{
if (requiresVisited())
{
if (state.mover() != state.next())
{
state.reInitVisited();
}
else
{
final int from = returnMove.fromNonDecision();
final int to = returnMove.toNonDecision();
state.visit(from);
state.visit(to);
}
}
//context.setUnionFindCalled(false);
//context.setUnionFindDeleteCalled(false);
state.setPrev(mover);
state.setMover(state.next());
// Count the number of turns played by the same player
if (state.prev() == state.mover() && !returnMove.isSwap())
state.incrementNumTurnSamePlayer();
else
state.reinitNumTurnSamePlayer();
int next = (state.mover()) % game.players.count() + 1;
while (!context.active(next))
{
next++;
if (next > game.players.count())
next = 1;
}
state.setNext(next);
state.updateNumConsecutivePasses(returnMove.isPass());
}
// To update the sum of the dice container.
if (hasHandDice())
{
for (int i = 0; i < handDice().size(); i++)
{
final Dice dice = handDice().get(i);
final ContainerState cs = context.containerState(dice.index());
final int siteFrom = context.sitesFrom()[dice.index()];
final int siteTo = context.sitesFrom()[dice.index()] + dice.numSites();
int sum = 0;
for (int site = siteFrom; site < siteTo; site++)
{
sum += context.components()[cs.whatCell(site)].getFaces()[cs.stateCell(site)];
//context.state().currentDice()[i][site - siteFrom] = context.components()[cs.whatCell(site)].getFaces()[cs.stateCell(site)];
}
state.sumDice()[i] = sum;
}
}
// tell the trial that it can save its current state (if it wants)
// need to do this last because mover switching etc. is included in state
trial.saveState(state);
// Store the current RNG for the undo methods.
final RandomProviderState randomProviderState = context.rng().saveState();
trial.addRNGState(randomProviderState);
trial.clearLegalMoves();
// Make sure our "real" context's RNG actually gets used and progresses
// For temporary copies of context, we need not do this
if (!(context instanceof TempContext) && !trial.over() && context.game().isStochasticGame())
context.game().moves(context);
// System.out.println("RETURN MOVE IS " + returnMove);
return returnMove;
}
/**
* To undo the last move previously played.
* @param context The context.
* @return The move applied to undo the last move played.
*/
@SuppressWarnings("static-method")
public Move undo(final Context context)
{
context.getLock().lock();
try
{
final Trial trial = context.trial();
// Step 1: restore previous RNG.
trial.removeLastRNGStates();
if(!trial.RNGStates().isEmpty())
{
final RandomProviderState previousRNGState = trial.RNGStates().get(trial.RNGStates().size()-1);
context.rng().restoreState(previousRNGState);
}
final Move move = context.trial().lastMove();
move.undo(context, true);
return move;
}
finally
{
context.getLock().unlock();
}
}
/**
* Ensures that the stalemated flag for the current mover in the given context
* is set correctly. Calling this should not be necessary if game.moves() has
* already been called to compute the full list of legal moves for the current
* state of the trial, but may be necessary otherwise.
*
* @param context The context.
*/
public void computeStalemated(final Context context)
{
final Trial trial = context.trial();
final State state = context.state();
final Game game = context.game();
final int mover = state.mover();
if (isAlternatingMoveGame())
{
if (context.active())
{
final int indexPhase = state.currentPhase(mover);
final Phase phase = context.game().rules().phases()[indexPhase];
boolean foundLegalMove = false;
if (metaRules.usesSwapRule() && trial.moveNumber() == context.game().players.count() - 1)
foundLegalMove = true;
else
foundLegalMove = phase.play().moves().canMove(context);
context.state().setStalemated(state.mover(), !foundLegalMove);
}
}
else
{
// Simultaneous-move case too difficult to deal with, just compute
// all legal moves to ensure stalemated flag is set
game.moves(context);
}
}
/**
* Tries to add some custom playout implementations to phases where possible.
*/
private void addCustomPlayouts()
{
if (mode.playout() == null)
{
// No global playout implementation specified
for (final Phase phase : rules.phases())
{
if (phase.playout() == null)
{
// No phase-specific playout implementation specified
final Moves moves = phase.play().moves();
// NOTE: not using equals() here is intentional! Most of our Moves
// do not have proper equals() implementations
if (!hasLargePiece() && moves instanceof Add && moves.then() == null)
{
final Add to = (Add) moves;
if
(
to.components().length == 1 &&
to.components()[0] instanceof Mover &&
to.region() instanceof SitesEmpty.EmptyDefault &&
to.legal() == null &&
!to.onStack()
)
{
if
(
mode.mode() == ModeType.Alternating &&
!usesNoRepeatPositionalInGame() &&
!usesNoRepeatPositionalInTurn()
)
{
// We can safely use AddToEmpty playouts in this phase
phase.setPlayout(new PlayoutAddToEmpty(to.type()));
}
}
}
else if (!isStochasticGame())
{
if (moves instanceof Do)
{
if (((Do) moves).ifAfter() != null)
{
// We can safely use FilterPlayouts in this phase
phase.setPlayout(new PlayoutFilter());
}
}
else if (moves instanceof game.rules.play.moves.nonDecision.operators.logical.If)
{
final game.rules.play.moves.nonDecision.operators.logical.If ifRule = (game.rules.play.moves.nonDecision.operators.logical.If) moves;
if (ifRule.elseList() instanceof Do)
{
if (((Do) ifRule.elseList()).ifAfter() != null)
{
// We can safely use FilterPlayouts in this phase
phase.setPlayout(new PlayoutFilter());
}
}
}
else if (moves instanceof game.rules.play.moves.nonDecision.operators.logical.Or)
{
final game.rules.play.moves.nonDecision.operators.logical.Or orRule = (game.rules.play.moves.nonDecision.operators.logical.Or) moves;
if
(
orRule.list().length == 2
&&
orRule.list()[0] instanceof Do
&&
orRule.list()[1] instanceof game.rules.play.moves.nonDecision.effect.Pass
)
{
if (((Do) orRule.list()[0]).ifAfter() != null)
{
// This is also a FilterPlayouts case we support (for Go for example)
phase.setPlayout(new PlayoutFilter());
}
}
}
}
if
(
phase.playout() == null
&&
(usesNoRepeatPositionalInGame() || usesNoRepeatPositionalInTurn())
)
{
// Can use no-repetition-playout
phase.setPlayout(new PlayoutNoRepetition());
}
}
}
}
}
/**
* Executes post-creation steps.
*/
private void postCreation()
{
//Optimiser.optimiseGame(this);
checkAddMoveCaches(this, true, new HashMap<Object, Set<String>>());
}
/**
* Traverses the tree of ludemes, and disables move caches
* in Add-move-generators that are inside other move generators
* with consequents (because otherwise consequents keep getting
* added to the same Move objects all the time).
*
* @param ludeme Root of subtree to traverse
* @param inAllowCache If false, we'll disable cache usage.
* @param visited Map of fields we've already visited, to avoid cycles
*/
private static void checkAddMoveCaches
(
final Ludeme ludeme,
final boolean inAllowCache,
final Map<Object, Set<String>> visited
)
{
final Class<? extends Ludeme> clazz = ludeme.getClass();
final List<Field> fields = ReflectionUtils.getAllFields(clazz);
try
{
for (final Field field : fields)
{
if (field.getName().contains("$"))
continue;
field.setAccessible(true);
if ((field.getModifiers() & Modifier.STATIC) != 0)
continue;
if (visited.containsKey(ludeme) && visited.get(ludeme).contains(field.getName()))
continue; // avoid stack overflow
final Object value = field.get(ludeme);
if (!visited.containsKey(ludeme))
visited.put(ludeme, new HashSet<String>());
visited.get(ludeme).add(field.getName());
if (value != null)
{
final Class<?> valueClass = value.getClass();
if (Enum.class.isAssignableFrom(valueClass))
continue;
if (Ludeme.class.isAssignableFrom(valueClass))
{
final Ludeme innerLudeme = (Ludeme) value;
final boolean allowCache = inAllowCache && allowsToActionCaches(ludeme, innerLudeme);
setActionCacheAllowed(innerLudeme, allowCache);
checkAddMoveCaches(innerLudeme, allowCache, visited);
}
else if (valueClass.isArray())
{
final Object[] array = ReflectionUtils.castArray(value);
for (final Object element : array)
{
if (element != null)
{
final Class<?> elementClass = element.getClass();
if (Ludeme.class.isAssignableFrom(elementClass))
{
final Ludeme innerLudeme = (Ludeme) element;
final boolean allowCache = inAllowCache
&&
allowsToActionCaches(ludeme, innerLudeme);
setActionCacheAllowed(innerLudeme, allowCache);
checkAddMoveCaches(innerLudeme, allowCache, visited);
}
}
}
}
else if (Iterable.class.isAssignableFrom(valueClass))
{
final Iterable<?> iterable = (Iterable<?>) value;
for (final Object element : iterable)
{
if (element != null)
{
final Class<?> elementClass = element.getClass();
if (Ludeme.class.isAssignableFrom(elementClass))
{
final Ludeme innerLudeme = (Ludeme) element;
final boolean allowCache = inAllowCache
&&
allowsToActionCaches(ludeme, innerLudeme);
setActionCacheAllowed(innerLudeme, allowCache);
checkAddMoveCaches(innerLudeme, allowCache, visited);
}
}
}
}
}
}
}
catch (final IllegalArgumentException | IllegalAccessException e)
{
e.printStackTrace();
}
}
/**
* Helper method for recursive method above.
*
* @param outerLudeme
* @param innerLudeme
* @return True if the given ludeme allows Add-ludemes or Claim-ludemes rooted in the
* inner ludeme to use action cache
*/
private static boolean allowsToActionCaches(final Ludeme outerLudeme, final Ludeme innerLudeme)
{
if (outerLudeme instanceof Moves)
{
if (innerLudeme instanceof Then)
return true; // consequents subtree itself is fine
return (((Moves) outerLudeme).then() == null);
}
return true;
}
/**
* Helper method for recursive method above. Disables action cache if not allowed
* on any given ludemes that are of type Add or Claim.
*
* @param ludeme
* @param allowed
*/
private static void setActionCacheAllowed(final Ludeme ludeme, final boolean allowed)
{
if (allowed)
return;
if (ludeme instanceof game.rules.play.moves.nonDecision.effect.Add)
((game.rules.play.moves.nonDecision.effect.Add) ludeme).disableActionCache();
else if (ludeme instanceof game.rules.play.moves.nonDecision.effect.Claim)
((game.rules.play.moves.nonDecision.effect.Claim) ludeme).disableActionCache();
}
/**
* Run a full playout for a game.
*/
@Override
public Trial playout
(
final Context context, final List<AI> ais, final double thinkingTime,
final PlayoutMoveSelector playoutMoveSelector, final int maxNumBiasedActions,
final int maxNumPlayoutActions, final Random random
)
{
// TODO should maybe turn this check into an assertion? or always run it???
// if (!context.haveStarted())
// System.err.println("Didn't start!");
final Random rng = (random != null) ? random : ThreadLocalRandom.current();
Trial trial = context.trial();
final int numStartMoves = trial.numMoves();
while (true)
{
if
(
trial.over()
||
(
maxNumPlayoutActions >= 0
&&
trial.numMoves() - numStartMoves >= maxNumPlayoutActions
)
)
break;
final int numAllowedActions;
final int numAllowedBiasedActions;
if (maxNumPlayoutActions >= 0)
numAllowedActions = Math.max(0, maxNumPlayoutActions - (trial.numMoves() - numStartMoves));
else
numAllowedActions = maxNumPlayoutActions;
if (maxNumBiasedActions >= 0)
numAllowedBiasedActions = Math.max(0, maxNumBiasedActions - (trial.numMoves() - numStartMoves));
else
numAllowedBiasedActions = maxNumBiasedActions;
final Phase phase = rules().phases()[context.state().currentPhase(context.state().mover())];
if (phase.playout() != null)
{
trial = phase.playout().playout(context, ais, thinkingTime, playoutMoveSelector,
numAllowedBiasedActions, numAllowedActions, rng);
}
else if (context.game().mode().playout() != null)
{
trial = context.game().mode().playout().playout(context, ais, thinkingTime, playoutMoveSelector,
numAllowedBiasedActions, numAllowedActions, rng);
}
else
{
trial = context.model().playout(context, ais, thinkingTime, playoutMoveSelector,
numAllowedBiasedActions, numAllowedActions, rng);
}
}
return trial;
}
/**
* To Compute the constraint variables from the set of constraints.
*
* @param constraints The constraints.
* @param context The context.
*/
public void initConstraintVariables(final BooleanFunction[] constraints, final Context context)
{
// if (context.game().equipment().verticesWithHints().length != 0)
// {
// if (context.game().equipment().verticesWithHints() != null)
// for (int i = 0; i < context.game().equipment().verticesWithHints().length; i++)
// for (int j = 0; j < context.game().equipment().verticesWithHints()[i].length; j++)
// if (!constraintVariables
// .contains(context.game().equipment().verticesWithHints()[i][j].intValue()))
// constraintVariables.add(context.game().equipment().verticesWithHints()[i][j].intValue());
// }
for (final BooleanFunction constraint: constraints)
{
if (constraint instanceof ForAll)
{
final int numSite = context.topology().getGraphElements(context.board().defaultSite()).size();
for (int index = 0; index < numSite; index++)
{
if (!constraintVariables.contains(index))
constraintVariables.add(index);
}
break;
}
else
{
if (constraint.staticRegion() != null && constraint.staticRegion().equals(RegionTypeStatic.Regions))
{
final Regions[] regions = context.game().equipment().regions();
for (final Regions region : regions)
{
if (region.regionTypes() != null)
{
final RegionTypeStatic[] areas = region.regionTypes();
for (final RegionTypeStatic area : areas)
{
final Integer[][] regionsList = region.convertStaticRegionOnLocs(area, context);
for (final Integer[] locs : regionsList)
{
for (final Integer loc : locs)
if (loc != null && !constraintVariables.contains(loc.intValue()))
constraintVariables.add(loc.intValue());
}
}
}
else if (region.sites() != null)
{
for (final int loc : region.sites())
{
if (!constraintVariables.contains(loc))
constraintVariables.add(loc);
}
}
else if (region.region() != null)
{
for (final RegionFunction regionFn : region.region())
{
final int[] sites = regionFn.eval(context).sites();
for (final int loc : sites)
{
if (!constraintVariables.contains(loc))
constraintVariables.add(loc);
}
}
}
}
}
else
{
if (constraint.locsConstraint() != null)
{
for (final IntFunction function: constraint.locsConstraint())
{
final int index = function.eval(context);
if(!constraintVariables.contains(index))
constraintVariables.add(index);
}
}
else
{
if (constraint.regionConstraint() != null)
{
final int[] sites = constraint.regionConstraint().eval(context).sites();
for (final int index : sites)
if (!constraintVariables.contains(index))
constraintVariables.add(index);
}
}
}
}
}
}
//-----------------------------------Max Turn------------------------------
/**
* @param context
* @return True if the max turn limit or move limit is reached.
*/
public boolean checkMaxTurns(final Context context)
{
return (context.state().numTurn() >= getMaxTurnLimit() * players.count()
|| (context.trial().numMoves() - context.trial().numInitialPlacementMoves()) >= getMaxMoveLimit());
}
/**
* To set the max turn limit.
*
* @param limitTurn
*/
public void setMaxTurns(final int limitTurn)
{
maxTurnLimit = limitTurn;
if (isDeductionPuzzle())
setMaxMoveLimit(limitTurn);
}
/**
* @return Max number of turns for this game
*/
public int getMaxTurnLimit()
{
return maxTurnLimit;
}
/**
* Set the maximum number of moves for this game
* @param limitMoves
*/
public void setMaxMoveLimit(final int limitMoves)
{
maxMovesLimit = limitMoves;
}
/**
* @return Max number of moves for this game
*/
public int getMaxMoveLimit()
{
return maxMovesLimit;
}
/**
* @return Options selected when compiling this game.
*/
public List<String> getOptions()
{
return options;
}
/**
* Set the options used when compiling this game.
*
* NOTE: call hierarchy in Eclipse is not entirely accurate,
* this method also gets called (through Reflection) by compiler!
*
* @param options
*/
public void setOptions(final List<String> options)
{
this.options = options;
}
//-------------------------------------------------------------------------
/**
* @return Ruleset that corresponds to the options selected when compiling this game.
*/
public Ruleset getRuleset()
{
final List<String> allOptions = description().gameOptions().allOptionStrings(getOptions());
for (final Ruleset r : description().rulesets())
if (!r.optionSettings().isEmpty())
if (description().gameOptions().allOptionStrings(r.optionSettings()).equals(allOptions))
return r;
return null;
}
//-------------------------------------------------------------------------
/**
* Disables any custom playout implementations in this game (or all of its
* instances in the case of a Match) that may cause trouble in cases where
* we need trials to memorise more info than just the applied moves (i.e.
* custom playouts that do not call game.moves() to generate complete lists of
* legal moves).
*/
public void disableMemorylessPlayouts()
{
if (mode().playout() != null && !mode().playout().callsGameMoves())
mode().setPlayout(null);
for (final Phase phase : rules().phases())
{
if (phase.playout() != null && !phase.playout().callsGameMoves())
phase.setPlayout(null);
}
}
/**
* Disables any custom playout implementations in this game (or all of its
* instances in the case of a Match).
*/
public void disableCustomPlayouts()
{
if (mode().playout() != null)
mode().setPlayout(null);
for (final Phase phase : rules().phases())
{
if (phase.playout() != null)
phase.setPlayout(null);
}
}
//-------------------------------------------------------------------------
/**
* Dummy class to grant the Game class access to the State's
* non-copy-constructor.
*
* No one else should call that constructor! Just copy our reference state!
*
* @author Dennis Soemers
*/
public static final class StateConstructorLock
{
/** Singleton instance; INTENTIONALLY PRIVATE! Only we should use! */
protected static final StateConstructorLock INSTANCE = new StateConstructorLock();
/**
* Constructor; intentionally private! Only we should use!
*/
private StateConstructorLock()
{
// Do nothing
}
}
// -----------------------------Graphics------------------------------------
/**
* @return True if we've finished preprocessing, false otherwise.
*/
public boolean finishedPreprocessing()
{
return finishedPreprocessing;
}
/**
* @return True if the game contains a component owned by a shared player.
*/
public boolean hasSharedPlayer()
{
for (final Container comp : equipment().containers())
if (comp.owner() > players.count())
return true;
return false;
}
/**
* To get a sub list of a moves corresponding to some specific coordinates (e.g.
* "A1" or "A1-B1"). Note: Uses for the API. Needs to be improved to take more
* parameters (level, siteType etc).
*
* @param str The coordinates corresponding the coordinates.
* @param context The context.
* @param originalMoves The list of moves.
* @return The moves corresponding to these coordinates.
*/
public static List<Move> getMovesFromCoordinates
(
final String str,
final Context context,
final List<Move> originalMoves
)
{
final String fromCoordinate = str.contains("-") ? str.substring(0, str.indexOf('-')) : str;
final String toCoordinate = str.contains("-") ? str.substring(str.indexOf('-') + 1, str.length())
: fromCoordinate;
final TopologyElement fromElement = SiteFinder.find(context.board(), fromCoordinate,
context.board().defaultSite());
final TopologyElement toElement = SiteFinder.find(context.board(), toCoordinate,
context.board().defaultSite());
final List<Move> moves = new ArrayList<Move>();
// If the entry is wrong.
if (fromElement == null || toElement == null)
return moves;
for (final Move m : originalMoves)
if (m.fromNonDecision() == fromElement.index() && m.toNonDecision() == toElement.index())
moves.add(m);
return moves;
}
/**
* @return True if all piece types are not defined with P1 to P16 roletypes.
*/
public boolean noPieceOwnedBySpecificPlayer()
{
final String pieceDescribed = "(piece";
final String expandedDesc = description.expanded();
int index = expandedDesc.indexOf(pieceDescribed, 0);
int startIndex = index;
int numParenthesis = 0;
while(index != Constants.UNDEFINED)
{
if(expandedDesc.charAt(index) == '(')
numParenthesis++;
else if(expandedDesc.charAt(index) == ')')
numParenthesis--;
// We get a complete piece description.
if(numParenthesis == 0)
{
index++;
String pieceDescription = expandedDesc.substring(startIndex+pieceDescribed.length()+1, index-1);
// This piece description is part of the equipment.
if(pieceDescription.charAt(0) == '\"')
{
pieceDescription = pieceDescription.substring(1);
pieceDescription = pieceDescription.substring(pieceDescription.indexOf('\"')+1);
int i = 0;
for(; i < pieceDescription.length();)
{
char c = Character.toLowerCase(pieceDescription.charAt(i));
// We found the roleType.
if(c >= 'a' && c <= 'z')
{
int j = i;
for(; j < pieceDescription.length();)
{
if(c < 'a' || c > 'z')
{
// This roletype is specific to a player.
if(pieceDescription.substring(i, j).equals("P"))
return false;
break;
}
j++;
if(j < pieceDescription.length())
c = Character.toLowerCase(pieceDescription.charAt(j));
}
break;
}
else if(c == '(' || c == ')')
break;
i++;
}
}
index = expandedDesc.indexOf(pieceDescribed, index);
startIndex = index;
numParenthesis = 0;
}
else
index++;
}
return true;
}
} | 118,475 | 28.435031 | 159 | java |
Ludii | Ludii-master/Core/src/game/package-info.java | /**
* @chapter The {\tt game} ludeme defines all aspects of the current game being played, including its equipment and rules.
* This ludeme is the root of the {\it ludemeplex} (i.e. structured tree of ludemes) that makes up this game.
*
* @section The base {\tt game} ludeme describes an instance of a single game.
*/
package game;
| 349 | 42.75 | 122 | java |
Ludii | Ludii-master/Core/src/game/equipment/Equipment.java | package game.equipment;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import game.Game;
import game.equipment.component.Component;
import game.equipment.component.Die;
import game.equipment.component.Piece;
import game.equipment.component.tile.Domino;
import game.equipment.container.Container;
import game.equipment.container.board.Board;
import game.equipment.container.board.Track;
import game.equipment.container.other.Deck;
import game.equipment.container.other.Dice;
import game.equipment.container.other.Hand;
import game.equipment.other.Dominoes;
import game.equipment.other.Hints;
import game.equipment.other.Map;
import game.equipment.other.Regions;
import game.functions.region.RegionFunction;
import game.types.board.RelationType;
import game.types.board.SiteType;
import game.types.play.RoleType;
import game.types.state.GameType;
import main.Constants;
import other.BaseLudeme;
import other.ItemType;
import other.context.Context;
import other.topology.Topology;
import other.topology.TopologyElement;
import other.translation.LanguageUtils;
import other.trial.Trial;
/**
* Defines the equipment list of the game.
*
* @author cambolbro and Eric.Piette
*
* @remarks To define the items (container, component etc.) of the game. Any
* type of component or container described in this chapter may be used
* as an \texttt{<item>} type.
*/
public final class Equipment extends BaseLudeme implements Serializable
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/** List of containers. */
private Container[] containers = null;
/** List of components. */
private Component[] components = null;
/** List of regions. */
private Regions[] regions = null;
/** List of maps. */
private Map[] maps = null;
/** Total number of sites over all containers. */
private int totalDefaultSites = 0;
/** Which container a given accumulated site index refers to. */
private int[] containerId;
/** Which actual site within its container a given accumulated site index refers to. */
private int[] offset;
/** Which accumulated site index a given container starts at. */
private int[] sitesFrom;
/** Vertex with hints for Deduction Puzzle. */
private Integer[][] vertexWithHints = new Integer[0][0];
/** Cell with hints for Deduction Puzzle. */
private Integer[][] cellWithHints = new Integer[0][0];
/** Edge with hints for Deduction Puzzle. */
private Integer[][] edgeWithHints = new Integer[0][0];
/** The hints of the vertices. */
private Integer[] vertexHints = new Integer[0];
/** The hints of the cells. */
private Integer[] cellHints = new Integer[0];
/** The hints of the edges. */
private Integer[] edgeHints = new Integer[0];
/** Here we store items received from constructor, to be created when game.create() is called. */
private Item[] itemsToCreate;
//-------------------------------------------------------------------------
/**
* @param items The items (container, component etc.).
*
* @example (equipment { (board (square 3)) (piece "Disc" P1) (piece "Cross" P2)
* })
*/
public Equipment
(
final Item[] items
)
{
boolean hasABoard = false;
for (final Item item : items)
{
if (item instanceof Board)
{
hasABoard = true;
break;
}
}
if (!hasABoard)
{
throw new IllegalArgumentException("At least a board has to be defined in the equipment.");
}
itemsToCreate = items;
}
//-------------------------------------------------------------------------
@Override
public String toEnglish(final Game game)
{
String text = "";
final HashMap<String, String> ruleMap = new HashMap<>();
// Only want the toEnglish of the board.
if (containers != null && containers.length > 0)
text += "on a " + containers[0].toEnglish(game) + ".";
if (regions.length > 0)
{
text += "\nRegions:";
for (final Regions region : regions)
text += "\n " + region.toEnglish(game);
}
if (components() != null && components().length > 1)
{
text += " ";
// We create a list of player names:
final ArrayList<RoleType> playerRoleList = new ArrayList<>();
// First we search for all player names:
for (int j = 1; j <= components().length-1; j++)
{
final RoleType playerRole = components()[j].role();
if(!playerRoleList.contains(playerRole))
playerRoleList.add(playerRole);
}
// Sort the names of player, so that every order of ludemes produce the same order of stuff here:
playerRoleList.sort((e1, e2) -> { return e1.name().compareToIgnoreCase(e2.name()); });
final List<String> playerPieceText = new ArrayList<>();
for(final RoleType playerRole: playerRoleList)
{
String pieceText = "";
final ArrayList<String> pieces = new ArrayList<>();
for (int j = 1; j <= components().length-1; j++)
{
if(playerRole.equals(components()[j].role()))
pieces.add(components()[j].toEnglish(game));
if(components()[j].generator() != null)
{
// Check if the old existing rule for this component should be updated.
final String newRule = components()[j].componentGeneratorRulesToEnglish(game);
final String oldRule = ruleMap.get(components()[j].componentGeneratorRulesToEnglish(game));
if(!newRule.equals(oldRule))
{
if(oldRule == null)
ruleMap.put(components()[j].getNameWithoutNumber(), newRule);
else
ruleMap.put(components()[j].getNameWithoutNumber() + "(" + components()[j].owner() + ")", newRule);
}
}
}
for(int n = 0; n < pieces.size(); n++)
{
if(n == pieces.size() - 1 && n > 0)
pieceText += " and ";
else if(n > 0)
pieceText += ", ";
pieceText += pieces.get(n);
}
pieceText += ".";
playerPieceText.add(pieceText);
}
// Check if all players have the same pieces.
boolean allSamePieces = true;
String lastPieceString = null;
for(int i = 0; i < playerRoleList.size(); i++)
{
final RoleType playerRole = playerRoleList.get(i);
if (!playerRole.equals(RoleType.Shared) && !playerRole.equals(RoleType.Neutral))
{
final String s = playerPieceText.get(i);
if (s.length() > 1)
{
if (lastPieceString == null)
{
lastPieceString = s;
}
else if (!lastPieceString.equals(s))
{
allSamePieces = false;
break;
}
}
}
}
// Combine the piece text for all players
String pieceText = "";
if (allSamePieces)
{
pieceText += "All players play with ";
pieceText += lastPieceString;
}
// Handle player specific cases
for(int i = 0; i < playerRoleList.size(); i++)
{
final RoleType playerRole = playerRoleList.get(i);
if (playerRole.equals(RoleType.Shared))
{
pieceText += (pieceText.isEmpty() ? "" : " ") + "The following pieces are shared by all players: " + playerPieceText.get(playerPieceText.size()-1);
}
if (playerRole.equals(RoleType.Neutral))
{
pieceText += (pieceText.isEmpty() ? "" : " ") + "The following pieces are neutral: " + playerPieceText.get(0);
}
else if (!allSamePieces)
{
final String playerName = LanguageUtils.RoleTypeAsText(playerRole, true);
pieceText += (pieceText.isEmpty() ? "" : " ") + playerName + " plays with ";
pieceText += playerPieceText.get(i);
}
}
text += (pieceText.isEmpty() ? "" : "\n") + pieceText;
// Adding the rules for the pieces in the end
if(!ruleMap.isEmpty())
{
final String[] ruleKeys = ruleMap.keySet().toArray(new String[ruleMap.size()]);
Arrays.sort(ruleKeys);
String ruleText = "";
for(final String rKey: ruleKeys)
ruleText += "\n " + ruleMap.get(rKey) + ".";
text += "\nRules for Pieces:" + ruleText;
}
}
return text;
}
//-------------------------------------------------------------------------
/**
* Creates all the items
*
* @param game The game.
*/
public void createItems(final Game game)
{
// First create these as lists; at the end, transform them to arrays
final List<Component> componentsWIP = new ArrayList<Component>();
final List<Container> containersWIP = new ArrayList<Container>();
final List<Regions> regionsWIP = new ArrayList<Regions>();
final List<Map> mapsWIP = new ArrayList<Map>();
// The empty component
// componentsWIP.add(null);
final Piece emptyPiece = new Piece("Disc", RoleType.Neutral, null, null, null, null, null, null);
emptyPiece.setIndex(0);
componentsWIP.add(emptyPiece);
if (itemsToCreate != null)
{
// To sort the list of items.
final Item[] sortItems = sort(itemsToCreate);
int indexDie = 1;
int indexCard = 1;
for (final Item item : sortItems)
{
// If this is container.
if (ItemType.isContainer(item.type()))
{
final Container c = (Container) item;
if
(
item.type().ordinal() >= ItemType.Hand.ordinal()
&&
item.type().ordinal() <= ItemType.Dice.ordinal()
)
{
if (c.role() != null && c.role() == RoleType.Each)
{
final Hand hand = (Hand) c;
for (int idPlayer = 1; idPlayer <= game.players().count(); idPlayer++)
{
final Hand newHand = hand.clone();
if (hand.name() == null)
newHand.setName("Hand");
newHand.setName(newHand.name() + idPlayer);
newHand.setRoleFromPlayerId(idPlayer);
containersWIP.add(newHand);
}
}
else if (c.type() == ItemType.Dice)
{
final int indexSameDice = multiDiceSameOwner((Dice) c, containersWIP);
if (indexSameDice == Constants.UNDEFINED)
{
containersWIP.add(c);
final Dice dice = (Dice) c;
for (int i = indexDie; i <= dice.numLocs() + indexDie - 1; i++)
{
final Die die = new Die("Die" + i, dice.role(), Integer.valueOf(dice.getNumFaces()),
null, null);
die.setBiased(dice.getBiased());
die.setFaces(dice.getFaces()[i - indexDie], dice.getStart());
componentsWIP.add(die);
}
indexDie += dice.numLocs();
}
else
{
final Dice dice = (Dice) c;
for (int i = indexDie; i <= dice.numLocs() + indexDie - 1; i++)
{
final Die die = new Die("Die" + i, dice.role(), Integer.valueOf(dice.getNumFaces()),
null, null);
die.setBiased(dice.getBiased());
die.setFaces(dice.getFaces()[i - indexDie], dice.getStart());
componentsWIP.add(die);
}
indexDie += dice.numLocs();
containersWIP.set(indexSameDice,
new Dice(Integer.valueOf(dice.getNumFaces()), null, dice.getFaces(), null,
dice.role(), Integer.valueOf(
((Dice) containersWIP.get(indexSameDice)).numLocs()
+ dice.numLocs()), null));
}
}
else if (c.isDeck())
{
containersWIP.add(c);
final Deck deck = (Deck) c;
final List<Component> cards = deck.generateCards(indexCard, componentsWIP.size());
componentsWIP.addAll(cards);
indexCard += cards.size();
}
else
{
if (c.name() == null)
c.setName("Hand"+((Hand)c).owner());
containersWIP.add(c);
}
}
else
{
containersWIP.add(c);
}
// To create the numbers
if (game.isDeductionPuzzle())
{
final Board puzzleBoard = (Board) c;
if (puzzleBoard.cellRange().max(new Context(game, new Trial(game))) != 0)
{
for (int num = puzzleBoard.cellRange()
.min(new Context(game, new Trial(game))); num <= puzzleBoard.cellRange()
.max(new Context(game, new Trial(game))); num++)
{
final Piece number = new Piece(Integer.valueOf(num) + "", RoleType.P1, null,
null, null, null, null, null);
//SettingsGeneral.setMaxNumberValue(
// puzzleBoard.cellRange().max(new Context(game, new Trial(game))));
componentsWIP.add(number);
}
}
}
}
else if (ItemType.isComponent(item.type()))
{
if (item.type() == ItemType.Component)
{
final Component comp = (Component)item;
// if (isNumber(comp))
// {
// // Special generation for number in case of puzzle
// if (comp.getValue() > SettingsGeneral.getMaxNumberValue())
// SettingsGeneral.setMaxNumberValue(comp.getValue());
// }
if (comp.role() != null && comp.role() == RoleType.Each)
{
for (int idPlayer = 1; idPlayer <= game.players().count(); idPlayer++)
{
final Component compCopy = comp.clone();
if (comp.name() == null)
{
final String className = comp.getClass().toString();
final String componentName = className.substring(className.lastIndexOf('.') + 1, className.length());
compCopy.setName(componentName);
}
compCopy.setRoleFromPlayerId(idPlayer);
compCopy.setName(compCopy.name());
compCopy.setIndex(componentsWIP.size() - 1);
componentsWIP.add(compCopy);
}
}
else
{
if (comp.name() == null)
{
final String className = comp.getClass().toString();
final String componentName = className.substring(className.lastIndexOf('.') + 1, className.length());
comp.setName(componentName + comp.owner());
}
componentsWIP.add(comp);
}
}
else if (item.type() == ItemType.Dominoes)
{
final Dominoes dominoes = (Dominoes) item;
final ArrayList<Domino> listDominoes = dominoes.generateDominoes();
for (final Domino domino : listDominoes)
componentsWIP.add(domino);
}
}
else if (ItemType.isRegion(item.type()))
{
regionsWIP.add((Regions) item);
}
else if (ItemType.isMap(item.type()))
{
mapsWIP.add((Map) item);
}
else if (ItemType.isHints(item.type()))
{
final Hints hints = (Hints) item;
final int minSize = Math.min(hints.where().length, hints.values().length);
final SiteType puzzleType = hints.getType();
if (puzzleType.equals(SiteType.Vertex))
{
setVertexWithHints(new Integer[minSize][]);
setVertexHints(new Integer[minSize]);
}
else if (puzzleType.equals(SiteType.Edge))
{
setEdgeWithHints(new Integer[minSize][]);
setEdgeHints(new Integer[minSize]);
}
else if (puzzleType.equals(SiteType.Cell))
{
setCellWithHints(new Integer[minSize][]);
setCellHints(new Integer[minSize]);
}
for (int i = 0; i < minSize; i++)
{
if (puzzleType.equals(SiteType.Vertex))
{
verticesWithHints()[i] = hints.where()[i];
vertexHints()[i] = hints.values()[i];
}
else if (puzzleType.equals(SiteType.Edge))
{
edgesWithHints()[i] = hints.where()[i];
edgeHints()[i] = hints.values()[i];
}
else if (puzzleType.equals(SiteType.Cell))
{
cellsWithHints()[i] = hints.where()[i];
cellHints()[i] = hints.values()[i];
}
}
}
}
}
// if (containersWIP.size() == 0)
// {
// // Create a default board
// //System.out.println("Creating default container...");
// containersWIP.add
// (
// new Board
// (
// new RectangleOnSquare(new DimConstant(3), null, null, null), null, null, null, null, null
// )
// );
// }
// Only null placeholder is present
if (componentsWIP.size() == 1 && !(game.isDeductionPuzzle()))
{
// Create a default piece per player
// System.out.println("Creating default components...");
for (int pid = 1; pid <= game.players().count(); pid++)
{
final String name = "Ball" + pid;
// System.out.println("-- Creating " + name + " for " + RoleType.values()[pid] +
// "...");
final Component piece = new Piece(name, RoleType.values()[pid], null, null, null, null, null, null);
componentsWIP.add(piece);
}
}
// Now we can transform our lists to arrays
containers = containersWIP.toArray(new Container[containersWIP.size()]);
components = componentsWIP.toArray(new Component[componentsWIP.size()]);
regions = regionsWIP.toArray(new Regions[regionsWIP.size()]);
maps = mapsWIP.toArray(new Map[mapsWIP.size()]);
initContainerAndParameters(game);
for (final Container cont : containers)
{
if (cont != null)
cont.create(game);
}
for (final Component comp : components)
{
if (comp != null)
comp.create(game);
}
for (final Regions reg : regions)
{
reg.create(game);
}
for (final Map map : maps)
{
map.create(game);
}
// We're done, so can clean up this memory
itemsToCreate = null;
if (game.hasTrack())
{
// Tell every track what its index is
for (int i = 0; i < game.board().tracks().size(); ++i)
{
game.board().tracks().get(i).setTrackIdx(i);
}
// We pre-computed the ownedTrack array.
final Track[][] ownedTracks = new Track[game.players().size() + 1][];
for (int i = 0; i < ownedTracks.length; i++)
{
final List<Track> ownedTrack = new ArrayList<Track>();
for (final Track track : game.board().tracks())
if (track.owner() == i)
ownedTrack.add(track);
final Track[] ownedTrackArray = new Track[ownedTrack.size()];
for (int j = 0; j < ownedTrackArray.length; j++)
ownedTrackArray[j] = ownedTrack.get(j);
ownedTracks[i] = ownedTrackArray;
}
game.board().setOwnedTrack(ownedTracks);
}
}
/**
* @return The list of items sorted by Main container, hands, dice, deck
* regions, maps, components.
*/
private static Item[] sort(final Item[] items)
{
final Item[] sortedItem = new Item[items.length];
final int maxOrdinalValue = ItemType.values().length;
int indexSortedItem = 0;
for (int ordinalValue = 0; ordinalValue < maxOrdinalValue; ordinalValue++)
for (final Item item : items)
{
if (item.type().ordinal() == ordinalValue)
{
sortedItem[indexSortedItem] = item;
indexSortedItem++;
}
}
return sortedItem;
}
/**
* @return The index of the dice if you have more than one Dice owner by the
* same player (even for the shared player) else -1.
*/
private static int multiDiceSameOwner(final Dice c, final List<Container> containers)
{
for (int i = 0 ; i < containers.size(); i++)
{
final Container container = containers.get(i);
if (container.isDice())
{
final Dice containerDice = (Dice) container;
if (containerDice.owner() == c.owner() && !containerDice.equals(c))
return i;
}
}
return Constants.UNDEFINED;
}
/**
* To init totalSites, offset, sitesFrom, containerId.
*
* @param game The game
*/
public void initContainerAndParameters(final Game game)
{
final long gameFlags = game.computeGameFlags(); // NOTE: need compute here!
int index = 0;
for (int e = 0; e < containers.length; e++)
{
final Container cont = containers[e];
// Creation of the graph
cont.createTopology(index,
(cont.index() == 0) ? Constants.UNDEFINED : containers[0].topology().numEdges());
final Topology topology = cont.topology();
for (final SiteType type : SiteType.values())
{
topology.computeRelation(type);
topology.computeSupportedDirection(type);
// Convert the properties to the list of each pregeneration.
for (final TopologyElement element : topology.getGraphElements(type))
topology.convertPropertiesToList(type, element);
final boolean threeDimensions = ((gameFlags & GameType.ThreeDimensions) != 0L);
topology.computeRows(type, threeDimensions);
topology.computeColumns(type, threeDimensions);
if (!cont.isBoardless())
{
topology.crossReferencePhases(type);
topology.computeLayers(type);
topology.computeCoordinates(type);
// Precompute distance tables
topology.preGenerateDistanceTables(type);
}
// We compute the step distance only if needed by the game.
if ((gameFlags & GameType.StepAdjacentDistance) != 0L)
topology.preGenerateDistanceToEachElementToEachOther(type, RelationType.Adjacent);
else if ((gameFlags & GameType.StepAllDistance) != 0L)
topology.preGenerateDistanceToEachElementToEachOther(type, RelationType.All);
else if ((gameFlags & GameType.StepOffDistance) != 0L)
topology.preGenerateDistanceToEachElementToEachOther(type, RelationType.OffDiagonal);
else if ((gameFlags & GameType.StepDiagonalDistance) != 0L)
topology.preGenerateDistanceToEachElementToEachOther(type, RelationType.Diagonal);
else if ((gameFlags & GameType.StepOrthogonalDistance) != 0L)
topology.preGenerateDistanceToEachElementToEachOther(type, RelationType.Orthogonal);
// We compute the edges crossing each other.
topology.computeDoesCross();
}
if (e == 0)
topology.pregenerateFeaturesData(game, cont);
cont.setIndex(e);
index += (cont.index() == 0)
? Math.max(cont.topology().cells().size(),
cont.topology().getGraphElements(cont.defaultSite()).size())
: cont.numSites();
topology.optimiseMemory();
}
// INIT TOTAL SITES
for (final Container cont : containers)
totalDefaultSites += cont.numSites();
final int maxSiteMainBoard = Math.max(containers[0].topology().cells().size(),
containers[0].topology().getGraphElements(containers[0].defaultSite()).size());
int fakeTotalDefaultSite = maxSiteMainBoard;
for (int i = 1; i < containers.length; i++)
fakeTotalDefaultSite += containers[i].topology().cells().size();
// INIT OFFSET
offset = new int[fakeTotalDefaultSite];
int accumulatedOffset = 0;
for (int i = 0; i < containers.length;i++)
{
final Container cont = containers[i];
if (i == 0)
{
for (int j = 0; j < maxSiteMainBoard; ++j)
{
offset[j + accumulatedOffset] = j;
}
accumulatedOffset += maxSiteMainBoard;
}
else
{
for (int j = 0; j < cont.numSites(); ++j)
{
offset[j + accumulatedOffset] = j;
}
accumulatedOffset += cont.numSites();
}
}
sitesFrom = new int[containers.length];
// INIT sitesFROM
int count = 0;
for (int i = 0; i < containers.length; i++)
{
sitesFrom[i] = count;
count += (i == 0) ? maxSiteMainBoard : containers[i].numSites();
}
// INIT CONTAINER ID
containerId = new int[fakeTotalDefaultSite];
count = 0;
int idBoard = 0;
for (int i = 0; i < containers.length - 1; i++)
{
for (int j = sitesFrom[i]; j < sitesFrom[i + 1]; j++)
{
containerId[count] = idBoard;
count++;
}
idBoard++;
}
for (int j = sitesFrom[sitesFrom.length - 1]; j < sitesFrom[sitesFrom.length - 1]
+ containers[idBoard].numSites(); j++)
{
containerId[count] = idBoard;
count++;
}
}
/**
* @return List of all static regions in this equipment
*/
public List<Regions> computeStaticRegions()
{
final List<Regions> staticRegions = new ArrayList<Regions>();
for (final Regions region : regions)
{
if (region.region() != null)
{
boolean allStatic = true;
for (final RegionFunction regionFunc : region.region())
{
if (!regionFunc.isStatic())
{
allStatic = false;
break;
}
}
if (!allStatic)
continue;
}
else if (region.sites() == null)
{
continue;
}
staticRegions.add(region);
}
return staticRegions;
}
//----------------------Getters--------------------------------------------
/**
* @return Array of containers.
*/
public Container[] containers()
{
return containers;
}
/**
* @return Array of component.
*/
public Component[] components()
{
return components;
}
/**
* Clear the components. Will always keep a null entry at index 0.
*/
public void clearComponents()
{
components = new Component[]{null};
}
/**
* @return Array of regions.
*/
public Regions[] regions()
{
return regions;
}
/**
* @return Array of maps.
*/
public Map[] maps()
{
return maps;
}
/**
* @return Total number of default sites over all containers.
*/
public int totalDefaultSites()
{
return totalDefaultSites;
}
/**
* @return Which container a given accumulated site index refers to.
*/
public int[] containerId()
{
return containerId;
}
/**
* @return Which actual site within its container a given accumulated site index
* refers to.
*/
public int[] offset()
{
return offset;
}
/**
* @return Which accumulated site index a given container starts at.
*/
public int[] sitesFrom()
{
return sitesFrom;
}
/**
* @return The vertices with hints.
*/
public Integer[][] verticesWithHints()
{
return vertexWithHints;
}
/**
* To set the vertices with hints.
*
* @param regionWithHints
*/
public void setVertexWithHints(final Integer[][] regionWithHints)
{
vertexWithHints = regionWithHints;
}
/**
* @return The cells with hints.
*/
public Integer[][] cellsWithHints()
{
return cellWithHints;
}
/**
* To set the cells with hints.
*
* @param cellWithHints
*/
public void setCellWithHints(final Integer[][] cellWithHints)
{
this.cellWithHints = cellWithHints;
}
/**
* @return The edges with hints.
*/
public Integer[][] edgesWithHints()
{
return edgeWithHints;
}
/**
* To set the edges with hints.
*
* @param edgeWithHints
*/
public void setEdgeWithHints(final Integer[][] edgeWithHints)
{
this.edgeWithHints = edgeWithHints;
}
/**
* @return The hints of each vertex.
*/
public Integer[] vertexHints()
{
return vertexHints;
}
/**
* To set the hints of the vertices.
*
* @param hints
*/
public void setVertexHints(final Integer[] hints)
{
vertexHints = hints;
}
/**
* @return The hints of each cell.
*/
public Integer[] cellHints()
{
return cellHints;
}
/**
* To set the hints of the cells.
*
* @param hints
*/
public void setCellHints(final Integer[] hints)
{
cellHints = hints;
}
/**
* @return The hints of each edge.
*/
public Integer[] edgeHints()
{
return edgeHints;
}
/**
* To set the hints of the edges.
*
* @param hints
*/
public void setEdgeHints(final Integer[] hints)
{
edgeHints = hints;
}
/**
* @param type The SiteType.
* @return The hints corresponding to the type.
*/
public Integer[] hints(final SiteType type)
{
switch (type)
{
case Edge:
return edgeHints();
case Vertex:
return vertexHints();
case Cell:
return cellHints();
}
return new Integer[0];
}
/**
* @param type The SiteType.
* @return The regions with hints corresponding to the type.
*/
public Integer[][] withHints(final SiteType type)
{
switch (type)
{
case Edge:
return edgesWithHints();
case Vertex:
return verticesWithHints();
case Cell:
return cellsWithHints();
}
return new Integer[0][0];
}
}
| 27,087 | 25.121504 | 152 | java |
Ludii | Ludii-master/Core/src/game/equipment/Item.java | package game.equipment;
import java.util.BitSet;
import game.Game;
import game.types.play.RoleType;
import main.Constants;
import other.BaseLudeme;
import other.ItemType;
/**
* Provides a Grammar placeholder for items to go in the equipment collection.
*
* @author Eric and cambolbro
*/
public abstract class Item extends BaseLudeme
{
/** The owner of the item. */
private RoleType owner;
/** The type of the item. */
private ItemType type;
/** Unique index in the corresponding item's list of equipment in game. */
private int index = -1;
/** Unique name within game. */
private String name;
/** ID of owner */
private int ownerID = Constants.UNDEFINED;
//-------------------------------------------------------------------------
/**
* @param name The name of the item.
* @param index The index of the item.
* @param owner The owner of the item.
*/
public Item
(
final String name,
final int index,
final RoleType owner
)
{
this.name = name;
this.index = index;
this.owner = owner;
}
//-------------------------------------------------------------------------
/**
* Copy constructor.
*
* Protected because we do not want the compiler to detect it, this is call only
* in Clone method.
*
* @param other
*/
protected Item(final Item other)
{
owner = other.owner;
index = other.index;
name = other.name;
type = other.type;
}
/**
* @return Unique index in master game object's list of equipment.
*/
public int index()
{
return index;
}
/**
* To set the index.
*
* @param id
*/
public void setIndex(final int id)
{
index = id;
}
/**
* @return role.
*/
public RoleType role()
{
return owner;
}
/**
* To set the owner of the item.
*
* @param role
*/
public void setRole(final RoleType role)
{
owner = role;
}
/**
* To set the owner of the item according to the id of a player.
*
* @param pid
*/
public void setRoleFromPlayerId(final int pid)
{
owner = RoleType.roleForPlayerId(pid);
}
/**
* @return owner.
*/
public int owner()
{
return ownerID;
}
/**
* Makes sure this item is fully created
* @param game
*/
public void create(final Game game)
{
if (owner == RoleType.Shared || owner == RoleType.All)
ownerID = game.players().count() + 1;
else
ownerID = owner.owner();
}
/**
* @return Unique name within game.
*/
public String name()
{
return name;
}
/**
* To set the name of the item.
*
* @param name
*/
public void setName(final String name)
{
this.name = name;
}
/**
* @return The type of the item.
*/
public ItemType type()
{
return type;
}
/**
* To set the type of the item.
*
* @param type The type of the item.
*/
public void setType(final ItemType type)
{
this.type = type;
}
/**
* @param game The game.
* @return Accumulated flags for ludeme.
*/
@SuppressWarnings("static-method")
public long gameFlags(final Game game)
{
return 0l;
}
@Override
public BitSet concepts(final Game game)
{
return new BitSet();
}
@Override
public BitSet writesEvalContextRecursive()
{
return new BitSet();
}
@Override
public BitSet readsEvalContextRecursive()
{
return new BitSet();
}
//-------------------------------------------------------------------------
/**
* @return Credit details for images and other resources, else null.
* Default behaviour: no credits for this item.
*/
@SuppressWarnings("static-method")
public String credit()
{
return null;
}
}
| 3,560 | 15.79717 | 81 | java |
Ludii | Ludii-master/Core/src/game/equipment/package-info.java | /**
* @chapter The {\it equipment} of a game refers to the items with which it is played.
* These include {\it components} such as pieces, cards, tiles, dice, etc., and {\it containers} that
* hold the components, such as boards, decks, player hands, etc.
* Each container has an underlying graph that defines its playable sites and adjacencies between them.
*
* @section The following ludemes describe the equipment used to play the game.
*/
package game.equipment;
| 478 | 46.9 | 103 | java |
Ludii | Ludii-master/Core/src/game/equipment/component/Card.java | package game.equipment.component;
import java.io.Serializable;
import java.util.BitSet;
import annotations.Name;
import annotations.Opt;
import game.Game;
import game.rules.play.moves.Moves;
import game.types.component.CardType;
import game.types.play.RoleType;
import game.types.state.GameType;
import main.Constants;
import metadata.graphics.util.ComponentStyleType;
import other.concept.Concept;
/**
* Defines a card with specific properties such as the suit or the rank of the
* card in the deck.
*
* @author Eric.Piette
*
* @remarks This ludeme creates a specific card. If this ludeme is used with no
* deck defined, the generated card will be not included in a deck by
* default. See also Deck ludeme.
*/
public class Card extends Component implements Serializable
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/** Trump value. */
private final int trumpValue;
/** Suit value. */
private final int suit;
/** Trump rank. */
private final int trumpRank;
/** Rank. */
private final int rank;
/** Value of the card. */
private final int value;
/** The CardType. */
private final CardType cardType;
/**
* @param label The name of the card.
* @param role The owner of the card.
* @param cardType The type of a card chosen from the possibilities in the
* CardType ludeme.
* @param rank The rank of the card in the deck.
* @param value The value of the card.
* @param trumpRank The trump rank of the card in the deck.
* @param trumpValue The trump value of the card.
* @param suit The suit of the card.
* @param generator The moves associated with the component.
* @param maxState To set the maximum local state the game should check.
* @param maxCount To set the maximum count the game should check.
* @param maxValue To set the maximum value the game should check.
*
* @example (card "Card" Shared King rank:6 value:4 trumpRank:3 trumpValue:4
* suit:1)
*/
public Card
(
final String label,
final RoleType role,
final CardType cardType,
@Name final Integer rank,
@Name final Integer value,
@Name final Integer trumpRank,
@Name final Integer trumpValue,
@Name final Integer suit,
@Opt final Moves generator,
@Opt @Name final Integer maxState,
@Opt @Name final Integer maxCount,
@Opt @Name final Integer maxValue
)
{
super(label, role, null, null, generator, maxState, maxCount, maxValue);
this.trumpValue = (trumpValue == null) ? Constants.OFF : trumpValue.intValue();
this.suit = (suit == null) ? Constants.OFF : suit.intValue();
this.trumpRank = (trumpValue == null) ? Constants.OFF : trumpRank.intValue();
this.rank = (suit == null) ? Constants.OFF : rank.intValue();
this.cardType = cardType;
this.value = value.intValue();
style = ComponentStyleType.Card;
}
/**
* Copy constructor.
*
* Protected because we do not want the compiler to detect it, this is called
* only in Clone method.
*
* @param other
*/
protected Card(final Card other)
{
super(other);
cardType = other.cardType;
suit = other.suit;
trumpValue = other.trumpValue;
rank = other.rank;
value = other.value;
trumpRank = other.trumpRank;
}
@Override
public Card clone()
{
return new Card(this);
}
@Override
public boolean isCard()
{
return true;
}
@Override
public int suit()
{
return suit;
}
@Override
public int getValue()
{
return value;
}
@Override
public int trumpValue()
{
return trumpValue;
}
@Override
public int rank()
{
return rank;
}
@Override
public int trumpRank()
{
return trumpRank;
}
@Override
public CardType cardType()
{
return cardType;
}
@Override
public long gameFlags(final Game game)
{
return super.gameFlags(game) | GameType.Card;
}
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
concepts.or(super.concepts(game));
concepts.set(Concept.Card.id(), true);
return concepts;
}
@Override
public BitSet writesEvalContextRecursive()
{
final BitSet writeEvalContext = new BitSet();
writeEvalContext.or(super.writesEvalContextRecursive());
return writeEvalContext;
}
@Override
public BitSet readsEvalContextRecursive()
{
final BitSet readEvalContext = new BitSet();
readEvalContext.or(super.readsEvalContextRecursive());
return readEvalContext;
}
@Override
public boolean missingRequirement(final Game game)
{
boolean missingRequirement = false;
if (role() != null)
{
final int indexOwnerPhase = role().owner();
if (
(
indexOwnerPhase < 1
&&
!role().equals(RoleType.Shared)
&&
!role().equals(RoleType.Neutral)
&&
!role().equals(RoleType.All)
)
||
indexOwnerPhase > game.players().count()
)
{
game.addRequirementToReport(
"A card is defined in the equipment with an incorrect owner: " + role() + ".");
missingRequirement = true;
}
}
return missingRequirement;
}
} | 5,188 | 22.269058 | 85 | java |
Ludii | Ludii-master/Core/src/game/equipment/component/Component.java |
package game.equipment.component;
import java.util.BitSet;
import java.util.List;
import annotations.Hide;
import game.Game;
import game.equipment.Item;
import game.equipment.component.tile.Path;
import game.rules.play.moves.BaseMoves;
import game.rules.play.moves.Moves;
import game.types.board.SiteType;
import game.types.board.StepType;
import game.types.component.CardType;
import game.types.play.RoleType;
import game.util.directions.DirectionFacing;
import game.util.graph.Step;
import game.util.moves.Flips;
import gnu.trove.list.array.TIntArrayList;
import main.Constants;
import main.StringRoutines;
import metadata.graphics.util.ComponentStyleType;
import other.ItemType;
import other.concept.Concept;
import other.context.Context;
import other.topology.Topology;
/**
* Defines a component.
*
* @author cambolbro and Eric.Piette
*/
@SuppressWarnings("static-method")
public class Component extends Item implements Cloneable
{
/** Current direction that piece is facing. */
private DirectionFacing dirn;
/** Optional generator which creates moves for this piece on demand */
private Moves generator;
/** The pre-generation of the moves of the generator in an empty board. */
private boolean[][] potentialMoves;
/** In case of large Piece, the walk to describe the shape of the piece. */
private final StepType[][] walk;
/** Use to keep the label without the role of the player for graphics. */
protected String nameWithoutNumber;
/** The style of the component. */
protected ComponentStyleType style;
/** Bias values for dice, cards, etc. */
protected int[] bias;
/** The maximum local state the game should check. */
private final int maxState;
/** The maximum count the game should check. */
private final int maxCount;
/** The maximum value the game should check. */
private final int maxValue;
//-------------------------------------------------------------------------
/**
* @param label The name of the component.
* @param role The owner of the component.
* @param walk The walk used to generate a large piece.
* @param dirn The direction where face the component.
* @param generator The moves associated with the component.
* @param maxState To set the maximum local state the game should check.
* @param maxCount To set the maximum count the game should check.
* @param maxValue To set the maximum value the game should check.
*/
@Hide
public Component
(
final String label,
final RoleType role,
final StepType[][] walk,
final DirectionFacing dirn,
final Moves generator,
final Integer maxState,
final Integer maxCount,
final Integer maxValue
)
{
super(label, Constants.UNDEFINED, role);
this.walk = walk;
this.dirn = (dirn == null) ? null : dirn;
this.generator = generator;
setType(ItemType.Component);
this.maxState = (maxState != null) ? maxState.intValue() : Constants.OFF;
this.maxCount = (maxCount != null) ? maxCount.intValue() : Constants.OFF;
this.maxValue = (maxValue != null) ? maxValue.intValue() : Constants.OFF;
}
//-------------------------------------------------------------------------
/**
* @return direction.
*/
public DirectionFacing getDirn()
{
return dirn;
}
/**
* @return The first value (for dominoes).
*/
public int getValue()
{
return Constants.UNDEFINED;
}
/**
* @return The flips values.
*/
public Flips getFlips()
{
return null;
}
/**
* @return Optional generator of moves for pieces
*/
public Moves generator()
{
return generator;
}
/**
* @return The maximum local state for that component.
*/
public int maxState()
{
return maxState;
}
/**
* @return The maximum count for that component.
*/
public int maxCount()
{
return maxCount;
}
/**
* @return The maximum value for that component.
*/
public int maxValue()
{
return maxValue;
}
/**
* @param context
* @return List of moves, possibly empty.
*/
public Moves generate(final Context context)
{
if (generator != null)
return generator.eval(context);
return new BaseMoves(null);
}
//-------------------------------------------------------------------------
@Override
public boolean equals(final Object o)
{
if (!(o instanceof Component))
return false;
final Component comp = (Component)o;
return name().equals(comp.name());
}
//-------------------------------------------------------------------------
/**
* Copy constructor.
*
* Protected because we do not want the compiler to detect it, this is called
* only in Clone method.
*
* @param other
*/
protected Component(final Component other)
{
super(other);
dirn = other.dirn;
generator = other.generator;
if (other.bias != null)
{
bias = new int[other.bias.length];
for (int i = 0; i < other.bias.length; i++)
bias[i] = other.bias[i];
}
else
bias = null;
if (other.potentialMoves != null)
{
potentialMoves = new boolean[other.potentialMoves.length][];
for (int i = 0; i < other.potentialMoves.length; i++)
{
potentialMoves[i] = new boolean[other.potentialMoves[i].length];
for (final int j = 0; j < other.potentialMoves[i].length; i++)
potentialMoves[i][j] = other.potentialMoves[i][j];
}
}
else
potentialMoves = null;
if (other.walk != null)
{
walk = new StepType[other.walk.length][];
for (int i = 0; i < other.walk.length; i++)
{
walk[i] = new StepType[other.walk[i].length];
for (int j = 0; j < other.walk[i].length; j++)
walk[i][j] = other.walk[i][j];
}
}
else
walk = null;
style = other.style;
nameWithoutNumber = other.nameWithoutNumber;
maxState = other.maxState;
maxCount = other.maxCount;
maxValue = other.maxValue;
}
@Override
public Component clone()
{
return new Component(this);
}
//-------------------------------------------------------------------------
/**
* Set the direction of the piece.
*
* @param direction
*/
public void setDirection(final DirectionFacing direction)
{
dirn = direction;
}
/**
* To clone the generator.
*
* @param generator
*/
public void setMoves(final Moves generator)
{
this.generator=generator;
}
@Override
public int hashCode()
{
return super.hashCode();
}
//-------------------------------------------------------------------------
/**
* @return True if this is a large piece.
*/
public boolean isLargePiece()
{
return walk != null;
}
/**
* @return The walk in case of large piece.
*/
public StepType[][] walk()
{
return walk;
}
/**
* @param context The context of the game.
* @param startLoc The root of the large piece.
* @param state The local state of the root.
* @param topology The graph of the board.
*
* @return The locs occupied by a large piece from a location according to the
* state.
*/
public TIntArrayList locs(final Context context, final int startLoc, final int state, final Topology topology)
{
final int from = startLoc;
if (from >= topology.cells().size())
return new TIntArrayList();
final TIntArrayList sitesAfterWalk = new TIntArrayList();
final int realState = (state >= 0) ? state : 0;
final List<DirectionFacing> orthogonalSupported = topology.supportedOrthogonalDirections(SiteType.Cell);
if(orthogonalSupported.size() <= 0)
return sitesAfterWalk;
final DirectionFacing startDirection = orthogonalSupported.get(realState % orthogonalSupported.size());
sitesAfterWalk.add(from);
final int indexWalk = realState / orthogonalSupported.size();
if(indexWalk >= walk.length)
return sitesAfterWalk;
final StepType[] steps = walk[indexWalk];
int currentLoc = from;
DirectionFacing currentDirection = startDirection;
for (final StepType step : steps)
{
if (step == StepType.F)
{
final List<Step> stepsDirection = topology.trajectories().steps(SiteType.Cell, currentLoc, currentDirection.toAbsolute());
int to = Constants.UNDEFINED;
for (final Step stepDirection : stepsDirection)
{
if (stepDirection.from().siteType() != stepDirection.to().siteType())
continue;
to = stepDirection.to().id();
}
// No correct walk with that state.
if (to == Constants.UNDEFINED)
return new TIntArrayList();
if (!sitesAfterWalk.contains(to))
sitesAfterWalk.add(to);
currentLoc = to;
}
else if (step == StepType.R)
{
currentDirection = currentDirection.right();
while (!orthogonalSupported.contains(currentDirection))
currentDirection = currentDirection.right();
}
else if (step == StepType.L)
{
currentDirection = currentDirection.left();
while (!orthogonalSupported.contains(currentDirection))
currentDirection = currentDirection.left();
}
}
return sitesAfterWalk;
}
/**
* @return The biased values of a die.
*/
public int[] getBias()
{
return bias;
}
/**
* To set the biased values of a die.
*
* @param biased The biased values.
*/
public void setBiased(final Integer[] biased)
{
if (biased != null)
{
bias = new int[biased.length];
for(int i = 0; i < biased.length; i++)
bias[i] = biased[i].intValue();
}
}
/**
* @param from
* @param to
* @return True if a move is potentially legal.
*/
public boolean possibleMove(final int from, final int to)
{
return potentialMoves[from][to];
}
/**
* @return Full matrix of all potential moves for this component type.
*/
public boolean[][] possibleMoves()
{
return potentialMoves;
}
/**
* To set the possible moves.
*
* @param possibleMoves
*/
public void setPossibleMove(final boolean[][] possibleMoves)
{
potentialMoves = possibleMoves;
}
//---------------------DIE--------------------------------
/**
* @return True if this component is a die.
*/
public boolean isDie()
{
return false;
}
/**
* @return The faces of a die.
*/
public int[] getFaces()
{
return new int[0];
}
/**
* @return The number of faces of a die.
*/
public int getNumFaces()
{
return Constants.UNDEFINED;
}
/**
* For rolling a die and returning its new value.
*
* @param context The context.
* @return The new value.
*/
public int roll(final Context context)
{
return Constants.OFF;
}
/**
* To set the faces of a die.
*
* @param faces The faces of the die.
* @param start The value corresponding to the first face.
*/
public void setFaces(final Integer[] faces, final Integer start)
{
// Nothing to do.
}
//---------------------CARD--------------------------------
/**
* @return True if this component is a card.
*/
public boolean isCard()
{
return false;
}
/**
* @return The suit value of a component.
*/
public int suit()
{
return Constants.OFF;
}
/**
* @return The trump value of a component.
*/
public int trumpValue()
{
return Constants.OFF;
}
/**
* @return The rank value of a component.
*/
public int rank()
{
return Constants.OFF;
}
/**
* @return The trump rank of a component.
*/
public int trumpRank()
{
return Constants.OFF;
}
/**
* @return The cardtype of the component.
*/
public CardType cardType()
{
return null;
}
//---------------------TILE--------------------------------
/**
* @return True if this is a tile piece.
*/
public boolean isTile()
{
return false;
}
/**
* @return The terminus of a tile pieces
*/
public int[] terminus()
{
return null;
}
/**
* @return The number of terminus of a tile pieces if this number is equal for
* all the sides.
*/
public Integer numTerminus()
{
return Integer.valueOf(Constants.OFF);
}
/**
* @return The number of sides of a tile piece.
*/
public int numSides()
{
return Constants.OFF;
}
/**
* To set the number of sides of a tile piece.
*
* @param numSides The number of sides.
*/
public void setNumSides(final int numSides)
{
// Nothing to do.
}
/**
* @return The paths of a Tile piece.
*/
public Path[] paths()
{
return null;
}
/**
* @param game The game.
* @return Accumulated flags for ludeme.
*/
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
if (dirn != null)
concepts.set(Concept.PieceDirection.id(), true);
return new BitSet();
}
@Override
public BitSet writesEvalContextRecursive()
{
final BitSet writeEvalContext = new BitSet();
if (generator != null)
writeEvalContext.or(generator.writesEvalContextRecursive());
return writeEvalContext;
}
@Override
public BitSet readsEvalContextRecursive()
{
final BitSet readEvalContext = new BitSet();
if (generator != null)
readEvalContext.or(generator.readsEvalContextRecursive());
return readEvalContext;
}
//---------------------DOMINO--------------------------------
/**
* @return If the domino is a double
*/
public boolean isDoubleDomino()
{
return false;
}
/**
* @return The second value (for Domino).
*/
public int getValue2()
{
return Constants.OFF;
}
/**
* @return True if this component is a domino.
*/
public boolean isDomino()
{
return false;
}
/**
* @return name of the piece without the owner.
*/
public String getNameWithoutNumber()
{
return nameWithoutNumber;
}
/**
* Set name of the piece without the owner.
*
* @param name The name of the piece.
*/
public void setNameWithoutNumber(final String name)
{
nameWithoutNumber = name;
}
/**
* @return The ComponentStyleType.
*/
public ComponentStyleType style()
{
return style;
}
/**
* @param st
*/
public void setStyle(final ComponentStyleType st)
{
style = st;
}
//-------------------------------------------------------------------------
@Override
public String credit()
{
//-----------------------------------------------------
// Common/res/img/svg
if (nameWithoutNumber.equalsIgnoreCase("Sandbox"))
return nameWithoutNumber + " image from https://www.pngwing.com/en/free-png-nmodo.";
//-----------------------------------------------------
// Common/res/img/svg/animals
if (nameWithoutNumber.equalsIgnoreCase("Bear"))
return nameWithoutNumber + " image by Freepik from http://www.flaticon.com.";
if (nameWithoutNumber.equalsIgnoreCase("Seal"))
return nameWithoutNumber + " image by Freepik from http://www.flaticon.com.";
if (nameWithoutNumber.equalsIgnoreCase("Camel"))
return nameWithoutNumber + " image from https://www.pngrepo.com/svg/297513/camel.";
if (nameWithoutNumber.equalsIgnoreCase("Cat"))
return nameWithoutNumber + " image from http://getdrawings.com/cat-head-icon#cat-head-icon-8.png.";
if (nameWithoutNumber.equalsIgnoreCase("Chicken"))
return nameWithoutNumber + " image by Stila from https://favpng.com/png_view/.";
if (nameWithoutNumber.equalsIgnoreCase("Cow"))
return nameWithoutNumber + " image from https://www.nicepng.com/ourpic/u2w7o0t4e6y3a9u2_animals-chinese-new-year-icon/.";
if (nameWithoutNumber.equalsIgnoreCase("Dog"))
return nameWithoutNumber + " image from https://favpng.com/png_view/albatross-gray-wolf-clip-art-png/R6VmvfkC.";
if (nameWithoutNumber.equalsIgnoreCase("Crab"))
return nameWithoutNumber + " image by Freepik from http://www.flaticon.com.";
if (nameWithoutNumber.equalsIgnoreCase("Dog"))
return nameWithoutNumber + " image from https://www.pngwing.com/en/free-png-hwzbd.";
if (nameWithoutNumber.equalsIgnoreCase("Dove"))
return nameWithoutNumber + " image from https://www.pngwing.com/en/free-png-xxwye.";
if (nameWithoutNumber.equalsIgnoreCase("Dragon"))
return nameWithoutNumber + " image from https://ya-webdesign.com/imgdownload.html";
if (nameWithoutNumber.equalsIgnoreCase("Duck"))
return nameWithoutNumber + " image from https://ya-webdesign.com/imgdownload.html";
if (nameWithoutNumber.equalsIgnoreCase("Eagle"))
return nameWithoutNumber + " image from https://www.pngbarn.com/png-image-tgmlh.";
if (nameWithoutNumber.equalsIgnoreCase("Elephant"))
return nameWithoutNumber + " image from http://getdrawings.com/get-icon#elephant-icon-app-2.png.";
if (nameWithoutNumber.equalsIgnoreCase("Fish"))
return nameWithoutNumber + " image from https://www.svgrepo.com/svg/109765/fish.";
if (nameWithoutNumber.equalsIgnoreCase("Chick"))
return nameWithoutNumber + " image from https://www.svgrepo.com/svg/123529/bird.";
if (nameWithoutNumber.equalsIgnoreCase("Hyena"))
return nameWithoutNumber + " image from https://www.svgrepo.com/svg/1841/hyena-head.";
if (nameWithoutNumber.equalsIgnoreCase("Fox"))
return nameWithoutNumber + " image from https://www.svgrepo.com/svg/40267/fox.";
if (nameWithoutNumber.equalsIgnoreCase("Goat"))
return nameWithoutNumber + " image from https://ya-webdesign.com/imgdownload.html.";
if (nameWithoutNumber.equalsIgnoreCase("Goose"))
return nameWithoutNumber + " image from https://depositphotos.com/129413072/stock-illustration-web-goose-icon.html.";
if (nameWithoutNumber.equalsIgnoreCase("Hare"))
return nameWithoutNumber + " image by Freepik from https://www.flaticon.com/free-icon/.";
if (nameWithoutNumber.equalsIgnoreCase("Horse"))
return nameWithoutNumber + " image from https://commons.wikimedia.org/wiki/File:Chess_tile_nl.svg.";
if (nameWithoutNumber.equalsIgnoreCase("Jaguar"))
return nameWithoutNumber + " image from https://icons8.com/icons/set/jaguar.";
if (nameWithoutNumber.equalsIgnoreCase("Lamb"))
return nameWithoutNumber + " image from https://ya-webdesign.com/imgdownload.html.";
if (nameWithoutNumber.equalsIgnoreCase("Leopard"))
return nameWithoutNumber + " image from https://www.svgrepo.com/svg/297517/leopard.";
if (nameWithoutNumber.equalsIgnoreCase("Lion"))
return nameWithoutNumber + " image by Freepik from https://www.flaticon.com/free-icon/.";
if (nameWithoutNumber.equalsIgnoreCase("Lioness"))
return nameWithoutNumber + " image by Freepik from https://www.flaticon.com/free-icon/.";
if (nameWithoutNumber.equalsIgnoreCase("Monkey"))
return nameWithoutNumber + " image from https://www.pngbarn.com/png-image-eonln.";
if (nameWithoutNumber.equalsIgnoreCase("Mountainlion"))
return nameWithoutNumber + " image by Tae S Yang from https://icon-icons.com/nl/pictogram/puma-dier/123525.";
if (nameWithoutNumber.equalsIgnoreCase("Mouse"))
return nameWithoutNumber + " image by Freepik from https://www.flaticon.com/free-icon/mouse_235093.";
if (nameWithoutNumber.equalsIgnoreCase("Ox"))
return nameWithoutNumber + " image from https://www.svgrepo.com/svg/19280/cattle-skull.";
if (nameWithoutNumber.equalsIgnoreCase("Panther"))
return nameWithoutNumber + " image by Freepik from https://www.flaticon.com/free-icon/cat-face-outline_57104.";
if (nameWithoutNumber.equalsIgnoreCase("Penguin"))
return nameWithoutNumber + " image from https://ya-webdesign.com/imgdownload.html.";
if (nameWithoutNumber.equalsIgnoreCase("Prawn"))
return nameWithoutNumber + " image by Freepik from https://www.flaticon.com/free-icon/prawn_202274.";
if (nameWithoutNumber.equalsIgnoreCase("Puma"))
return nameWithoutNumber + " image by Tae S Yang from https://icon-icons.com/nl/pictogram/puma-dier/123525.";
if (nameWithoutNumber.equalsIgnoreCase("Rabbit"))
return nameWithoutNumber + " image from https://ya-webdesign.com/imgdownload.html.";
if (nameWithoutNumber.equalsIgnoreCase("Rat"))
return nameWithoutNumber + " image from https://webstockreview.net/image/clipart-rat-head-cartoon/642646.html.";
if (nameWithoutNumber.equalsIgnoreCase("Rhino"))
return nameWithoutNumber + " image by Freepik from https://www.flaticon.com/free-icon/.";
if (nameWithoutNumber.equalsIgnoreCase("Seal"))
return nameWithoutNumber + " image by Freepik from https://www.flaticon.com/free-icon/.";
if (nameWithoutNumber.equalsIgnoreCase("Sheep"))
return nameWithoutNumber + " image from https://www.pngwing.com/en/free-png-nirzv.";
if (nameWithoutNumber.equalsIgnoreCase("Snake"))
return nameWithoutNumber + " image by Freepik from https://www.flaticon.com/free-icon/.";
if (nameWithoutNumber.equalsIgnoreCase("Tiger"))
return nameWithoutNumber + " image from https://www.pngwing.com/en/free-png-hbgdy.";
if (nameWithoutNumber.equalsIgnoreCase("Wolf"))
return nameWithoutNumber + " image by Freepik from https://www.flaticon.com.";
//-----------------------------------------------------
// Common/res/img/svg/cards
if (nameWithoutNumber.equalsIgnoreCase("Jack"))
return nameWithoutNumber + " image by popicon from https://www.shutterstock.com.";
if (nameWithoutNumber.equalsIgnoreCase("Joker"))
return nameWithoutNumber + " image \"Joker Icon\" from https://icons8.com.";
if (nameWithoutNumber.equalsIgnoreCase("King"))
return nameWithoutNumber + " image from https://www.pngwing.com/en/free-png-ptuag.";
if (nameWithoutNumber.equalsIgnoreCase("Queen"))
return nameWithoutNumber + " image from https://www.pngguru.com/free-transparent-background-png-clipart-tlaxu.";
if (nameWithoutNumber.equalsIgnoreCase("Card-suit-club"))
return nameWithoutNumber + " image from https://en.wikipedia.org/wiki/File:Card_club.svg.";
if (nameWithoutNumber.equalsIgnoreCase("Card-suit-diamond"))
return nameWithoutNumber + " image from https://en.wikipedia.org/wiki/File:Card_diamond.svg.";
if (nameWithoutNumber.equalsIgnoreCase("Card-suit-heart"))
return nameWithoutNumber + " image from https://en.wikipedia.org/wiki/File:Card_heart.svg.";
if (nameWithoutNumber.equalsIgnoreCase("Card-suit-spade"))
return nameWithoutNumber + " image from https://en.wikipedia.org/wiki/File:Card_spade.svg.";
if (nameWithoutNumber.equalsIgnoreCase("CardBack"))
return nameWithoutNumber + " image from Symbola TTF font.";
//-----------------------------------------------------
// Common/res/img/svg/checkers
if
(
nameWithoutNumber.equalsIgnoreCase("counter")
||
nameWithoutNumber.equalsIgnoreCase("counterstar")
||
nameWithoutNumber.equalsIgnoreCase("doublecounter")
)
return nameWithoutNumber + " image from Symbola TTF font.";
//-----------------------------------------------------
// Common/res/img/svg/chess
if
(
nameWithoutNumber.equalsIgnoreCase("Bishop")
||
nameWithoutNumber.equalsIgnoreCase("King")
||
nameWithoutNumber.equalsIgnoreCase("Knight")
||
nameWithoutNumber.equalsIgnoreCase("Pawn")
||
nameWithoutNumber.equalsIgnoreCase("Queen")
||
nameWithoutNumber.equalsIgnoreCase("Rook")
)
return nameWithoutNumber + " images from the Casefont, Arial Unicode MS, PragmataPro and Symbola TTF fonts.";
//-----------------------------------------------------
// Common/res/img/svg/faces
if
(
nameWithoutNumber.equalsIgnoreCase("symbola_cool")
||
nameWithoutNumber.equalsIgnoreCase("symbola_happy")
||
nameWithoutNumber.equalsIgnoreCase("symbola_neutral")
||
nameWithoutNumber.equalsIgnoreCase("symbola_pleased")
||
nameWithoutNumber.equalsIgnoreCase("symbola_sad")
||
nameWithoutNumber.equalsIgnoreCase("symbola_scared")
||
nameWithoutNumber.equalsIgnoreCase("symbola_worried")
)
return nameWithoutNumber + " image from Symbola TTF font.";
//-----------------------------------------------------
// Common/res/img/svg/fairyChess
if (nameWithoutNumber.equalsIgnoreCase("Amazon"))
return nameWithoutNumber + " image from images from the Arial Unicode MS, PragmataPro and Symbola \\n\"\n" +
"TTF fonts and https://www.pngwing.com.";
if (nameWithoutNumber.equalsIgnoreCase("Bishop_noCross"))
return nameWithoutNumber + " images from the Arial Unicode MS, PragmataPro and Symbola \\n\"\n" +
"TTF fonts and https://www.pngwing.com.";
if (nameWithoutNumber.equalsIgnoreCase("Boat"))
return nameWithoutNumber + " image by Freepik from https://www.flaticon.com/free-icon/viking-ship_22595.";
if (nameWithoutNumber.equalsIgnoreCase("Cannon"))
return nameWithoutNumber + " image from https://www.pngbarn.com/.";
if (nameWithoutNumber.equalsIgnoreCase("Chariot"))
return nameWithoutNumber + " image by Freepik from https://www.flaticon.com/free-icon/wheel_317722.";
if (nameWithoutNumber.equalsIgnoreCase("Commoner"))
return nameWithoutNumber + " image by Sunny3113 from \n" +
"https://commons.wikimedia.org/wiki/File:Commoner_Transparent.svg \n" +
"under license https://creativecommons.org/licenses/by-sa/4.0/deed.en.";
if (nameWithoutNumber.equalsIgnoreCase("Ferz_noCross"))
return nameWithoutNumber + " images from the Arial Unicode MS, PragmataPro and Symbola \n" +
"TTF fonts and https://www.pngwing.com.";
if (nameWithoutNumber.equalsIgnoreCase("Ferz"))
return nameWithoutNumber + " images from the Arial Unicode MS, PragmataPro and Symbola \n" +
"TTF fonts and https://www.pngwing.com.";
if (nameWithoutNumber.equalsIgnoreCase("Flag"))
return nameWithoutNumber + " image from https://www.pngwing.com/en/free-png-siuwt.";
if (nameWithoutNumber.equalsIgnoreCase("Fool"))
return nameWithoutNumber + " image by Mykola Dolgalov based on Omega Chess Advanced from \n" +
"https://commons.wikimedia.org/wiki/File:Chess_tll45.svg under \n" +
"license https://creativecommons.org/licenses/by-sa/3.0/deed.en.";
if (nameWithoutNumber.equalsIgnoreCase("Giraffe"))
return nameWithoutNumber + " image from https://www.pngfuel.com/free-png/tfali.";
if (nameWithoutNumber.equalsIgnoreCase("King_noCross"))
return nameWithoutNumber + " images from the Arial Unicode MS, PragmataPro and Symbola \\n\"\n" +
"TTF fonts and https://www.pngwing.com.";
if (nameWithoutNumber.equalsIgnoreCase("Knight_bishop"))
return nameWithoutNumber + " image by OMega Chess Fan derivative work of NikNaks93 from \n" +
"https://en.wikipedia.org/wiki/Princess_(chess)#/media/File:Chess_alt45.svg under \n" +
"license https://creativecommons.org/licenses/by-sa/3.0/.";
if (nameWithoutNumber.equalsIgnoreCase("Knight_king"))
return nameWithoutNumber + " image from https://www.pngwing.com/en/free-png-ynnmd.";
if (nameWithoutNumber.equalsIgnoreCase("Knight_queen"))
return nameWithoutNumber + " image bu NikNaks from https://commons.wikimedia.org/wiki/File:Chess_Alt26.svg \n" +
"under license https://creativecommons.org/licenses/by-sa/3.0/deed.en.";
if (nameWithoutNumber.equalsIgnoreCase("Knight_rook"))
return nameWithoutNumber + " image byfrom https://en.wikipedia.org/wiki/Empress_(chess)#/media/File:Chess_clt45.svg.";
if (nameWithoutNumber.equalsIgnoreCase("Knight-rotated"))
return nameWithoutNumber + " image from the Arial Unicode MS, PragmataPro and Symbola \\n\"\n" +
"TTF fonts and https://www.pngwing.com.";
if (nameWithoutNumber.equalsIgnoreCase("Mann"))
return nameWithoutNumber + " image by CheChe from the original by LithiumFlash from \n" +
"https://commons.wikimedia.org/wiki/File:Chess_Mlt45.svg.";
if (nameWithoutNumber.equalsIgnoreCase("Moon"))
return nameWithoutNumber + " image from https://www.freeiconspng.com.";
if (nameWithoutNumber.equalsIgnoreCase("Unicorn"))
return nameWithoutNumber + " image by CBurnett and Francois-Pier from \n" +
"https://commons.wikimedia.org/wiki/File:Chess_Ult45.svg under \n" +
"license https://www.gnu.org/licenses/gpl-3.0.html.";
if (nameWithoutNumber.equalsIgnoreCase("Wazir"))
return nameWithoutNumber + " images from the Arial Unicode MS, PragmataPro and Symbola \\n\"\n" +
"TTF fonts and https://www.pngwing.com.";
if (nameWithoutNumber.equalsIgnoreCase("Zebra-neck"))
return nameWithoutNumber + " image from https://imgbin.com/png/qH6bNDwM/.";
if (nameWithoutNumber.equalsIgnoreCase("Zebra"))
return nameWithoutNumber + " image by Francois-PIer after CBurnett from \n" +
"https://commons.wikimedia.org/wiki/File:Chess_Zlt45.svg under \n" +
"license https://creativecommons.org/licenses/by-sa/3.0/deed.en.";
//-----------------------------------------------------
// Common/res/img/svg/hands
if
(
nameWithoutNumber.equalsIgnoreCase("hand0")
||
nameWithoutNumber.equalsIgnoreCase("hand1")
||
nameWithoutNumber.equalsIgnoreCase("hand2")
||
nameWithoutNumber.equalsIgnoreCase("hand3")
||
nameWithoutNumber.equalsIgnoreCase("hand4")
||
nameWithoutNumber.equalsIgnoreCase("hand5")
||
nameWithoutNumber.equalsIgnoreCase("paper")
||
nameWithoutNumber.equalsIgnoreCase("rock")
||
nameWithoutNumber.equalsIgnoreCase("scissors")
)
return nameWithoutNumber + " image based on \"Click - Index Finger Clip Art\" by Adanteh \n" +
"from https://favpng.com/png_view/click-index-finger-clip-art-png/NJXExGMM.";
//-----------------------------------------------------
// Common/res/img/svg/hieroglyphs
if
(
nameWithoutNumber.equalsIgnoreCase("2human_knee")
||
nameWithoutNumber.equalsIgnoreCase("2human")
||
nameWithoutNumber.equalsIgnoreCase("3ankh_side")
||
nameWithoutNumber.equalsIgnoreCase("3ankh")
||
nameWithoutNumber.equalsIgnoreCase("3bird")
||
nameWithoutNumber.equalsIgnoreCase("3nefer")
||
nameWithoutNumber.equalsIgnoreCase("ankh_waset")
||
nameWithoutNumber.equalsIgnoreCase("water")
||
nameWithoutNumber.equalsIgnoreCase("senetpiece")
||
nameWithoutNumber.equalsIgnoreCase("senetpiece2")
)
return nameWithoutNumber + " image part of the AegyptusSubset TTF font , from:\n" +
"https://mjn.host.cs.st-andrews.ac.uk/egyptian/fonts/newgardiner.html.";
//-----------------------------------------------------
// Common/res/img/svg/janggi
if
(
nameWithoutNumber.equalsIgnoreCase("Byeong")
||
nameWithoutNumber.equalsIgnoreCase("Cha")
||
nameWithoutNumber.equalsIgnoreCase("Cho")
||
nameWithoutNumber.equalsIgnoreCase("Han")
||
nameWithoutNumber.equalsIgnoreCase("Jol")
||
nameWithoutNumber.equalsIgnoreCase("Majanggi")
||
nameWithoutNumber.equalsIgnoreCase("Po")
||
nameWithoutNumber.equalsIgnoreCase("Sa")
||
nameWithoutNumber.equalsIgnoreCase("Sang")
)
return nameWithoutNumber + " image created by Matthew Stephenson for Ludii from the Casefont TTF font.";
//-----------------------------------------------------
// Common/res/img/svg/letters
if (nameWithoutNumber.length() == 1)
{
final char ch = Character.toUpperCase(nameWithoutNumber.charAt(0));
if (ch >= 'A' && ch <= 'Z')
return nameWithoutNumber + " image from the Arial TTF font.";
else if (ch >= '9' && ch <= '0')
return nameWithoutNumber + " image from the Arial TTF font.";
}
//-----------------------------------------------------
// Common/res/img/svg/mahjong
if
(
nameWithoutNumber.equalsIgnoreCase("BambooOne")
||
nameWithoutNumber.equalsIgnoreCase("BambooTwo")
||
nameWithoutNumber.equalsIgnoreCase("BambooThree")
||
nameWithoutNumber.equalsIgnoreCase("BambooFour")
||
nameWithoutNumber.equalsIgnoreCase("BambooFive")
||
nameWithoutNumber.equalsIgnoreCase("BambooSix")
||
nameWithoutNumber.equalsIgnoreCase("BambooSeven")
||
nameWithoutNumber.equalsIgnoreCase("BambooEight")
||
nameWithoutNumber.equalsIgnoreCase("BambooNine")
||
nameWithoutNumber.equalsIgnoreCase("CharacterOne")
||
nameWithoutNumber.equalsIgnoreCase("CharacterTwo")
||
nameWithoutNumber.equalsIgnoreCase("CharacterThree")
||
nameWithoutNumber.equalsIgnoreCase("CharacterFour")
||
nameWithoutNumber.equalsIgnoreCase("CharacterFive")
||
nameWithoutNumber.equalsIgnoreCase("CharacterSix")
||
nameWithoutNumber.equalsIgnoreCase("CharacterSeven")
||
nameWithoutNumber.equalsIgnoreCase("CharacterEight")
||
nameWithoutNumber.equalsIgnoreCase("CharacterNine")
||
nameWithoutNumber.equalsIgnoreCase("CircleOne")
||
nameWithoutNumber.equalsIgnoreCase("CircleTwo")
||
nameWithoutNumber.equalsIgnoreCase("CircleThree")
||
nameWithoutNumber.equalsIgnoreCase("CircleFour")
||
nameWithoutNumber.equalsIgnoreCase("CircleFive")
||
nameWithoutNumber.equalsIgnoreCase("CircleSix")
||
nameWithoutNumber.equalsIgnoreCase("CircleSeven")
||
nameWithoutNumber.equalsIgnoreCase("CircleEight")
||
nameWithoutNumber.equalsIgnoreCase("CircleNine")
||
nameWithoutNumber.equalsIgnoreCase("DragonGreen")
||
nameWithoutNumber.equalsIgnoreCase("DragonRed")
||
nameWithoutNumber.equalsIgnoreCase("DragonWhite")
||
nameWithoutNumber.equalsIgnoreCase("FlowerBamboo")
||
nameWithoutNumber.equalsIgnoreCase("FlowerChrysanthemum")
||
nameWithoutNumber.equalsIgnoreCase("FlowerOrchid")
||
nameWithoutNumber.equalsIgnoreCase("FlowerPlum")
||
nameWithoutNumber.equalsIgnoreCase("SeasonAutumn")
||
nameWithoutNumber.equalsIgnoreCase("SeasonSpring")
||
nameWithoutNumber.equalsIgnoreCase("SeasonSummer")
||
nameWithoutNumber.equalsIgnoreCase("SeasonWinter")
||
nameWithoutNumber.equalsIgnoreCase("TileBack")
||
nameWithoutNumber.equalsIgnoreCase("TileJoker")
||
nameWithoutNumber.equalsIgnoreCase("WindEast")
||
nameWithoutNumber.equalsIgnoreCase("WindNorth")
||
nameWithoutNumber.equalsIgnoreCase("WindSouth")
||
nameWithoutNumber.equalsIgnoreCase("WindWest")
)
return nameWithoutNumber + " image from the Symbola TTF font.";
//-----------------------------------------------------
// Common/res/img/svg/misc
if (nameWithoutNumber.equalsIgnoreCase("bean"))
return nameWithoutNumber + " image from svgrepo.com.";
if (nameWithoutNumber.equalsIgnoreCase("crown"))
return nameWithoutNumber + " image from svgrepo.com.";
if (nameWithoutNumber.equalsIgnoreCase("bike"))
return nameWithoutNumber + " image from svgrepo.com.";
if (nameWithoutNumber.equalsIgnoreCase("bread"))
return nameWithoutNumber + " image from svgrepo.com.";
if (nameWithoutNumber.equalsIgnoreCase("car"))
return nameWithoutNumber + " image from svgrepo.com.";
if (nameWithoutNumber.equalsIgnoreCase("castle"))
return nameWithoutNumber + " image from svgrepo.com.";
if (nameWithoutNumber.equalsIgnoreCase("cone"))
return nameWithoutNumber + " image from svgrepo.com.";
if (nameWithoutNumber.equalsIgnoreCase("corn"))
return nameWithoutNumber + " image from svgrepo.com.";
if (nameWithoutNumber.equalsIgnoreCase("cross"))
return nameWithoutNumber + " image from svgrepo.com.";
if (nameWithoutNumber.equalsIgnoreCase("minus"))
return nameWithoutNumber + " image from svgrepo.com.";
if (nameWithoutNumber.equalsIgnoreCase("diamond"))
return nameWithoutNumber + " image from svgrepo.com.";
if (nameWithoutNumber.equalsIgnoreCase("disc"))
return nameWithoutNumber + " image from svgrepo.com.";
if (nameWithoutNumber.equalsIgnoreCase("discDouble"))
return nameWithoutNumber + " edited image from svgrepo.com.";
if (nameWithoutNumber.equalsIgnoreCase("discDoubleStick"))
return nameWithoutNumber + " edited image from svgrepo.com.";
if (nameWithoutNumber.equalsIgnoreCase("discStick"))
return nameWithoutNumber + " image from svgrepo.com.";
if (nameWithoutNumber.equalsIgnoreCase("dot"))
return nameWithoutNumber + " image from svgrepo.com.";
if (nameWithoutNumber.equalsIgnoreCase("egyptLion"))
return nameWithoutNumber + " image part of the AegyptusSubset TTF font, from:\n" +
"https://mjn.host.cs.st-andrews.ac.uk/egyptian/fonts/newgardiner.html.";
if (nameWithoutNumber.equalsIgnoreCase("fan"))
return nameWithoutNumber + " image created by Dale Walton.";
if (nameWithoutNumber.equalsIgnoreCase("flower"))
return nameWithoutNumber + " image from svgrepo.com.";
if (nameWithoutNumber.equalsIgnoreCase("flowerHalf1"))
return nameWithoutNumber + " edited image from svgrepo.com.";
if (nameWithoutNumber.equalsIgnoreCase("flowerHalf2"))
return nameWithoutNumber + " edited image from svgrepo.com.";
if (nameWithoutNumber.equalsIgnoreCase("hex"))
return nameWithoutNumber + " image from svgrepo.com.";
if (nameWithoutNumber.equalsIgnoreCase("hexE"))
return nameWithoutNumber + " image from svgrepo.com.";
if (nameWithoutNumber.equalsIgnoreCase("heptagon"))
return nameWithoutNumber + " image from https://commons.wikimedia.org/wiki/File:Heptagon.svg.";
if (nameWithoutNumber.equalsIgnoreCase("none"))
return nameWithoutNumber + " edited image from svgrepo.com.";
if (nameWithoutNumber.equalsIgnoreCase("octagon"))
return nameWithoutNumber + " image from svgrepo.com.";
if (nameWithoutNumber.equalsIgnoreCase("paddle"))
return nameWithoutNumber + " edited image from svgrepo.com.";
if (nameWithoutNumber.equalsIgnoreCase("pentagon"))
return nameWithoutNumber + " image from svgrepo.com.";
if (nameWithoutNumber.equalsIgnoreCase("pyramid"))
return nameWithoutNumber + " image from svgrepo.com.";
if (nameWithoutNumber.equalsIgnoreCase("rectangle"))
return nameWithoutNumber + " image from svgrepo.com.";
if (nameWithoutNumber.equalsIgnoreCase("square"))
return nameWithoutNumber + " image from svgrepo.com.";
if (nameWithoutNumber.equalsIgnoreCase("star"))
return nameWithoutNumber + " image from svgrepo.com.";
if (nameWithoutNumber.equalsIgnoreCase("starOutline"))
return nameWithoutNumber + " image from svgrepo.com.";
if (nameWithoutNumber.equalsIgnoreCase("thinCross"))
return nameWithoutNumber + " image from svgrepo.com.";
if (nameWithoutNumber.equalsIgnoreCase("triangle"))
return nameWithoutNumber + " image from svgrepo.com.";
if (nameWithoutNumber.equalsIgnoreCase("urpiece"))
return nameWithoutNumber + " image created by Matthew Stephenson for Ludii.";
if (nameWithoutNumber.equalsIgnoreCase("waves"))
return nameWithoutNumber + " image from svgrepo.com.";
if (nameWithoutNumber.equalsIgnoreCase("oldMan"))
return nameWithoutNumber + " image from svgrepo.com.";
if (nameWithoutNumber.equalsIgnoreCase("boy"))
return nameWithoutNumber + " image from svgrepo.com.";
if (nameWithoutNumber.equalsIgnoreCase("theseus"))
return nameWithoutNumber + " image from svgrepo.com.";
if (nameWithoutNumber.equalsIgnoreCase("minotaur"))
return nameWithoutNumber + " image from https://www.flaticon.com/free-icon/minotaur_1483069.";
if (nameWithoutNumber.equalsIgnoreCase("robot"))
return nameWithoutNumber + " image from svgrepo.com.";
if (nameWithoutNumber.equalsIgnoreCase("door"))
return nameWithoutNumber + " image from svgrepo.com.";
if (nameWithoutNumber.equalsIgnoreCase("human"))
return nameWithoutNumber + " image from svgrepo.com.";
if (nameWithoutNumber.equalsIgnoreCase("rubble"))
return nameWithoutNumber + " image from svgrepo.com.";
//-----------------------------------------------------
// Common/res/img/svg/ploy
if
(
nameWithoutNumber.equalsIgnoreCase("Commander")
||
nameWithoutNumber.equalsIgnoreCase("LanceT")
||
nameWithoutNumber.equalsIgnoreCase("LanceW")
||
nameWithoutNumber.equalsIgnoreCase("LanceY")
||
nameWithoutNumber.equalsIgnoreCase("ProbeBigV")
||
nameWithoutNumber.equalsIgnoreCase("ProbeMinV")
||
nameWithoutNumber.equalsIgnoreCase("Shield")
)
return nameWithoutNumber + " image created by Matthew Stephenson for Ludii.";
//-----------------------------------------------------
// Common/res/img/svg/salta
if
(
nameWithoutNumber.equalsIgnoreCase("Salta1Dot")
||
nameWithoutNumber.equalsIgnoreCase("Salta2Dot")
||
nameWithoutNumber.equalsIgnoreCase("Salta3Dot")
||
nameWithoutNumber.equalsIgnoreCase("Salta4Dot")
||
nameWithoutNumber.equalsIgnoreCase("Salta5Dot")
||
nameWithoutNumber.equalsIgnoreCase("Salta1Moon")
||
nameWithoutNumber.equalsIgnoreCase("Salta2Moon")
||
nameWithoutNumber.equalsIgnoreCase("Salta3Moon")
||
nameWithoutNumber.equalsIgnoreCase("Salta4Moon")
||
nameWithoutNumber.equalsIgnoreCase("Salta5Moon")
||
nameWithoutNumber.equalsIgnoreCase("Salta1Star")
||
nameWithoutNumber.equalsIgnoreCase("Salta2Star")
||
nameWithoutNumber.equalsIgnoreCase("Salta3Star")
||
nameWithoutNumber.equalsIgnoreCase("Salta4Star")
||
nameWithoutNumber.equalsIgnoreCase("Salta5Star")
)
return nameWithoutNumber + " image created by Matthew Stephenson for Ludii.";
//-----------------------------------------------------
// Common/res/img/svg/shogi
if
(
nameWithoutNumber.equalsIgnoreCase("fuhyo")
||
nameWithoutNumber.equalsIgnoreCase("ginsho")
||
nameWithoutNumber.equalsIgnoreCase("hisha")
||
nameWithoutNumber.equalsIgnoreCase("kakugyo")
||
nameWithoutNumber.equalsIgnoreCase("keima")
||
nameWithoutNumber.equalsIgnoreCase("kinsho")
||
nameWithoutNumber.equalsIgnoreCase("kyosha")
||
nameWithoutNumber.equalsIgnoreCase("narigin")
||
nameWithoutNumber.equalsIgnoreCase("narikei")
||
nameWithoutNumber.equalsIgnoreCase("narikyo")
||
nameWithoutNumber.equalsIgnoreCase("osho")
||
nameWithoutNumber.equalsIgnoreCase("osho1")
||
nameWithoutNumber.equalsIgnoreCase("ryuma")
||
nameWithoutNumber.equalsIgnoreCase("ryuo")
||
nameWithoutNumber.equalsIgnoreCase("tokin")
)
return nameWithoutNumber + " image created by Matthew Stephenson for Ludii, using the Quivira and Arial TTF fonts.";
if (nameWithoutNumber.equalsIgnoreCase("shogi_blank"))
return nameWithoutNumber + " image from the Quivira TTF font.";
//-----------------------------------------------------
// Common/res/img/svg/stickDice
if
(
nameWithoutNumber.equalsIgnoreCase("oldMan0")
||
nameWithoutNumber.equalsIgnoreCase("oldMan1")
||
nameWithoutNumber.equalsIgnoreCase("oldWoman0")
||
nameWithoutNumber.equalsIgnoreCase("oldWoman1")
||
nameWithoutNumber.equalsIgnoreCase("youngMan0")
||
nameWithoutNumber.equalsIgnoreCase("youngMan1")
||
nameWithoutNumber.equalsIgnoreCase("youngWoman0")
||
nameWithoutNumber.equalsIgnoreCase("youngWoman1")
)
return nameWithoutNumber + " image created by Matthew Stephenson for Ludii.";
//-----------------------------------------------------
// Common/res/img/svg/stratego
if
(
nameWithoutNumber.equalsIgnoreCase("bomb")
||
nameWithoutNumber.equalsIgnoreCase("captain")
||
nameWithoutNumber.equalsIgnoreCase("colonel")
||
nameWithoutNumber.equalsIgnoreCase("flag")
||
nameWithoutNumber.equalsIgnoreCase("general")
||
nameWithoutNumber.equalsIgnoreCase("lieutenant")
||
nameWithoutNumber.equalsIgnoreCase("major")
||
nameWithoutNumber.equalsIgnoreCase("marshal")
||
nameWithoutNumber.equalsIgnoreCase("miner")
||
nameWithoutNumber.equalsIgnoreCase("scout")
||
nameWithoutNumber.equalsIgnoreCase("sergeant")
||
nameWithoutNumber.equalsIgnoreCase("spy")
)
return nameWithoutNumber + " image courtesy of Sjoerd Langkemper.";
//-----------------------------------------------------
// Common/res/img/svg/tafl
if
(
nameWithoutNumber.equalsIgnoreCase("jarl")
||
nameWithoutNumber.equalsIgnoreCase("thrall")
)
return nameWithoutNumber + " image from chess.medium OTF font.";
if (nameWithoutNumber.equalsIgnoreCase("knotSquare"))
return nameWithoutNumber + " by Smeshinka from https://www.dreamstime.com/.";
if (nameWithoutNumber.equalsIgnoreCase("knotTriangle"))
return nameWithoutNumber + " image from https://www.flaticon.com/free-icon/triquetra_1151995.";
//-----------------------------------------------------
// Common/res/img/svg/war
if
(
nameWithoutNumber.equalsIgnoreCase("bow")
||
nameWithoutNumber.equalsIgnoreCase("catapult")
||
nameWithoutNumber.equalsIgnoreCase("crossbow")
||
nameWithoutNumber.equalsIgnoreCase("knife")
||
nameWithoutNumber.equalsIgnoreCase("scimitar")
||
nameWithoutNumber.equalsIgnoreCase("smallSword")
||
nameWithoutNumber.equalsIgnoreCase("sword")
)
return nameWithoutNumber + " image from svgrepo.com.";
//-----------------------------------------------------
// Common/res/img/svg/army
if
(
nameWithoutNumber.equalsIgnoreCase("antiair")
||
nameWithoutNumber.equalsIgnoreCase("artillery")
||
nameWithoutNumber.equalsIgnoreCase("battleship")
||
nameWithoutNumber.equalsIgnoreCase("bomber")
||
nameWithoutNumber.equalsIgnoreCase("boss")
||
nameWithoutNumber.equalsIgnoreCase("builder")
||
nameWithoutNumber.equalsIgnoreCase("cruiser")
||
nameWithoutNumber.equalsIgnoreCase("demolisher")
||
nameWithoutNumber.equalsIgnoreCase("fighter")
||
nameWithoutNumber.equalsIgnoreCase("helicopter")
||
nameWithoutNumber.equalsIgnoreCase("launcher")
||
nameWithoutNumber.equalsIgnoreCase("motorbike")
||
nameWithoutNumber.equalsIgnoreCase("shooter")
||
nameWithoutNumber.equalsIgnoreCase("solider")
||
nameWithoutNumber.equalsIgnoreCase("speeder")
||
nameWithoutNumber.equalsIgnoreCase("submarine")
||
nameWithoutNumber.equalsIgnoreCase("tank")
)
return nameWithoutNumber + " image from svgrepo.com.";
//-----------------------------------------------------
// Common/res/img/svg/xiangqi
if
(
nameWithoutNumber.equalsIgnoreCase("jiang")
||
nameWithoutNumber.equalsIgnoreCase("ju")
||
nameWithoutNumber.equalsIgnoreCase("ma")
||
nameWithoutNumber.equalsIgnoreCase("pao")
||
nameWithoutNumber.equalsIgnoreCase("shi")
||
nameWithoutNumber.equalsIgnoreCase("xiang")
||
nameWithoutNumber.equalsIgnoreCase("zu")
)
return nameWithoutNumber + " image from BabelStoneXiangqi, Casefont, Arial Unicode MS, PragmataPro and Symbola TTF fonts.";
//-----------------------------------------------------
// ToolButtons
if
(
nameWithoutNumber.equalsIgnoreCase("button-about")
||
nameWithoutNumber.equalsIgnoreCase("button-dots-c")
||
nameWithoutNumber.equalsIgnoreCase("button-dots-d")
||
nameWithoutNumber.equalsIgnoreCase("button-dots")
||
nameWithoutNumber.equalsIgnoreCase("button-end-a")
||
nameWithoutNumber.equalsIgnoreCase("button-end")
||
nameWithoutNumber.equalsIgnoreCase("button-match-end")
||
nameWithoutNumber.equalsIgnoreCase("button-match-start")
||
nameWithoutNumber.equalsIgnoreCase("button-next")
||
nameWithoutNumber.equalsIgnoreCase("button-pass")
||
nameWithoutNumber.equalsIgnoreCase("button-pause")
||
nameWithoutNumber.equalsIgnoreCase("button-play")
||
nameWithoutNumber.equalsIgnoreCase("button-previous")
||
nameWithoutNumber.equalsIgnoreCase("button-settings-a")
||
nameWithoutNumber.equalsIgnoreCase("button-settings-b")
||
nameWithoutNumber.equalsIgnoreCase("button-start-a")
||
nameWithoutNumber.equalsIgnoreCase("button-start")
||
nameWithoutNumber.equalsIgnoreCase("button-swap")
)
return nameWithoutNumber + " image from https://www.flaticon.com/.";
//-----------------------------------------------------
return null;
}
//-------------------------------------------------------------------------
/**
* @return The maximum number of forward steps for a walk of this piece
*/
public int maxStepsForward()
{
int maxStepsForward = 0;
for (int i = 0; i < walk().length; i++)
{
int stepsForward = 0;
for (int j = 0; j < walk()[i].length; j++)
{
if (walk()[i][j] == StepType.F)
{
stepsForward++;
}
}
if (stepsForward > maxStepsForward)
{
maxStepsForward = stepsForward;
}
}
return maxStepsForward;
}
//-------------------------------------------------------------------------
/**
* @param game
* @return the rules of this component in an English language format.
*/
public String componentGeneratorRulesToEnglish(final Game game)
{
return nameWithoutNumber + StringRoutines.getPlural(nameWithoutNumber) + " " + generator().toEnglish(game);
}
}
| 48,546 | 28.369026 | 126 | java |
Ludii | Ludii-master/Core/src/game/equipment/component/Die.java | package game.equipment.component;
import java.io.Serializable;
import java.util.Arrays;
import java.util.BitSet;
import annotations.Name;
import annotations.Opt;
import game.Game;
import game.rules.play.moves.Moves;
import game.types.play.RoleType;
import game.util.directions.DirectionFacing;
import main.StringRoutines;
import metadata.graphics.util.ComponentStyleType;
import other.concept.Concept;
import other.context.Context;
/**
* Defines a single non-stochastic die used as a piece.
*
* @author Eric.Piette and cambolbro
*
* @remarks The die defined with this ludeme will be not included in a dice
* container and cannot be rolled with the roll ludeme, but can
* be turned to show each of its faces.
*/
public class Die extends Component implements Serializable
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/** The number of faces of the die. */
private final int numFaces;
/** The faces values. */
private int[] faces;
/**
* @param name The name of the die.
* @param role The owner of the die.
* @param numFaces The number of faces of the die.
* @param dirn The direction of the component.
* @param generator The moves associated with the component.
*
* @example (die "Die6" All numFaces:6)
*/
public Die
(
final String name,
final RoleType role,
@Name final Integer numFaces,
@Opt final DirectionFacing dirn,
@Opt final Moves generator
)
{
super(name, role, null, dirn, generator, null,null,null);
this.numFaces = numFaces.intValue();
style = ComponentStyleType.Die;
}
/**
* Copy constructor.
*
* Protected because we do not want the compiler to detect it, this is called
* only in Clone method.
*
* @param other
*/
protected Die(final Die other)
{
super(other);
numFaces = other.numFaces;
if (other.faces != null)
{
faces = new int[other.faces.length];
for (int i = 0; i < other.faces.length; i++)
faces[i] = other.faces[i];
}
else
other.faces = null;
}
@Override
public Die clone()
{
return new Die(this);
}
@Override
public boolean isDie()
{
return true;
}
@Override
public int[] getFaces()
{
return faces;
}
@Override
public int getNumFaces()
{
return numFaces;
}
@Override
public int roll(final Context context)
{
return (context.rng().nextInt(faces.length));
}
@Override
public void setFaces(final Integer[] faces, final Integer start)
{
if (start != null)
{
this.faces = new int[numFaces];
for (int i = start.intValue(); i < start.intValue() + numFaces; i++)
this.faces[i - start.intValue()] = i;
}
else if (faces != null)
{
this.faces = new int[faces.length];
for (int i = 0; i < faces.length; i++)
this.faces[i] = faces[i].intValue();
}
}
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
concepts.or(super.concepts(game));
concepts.set(Concept.Dice.id(), true);
return concepts;
}
@Override
public BitSet writesEvalContextRecursive()
{
final BitSet writeEvalContext = new BitSet();
writeEvalContext.or(super.writesEvalContextRecursive());
return writeEvalContext;
}
@Override
public BitSet readsEvalContextRecursive()
{
final BitSet readEvalContext = new BitSet();
readEvalContext.or(super.readsEvalContextRecursive());
return readEvalContext;
}
@Override
public boolean missingRequirement(final Game game)
{
boolean missingRequirement = false;
if (role() != null)
{
final int indexOwnerPhase = role().owner();
if (((indexOwnerPhase < 1 && !role().equals(RoleType.Shared)) && !role().equals(RoleType.Neutral)
&& !role().equals(RoleType.All)) || indexOwnerPhase > game.players().count())
{
game.addRequirementToReport(
"A die is defined in the equipment with an incorrect owner: " + role() + ".");
missingRequirement = true;
}
}
return missingRequirement;
}
//-------------------------------------------------------------------------
@Override
public String toEnglish(final Game game)
{
String string = nameWithoutNumber == null ? "Die" : nameWithoutNumber;
String plural = StringRoutines.getPlural(string);
string += plural;
string += " with " + numFaces + " faces valued " + Arrays.toString(faces);
return string;
}
//-------------------------------------------------------------------------
}
| 4,525 | 22.450777 | 100 | java |
Ludii | Ludii-master/Core/src/game/equipment/component/Piece.java | package game.equipment.component;
import java.io.Serializable;
import java.util.BitSet;
import annotations.Name;
import annotations.Opt;
import game.Game;
import game.rules.play.moves.Moves;
import game.types.play.RoleType;
import game.util.directions.DirectionFacing;
import game.util.moves.Flips;
import main.StringRoutines;
import other.concept.Concept;
/**
* Defines a piece.
*
* @author Eric.Piette and cambolbro
*
* @remarks Useful to create a pawn, a disc or a representation of an animal for
* example.
*/
public class Piece extends Component implements Serializable
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/** The flips value of a piece. */
private final Flips flips;
/**
* @param name The name of the piece.
* @param role The owner of the piece [Each].
* @param dirn The direction of the piece.
* @param flips The corresponding values to flip, e.g. (flip 1 2) 1 is
* flipped to 2 and 2 is flipped to 1.
* @param generator The moves associated with the piece.
* @param maxState To set the maximum local state the game should check.
* @param maxCount To set the maximum count the game should check.
* @param maxValue To set the maximum value the game should check.
*
* @example (piece "Pawn" Each)
*
* @example (piece "Disc" Neutral (flips 1 2))
*
* @example (piece "Dog" P1 (step (to if:(is Empty (to)))))
*/
public Piece
(
final String name,
@Opt final RoleType role,
@Opt final DirectionFacing dirn,
@Opt final Flips flips,
@Opt final Moves generator,
@Opt @Name final Integer maxState,
@Opt @Name final Integer maxCount,
@Opt @Name final Integer maxValue
)
{
super(name, (role == null ? RoleType.Each : role), null, dirn, generator, maxState, maxCount, maxValue);
// To remove any numbers at the end of the name of the component to find the correct image. (e.g. Tower of Hanoi)
nameWithoutNumber = StringRoutines.removeTrailingNumbers(name);
this.flips = flips;
}
//-------------------------------------------------------------------------
/**
* Copy constructor.
*
* Protected because we do not want the compiler to detect it, this is called
* only in Clone method.
*
* @param other
*/
protected Piece(final Piece other)
{
super(other);
flips = (other.getFlips() != null)
? new Flips(Integer.valueOf(other.getFlips().flipA()), Integer.valueOf(other.getFlips().flipB()))
: null;
}
@Override
public Piece clone()
{
return new Piece(this);
}
@Override
public Flips getFlips()
{
return flips;
}
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
concepts.or(super.concepts(game));
concepts.set(Concept.Piece.id(), true);
return concepts;
}
@Override
public BitSet writesEvalContextRecursive()
{
final BitSet writeEvalContext = new BitSet();
writeEvalContext.or(super.writesEvalContextRecursive());
return writeEvalContext;
}
@Override
public BitSet readsEvalContextRecursive()
{
final BitSet readEvalContext = new BitSet();
readEvalContext.or(super.readsEvalContextRecursive());
return readEvalContext;
}
@Override
public boolean missingRequirement(final Game game)
{
boolean missingRequirement = false;
if (role() != null)
{
final int indexOwnerPhase = role().owner();
if (
(
indexOwnerPhase < 1
&&
!role().equals(RoleType.Shared)
&&
!role().equals(RoleType.Neutral)
&&
!role().equals(RoleType.All)
)
||
indexOwnerPhase > game.players().count()
)
{
game.addRequirementToReport(
"A piece is defined in the equipment with an incorrect owner: " + role() + ".");
missingRequirement = true;
}
}
if(generator() != null)
if(generator().missingRequirement(game))
missingRequirement = true;
return missingRequirement;
}
//-------------------------------------------------------------------------
@Override
public String toEnglish(final Game game)
{
String string = nameWithoutNumber;
String plural = StringRoutines.getPlural(nameWithoutNumber);
string += plural;
if (flips != null)
string += ", " + flips.toEnglish(game);
return string;
}
//-------------------------------------------------------------------------
} | 4,509 | 24.625 | 115 | java |
Ludii | Ludii-master/Core/src/game/equipment/component/package-info.java | /**
* Components correspond to physical pieces of equipment used in games,
* other than boards. For example: pieces, dice, etc. All types of
* components listed in this section may be used for \texttt{<item>}
* parameters in \hyperref[Subsec:game.equipment.Equipment]{Equipment definitions}.
*/
package game.equipment.component;
| 334 | 40.875 | 83 | java |
Ludii | Ludii-master/Core/src/game/equipment/component/tile/Domino.java | package game.equipment.component.tile;
import java.io.Serializable;
import java.util.BitSet;
import annotations.Name;
import annotations.Opt;
import game.Game;
import game.equipment.component.Component;
import game.rules.play.moves.Moves;
import game.types.board.StepType;
import game.types.play.RoleType;
import main.StringRoutines;
import metadata.graphics.util.ComponentStyleType;
import other.concept.Concept;
/**
* Defines a single domino.
*
* @author Eric.Piette
*
* @remarks The domino defined with this ludeme will be not included in the
* dominoes container by default and so cannot be shuffled with other
* dominoes.
*/
public class Domino extends Component implements Serializable
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/** First Piece Value. */
private final int value;
/** Second Piece Value. */
private final int value2;
/**
* @param name The name of the domino.
* @param role The owner of the domino.
* @param value The first value of the domino.
* @param value2 The second value of the domino.
* @param generator The moves associated with the component.
* @example (domino "Domino45" Shared value:4 value2:5)
*/
public Domino
(
final String name,
final RoleType role,
@Name final Integer value,
@Name final Integer value2,
@Opt final Moves generator
)
{
super(name, role, new StepType[][]
{ new StepType[]
{ StepType.F, StepType.R, StepType.F, StepType.R, StepType.F, StepType.L, StepType.F, StepType.L,
StepType.F, StepType.R, StepType.F, StepType.R, StepType.F } },
null,
generator, null, null, null);
this.value = value.intValue();
this.value2 = value2.intValue();
nameWithoutNumber = StringRoutines.removeTrailingNumbers(name);
style = ComponentStyleType.Domino;
}
//-------------------------------------------------------------------------
/**
* Copy constructor.
*
* Protected because we do not want the compiler to detect it, this is called
* only in Clone method.
*
* @param other
*/
protected Domino(final Domino other)
{
super(other);
value = other.value;
value2 = other.value2;
}
@Override
public Domino clone()
{
return new Domino(this);
}
@Override
public int getValue()
{
return value;
}
@Override
public int getValue2()
{
return value2;
}
@Override
public boolean isDoubleDomino()
{
return getValue() == getValue2();
}
@Override
public boolean isDomino()
{
return true;
}
@Override
public int numSides()
{
return 4;
}
@Override
public boolean isTile()
{
return true;
}
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
concepts.set(Concept.CanNotMove.id(), true);
concepts.set(Concept.LargePiece.id(), true);
concepts.set(Concept.Tile.id(), true);
concepts.or(super.concepts(game));
return concepts;
}
@Override
public BitSet writesEvalContextRecursive()
{
final BitSet writeEvalContext = new BitSet();
writeEvalContext.or(super.writesEvalContextRecursive());
return writeEvalContext;
}
@Override
public BitSet readsEvalContextRecursive()
{
final BitSet readEvalContext = new BitSet();
readEvalContext.or(super.readsEvalContextRecursive());
return readEvalContext;
}
@Override
public boolean missingRequirement(final Game game)
{
boolean missingRequirement = false;
if (role() != null)
{
final int indexOwnerPhase = role().owner();
if (
(
indexOwnerPhase < 1
&&
!role().equals(RoleType.Shared)
&&
!role().equals(RoleType.Neutral)
&&
!role().equals(RoleType.All)
)
||
indexOwnerPhase > game.players().count()
)
{
game.addRequirementToReport(
"A domino is defined in the equipment with an incorrect owner: " + role() + ".");
missingRequirement = true;
}
}
return missingRequirement;
}
@Override
public String toEnglish(final Game game)
{
//-----------------------------------------------------
String string = nameWithoutNumber;
String plural = StringRoutines.getPlural(nameWithoutNumber);
string += plural;
string += ", with values " + value + " and " + value2;
return string;
//-----------------------------------------------------
}
}
| 4,420 | 20.886139 | 101 | java |
Ludii | Ludii-master/Core/src/game/equipment/component/tile/Path.java | package game.equipment.component.tile;
import java.io.Serializable;
import annotations.Name;
import annotations.Opt;
import game.Game;
import other.BaseLudeme;
/**
* Defines the internal path of a tile component.
*
* @author Eric.Piette
* @remarks To define the path of the internal connection of a tile component.
* The number side 0 = the first direction of the tiling, in general 0
* = North.
*/
public final class Path extends BaseLudeme implements Serializable
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/** The from side. */
private final Integer from;
/** The first terminus of the path. */
private final Integer slotsFrom;
/** The second side of the path. */
private final Integer to;
/** The second terminus of the path. */
private final Integer slotsTo;
/** The colour of the path. */
private final Integer colour;
//-------------------------------------------------------------------------
/**
* @param from The "from" side of the connection.
* @param slotsFrom The slot of the "from" side [0].
* @param to The "to" side of the connection.
* @param slotsTo The slot of the "to" side [0].
* @param colour The colour of the connection.
* @example (path from:0 to:2 colour:1)
*/
public Path
(
@Name final Integer from,
@Name @Opt final Integer slotsFrom,
@Name final Integer to,
@Name @Opt final Integer slotsTo,
@Name final Integer colour
)
{
this.from = from;
this.slotsFrom = (slotsFrom == null) ? Integer.valueOf(0) : slotsFrom;
this.to = to;
this.slotsTo = (slotsTo == null) ? Integer.valueOf(0) : slotsTo;
this.colour = colour;
}
//-------------------------------------------------------------------------
/**
* @return Side 1
*/
public Integer side1()
{
return from;
}
/**
* @return Side 2
*/
public Integer side2()
{
return to;
}
/**
* @return Terminus 1
*/
public Integer terminus1()
{
return slotsFrom;
}
/**
* @return Terminus 2
*/
public Integer terminus2()
{
return slotsTo;
}
/**
* @return the colour of the path.
*/
public Integer colour()
{
return colour;
}
/**
* @param rotation The rotation.
* @param maxOrthoRotation The max number of orthogonal rotations.
* @return The index of the first side with the rotation.
*/
public int side1(final int rotation, final int maxOrthoRotation)
{
return (from.intValue() + rotation) % maxOrthoRotation;
}
/**
* @param rotation The rotation.
* @param maxOrthoRotation The max number of orthogonal rotations.
* @return The index of the second side with the rotation.
*/
public int side2(final int rotation, final int maxOrthoRotation)
{
return (to.intValue() + rotation) % maxOrthoRotation;
}
//-------------------------------------------------------------------------
@Override
public String toEnglish(final Game game)
{
return "with path from side " + from + " (terminus " + slotsFrom + ") to side " + to + " (terminus " + slotsTo + ") coloured " + colour;
}
//-------------------------------------------------------------------------
}
| 3,224 | 22.369565 | 138 | java |
Ludii | Ludii-master/Core/src/game/equipment/component/tile/Tile.java | package game.equipment.component.tile;
import java.io.Serializable;
import java.util.BitSet;
import annotations.Name;
import annotations.Opt;
import annotations.Or;
import game.Game;
import game.equipment.component.Component;
import game.rules.play.moves.Moves;
import game.types.board.StepType;
import game.types.play.RoleType;
import game.util.moves.Flips;
import main.Constants;
import main.StringRoutines;
import metadata.graphics.util.ComponentStyleType;
import other.concept.Concept;
/**
* Defines a tile, a component following the tiling with internal connection.
*
* @author Eric.Piette
*/
public class Tile extends Component implements Serializable
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/** The terminus. */
private int[] terminus;
/** The number of terminus, if this is the same for each side. */
private final Integer numTerminus;
/** The paths. */
private final Path[] paths;
/** The number of sides of the tile. */
private int numSides;
/** The flips value of a piece. */
private final Flips flips;
/**
* @param name The name of the tile.
* @param role The owner of the tile.
* @param walk A turtle graphics walk to define the shape of a large
* tile.
* @param walks Many turtle graphics walks to define the shape of a large
* tile.
* @param numSides The number of sides of the tile.
* @param slots The number of slots for each side.
* @param slotsPerSide The number of slots for each side if this is the same
* number for each side [1].
* @param paths The connection in the tile.
* @param flips The corresponding values to flip, e.g. (flip 1 2) 1 is
* flipped to 2 and 2 is flipped to 1.
* @param generator The associated moves of this component.
* @param maxState To set the maximum local state the game should check.
* @param maxCount To set the maximum count the game should check.
* @param maxValue To set the maximum value the game should check.
*
* @example (tile "TileX" numSides:4 { (path from:0 to:2 colour:1) (path from:1
* to:3 colour:2) } )
*/
public Tile
(
final String name,
@Opt final RoleType role,
@Opt @Or final StepType[] walk,
@Opt @Or final StepType[][] walks,
@Opt @Name final Integer numSides,
@Opt @Or @Name final Integer[] slots,
@Opt @Or @Name final Integer slotsPerSide,
@Opt final Path[] paths,
@Opt final Flips flips,
@Opt final Moves generator,
@Opt @Name final Integer maxState,
@Opt @Name final Integer maxCount,
@Opt @Name final Integer maxValue
)
{
super
(
name,
(role == null) ? RoleType.Shared : role,
(walk != null) ? new StepType[][] { walk } : walks,
null,
generator, maxState, maxCount, maxValue
);
// Limit on the max number of sides.
if (numSides != null)
{
if (numSides.intValue() < 0 || numSides.intValue() > Constants.MAX_SIDES_TILE)
throw new IllegalArgumentException(
"The number of sides of a tile piece can not be negative or to exceed "
+ Constants.MAX_SIDES_TILE + ".");
}
int numNonNull = 0;
if (walk != null)
numNonNull++;
if (walks != null)
numNonNull++;
if (numNonNull > 1)
throw new IllegalArgumentException("Only one of 'walk' and 'walks' can be specified.");
numNonNull = 0;
if (slots != null)
numNonNull++;
if (slotsPerSide != null)
numNonNull++;
if (numNonNull > 1)
throw new IllegalArgumentException("Zero or one Or parameter can be non-null.");
if (slots != null)
{
terminus = new int[slots.length];
for (int i = 0; i < terminus.length; i++)
terminus[i] = slots[i].intValue();
}
else
{
terminus = null;
}
numTerminus = (slots == null && slotsPerSide == null) ? Integer.valueOf(1) : slotsPerSide;
this.paths = paths;
nameWithoutNumber = StringRoutines.removeTrailingNumbers(name);
if (walk() != null)
style = ComponentStyleType.LargePiece;
else
style = ComponentStyleType.Tile;
this.numSides = (numSides != null) ? numSides.intValue() : Constants.OFF;
this.flips = flips;
}
//-------------------------------------------------------------------------
/**
* Copy constructor.
*
* Protected because we do not want the compiler to detect it, this is called
* only in Clone method.
*
* @param other
*/
protected Tile(final Tile other)
{
super(other);
terminus = other.terminus;
numSides = other.numSides;
if (other.terminus != null)
{
terminus = new int[other.terminus.length];
for (int i = 0; i < other.terminus.length; i++)
terminus[i] = other.terminus[i];
}
else
terminus = null;
numTerminus = other.numTerminus;
if (other.paths != null)
{
paths = new Path[other.paths.length];
for (int i = 0; i < other.paths.length; i++)
paths[i] = other.paths[i];
}
else
paths = null;
flips = (other.getFlips() != null)
? new Flips(Integer.valueOf(other.getFlips().flipA()), Integer.valueOf(other.getFlips().flipB()))
: null;
}
@Override
public Tile clone()
{
return new Tile(this);
}
@Override
public boolean isTile()
{
return true;
}
@Override
public int[] terminus()
{
return terminus;
}
@Override
public Integer numTerminus()
{
return numTerminus;
}
@Override
public Path[] paths()
{
return paths;
}
@Override
public int numSides()
{
return numSides;
}
@Override
public void setNumSides(final int numSides)
{
this.numSides = numSides;
}
@Override
public Flips getFlips()
{
return flips;
}
//-------------------------------------------------------------------------
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
concepts.or(super.concepts(game));
concepts.set(Concept.Tile.id(), true);
if (walk() != null)
concepts.set(Concept.LargePiece.id(), true);
return concepts;
}
@Override
public BitSet writesEvalContextRecursive()
{
final BitSet writeEvalContext = new BitSet();
writeEvalContext.or(super.writesEvalContextRecursive());
return writeEvalContext;
}
@Override
public BitSet readsEvalContextRecursive()
{
final BitSet readEvalContext = new BitSet();
readEvalContext.or(super.readsEvalContextRecursive());
return readEvalContext;
}
@Override
public boolean missingRequirement(final Game game)
{
boolean missingRequirement = false;
if (role() != null)
{
final int indexOwnerPhase = role().owner();
if (
(
indexOwnerPhase < 1
&&
!role().equals(RoleType.Shared)
&&
!role().equals(RoleType.Neutral)
&&
!role().equals(RoleType.All)
)
||
indexOwnerPhase > game.players().count()
)
{
game.addRequirementToReport(
"A tile is defined in the equipment with an incorrect owner: " + role() + ".");
missingRequirement = true;
}
}
return missingRequirement;
}
//-------------------------------------------------------------------------
@Override
public String toEnglish(final Game game)
{
String string = nameWithoutNumber;
final String plural = StringRoutines.getPlural(nameWithoutNumber);
string += plural;
if (flips != null)
string += ", " + flips.toEnglish(game);
String pathString = "";
if (paths != null && paths.length > 0)
{
pathString = " [";
for (final Path p : paths)
pathString += p.toEnglish(game) + ",";
pathString = pathString.substring(pathString.length()-1) + "]";
}
String terminusString = "";
if (terminus != null && terminus.length > 0)
{
terminusString = " [";
for (final int i : terminus)
terminusString += i + ",";
terminusString = terminusString.substring(terminusString.length()-1) + "]";
}
string += ", with " + numSides + " sides and " + numTerminus + " terminus" + pathString + terminusString;
return string;
}
//-------------------------------------------------------------------------
} | 8,224 | 23.848943 | 107 | java |
Ludii | Ludii-master/Core/src/game/equipment/component/tile/package-info.java | /**
* Tiles are (typically flat) pieces that completely fill
* the cells they are placed in, and may have additional
* decorations (such as paths) drawn on them.
*/
package game.equipment.component.tile;
| 208 | 28.857143 | 57 | java |
Ludii | Ludii-master/Core/src/game/equipment/container/Container.java | package game.equipment.container;
import java.awt.geom.Point2D;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.BitSet;
import java.util.Collections;
import java.util.List;
import game.Game;
import game.equipment.Item;
import game.equipment.container.board.Track;
import game.types.board.SiteType;
import game.types.play.RoleType;
import metadata.graphics.util.ContainerStyleType;
import metadata.graphics.util.ControllerType;
import other.ItemType;
import other.concept.Concept;
import other.state.symmetry.SymmetryUtils;
import other.topology.Cell;
import other.topology.Edge;
import other.topology.Topology;
import other.topology.Vertex;
/**
* Defines a container.
*
* @author cambolbro and Eric.Piette
*/
@SuppressWarnings("static-method")
public abstract class Container extends Item implements Serializable, Cloneable
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
private static final double SYMMETRY_ACCURACY = 1e-6; // Allows for errors caused by double precision/trig functions
/** The graph associated with the container. */
protected Topology topology = new Topology();
/** Number of sites. */
protected int numSites = 0;
/** List of tracks. */
protected List<Track> tracks = new ArrayList<Track>();
/** List of tracks referring by owner. */
protected Track[][] ownedTracks;
//-------------------------GUI---------------------------------
/** The style of the container. */
protected ContainerStyleType style;
/** MVC controller for this container. */
protected ControllerType controller;
//-------------------------------------------------------------------------
/** The default type of graph element used by the game/board. */
protected SiteType defaultSite = SiteType.Cell;
//-------------------------------------------------------------------------
/**
* @param label The name of the container.
* @param index the unique index of the container.
* @param role The owner of the container.
*/
public Container
(
final String label,
final int index,
final RoleType role
)
{
super(label, index, role);
setType(ItemType.Container);
}
/**
* Copy constructor.
*
* Protected because we do not want the compiler to detect it, this is called
* only in Clone method.
*
* @param other
*/
protected Container(final Container other)
{
super(other);
topology = other.topology;
numSites = other.numSites;
tracks = other.tracks;
style = other.style;
controller = other.controller;
defaultSite = other.defaultSite;
style = other.style;
controller = other.controller;
}
//-------------------------------------------------------------------------
/**
* To create the graph of the container.
*
* @param beginIndex The first index to count the site of the cells.
* @param numEdges The number of edges by cell.
*/
public abstract void createTopology(final int beginIndex, final int numEdges);
//-------------------------------------------------------------------------
/**
* @return The default type of graph element to play.
*/
public SiteType defaultSite()
{
return defaultSite;
}
/**
* @return Number of sites this container contains. If this is the board, it
* returns the number of default sites (Cells, Vertices, Edges).
*/
public int numSites()
{
if (!defaultSite.equals(SiteType.Cell))
return topology.getGraphElements(defaultSite).size();
return numSites;
}
//-------------------------------------------------------------------------
/**
* @return True if the container is a hand.
*/
public boolean isHand()
{
return false;
}
/**
* @return True if the container is a dice.
*/
public boolean isDice()
{
return false;
}
/**
* @return True if the container is a deck.
*/
public boolean isDeck()
{
return false;
}
/**
* @return True if the container is boardless.
*/
public boolean isBoardless()
{
return false;
}
//-------------------------------------------------------------
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
concepts.or(super.concepts(game));
if (!this.tracks().isEmpty())
{
concepts.set(Concept.Track.id(), true);
for (final Track track : this.tracks())
concepts.or(track.concepts(game));
}
return concepts;
}
@Override
public Container clone()
{
Container c;
try
{
c = (Container)super.clone();
c.setName(name());
c.setIndex(index());
c.setNumSites(numSites);
}
catch (final CloneNotSupportedException e)
{
throw new Error();
}
return c;
}
/**
* Set the number of sites of the container.
*
* @param numSites The number of sites.
*/
public void setNumSites(final int numSites)
{
this.numSites = numSites;
}
//-------------------------------------------------------------------------
/**
* @return List of track.
*/
public List<Track> tracks()
{
return Collections.unmodifiableList(tracks);
}
/**
* @return The graph of the container.
*/
public Topology topology()
{
return topology;
}
//-------------------------------------------------------------------------
/**
* @return The style of the board.
*/
public ContainerStyleType style()
{
return style;
}
/**
* To set the style of the board.
*
* @param st
*/
public void setStyle(final ContainerStyleType st)
{
style = st;
}
//-------------------------------------------------------------------------
/**
* @return The controller of the board.
*/
public ControllerType controller()
{
return controller;
}
/**
* To set the controller of the board.
*
* @param controller
*/
public void setController(final ControllerType controller)
{
this.controller = controller;
}
/**
* @param owner The owner of the track.
* @return The tracks owned by a specific player.
*/
public Track[] ownedTracks(final int owner)
{
if (owner < ownedTracks.length)
return ownedTracks[owner];
else
return new Track[0];
}
/**
* Set the owned Tracks.
*
* @param ownedTracks The owned tracks.
*/
public void setOwnedTrack(final Track[][] ownedTracks)
{
this.ownedTracks = ownedTracks;
}
// ---------------------------------------Symmetries-----------------------------------------------------------------
/**
* Tries to find symmetries by rotating topologies, edges, and vertices at all
* reasonable angles The following will be caught by this code:
*
* no symmetry half-turn symmetry; e.g. hex board 3-fold symmetry (triangle)
* quarter turn symmetry (square) 5-fold symmetry (Kaooa) 6-fold symmetry
* (hexagon)
*
* Other symmetries can be added if needed
*
* @param topo
*/
public static void createSymmetries(final Topology topo)
{
createSymmetries(topo, 24); // Will create 2-, 3-, 4-, and 6- fold symmetries;
if (topo.cellReflectionSymmetries().length == 0 && topo.cellRotationSymmetries().length == 0)
createSymmetries(topo, 5); // There are one or two traditional games that use 5-fold symmetry
if (topo.cellReflectionSymmetries().length == 0 && topo.cellRotationSymmetries().length == 0)
createSymmetries(topo, 7); // There are one or two traditional games that use 5-fold symmetry
}
/**
* Tries to find symmetries by rotating topologies, edges, and vertices by the
* angles suggested by symmetries
*
* @param topology
* @param symmetries
*/
private static void createSymmetries(final Topology topology, final int symmetries)
{
final List<Cell> cells = topology.cells();
final List<Edge> edges = topology.edges();
final List<Vertex> vertices = topology.vertices();
final Point2D origin1 = topology.centrePoint();
Point2D origin2 = new Point2D.Double(0.5, 0.5);
if (origin1.equals(origin2))
origin2 = null; // avoids unnecessary processing
// All rotation processing
// Rotation angles are 0 <= angle < 2*PI
{
final int[][] cellRotations = new int[symmetries][];
final int[][] edgeRotations = new int[symmetries][];
final int[][] vertexRotations = new int[symmetries][];
int rotCount = 0;
for (int turns = 0; turns < symmetries; turns++)
{
int[] cRots = calcCellRotation(cells, origin1, turns, symmetries);
int[] eRots = calcEdgeRotation(edges, origin1, turns, symmetries);
int[] vRots = calcVertexRotation(vertices, origin1, turns, symmetries);
// Try again with origin2, if origin1 failed
if (origin2 != null && (!SymmetryUtils.isBijective(cRots) || !SymmetryUtils.isBijective(eRots)
|| !SymmetryUtils.isBijective(vRots)))
{
cRots = calcCellRotation(cells, origin1, turns, symmetries);
eRots = calcEdgeRotation(edges, origin1, turns, symmetries);
vRots = calcVertexRotation(vertices, origin1, turns, symmetries);
}
// If we successfully rotated everything, store the symmetry
if (SymmetryUtils.isBijective(cRots) && SymmetryUtils.isBijective(eRots)
&& SymmetryUtils.isBijective(vRots))
{
cellRotations[rotCount] = cRots;
edgeRotations[rotCount] = eRots;
vertexRotations[rotCount] = vRots;
rotCount++;
}
}
topology.setCellRotationSymmetries(Arrays.copyOf(cellRotations, rotCount));
topology.setEdgeRotationSymmetries(Arrays.copyOf(edgeRotations, rotCount));
topology.setVertexRotationSymmetries(Arrays.copyOf(vertexRotations, rotCount));
}
// All reflection processing
// Note that because of symmetries, reflection angles are 0 <= angle < PI, not
// 2PI - this is taken care of in the reflection routine.
{
final int[][] cellReflections = new int[symmetries][];
final int[][] edgeReflections = new int[symmetries][];
final int[][] vertexReflections = new int[symmetries][];
int refCount = 0;
for (int turns = 0; turns < symmetries; turns++)
{
int[] cRefs = calcCellReflection(cells, origin1, turns, symmetries);
int[] eRefs = calcEdgeReflection(edges, origin1, turns, symmetries);
int[] vRefs = calcVertexReflection(vertices, origin1, turns, symmetries);
// Try again with origin2, if origin1 failed
if (origin2 != null && (!SymmetryUtils.isBijective(cRefs) || !SymmetryUtils.isBijective(eRefs)
|| !SymmetryUtils.isBijective(vRefs)))
{
cRefs = calcCellReflection(cells, origin1, turns, symmetries);
eRefs = calcEdgeReflection(edges, origin1, turns, symmetries);
vRefs = calcVertexReflection(vertices, origin1, turns, symmetries);
}
// If we successfully rotated everything, store the symmetry
if (SymmetryUtils.isBijective(cRefs) && SymmetryUtils.isBijective(eRefs)
&& SymmetryUtils.isBijective(vRefs))
{
cellReflections[refCount] = cRefs;
edgeReflections[refCount] = eRefs;
vertexReflections[refCount] = vRefs;
refCount++;
}
}
topology.setCellReflectionSymmetries(Arrays.copyOf(cellReflections, refCount));
topology.setEdgeReflectionSymmetries(Arrays.copyOf(edgeReflections, refCount));
topology.setVertexReflectionSymmetries(Arrays.copyOf(vertexReflections, refCount));
}
}
private static int[] calcCellRotation(final List<Cell> cells, final Point2D origin, final int turns,
final int symmetries)
{
final int[] rots = new int[cells.size()];
for (int cell = 0; cell < cells.size(); cell++)
{
final Point2D start = cells.get(cell).centroid();
final Point2D end = SymmetryUtils.rotateAroundPoint(origin, start, turns, symmetries);
rots[cell] = findMatchingCell(cells, end);
if (rots[cell] == -1)
break; // Symmetry broken, early exit
}
return rots;
}
private static int[] calcEdgeRotation(final List<Edge> edges, final Point2D origin, final int turns,
final int symmetries)
{
final int[] rots = new int[edges.size()];
for (int edge = 0; edge < edges.size(); edge++)
{
final Point2D pt1 = edges.get(edge).vA().centroid();
final Point2D pt2 = edges.get(edge).vB().centroid();
final Point2D end1 = SymmetryUtils.rotateAroundPoint(origin, pt1, turns, symmetries);
final Point2D end2 = SymmetryUtils.rotateAroundPoint(origin, pt2, turns, symmetries);
rots[edge] = findMatchingEdge(edges, end1, end2);
if (rots[edge] == -1)
break; // Symmetry broken, early exit
}
return rots;
}
private static int[] calcVertexRotation(final List<Vertex> vertices, final Point2D origin, final int turns,
final int symmetries)
{
final int[] rots = new int[vertices.size()];
for (int vertexIndex = 0; vertexIndex < vertices.size(); vertexIndex++)
{
final Point2D start = vertices.get(vertexIndex).centroid();
final Point2D end = SymmetryUtils.rotateAroundPoint(origin, start, turns, symmetries);
rots[vertexIndex] = findMatchingVertex(vertices, end);
if (rots[vertexIndex] == -1)
break; // Symmetry broken, early exit
}
return rots;
}
private static int findMatchingVertex(List<Vertex> vertices, Point2D end)
{
for (int vertex = 0; vertex < vertices.size(); vertex++)
if (SymmetryUtils.closeEnough(end, vertices.get(vertex).centroid(), SYMMETRY_ACCURACY))
return vertex;
return -1;
}
private static int findMatchingEdge(final List<Edge> edges, final Point2D pos1, final Point2D pos2)
{
for (int edgeIndex = 0; edgeIndex < edges.size(); edgeIndex++)
{
final Edge edge = edges.get(edgeIndex);
final Point2D ptA = edge.vA().centroid();
final Point2D ptB = edge.vB().centroid();
if (SymmetryUtils.closeEnough(pos1, ptA, SYMMETRY_ACCURACY)
&& SymmetryUtils.closeEnough(pos2, ptB, SYMMETRY_ACCURACY)
|| SymmetryUtils.closeEnough(pos1, ptB, SYMMETRY_ACCURACY)
&& SymmetryUtils.closeEnough(pos2, ptA, SYMMETRY_ACCURACY))
return edgeIndex;
}
return -1;
}
private static int findMatchingCell(final List<Cell> cells, final Point2D pos)
{
for (int cell = 0; cell < cells.size(); cell++)
if (SymmetryUtils.closeEnough(pos, cells.get(cell).centroid(), SYMMETRY_ACCURACY))
return cell;
return -1;
}
private static int[] calcCellReflection(final List<Cell> cells, final Point2D origin, final int turns,
final int symmetries)
{
final int[] refs = new int[cells.size()];
for (int cell = 0; cell < cells.size(); cell++)
{
final Point2D start = cells.get(cell).centroid();
final Point2D end = SymmetryUtils.reflectAroundLine(origin, start, turns, symmetries);
refs[cell] = findMatchingCell(cells, end);
if (refs[cell] == -1)
break; // Symmetry broken - early exit
}
return refs;
}
private static int[] calcEdgeReflection(final List<Edge> edges, final Point2D origin, final int turns,
final int symmetries)
{
final int[] refs = new int[edges.size()];
for (int edgeIndex = 0; edgeIndex < edges.size(); edgeIndex++)
{
final Point2D p1 = edges.get(edgeIndex).vA().centroid();
final Point2D p2 = edges.get(edgeIndex).vB().centroid();
final Point2D end1 = SymmetryUtils.reflectAroundLine(origin, p1, turns, symmetries);
final Point2D end2 = SymmetryUtils.reflectAroundLine(origin, p2, turns, symmetries);
refs[edgeIndex] = findMatchingEdge(edges, end1, end2);
if (refs[edgeIndex] == -1)
break; // Symmetry broken - early exit
}
return refs;
}
private static int[] calcVertexReflection(final List<Vertex> vertices, final Point2D origin, final int turns,
final int symmetries)
{
final int[] refs = new int[vertices.size()];
for (int vertex = 0; vertex < vertices.size(); vertex++)
{
final Point2D start = vertices.get(vertex).centroid();
final Point2D end = SymmetryUtils.reflectAroundLine(origin, start, turns, symmetries);
refs[vertex] = findMatchingVertex(vertices, end);
if (refs[vertex] == -1)
break; // Symmetry broken - early exit
}
return refs;
}
} | 15,772 | 28.155268 | 118 | java |
Ludii | Ludii-master/Core/src/game/equipment/container/board/Board.java | package game.equipment.container.board;
import java.util.BitSet;
import annotations.Name;
import annotations.Opt;
import annotations.Or;
import annotations.Or2;
import game.Game;
import game.equipment.container.Container;
import game.functions.graph.GraphFunction;
import game.functions.ints.IntConstant;
import game.functions.range.Range;
import game.types.board.BasisType;
import game.types.board.ShapeType;
import game.types.board.SiteType;
import game.types.play.RoleType;
import game.util.equipment.Values;
import game.util.graph.Face;
import game.util.graph.Graph;
import main.Constants;
import main.math.Vector;
import metadata.graphics.util.ContainerStyleType;
import other.BaseLudeme;
import other.concept.Concept;
import other.topology.Cell;
import other.topology.Edge;
import other.topology.Topology;
import other.topology.Vertex;
/**
* Defines a board by its graph, consisting of vertex locations and edge pairs.
*
* @author Eric.Piette and cambolbro
*
* @remarks The values range are used for deduction puzzles. The state model for
* these puzzles is a Constraint Satisfaction Problem (CSP) model,
* possibly with a variable for each graph element (i.e. vertex, edge
* and cell), each with a range of possible values.
*/
public class Board extends Container
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/** The graph generated by the graph function. */
protected Graph graph = null;
/** The graph function. */
private final GraphFunction graphFunction;
/** The domain of the edge variables. */
private Range edgeRange;
/** The domain of the cell variables. */
private Range cellRange;
/** The domain of the vertex variables. */
private Range vertexRange;
/** The game can involves large stack. */
private final boolean largeStack;
//-------------------------------------------------------------------------
/**
* @param graphFn The graph function used to build the board.
* @param track The track on the board.
* @param tracks The tracks on the board.
* @param values The range values of a graph element used for deduction puzzle.
* @param valuesArray The range values of many graph elements used for deduction puzzle.
* @param use Graph element type to use by default [Cell].
* @param largeStack The game can involves stack(s) higher than 32.
*
* @example (board (graph vertices:{ {1 0} {2 0} {0 1} {1 1} {2 1} {3 1}
* {0 2} {1 2} {2 2} {3 2} {1 3} {2 3}} edges:{ {0 2} {0 3} {3 2} {3 4}
* {1 4} {4 5} {1 5} {3 7} {4 8} {6 7} {7 8} {8 9} {6 10} {11 9} {10 7}
* {11 8}} ) )
*/
public Board
(
final GraphFunction graphFn,
@Opt @Or final Track track,
@Opt @Or final Track[] tracks,
@Opt @Or2 final Values values,
@Opt @Or2 final Values[] valuesArray,
@Opt @Name final SiteType use,
@Opt @Name final Boolean largeStack
)
{
super("Board", Constants.UNDEFINED, RoleType.Neutral);
int numNonNull = 0;
if (track != null)
numNonNull++;
if (tracks != null)
numNonNull++;
if (numNonNull > 1)
throw new IllegalArgumentException("Board: Only one of `track' or `tracks' can be non-null.");
int valuesNonNull = 0;
if (values != null)
valuesNonNull++;
if (valuesArray != null)
valuesNonNull++;
if (valuesNonNull > 1)
throw new IllegalArgumentException("Board(): Only one of `values' or `valuesArray' parameter can be non-null.");
defaultSite = (use == null) ? SiteType.Cell : use;
graphFunction = graphFn;
if (valuesNonNull == 1) // If values are used that's a deduction puzzle.
{
final Values[] valuesLocal = (valuesArray != null) ? valuesArray : new Values[] {values};
for (final Values valuesGraphElement : valuesLocal)
{
switch (valuesGraphElement.type())
{
case Cell:
cellRange = valuesGraphElement.range();
break;
case Edge:
edgeRange = valuesGraphElement.range();
break;
case Vertex:
vertexRange = valuesGraphElement.range();
break;
}
}
if (vertexRange == null)
vertexRange = new Range(new IntConstant(0), new IntConstant(0));
if (edgeRange == null)
edgeRange = new Range(new IntConstant(0), new IntConstant(0));
if (cellRange == null)
cellRange = new Range(new IntConstant(0), new IntConstant(0));
style = ContainerStyleType.Puzzle;
}
else
{
if (tracks != null)
for (final Track t : tracks)
this.tracks.add(t);
else if (track != null)
this.tracks.add(track);
if (defaultSite == SiteType.Vertex || defaultSite == SiteType.Edge)
style = ContainerStyleType.Graph;
else
style = ContainerStyleType.Board;
}
this.largeStack = largeStack == null ? false : largeStack.booleanValue();
}
//-------------------------------------------------------------------------
/**
* @return The graph of the game.
*/
public Graph graph()
{
return graph;
}
//-------------------------------------------------------------------------
/**
* Built the graph and compute the trajectories.
*
* @param siteType
* @param boardless
*/
public void init(final SiteType siteType, final boolean boardless)
{
graph = graphFunction.eval(null, siteType);
//System.out.println("Graph basis and shape: " + graph.basis() + " " + graph.shape());
graph.measure(boardless);
graph.trajectories().create(graph);
graph.setDim(graphFunction.dim());
topology.setGraph(graph);
//System.out.println("Graph basis and shape: " + graph.basis() + " " + graph.shape());
}
//-------------------------------------------------------------------------
@Override
public void createTopology(final int beginIndex, final int numEdges)
{
init(defaultSite, isBoardless());
// Add the perimeter computed in the graph to the topology.
topology.setPerimeter(graph.perimeters());
// Set the trajectories.
topology.setTrajectories(graph.trajectories());
// Add the vertices to the topology
for (int i = 0; i < graph.vertices().size(); i++)
{
final game.util.graph.Vertex graphVertex = graph.vertices().get(i);
final double x = graphVertex.pt().x();
final double y = graphVertex.pt().y();
final double z = graphVertex.pt().z();
final Vertex vertex = new Vertex(i, x, y, z);
vertex.setProperties(graphVertex.properties());
vertex.setRow(graphVertex.situation().rcl().row());
vertex.setColumn(graphVertex.situation().rcl().column());
vertex.setLayer(graphVertex.situation().rcl().layer());
vertex.setLabel(graphVertex.situation().label());
topology.vertices().add(vertex);
}
// Link up pivots AFTER creating all vertices
for (int i = 0; i < graph.vertices().size(); i++)
{
final game.util.graph.Vertex vertex = graph.vertices().get(i);
if (vertex.pivot() != null)
topology.vertices().get(i).setPivot(topology.vertices().get(vertex.pivot().id()));
}
// Add the edges to the topology
for (int i = 0; i < graph.edges().size(); i++)
{
final game.util.graph.Edge graphEdge = graph.edges().get(i);
final Vertex vA = topology.vertices().get(graphEdge.vertexA().id());
final Vertex vB = topology.vertices().get(graphEdge.vertexB().id());
final Edge edge = new Edge(i, vA, vB);
// if (graph.edges().get(i).curved())
// edge.setCurved(true);
edge.setProperties(graphEdge.properties());
edge.setRow(graphEdge.situation().rcl().row());
edge.setColumn(graphEdge.situation().rcl().column());
edge.setLayer(graphEdge.situation().rcl().layer());
edge.setLabel(graphEdge.situation().label());
if (graphEdge.tangentA() != null)
edge.setTangentA(new Vector(graphEdge.tangentA()));
if (graphEdge.tangentB() != null)
edge.setTangentB(new Vector(graphEdge.tangentB()));
topology.edges().add(edge);
vA.edges().add(edge);
vB.edges().add(edge);
}
// Add the cells to the topology.
for (final Face face : graph.faces())
{
final Cell cell = new Cell(face.id(), face.pt().x(), face.pt().y(), face.pt().z());
cell.setProperties(face.properties());
cell.setRow(face.situation().rcl().row());
cell.setColumn(face.situation().rcl().column());
cell.setLayer(face.situation().rcl().layer());
cell.setLabel(face.situation().label());
topology.cells().add(cell);
// We add the vertices of the cells and vice versa.
for (final game.util.graph.Vertex v : face.vertices())
{
final Vertex vertex = topology().vertices().get(v.id());
cell.vertices().add(vertex);
vertex.cells().add(cell);
}
// We add the edges of the cells and vice versa.
for (final game.util.graph.Edge e : face.edges())
{
final Edge edge = topology().edges().get(e.id());
cell.edges().add(edge);
edge.cells().add(cell);
}
}
numSites = topology.cells().size();
// We compute the number of edges of each tiling if the graph uses a regular
// tiling.
topology.computeNumEdgeIfRegular();
}
//-------------------------------------------------------------------------
@Override
public String toEnglish(final Game game)
{
String text = "";
final ShapeType boardShape = topology().graph().shape();
final BasisType boardBasis = topology().graph().basis();
// Determine the dimensions of the board.
if(topology().graph().dim() != null)
{
for(final int dim: topology().graph().dim())
text += dim + "x";
if (topology().graph().dim().length == 1)
text += topology().graph().dim()[0];
else
text = text.substring(0, text.length()-1);
}
if (boardShape != null || boardBasis != null)
{
if(boardShape != null)
text += " " + boardShape.name().toLowerCase();
text += " " + name().toLowerCase();
if(boardBasis != null)
text += " with " + boardBasis.name().toLowerCase() + " tiling";
}
else
{
text = ((BaseLudeme) graphFunction).toEnglish(game).toLowerCase() + " " + name().toLowerCase();
}
return text.trim();
}
//----------------------------------
/**
* Set the topology.
* Note: use by LargePieceStyle only.
*
* @param topo
*/
public void setTopology(final Topology topo)
{
topology = topo;
}
/**
* @return The domain of the vertex variables.
*/
public Range vertexRange()
{
return vertexRange;
}
/**
* @return The domain of the edge variables.
*/
public Range edgeRange()
{
return edgeRange;
}
/**
* @return The domain of the face variables.
*/
public Range cellRange()
{
return cellRange;
}
/**
* @param type The siteType.
* @return The corresponding range of the siteType.
*/
public Range getRange(final SiteType type)
{
switch (type)
{
case Vertex:
return vertexRange();
case Cell:
return cellRange();
case Edge:
return edgeRange();
}
return null;
}
// ----------------------------------
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
concepts.or(super.concepts(game));
concepts.or(graphFunction.concepts(game));
if (style.equals(ContainerStyleType.Graph))
concepts.set(Concept.GraphStyle.id(), true);
return concepts;
}
@Override
public BitSet writesEvalContextRecursive()
{
final BitSet writeEvalContext = new BitSet();
writeEvalContext.or(super.writesEvalContextRecursive());
writeEvalContext.or(graphFunction.writesEvalContextRecursive());
return writeEvalContext;
}
@Override
public BitSet readsEvalContextRecursive()
{
final BitSet readEvalContext = new BitSet();
readEvalContext.or(super.readsEvalContextRecursive());
readEvalContext.or(graphFunction.readsEvalContextRecursive());
return readEvalContext;
}
/**
* @return The game can involves stack higher than 32.
*/
public boolean largeStack()
{
return largeStack;
}
} | 11,935 | 26.502304 | 115 | java |
Ludii | Ludii-master/Core/src/game/equipment/container/board/Boardless.java | package game.equipment.container.board;
import java.util.BitSet;
import annotations.Name;
import annotations.Opt;
import game.Game;
import game.functions.dim.DimConstant;
import game.functions.dim.DimFunction;
import game.functions.graph.generators.basis.hex.HexagonOnHex;
import game.functions.graph.generators.basis.square.RectangleOnSquare;
import game.functions.graph.generators.basis.tri.TriangleOnTri;
import game.types.board.SiteType;
import game.types.board.TilingBoardlessType;
import game.types.state.GameType;
import main.Constants;
import metadata.graphics.util.ContainerStyleType;
import other.concept.Concept;
/**
* Defines a boardless container growing in function of the pieces played.
*
* @author Eric.Piette
*
* @remarks The playable sites of the board will be all the sites adjacent to
* the places already played/placed. No pregeneration is computed on
* the graph except the centre.
*/
public class Boardless extends Board
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/**
* @param tiling The tiling of the boardless container.
* @param dimension The "fake" size of the board used for boardless [41].
* @param largeStack The game can involves stack(s) higher than 32.
*
* @example (boardless Hexagonal)
*/
public Boardless
(
final TilingBoardlessType tiling,
@Opt final DimFunction dimension,
@Opt @Name final Boolean largeStack
)
{
super
(
tiling == TilingBoardlessType.Square
? new RectangleOnSquare(dimension == null ? new DimConstant(Constants.SIZE_BOARDLESS) : dimension, null, null, null)
: tiling == TilingBoardlessType.Hexagonal
? new HexagonOnHex(dimension == null ? new DimConstant(Constants.SIZE_HEX_BOARDLESS) : dimension)
: new TriangleOnTri(dimension == null ? new DimConstant(Constants.SIZE_BOARDLESS) : dimension),
null,
null,
null,
null,
SiteType.Cell,
largeStack
);
this.style = ContainerStyleType.Boardless;
}
@Override
public boolean isBoardless()
{
return true;
}
@Override
public long gameFlags(final Game game)
{
return super.gameFlags(game) | GameType.Boardless;
}
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
concepts.or(super.concepts(game));
concepts.set(Concept.Boardless.id(), true);
return concepts;
}
@Override
public BitSet writesEvalContextRecursive()
{
final BitSet writeEvalContext = new BitSet();
writeEvalContext.or(super.writesEvalContextRecursive());
return writeEvalContext;
}
@Override
public BitSet readsEvalContextRecursive()
{
final BitSet readEvalContext = new BitSet();
readEvalContext.or(super.readsEvalContextRecursive());
return readEvalContext;
}
@Override
public String toEnglish(final Game game)
{
return "table" ;
}
} | 2,944 | 26.018349 | 120 | java |
Ludii | Ludii-master/Core/src/game/equipment/container/board/Track.java | package game.equipment.container.board;
import java.io.Serializable;
import java.util.BitSet;
import java.util.List;
import annotations.Name;
import annotations.Opt;
import annotations.Or;
import game.Game;
import game.types.board.SiteType;
import game.types.play.RoleType;
import game.util.directions.DirectionFacing;
import game.util.equipment.TrackStep;
import game.util.graph.Radial;
import gnu.trove.list.array.TIntArrayList;
import main.Constants;
import other.BaseLudeme;
import other.concept.Concept;
import other.topology.Cell;
import other.topology.Topology;
import other.topology.Vertex;
/**
* Defines a named track for a container, which is typically the board.
*
* @author Eric.Piette
*
* @remarks Tracks are typically used for race games, or any game in which
* pieces move around a track. A number after a direction indicates the
* number of steps in that direction. For example, "N1,E3" means that
* track goes North for one step then turns East for three steps.
*/
public class Track extends BaseLudeme implements Serializable
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------------
/**
* An element of a track
*
* @author Eric.Piette
*/
public class Elem implements Serializable
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------------
/** The site of the element. */
public final int site;
/** The previous site of the element. */
public final int prev;
/** The index on the track of the previous element. */
public final int prevIndex;
/** The next site of the element. */
public final int next;
/** The index on the track of the next element. */
public final int nextIndex;
/** The number of bumps on that elements. */
public final int bump;
/***
* An element of the track.
*
* @param site The site of the element.
* @param prev The previous site of the element.
* @param prevIndex The index on the track of the previous element.
* @param next The next site of the element.
* @param nextIndex The index on the track of the next element.
* @param bump The number of bumps on that elements
*/
public Elem
(
final Integer site,
final Integer prev,
final Integer prevIndex,
final Integer next,
final Integer nextIndex,
final Integer bump
)
{
this.site = (site == null) ? -1 : site.intValue();
this.prev = (prev == null) ? -1 : prev.intValue();
this.prevIndex = (prevIndex == null) ? -1 : prevIndex.intValue();
this.next = (next == null) ? -1 : next.intValue();
this.nextIndex = (nextIndex == null) ? -1 : nextIndex.intValue();
this.bump = bump.intValue();
}
}
//-------------------------------------------------------------------------------
/** The name of the track. */
private final String name;
/** The elements of the track. */
private Elem[] elems;
/** The tracks defined in the game description. */
private Integer[] track;
/** The track defined in the game description. */
private final String trackDirection;
/** The owner of the track.*/
private final int owner;
/** True if the track is a loop. */
private final boolean looped;
/** True if the track is directed. */
private final boolean direct;
/**
* True if the track has an internal loop (e.g. UR or big Pachisi).
*/
private boolean internalLoop = false;
/** Our index in the board's list of tracks */
private int trackIdx = Constants.UNDEFINED;
//-------------------------------------------------------------------------------
/**
* @param name The name of the track.
* @param track List of integers describing board site indices.
* @param trackDirection Description including site indices and cardinal.
* @param trackSteps Description using track steps.
* directions (N, E, S, W).
* @param loop True if the track is a loop [False].
* @param owner The owner of the track [0].
* @param role The role of the owner of the track [Neutral].
* @param directed True if the track is directed [False].
*
* @example (track "Track" "1,E,N,W" loop:True)
*
* @example (track "Track1" {6 12..7 5..0 13..18 20..25 End} P1 directed:True)
*
* @example (track "Track1" "20,3,W,N1,E,End" P1 directed:True)
*/
public Track
(
final String name,
@Or final Integer[] track,
@Or final String trackDirection,
@Or final TrackStep[] trackSteps,
@Opt @Name final Boolean loop,
@Opt @Or final Integer owner,
@Opt @Or final RoleType role,
@Opt @Name final Boolean directed
)
{
int numNonNull = 0;
if (track != null)
numNonNull++;
if (trackDirection != null)
numNonNull++;
if (trackSteps != null)
numNonNull++;
if (numNonNull != 1)
throw new IllegalArgumentException("Exactly one Or parameter must be non-null.");
int numNonNull2 = 0;
if (owner != null)
numNonNull2++;
if (role != null)
numNonNull2++;
if (numNonNull2 > 1)
throw new IllegalArgumentException("Zero or one Or parameter must be non-null.");
this.name = (name == null) ? "Track" : name;
this.owner = (owner == null) ? (role == null) ? 0 : role.owner() : owner.intValue();
this.looped = (loop == null) ? false : loop.booleanValue();
this.direct = (directed == null) ? false : directed.booleanValue();
this.track = track;
this.trackDirection = trackDirection;
elems = null;
}
//-------------------------------------------------------------------------------------
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
concepts.or(super.concepts(game));
if (looped)
concepts.set(Concept.TrackLoop.id(), true);
if (owner != 0)
concepts.set(Concept.TrackOwned.id(), true);
return concepts;
}
/**
* To build the graph.
*
* @param game
*/
public void buildTrack(final Game game)
{
// Temporary until the track steps are fully implementing.
if (trackDirection == null && track == null)
return;
final Topology topology = game.board().topology();
if (game.board().defaultSite() == SiteType.Cell)
{
if (trackDirection != null)
{
final String[] steps = trackDirection.split(",");
if (steps.length < 1)
throw new IllegalArgumentException("The track " + name + " is not correct");
if (!isNumber(steps[0]))
throw new IllegalArgumentException("The first step in the track " + name + " is not a number");
final int start = Integer.parseInt(steps[0]);
// if (start >= graph.vertices().size())
// throw new IllegalArgumentException(
// "The site " + start + " is greater than the number of sites in the main
// board");
final TIntArrayList trackList = new TIntArrayList();
trackList.add(start);
Cell current = (start < game.board().topology().cells().size()) ? game.board().topology().cells().get(start)
: null;
for (int i = 1; i < steps.length; i++)
{
final String step = steps[i];
final boolean stepIsNumber = isNumber(step);
if (stepIsNumber)
{
final int site = Integer.valueOf(step).intValue();
current = (site < game.board().topology().cells().size()) ? game.board().topology().cells().get(site)
: null;
trackList.add(site);
}
else if (step.equals("End"))
{
final int site = Integer.valueOf(Constants.END).intValue();
trackList.add(site);
}
else
{
if (current == null)
throw new IllegalArgumentException("The step " + step + " in the track " + name
+ " is impossible without a correct site in the main board.");
String direction = "";
for (int j = 0; j < step.length(); j++)
if (!Character.isDigit(step.charAt(j)))
direction += step.charAt(j);
int size = Constants.UNDEFINED;
if (direction.length() != step.length())
size = Integer.parseInt(step.substring(direction.length()));
final DirectionFacing dirn = convertStringDirection(direction,
game.board().topology().supportedDirections(SiteType.Cell));
if (dirn == null)
throw new IllegalArgumentException("The step " + step + " is wrong in the track " + name);
final List<Radial> radials = topology.trajectories().radials(SiteType.Cell, current.index(),
dirn.toAbsolute());
if (size == Constants.UNDEFINED)
{
for (final Radial radial : radials)
{
for (int toIdx = 1; toIdx < radial.steps().length; toIdx++)
{
final int site = radial.steps()[toIdx].id();
current = game.board().topology().cells().get(site);
trackList.add(site);
}
}
}
else
{
for (final Radial radial : radials)
{
for (int toIdx = 1; toIdx < radial.steps().length && toIdx < size + 1; toIdx++)
{
final int site = radial.steps()[toIdx].id();
current = game.board().topology().cells().get(site);
trackList.add(site);
}
}
}
}
}
track = new Integer[trackList.size()];
for (int i = 0; i < trackList.size(); i++)
{
final int loc = trackList.getQuick(i);
track[i] = Integer.valueOf(loc);
}
}
}
else if (game.board().defaultSite() == SiteType.Vertex)
{
if (trackDirection != null)
{
final String[] steps = trackDirection.split(",");
if (steps.length < 1)
throw new IllegalArgumentException("The track " + name + " is not correct.");
if (!isNumber(steps[0]))
throw new IllegalArgumentException("The first step in the track " + name + " is not a number.");
final int start = Integer.parseInt(steps[0]);
// if (start >= graph.vertices().size())
// throw new IllegalArgumentException(
// "The site " + start + " is greater than the number of sites in the main
// board");
final TIntArrayList trackList = new TIntArrayList();
trackList.add(start);
Vertex current = (start < game.board().topology().vertices().size())
? game.board().topology().vertices().get(start)
: null;
for (int i = 1; i < steps.length; i++)
{
final String step = steps[i];
final boolean stepIsNumber = isNumber(step);
if (stepIsNumber)
{
final int site = Integer.valueOf(step).intValue();
current = (site < game.board().topology().vertices().size())
? game.board().topology().vertices().get(site)
: null;
trackList.add(site);
}
else if (step.equals("End"))
{
final int site = Integer.valueOf(Constants.END).intValue();
trackList.add(site);
}
else
{
if (current == null)
throw new IllegalArgumentException("The step " + step + " in the track " + name
+ " is impossible without a correct site in the main board.");
String direction = "";
for (int j = 0; j < step.length(); j++)
if (!Character.isDigit(step.charAt(j)))
direction += step.charAt(j);
int size = Constants.UNDEFINED;
if (direction.length() != step.length())
size = Integer.parseInt(step.substring(direction.length()));
final DirectionFacing dirn = convertStringDirection(direction,
game.board().topology().supportedDirections(SiteType.Vertex));
if (dirn == null)
throw new IllegalArgumentException("The step " + step + " is wrong in the track " + name);
final List<Radial> radials = topology.trajectories().radials(SiteType.Vertex, current.index(),
dirn.toAbsolute());
if (size == Constants.UNDEFINED)
{
for (final Radial radial : radials)
{
for (int toIdx = 1; toIdx < radial.steps().length; toIdx++)
{
final int site = radial.steps()[toIdx].id();
current = game.board().topology().vertices().get(site);
trackList.add(site);
}
}
}
else
{
for (final Radial radial : radials)
{
for (int toIdx = 1; toIdx < radial.steps().length && toIdx < size + 1; toIdx++)
{
final int site = radial.steps()[toIdx].id();
current = game.board().topology().vertices().get(site);
trackList.add(site);
}
}
}
}
}
track = new Integer[trackList.size()];
for (int i = 0; i < trackList.size(); i++)
{
final int loc = trackList.getQuick(i);
track[i] = Integer.valueOf(loc);
}
}
}
final TIntArrayList trackWithoutBump = new TIntArrayList();
final TIntArrayList nbBumpByElem = new TIntArrayList();
boolean hasBump = false;
int countBump = 0;
for (int i = 0; i < track.length; i++)
{
if (i == track.length - 1 || track[i].intValue() != track[i + 1].intValue())
{
trackWithoutBump.add(track[i].intValue());
nbBumpByElem.add(countBump);
countBump = 0;
}
else
{
hasBump = true;
countBump++;
}
}
final int[] newTrack = trackWithoutBump.toArray();
this.elems = new Elem[newTrack.length];
for (int i = 0; i < newTrack.length; i++)
{
Elem e = null;
if (i == 0 && looped)
e = new Elem(Integer.valueOf(newTrack[i]), Integer.valueOf(newTrack[newTrack.length-1]), Integer.valueOf(newTrack.length-1), Integer.valueOf(newTrack[i+1]), Integer.valueOf(i +1), Integer.valueOf(nbBumpByElem.getQuick(i)));
else if (i == 0 && !looped)
e = new Elem(Integer.valueOf(newTrack[i]), null, null, Integer.valueOf(newTrack[i+1]), Integer.valueOf(i+1), Integer.valueOf(nbBumpByElem.getQuick(i)));
else if (i == (newTrack.length-1) && looped)
e = new Elem(Integer.valueOf(newTrack[i]), Integer.valueOf(newTrack[i-1]), Integer.valueOf(i-1), Integer.valueOf(newTrack[0]), Integer.valueOf(0), Integer.valueOf(nbBumpByElem.getQuick(i)));
else if(i == (newTrack.length-1) && !looped)
e = new Elem(Integer.valueOf(newTrack[i]), Integer.valueOf(newTrack[i-1]), Integer.valueOf(i-1), null, null, Integer.valueOf(nbBumpByElem.getQuick(i)));
else if(direct)
e = new Elem(Integer.valueOf(newTrack[i]), null, null, Integer.valueOf(newTrack[i+1]), Integer.valueOf(i+1), Integer.valueOf(nbBumpByElem.getQuick(i)));
else
e = new Elem(Integer.valueOf(newTrack[i]),Integer.valueOf(newTrack[i-1]), Integer.valueOf(i-1), Integer.valueOf(newTrack[i+1]), Integer.valueOf(i+1), Integer.valueOf(nbBumpByElem.getQuick(i)));
this.elems[i] = e;
}
// We check if the track has an internal loop.
if (!hasBump)
{
final TIntArrayList listSites = new TIntArrayList();
for (final Elem elem : elems)
{
final int site = elem.site;
if (listSites.contains(site))
{
internalLoop = true;
break;
}
listSites.add(site);
}
}
}
/**
* @param direction
* @param supportedDirectionTypes
* @return The direction corresponding to a string name if it exists
*/
private static DirectionFacing convertStringDirection(String direction, List<DirectionFacing> supportedDirections)
{
for (final DirectionFacing directionSupported : supportedDirections)
if (directionSupported.uniqueName().toString().equals(direction))
return directionSupported;
return null;
}
/**
*
* @param str
* @return True if the string is a number.
*/
private static boolean isNumber(String str)
{
for (int i = 0; i < str.length(); i++)
if (str.charAt(i) < '0' || str.charAt(i) > '9')
return false;
return true;
}
/**
* @return The name of the track.
*/
public String name()
{
return this.name;
}
/**
* @return The elements of the tracks.
*/
public Elem[] elems()
{
return this.elems;
}
/**
* @return The owner of the track.
*/
public int owner()
{
return this.owner;
}
/**
* @return True if the track is looped (e.g. mancala games).
*/
public boolean islooped()
{
return this.looped;
}
/**
* @return True if the track has an internal looped (e.g. Ur variant or big
* pachisi).
*/
public boolean hasInternalLoop()
{
return this.internalLoop;
}
/**
* @return This track's index in the board's list of tracks
*/
public int trackIdx()
{
return trackIdx;
}
/**
* Sets the track index
* @param trackIdx
*/
public void setTrackIdx(final int trackIdx)
{
this.trackIdx = trackIdx;
}
/**
* Note: That method is working only for simple track with no loop (loop track
* or track with internal loop).
*
* @param site The board index of the site.
* @return The track index of the site.
*/
public int siteIndex(final int site)
{
for (int i = 0; i < elems().length; i++)
if (elems()[i].site == site)
return i;
return Constants.UNDEFINED;
}
}
| 16,887 | 28.017182 | 228 | java |
Ludii | Ludii-master/Core/src/game/equipment/container/board/package-info.java | /**
* This section lists a variety of basic board types. All of these types may be
* used for \texttt{<item>} parameters in
* \hyperref[Subsec:game.equipment.Equipment]{Equipment definitions}.
*/
package game.equipment.container.board;
| 240 | 33.428571 | 79 | java |
Ludii | Ludii-master/Core/src/game/equipment/container/board/custom/MancalaBoard.java | package game.equipment.container.board.custom;
import java.util.BitSet;
import annotations.Name;
import annotations.Opt;
import annotations.Or;
import game.Game;
import game.equipment.container.board.Board;
import game.equipment.container.board.Track;
import game.functions.dim.DimConstant;
import game.functions.floats.FloatConstant;
import game.functions.graph.BaseGraphFunction;
import game.functions.graph.GraphFunction;
import game.functions.graph.generators.basis.square.Square;
import game.functions.graph.generators.shape.Rectangle;
import game.functions.graph.operators.Shift;
import game.functions.graph.operators.Union;
import game.types.board.SiteType;
import game.types.board.StoreType;
import game.util.graph.Graph;
import other.context.Context;
/**
* Defines a Mancala-style board.
*
* @author Eric.Piette
*/
public class MancalaBoard extends Board
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/** Number of rows. */
private final int numRows;
/** Number of columns. */
private final int numColumns;
/** Type of the store. */
private final StoreType storeType;
/** Number of stores. */
private final int numStore;
//-------------------------------------------------------------------------
/**
*
* @param rows The number of rows.
* @param columns The number of columns.
* @param store The type of the store.
* @param numStores The number of store.
* @param track The track on the board.
* @param tracks The tracks on the board.
* @param largeStack The game can involves stack(s) higher than 32.
*
* @example (mancalaBoard 2 6)
*/
public MancalaBoard
(
final Integer rows,
final Integer columns,
@Opt @Name final StoreType store,
@Opt @Name final Integer numStores,
@Opt @Name final Boolean largeStack,
@Opt @Or final Track track,
@Opt @Or final Track[] tracks
)
{
super(new BaseGraphFunction()
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
@Override
public Graph eval(final Context context, final SiteType siteType)
{
final int numRows = rows.intValue();
final int numColumns = columns.intValue();
final StoreType storeType = (store == null) ? StoreType.Outer : store;
final int numberStore = (numStores == null) ? 2 : numStores.intValue();
if (storeType.equals(StoreType.Inner) || numberStore != 2 || numRows < 2 || numRows > 6)
return Square.construct(null, new DimConstant(rows.intValue()), null, null).eval(context, siteType);
if (numRows == 2)
return makeMancalaTwoRows(storeType, numColumns).eval(context, siteType);
else if (numRows == 3)
return makeMancalaThreeRows(storeType, numColumns).eval(context, siteType);
else if (numRows == 4)
return makeMancalaFourRows(storeType, numColumns).eval(context, siteType);
else if (numRows == 5)
return makeMancalaFiveRows(storeType, numColumns).eval(context, siteType);
else if (numRows == 6)
return makeMancalaSixRows(storeType, numColumns).eval(context, siteType);
// If wrong parameter, no need of a graph.
return new Graph(new Float[0][0], new Integer[0][0]);
}
@Override
public long gameFlags(Game game)
{
return 0;
}
@Override
public void preprocess(Game game)
{
// Nothing to do.
}
/**
* @return A GraphFunction for a Mancala board with two rows.
*/
public GraphFunction makeMancalaTwoRows(final StoreType storeType, final int numColumns)
{
final GraphFunction bottomRow =
Rectangle.construct
(
new DimConstant(1), new DimConstant(numColumns), null
);
final GraphFunction topRow =
new Shift
(
new FloatConstant(0), new FloatConstant(1), null,
Rectangle.construct(new DimConstant(1),
new DimConstant(numColumns), null)
);
if (!storeType.equals(StoreType.None))
{
final GraphFunction leftStore =
new Graph
(
new Float[][] {{ Float.valueOf(-0.85f), Float.valueOf(0.5f) }},
null
);
final GraphFunction rightStore =
new Shift
(
new FloatConstant(-0.15f), new FloatConstant(0f), null,
new Graph
(
new Float[][] {{ Float.valueOf(numColumns), Float.valueOf(0.5f) }},
null
)
);
return new Union
(
new GraphFunction[] { leftStore, bottomRow, topRow, rightStore },
Boolean.TRUE
);
}
return new Union
(
new GraphFunction[] { bottomRow, topRow },
Boolean.TRUE
);
}
/**
* @return A GraphFunction for a Mancala board with three rows.
*/
public GraphFunction makeMancalaThreeRows(final StoreType storeType, final int numColumns)
{
final GraphFunction bottomRow = Rectangle.construct(new DimConstant(1), new DimConstant(numColumns),
null);
final GraphFunction middleRow = new Shift(new FloatConstant(0), new FloatConstant(1), null,
Rectangle.construct(new DimConstant(1), new DimConstant(numColumns), null));
final GraphFunction topRow = new Shift(new FloatConstant(0), new FloatConstant(2), null,
Rectangle.construct(new DimConstant(1), new DimConstant(numColumns), null));
if (!storeType.equals(StoreType.None))
{
final GraphFunction leftStore = new Graph(new Float[][]
{
{ Float.valueOf(-1), Float.valueOf(1) } }, null);
final GraphFunction rightStore = new Shift(new FloatConstant(0), new FloatConstant(0), null,
new Graph(new Float[][]
{
{ Float.valueOf(numColumns), Float.valueOf(1) }
}, null));
return new Union(new GraphFunction[]
{ leftStore, bottomRow, middleRow, topRow, rightStore }, Boolean.TRUE);
}
return new Union(new GraphFunction[]
{ bottomRow, middleRow, topRow }, Boolean.TRUE);
}
/**
* @return A GraphFunction for a Mancala board with four rows.
*/
public GraphFunction makeMancalaFourRows(final StoreType storeType, final int numColumns)
{
final GraphFunction bottomOuterRow = Rectangle.construct(new DimConstant(1),
new DimConstant(numColumns), null);
final GraphFunction bottomInnerRow = new Shift(new FloatConstant(0), new FloatConstant(1), null,
Rectangle.construct(new DimConstant(1), new DimConstant(numColumns), null));
final GraphFunction topInnerRow = new Shift(new FloatConstant(0), new FloatConstant(2), null,
Rectangle.construct(new DimConstant(1), new DimConstant(numColumns), null));
final GraphFunction topOuterRow = new Shift(new FloatConstant(0), new FloatConstant(3), null,
Rectangle.construct(new DimConstant(1), new DimConstant(numColumns), null));
if (!storeType.equals(StoreType.None))
{
final GraphFunction leftStore = new Graph(new Float[][]
{
{ Float.valueOf((float) -0.9), Float.valueOf((float) 1.5) } }, null);
final GraphFunction rightStore = new Shift(new FloatConstant((float) -0.1), new FloatConstant(0),
null,
new Graph(new Float[][]
{
{ Float.valueOf(numColumns), Float.valueOf((float) 1.5) } }, null));
return new Union(new GraphFunction[]
{ leftStore, bottomOuterRow, bottomInnerRow, topInnerRow, topOuterRow, rightStore }, Boolean.TRUE);
}
return new Union(new GraphFunction[]
{ bottomOuterRow, bottomInnerRow, topInnerRow, topOuterRow }, Boolean.TRUE);
}
/**
* @return A GraphFunction for a Mancala board with five rows.
*/
public GraphFunction makeMancalaFiveRows(final StoreType storeType, final int numColumns)
{
final GraphFunction bottomOuterRow = Rectangle.construct(new DimConstant(1),
new DimConstant(numColumns), null);
final GraphFunction bottomInnerRow = new Shift(new FloatConstant(0), new FloatConstant(1), null,
Rectangle.construct(new DimConstant(1), new DimConstant(numColumns), null));
final GraphFunction middleRow = new Shift(new FloatConstant(0), new FloatConstant(2), null,
Rectangle.construct(new DimConstant(1), new DimConstant(numColumns), null));
final GraphFunction topInnerRow = new Shift(new FloatConstant(0), new FloatConstant(3), null,
Rectangle.construct(new DimConstant(1), new DimConstant(numColumns), null));
final GraphFunction topOuterRow = new Shift(new FloatConstant(0), new FloatConstant(4), null,
Rectangle.construct(new DimConstant(1), new DimConstant(numColumns), null));
if (!storeType.equals(StoreType.None))
{
final GraphFunction leftStore = new Graph(new Float[][]
{
{ Float.valueOf((float) -1.0), Float.valueOf((float) 2.0) } }, null);
final GraphFunction rightStore = new Shift(new FloatConstant((float) -0.1), new FloatConstant(0),
null, new Graph(new Float[][]
{
{ Float.valueOf((float) (numColumns + 0.1)), Float.valueOf((float) 2.0) } }, null));
return new Union(new GraphFunction[]
{ leftStore, bottomOuterRow, bottomInnerRow, middleRow, topInnerRow, topOuterRow, rightStore },
Boolean.TRUE);
}
return new Union(new GraphFunction[]
{ bottomOuterRow, bottomInnerRow, middleRow, topInnerRow, topOuterRow }, Boolean.TRUE);
}
/**
* @return A GraphFunction for a Mancala board with six rows.
*/
public GraphFunction makeMancalaSixRows(final StoreType storeType, final int numColumns)
{
final GraphFunction bottomOuterRow = Rectangle.construct(new DimConstant(1),
new DimConstant(numColumns), null);
final GraphFunction bottomInnerRow = new Shift(new FloatConstant(0), new FloatConstant(1), null,
Rectangle.construct(new DimConstant(1), new DimConstant(numColumns), null));
final GraphFunction bottomInnerInnerRow = new Shift(new FloatConstant(0), new FloatConstant(2), null,
Rectangle.construct(new DimConstant(1), new DimConstant(numColumns), null));
final GraphFunction topInnerInnerRow = new Shift(new FloatConstant(0), new FloatConstant(3), null,
Rectangle.construct(new DimConstant(1), new DimConstant(numColumns), null));
final GraphFunction topInnerRow = new Shift(new FloatConstant(0), new FloatConstant(4), null,
Rectangle.construct(new DimConstant(1), new DimConstant(numColumns), null));
final GraphFunction topOuterRow = new Shift(new FloatConstant(0), new FloatConstant(5), null,
Rectangle.construct(new DimConstant(1), new DimConstant(numColumns), null));
if (!storeType.equals(StoreType.None))
{
final GraphFunction leftStore = new Graph(new Float[][]
{
{ Float.valueOf((float) -0.9), Float.valueOf((float) 2.5) } }, null);
final GraphFunction rightStore = new Shift(new FloatConstant((float) -0.1), new FloatConstant(0),
null, new Graph(new Float[][]
{
{ Float.valueOf(numColumns), Float.valueOf((float) 2.5) } }, null));
return new Union(new GraphFunction[]
{ leftStore, bottomOuterRow, bottomInnerRow, bottomInnerInnerRow, topInnerInnerRow, topInnerRow,
topOuterRow, rightStore }, Boolean.TRUE);
}
return new Union(new GraphFunction[]
{ bottomOuterRow, bottomInnerRow, bottomInnerInnerRow, topInnerInnerRow, topInnerRow, topOuterRow },
Boolean.TRUE);
}
}, track, tracks, null, null, SiteType.Vertex, largeStack);
// We store these parameters to access them in the Mancala design.
this.numRows = rows.intValue();
this.numColumns = columns.intValue();
this.storeType = (store == null) ? StoreType.Outer : store;
this.numStore = (numStores == null) ? 2 : numStores.intValue();
if (numRows > 6 || numRows < 2)
throw new IllegalArgumentException("Board: Only 2 to 6 rows are supported for the Mancala board.");
int numNonNull = 0;
if (track != null)
numNonNull++;
if (tracks != null)
numNonNull++;
if (numNonNull > 1)
throw new IllegalArgumentException("Board: Only one of `track' or `tracks' can be non-null.");
}
//-------------------------------------------------------------------------
/**
* @return The number of rows.
*/
public int numRows()
{
return numRows;
}
/**
* @return The number of columns.
*/
public int numColumns()
{
return numColumns;
}
/**
* @return The type of the store.
*/
public StoreType storeType()
{
return storeType;
}
/**
* @return The number of stores.
*/
public int numStore()
{
return numStore;
}
/**
* @return The graph function corresponding to a two rows mancala board.
*/
public GraphFunction createTwoRowMancala()
{
final GraphFunction leftStore = new Graph(new Float[][]
{
{ Float.valueOf((float) 0.85), Float.valueOf((float) 0.5) } }, null);
final GraphFunction rightStore = new Shift(new FloatConstant((float) -0.15), new FloatConstant(0), null,
new Graph(new Float[][]
{
{ Float.valueOf(numColumns), Float.valueOf((float) 0.5) } }, null));
final GraphFunction bottomRow = Rectangle.construct(new DimConstant(1), new DimConstant(numColumns), null);
final GraphFunction topRow = new Shift(new FloatConstant(0), new FloatConstant(1), null,
Rectangle.construct(new DimConstant(1), new DimConstant(numColumns), null));
return new Union(new GraphFunction[]
{ leftStore, bottomRow, topRow, rightStore }, Boolean.TRUE);
}
// ----------------------------------
@Override
public String toEnglish(final Game game)
{
String englishString = numRows + " x " + numColumns + " Mancala board";
if (numStore > 0)
englishString += " with " + numStore + " " + storeType.name().toLowerCase() + " stores";
return englishString;
}
// ----------------------------------
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
concepts.or(super.concepts(game));
return concepts;
}
@Override
public BitSet writesEvalContextRecursive()
{
final BitSet writeEvalContext = new BitSet();
writeEvalContext.or(super.writesEvalContextRecursive());
return writeEvalContext;
}
@Override
public BitSet readsEvalContextRecursive()
{
final BitSet readEvalContext = new BitSet();
readEvalContext.or(super.readsEvalContextRecursive());
return readEvalContext;
}
}
| 14,345 | 31.383747 | 109 | java |
Ludii | Ludii-master/Core/src/game/equipment/container/board/custom/SurakartaBoard.java | package game.equipment.container.board.custom;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.Collections;
import java.util.List;
import annotations.Name;
import annotations.Opt;
import game.Game;
import game.equipment.container.board.Board;
import game.equipment.container.board.Track;
import game.functions.graph.GraphFunction;
import game.types.board.SiteType;
import main.Constants;
import metadata.graphics.util.ContainerStyleType;
/**
* Defines a Surakarta-style board.
*
* @author cambolbro
*
* @remarks Surakata-style boards have loops that pieces must travel around
* in order to capture other pieces.
* The following board shapes are supported:
* Square, Rectangle, Hexagon, Triangle.
*/
public class SurakartaBoard extends Board
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
// Number of loops to create
private int numLoops;
// Row to start loops from (corners are row 0).
private final int startAtRow;
//-------------------------------------------------------------------------
/**
* @param graphFn The graph function used to build the board.
* @param loops Number of loops, i.e. special capture tracks [(minDim - 1) / 2].
* @param from Which row to start loops from [1].
* @param largeStack The game can involves stack(s) higher than 32.
*
* @example (surakartaBoard (square 6) loops:2)
*/
public SurakartaBoard
(
final GraphFunction graphFn,
@Opt @Name final Integer loops,
@Opt @Name final Integer from,
@Opt @Name final Boolean largeStack
)
{
super(graphFn, null, null, null, null, SiteType.Vertex, largeStack);
numLoops = (loops != null) ? loops.intValue() : Constants.UNDEFINED;
startAtRow = (from != null) ? from.intValue() : 1;
}
//-------------------------------------------------------------------------
@Override
public void createTopology(final int beginIndex, final int numEdges)
{
super.createTopology(beginIndex, numEdges);
// Done here because that's needed in the computation of the tracks for Surakarta
for (final SiteType type : SiteType.values())
{
topology.computeRows(type, false);
topology.computeColumns(type, false);
}
final int dim0 = topology().rows(SiteType.Vertex).size() - 1;
final int dim1 = topology().columns(SiteType.Vertex).size() - 1;
if (numLoops == Constants.UNDEFINED)
{
switch (topology().graph().basis())
{
case Square: numLoops = (Math.min(dim0, dim1) - 1) / 2; break;
case Triangular: numLoops = (dim0 ) / 2; break;
//$CASES-OMITTED$
default: System.out.println("** Board type " + topology().graph().basis() + " not supported for Surkarta.");
}
}
final int totalLoops = numLoops;
// System.out.println("SurakartaBoard: dim0=" + dim0 + ", dim1=" + dim1 + ".");
// System.out.println(" numLoops=" + numLoop + ", startAtRow=" + startAtRow + ".");
// System.out.println("dim0=" + dim0 + ", dim1=" + dim1);
switch (topology().graph().basis())
{
case Square: createTracksSquare(dim0, dim1, totalLoops); break;
case Triangular: createTracksTriangular(dim0, totalLoops); break;
//$CASES-OMITTED$
default: System.out.println("** Board type " + topology().graph().basis() + " not supported for Surkarta.");
}
numSites = topology.vertices().size();
style = ContainerStyleType.Graph;
}
//-------------------------------------------------------------------------
/**
* @param dim0 Number of cells vertically.
* @param dim1 Number of cells horizontally.
* @param totalLoops Number of loops to create.
*/
void createTracksSquare(final int dim0, final int dim1, final int totalLoops)
{
final int rows = dim0 + 1;
final int cols = dim1 + 1;
// Create the tracks, forward and backward for each loop
final List<Integer> track = new ArrayList<Integer>();
for (int lid = 0; lid < totalLoops; lid++)
{
// Generate the basic loop, negating potential speed bumps
final int loop = startAtRow + lid;
track.clear();
// Bottom row rightwards
for (int col = 0; col < cols; col++)
{
int site = loop * cols + col;
if (col == 0 || col == cols - 1)
site = -site;
track.add(Integer.valueOf(site));
}
// Right column upwards
for (int row = 0; row < rows; row++)
{
int site = cols - 1 - loop + row * cols;
if (row == 0 || row == rows - 1)
site = -site;
track.add(Integer.valueOf(site));
}
// Top row leftwards
for (int col = 0; col < cols; col++)
{
int site = rows * cols - 1 - loop * cols - col;
if (col == 0 || col == cols - 1)
site = -site;
track.add(Integer.valueOf(site));
}
// Left column downwards
for (int row = 0; row < rows; row++)
{
int site = rows * cols - cols + loop - row * cols;
if (row == 0 || row == rows - 1)
site = -site;
track.add(Integer.valueOf(site));
}
// System.out.println("Track: " + track);
// Generate the forward and backward track with speed bumps
final List<Integer> forward = new ArrayList<Integer>();
for (int n = 0; n < track.size(); n++)
{
final int a = track.get(n).intValue();
final int b = track.get((n + 1) % track.size()).intValue();
forward.add(Integer.valueOf(Math.abs(a)));
if (a < 0 && b < 0)
forward.add(Integer.valueOf(Math.abs(a))); // add double speed bump
}
final List<Integer> backward = new ArrayList<Integer>();
Collections.reverse(track);
for (int n = 0; n < track.size(); n++)
{
final int a = track.get(n).intValue();
final int b = track.get((n + 1) % track.size()).intValue();
backward.add(Integer.valueOf(Math.abs(a)));
if (a < 0 && b < 0)
backward.add(Integer.valueOf(Math.abs(a))); // add double speed bump
}
final Integer[] arrayForward = forward.toArray(new Integer[0]);
final Integer[] arrayBackward = backward.toArray(new Integer[0]);
final String nameForward = "Track" + loop + "F";
final String nameBackward = "Track" + loop + "B";
final Track trackForward = new Track(nameForward, arrayForward, null, null, Boolean.TRUE, null, null, Boolean.TRUE);
final Track trackBackward = new Track(nameBackward, arrayBackward, null, null, Boolean.TRUE, null, null, Boolean.TRUE);
tracks.add(trackForward);
tracks.add(trackBackward);
}
}
//-------------------------------------------------------------------------
/**
* @param dim Number of cells on a side.
* @param totalLoops Number of loops to create.
*/
void createTracksTriangular(final int dim, final int totalLoops)
{
final int rows = dim + 1;
final int cols = dim + 1;
// Create the tracks, forward and backward for each loop
final List<Integer> track = new ArrayList<Integer>();
for (int lid = 0; lid < totalLoops; lid++)
{
// Generate the basic loop, negating potential speed bumps
final int loop = startAtRow + lid;
track.clear();
// Three runs
int v = 0;
int dec = cols;
for (int step = 0; step < loop; step++)
v += dec--;
// Bottom row rightwards
// System.out.println("v starts at " + v);
for (int step = 0; step < rows - loop; step++)
{
int site = v;
if (step == 0 || step >= rows - loop - 1)
site = -site;
track.add(Integer.valueOf(site));
v++;
}
// Right column upwards \
v = cols - 1 - loop;
dec = rows - 1;
for (int step = 0; step < rows - loop; step++)
{
int site = v;
if (step == 0 || step >= rows - loop - 1)
site = -site;
track.add(Integer.valueOf(site));
v += dec--;
}
// Left column downwards /
// v should be at the correct value
dec += 3;
for (int step = 0; step < rows - loop; step++)
{
int site = v;
if (step == 0 || step >= rows - loop - 1)
site = -site;
track.add(Integer.valueOf(site));
v -= dec++;
}
// System.out.println("Track: " + track);
// Generate the forward and backward track with speed bumps
final List<Integer> forward = new ArrayList<Integer>();
for (int n = 0; n < track.size(); n++)
{
final int a = track.get(n).intValue();
final int b = track.get((n + 1) % track.size()).intValue();
forward.add(Integer.valueOf(Math.abs(a)));
if (a < 0 && b < 0)
forward.add(Integer.valueOf(Math.abs(a))); // add double speed bump
}
final List<Integer> backward = new ArrayList<Integer>();
Collections.reverse(track);
for (int n = 0; n < track.size(); n++)
{
final int a = track.get(n).intValue();
final int b = track.get((n + 1) % track.size()).intValue();
backward.add(Integer.valueOf(Math.abs(a)));
if (a < 0 && b < 0)
backward.add(Integer.valueOf(Math.abs(a))); // add double speed bump
}
final Integer[] arrayForward = forward.toArray(new Integer[0]);
final Integer[] arrayBackward = backward.toArray(new Integer[0]);
final String nameForward = "Track" + loop + "F";
final String nameBackward = "Track" + loop + "B";
final Track trackForward = new Track(nameForward, arrayForward, null, null, Boolean.TRUE, null, null, Boolean.TRUE);
final Track trackBackward = new Track(nameBackward, arrayBackward, null, null, Boolean.TRUE, null, null, Boolean.TRUE);
tracks.add(trackForward);
tracks.add(trackBackward);
}
}
//-------------------------------------------------------------------------
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
concepts.or(super.concepts(game));
return concepts;
}
@Override
public BitSet writesEvalContextRecursive()
{
final BitSet writeEvalContext = new BitSet();
writeEvalContext.or(super.writesEvalContextRecursive());
return writeEvalContext;
}
@Override
public BitSet readsEvalContextRecursive()
{
final BitSet readEvalContext = new BitSet();
readEvalContext.or(super.readsEvalContextRecursive());
return readEvalContext;
}
//-------------------------------------------------------------------------
@Override
public String toEnglish(final Game game)
{
final int dim0 = topology().rows(SiteType.Vertex).size() - 1;
final int dim1 = topology().columns(SiteType.Vertex).size() - 1;
String englishString = dim0 + " x " + dim1 + " Surakarta board";
englishString += " with " + topology().graph().basis().name() + " tiling,";
englishString += " with " + numLoops + " loops which start at row " + startAtRow;
return englishString;
}
//-------------------------------------------------------------------------
}
| 10,735 | 29.413598 | 122 | java |
Ludii | Ludii-master/Core/src/game/equipment/container/board/custom/package-info.java | /**
* This section lists a variety of customised, special board types. All of these
* types may be used for \texttt{<item>} parameters in
* \hyperref[Subsec:game.equipment.Equipment]{Equipment definitions}.
*/
package game.equipment.container.board.custom;
| 261 | 36.428571 | 80 | java |
Ludii | Ludii-master/Core/src/game/equipment/container/other/Deck.java | package game.equipment.container.other;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.List;
import annotations.Name;
import annotations.Opt;
import game.Game;
import game.equipment.component.Card;
import game.equipment.component.Component;
import game.equipment.container.Container;
import game.functions.dim.DimConstant;
import game.functions.graph.generators.basis.hex.RectangleOnHex;
import game.functions.graph.generators.basis.square.RectangleOnSquare;
import game.functions.graph.generators.basis.tri.RectangleOnTri;
import game.types.board.SiteType;
import game.types.component.CardType;
import game.types.play.RoleType;
import game.util.graph.Face;
import game.util.graph.Graph;
import gnu.trove.list.array.TIntArrayList;
import main.Constants;
import metadata.graphics.util.ContainerStyleType;
import other.ItemType;
import other.concept.Concept;
import other.topology.Cell;
import other.topology.Topology;
import other.topology.Vertex;
/**
* Generates a deck of cards.
*
* @author Eric.Piette
*/
public class Deck extends Container
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/** The number of cards by suit. */
private final Integer cardsBySuit;
/** The number of suits. */
private final Integer suits;
/** The ranks of each card. */
private Integer[] ranks;
/** The values of each card. */
private Integer[] values;
/** The trump ranks of each card. */
private Integer[] trumpRanks;
/** The trump values of each card. */
private Integer[] trumpValues;
/** The biased value of the deck. */
private Integer[] biased;
/** The type of the card. */
private CardType[] types;
/** The indices of the components in the deck. */
private final TIntArrayList indexComponent;
/** The number of locations in this container. */
protected int numLocs;
//-------------------------------------------------------------------------
/**
* @param role The owner of the deck [Shared].
* @param cardsBySuit The number of cards per suit [13].
* @param suits The number of suits in the deck [4].
* @param cards Specific data about each kind of card for each suit.
*
* @example (deck)
*
* @example (deck { (card Seven rank:0 value:0 trumpRank:0 trumpValue:0) (card
* Eight rank:1 value:0 trumpRank:1 trumpValue:0) (card Nine rank:2
* value:0 trumpRank:6 trumpValue:14) (card Ten rank:3 value:10
* trumpRank:4 trumpValue:10) (card Jack rank:4 value:2 trumpRank:7
* trumpValue:20) (card Queen rank:5 value:3 trumpRank:2 trumpValue:3)
* (card King rank:6 value:4 trumpRank:3 trumpValue:4) (card Ace rank:7
* value:11 trumpRank:5 trumpValue:11) })
*/
public Deck
(
@Opt final RoleType role,
@Opt @Name final Integer cardsBySuit,
@Opt @Name final Integer suits,
@Opt final game.util.equipment.Card[] cards
)
{
super(null, Constants.UNDEFINED, (role == null) ? RoleType.Shared : role);
final String className = this.getClass().toString();
final String containerName = className.substring(className.lastIndexOf('.') + 1, className.length());
final RoleType realRole = (role == null) ? RoleType.Shared : role;
if (realRole.owner() > 0 && realRole.owner() <= Constants.MAX_PLAYERS)
{
if (name() == null)
this.setName(containerName + realRole.owner());
}
else if (realRole == RoleType.Neutral)
{
if (name() == null)
this.setName(containerName + realRole.owner());
}
else if (realRole == RoleType.Shared)
{
if (name() == null)
this.setName(containerName + realRole.owner());
}
this.numLocs = 1;
this.style = ContainerStyleType.Hand;
setType(ItemType.Hand);
this.cardsBySuit = (cardsBySuit == null && cards == null) ? Integer.valueOf(13)
: ((cards != null) ? Integer.valueOf(cards.length) : cardsBySuit);
this.suits = (suits == null) ? Integer.valueOf(4) : suits;
final Integer[] valuesOfCards = (cards == null) ? null : new Integer[cards.length];
final Integer[] trumpValuesOfCards = (cards == null) ? null : new Integer[cards.length];
final Integer[] ranksOfCards = (cards == null) ? null : new Integer[cards.length];
final Integer[] trumpRanksOfCards = (cards == null) ? null : new Integer[cards.length];
final Integer[] biasedValuesOfCards = (cards == null) ? null : new Integer[cards.length];
CardType[] typeOfCards = (cards == null) ? null : new CardType[cards.length];
if (cards != null)
for (int i = 0; i < cards.length; i++)
{
final game.util.equipment.Card card = cards[i];
valuesOfCards[i] = Integer.valueOf(card.value());
trumpValuesOfCards[i] = Integer.valueOf(card.trumpValue());
ranksOfCards[i] = Integer.valueOf(card.rank());
biasedValuesOfCards[i] = Integer.valueOf(card.biased());
trumpRanksOfCards[i] = Integer.valueOf(card.trumpRank());
typeOfCards[i] = card.type();
}
final Integer[] val = (valuesOfCards == null) ? new Integer[this.cardsBySuit.intValue()] : valuesOfCards;
if (val[0] == null)
{
for (int i = 1; i <= this.cardsBySuit.intValue(); i++)
val[i - 1] = Integer.valueOf(i);
}
if (typeOfCards == null)
{
typeOfCards = new CardType[this.cardsBySuit.intValue()];
for (int i = 1; i <= this.cardsBySuit.intValue(); i++)
typeOfCards[i - 1] = CardType.values()[i];
}
this.types = typeOfCards;
this.values = val;
this.trumpValues = (trumpValuesOfCards == null) ? val : trumpValuesOfCards;
this.trumpRanks = (trumpRanksOfCards == null) ? val : trumpRanksOfCards;
this.ranks = (ranksOfCards == null) ? val : ranksOfCards;
this.biased = biasedValuesOfCards;
this.indexComponent = new TIntArrayList();
}
//-------------------------------------------------------------------------
/**
* Copy constructor.
*
* Protected because we do not want the compiler to detect it, this is called
* only in Clone method.
*
* @param other
*/
protected Deck(final Deck other)
{
super(other);
cardsBySuit = other.cardsBySuit;
suits = other.suits;
indexComponent = other.indexComponent;
if (other.biased != null)
{
biased = new Integer[other.biased.length];
for (int i = 0; i < other.biased.length; i++)
biased[i] = other.biased[i];
}
else
biased = null;
if (other.ranks != null)
{
ranks = new Integer[other.ranks.length];
for (int i = 0; i < other.ranks.length; i++)
ranks[i] = other.ranks[i];
}
else
ranks = null;
if (other.values != null)
{
values = new Integer[other.values.length];
for (int i = 0; i < other.values.length; i++)
values[i] = other.values[i];
}
else
values = null;
if (other.trumpRanks != null)
{
trumpRanks = new Integer[other.trumpRanks.length];
for (int i = 0; i < other.trumpRanks.length; i++)
trumpRanks[i] = other.trumpRanks[i];
}
else
trumpRanks = null;
if (other.trumpValues != null)
{
trumpValues = new Integer[other.trumpValues.length];
for (int i = 0; i < other.trumpValues.length; i++)
trumpValues[i] = other.trumpValues[i];
}
else
trumpValues = null;
if (other.types != null)
{
types = new CardType[other.types.length];
for (int i = 0; i < other.types.length; i++)
types[i] = other.types[i];
}
else
types = null;
}
@Override
public Deck clone()
{
return new Deck(this);
}
/**
* @param indexCard
* @param cid
* @return The list of cards generated according to the deck.
*/
public List<Component> generateCards(final int indexCard, final int cid)
{
final List<Component> cards = new ArrayList<Component>();
int i = cid;
int cardIndex = indexCard;
for (int indexSuit = 1; indexSuit <= suits().intValue(); indexSuit++)
for (int indexCardSuit = 0; indexCardSuit < cardsBySuits().intValue(); indexCardSuit++)
{
final Card card = new Card("Card" + cardIndex, role(), types()[indexCardSuit],
ranks()[indexCardSuit], values()[indexCardSuit], trumpRanks()[indexCardSuit],
trumpValues()[indexCardSuit], Integer.valueOf(indexSuit), null, null, null, null);
card.setBiased(getBiased());
cards.add(card);
indexComponent().add(i);
i++;
cardIndex++;
}
return cards;
}
//-------------------------------------------------------------------------
/**
* @return Biased values.
*/
public Integer[] getBiased()
{
return biased;
}
/**
* @return Ranks of each card.
*/
public Integer[] ranks()
{
return ranks;
}
/**
* @return Values of each card.
*/
public Integer[] values()
{
return values;
}
/**
* @return The number of suits.
*/
public Integer suits()
{
return suits;
}
/**
* @return The card types.
*/
public CardType[] types()
{
return types;
}
/**
* @return The number of cards by suit.
*/
public Integer cardsBySuits()
{
return cardsBySuit;
}
/**
* @return The trump values of the cards.
*/
public Integer[] trumpValues()
{
return trumpValues;
}
/**
* @return The trump ranks of the cards.
*/
public Integer[] trumpRanks()
{
return trumpRanks;
}
/**
* @return The index of all the cards components.
*/
public TIntArrayList indexComponent()
{
return indexComponent;
}
@Override
public boolean isDeck()
{
return true;
}
@Override
public boolean isHand()
{
return true;
}
//-------------------------------------------------------------------------
@Override
public void createTopology(final int beginIndex, final int numEdge)
{
final double unit = 1.0 / numLocs;
topology = new Topology();
final int realNumEdge = (numEdge == Constants.UNDEFINED) ? 4 : numEdge;
Graph graph = null;
if (realNumEdge == 6)
graph = new RectangleOnHex(new DimConstant(1), new DimConstant(this.numLocs)).eval(null, SiteType.Cell);
else if (realNumEdge == 3)
graph = new RectangleOnTri(new DimConstant(1), new DimConstant(this.numLocs)).eval(null, SiteType.Cell);
else
graph = new RectangleOnSquare(new DimConstant(1), new DimConstant(this.numLocs), null, null).eval(null, SiteType.Cell);
// Add the cells to the topology.
for (int i = 0; i < graph.faces().size(); i++)
{
final Face face = graph.faces().get(i);
final Cell cell = new Cell(face.id() + beginIndex, face.pt().x() + (i * unit), face.pt().y(), face.pt().z());
cell.setCoord(cell.row(), cell.col(), 0);
cell.setCentroid(face.pt().x(), face.pt().y(), 0);
topology.cells().add(cell);
// We add the vertices of the cells and vice versa.
for (final game.util.graph.Vertex v : face.vertices())
{
final double x = v.pt().x();
final double y = v.pt().y();
final double z = v.pt().z();
final Vertex vertex = new Vertex(Constants.UNDEFINED, x, y, z);
cell.vertices().add(vertex);
}
}
numSites = topology.cells().size();
}
/**
* @return The number of sites on this deck container.
*/
public static int numLocs()
{
return 1;
}
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
concepts.set(Concept.Card.id(), true);
return concepts;
}
@Override
public BitSet writesEvalContextRecursive()
{
final BitSet writeEvalContext = new BitSet();
return writeEvalContext;
}
@Override
public BitSet readsEvalContextRecursive()
{
final BitSet readEvalContext = new BitSet();
return readEvalContext;
}
@Override
public boolean missingRequirement(final Game game)
{
boolean missingRequirement = false;
if (role() != null)
{
final int indexOwnerPhase = role().owner();
if (
(
indexOwnerPhase < 1
&&
!role().equals(RoleType.Shared)
&&
!role().equals(RoleType.Neutral)
&&
!role().equals(RoleType.All)
)
||
indexOwnerPhase > game.players().count()
)
{
game.addRequirementToReport(
"A deck is defined in the equipment with an incorrect owner: " + role() + ".");
missingRequirement = true;
}
}
return missingRequirement;
}
} | 12,064 | 24.946237 | 122 | java |
Ludii | Ludii-master/Core/src/game/equipment/container/other/Dice.java | package game.equipment.container.other;
import java.util.BitSet;
import annotations.Name;
import annotations.Opt;
import annotations.Or;
import game.Game;
import game.equipment.container.Container;
import game.functions.dim.DimConstant;
import game.functions.graph.generators.basis.hex.RectangleOnHex;
import game.functions.graph.generators.basis.square.RectangleOnSquare;
import game.functions.graph.generators.basis.tri.RectangleOnTri;
import game.types.board.SiteType;
import game.types.play.RoleType;
import game.util.graph.Face;
import game.util.graph.Graph;
import main.Constants;
import metadata.graphics.util.ContainerStyleType;
import other.ItemType;
import other.concept.Concept;
import other.topology.Cell;
import other.topology.Topology;
import other.topology.Vertex;
/**
* Generates a set of dice.
*
* @author Eric.Piette
*
* @remarks Used for any dice game to define a set of dice. Only the set of dice
* can be rolled.
*/
public final class Dice extends Container
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/** The number of faces of the die. */
private final int numFaces;
/** The start value of the die. */
private final Integer start;
/** The faces of the die. */
private Integer[][] faces;
/** The biased value of the die. */
private Integer[] biased;
/** The number of locations in this container. */
protected int numLocs;
//-------------------------------------------------------------------------
/**
* @param d The number of faces of the die [6].
* @param faces The values of each face.
* @param facesByDie The values of each face for each die.
* @param from The starting value of each die [1].
* @param role The owner of the dice [Shared].
* @param num The number of dice in the set.
* @param biased The biased values of each die.
*
* @example (dice d:2 from:0 num:4)
*/
public Dice
(
@Opt @Name final Integer d,
@Or @Opt @Name final Integer[] faces,
@Or @Opt @Name final Integer[][] facesByDie,
@Or @Opt @Name final Integer from,
@Opt final RoleType role,
@Name final Integer num,
@Opt @Name final Integer[] biased
)
{
super(null, Constants.UNDEFINED, (role == null) ? RoleType.Shared : role);
// Limit on the max number of faces.
if (d != null)
{
if (d.intValue() < 0 || d.intValue() > Constants.MAX_FACE_DIE)
throw new IllegalArgumentException("The number of faces of a die can not be negative or to exceed "
+ Constants.MAX_FACE_DIE + ".");
}
else if (faces != null)
{
if (faces.length > Constants.MAX_FACE_DIE)
throw new IllegalArgumentException(
"The number of faces of a die can not exceed " + Constants.MAX_FACE_DIE + ".");
}
else if (facesByDie != null)
{
if (facesByDie.length > Constants.MAX_FACE_DIE)
throw new IllegalArgumentException(
"The number of faces of a die can not exceed " + Constants.MAX_FACE_DIE + ".");
}
final String className = this.getClass().toString();
final String containerName = className.substring(className.lastIndexOf('.') + 1, className.length());
final RoleType realRole = (role == null) ? RoleType.Shared : role;
if (realRole.owner() > 0 && realRole.owner() <= Constants.MAX_PLAYERS)
{
if (name() == null)
this.setName(containerName + realRole.owner());
}
else if (realRole == RoleType.Neutral)
{
if (name() == null)
this.setName(containerName + realRole.owner());
}
else if (realRole == RoleType.Shared)
{
if (name() == null)
this.setName(containerName + realRole.owner());
}
this.numLocs = num.intValue();
this.style = ContainerStyleType.Hand;
this.numFaces = (d != null) ? d.intValue()
: (faces != null) ? faces.length : facesByDie != null ? facesByDie[0].length : 6;
int numNonNull = 0;
if (from != null)
numNonNull++;
if (faces != null)
numNonNull++;
if (numNonNull > 1)
throw new IllegalArgumentException("Zero or one Or parameter must be non-null.");
this.start = (faces != null || facesByDie != null) ? null : (from == null) ? Integer.valueOf(1) : from;
if (facesByDie != null)
this.faces = facesByDie;
else if (faces != null)
{
final Integer[][] sameFacesByDie = new Integer[this.numLocs][faces.length];
for (int i = 0; i < this.numLocs; i++)
sameFacesByDie[i] = faces;
this.faces = sameFacesByDie;
}
else
{
final Integer[][] sequentialFaces = new Integer[this.numLocs][this.numFaces];
for (int i = 0; i < this.numLocs; i++)
for (int j = 0; j < this.numFaces; j++)
sequentialFaces[i][j] = Integer.valueOf(start.intValue() + j);
this.faces = sequentialFaces;
}
this.biased = biased;
setType(ItemType.Dice);
}
//-------------------------------------------------------------------------
/**
* Copy constructor.
*
* Protected because we do not want the compiler to detect it, this is called
* only in Clone method.
*
* @param other The dice.
*/
protected Dice(final Dice other)
{
super(other);
numFaces = other.numFaces;
start = other.start;
if (other.biased != null)
{
biased = new Integer[other.biased.length];
for (int i = 0; i < other.biased.length; i++)
biased[i] = other.biased[i];
}
else
biased = null;
if (other.faces != null)
{
faces = new Integer[other.faces.length][];
for (int i = 0; i < other.faces.length; i++)
for (int j = 0; j < other.faces[i].length; j++)
faces[i][j] = other.faces[i][j];
}
else
faces = null;
}
@Override
public Dice clone()
{
return new Dice(this);
}
//-------------------------------------------------------------------------
/**
* @return The biased values.
*/
public Integer[] getBiased()
{
return biased;
}
/**
* @return The faces values of each die.
*/
public Integer[][] getFaces()
{
return faces;
}
/**
* @return The starting value of each die.
*/
public Integer getStart()
{
return start;
}
/**
* @return The number of faces of each die.
*/
public int getNumFaces()
{
return numFaces;
}
@Override
public boolean isDice()
{
return true;
}
@Override
public boolean isHand()
{
return true;
}
@Override
public void createTopology(int beginIndex, int numEdge)
{
final double unit = 1.0 / numLocs;
topology = new Topology();
final int realNumEdge = (numEdge == Constants.UNDEFINED) ? 4 : numEdge;
Graph graph = null;
if (realNumEdge == 6)
graph = new RectangleOnHex(new DimConstant(1), new DimConstant(this.numLocs)).eval(null, SiteType.Cell);
else if (realNumEdge == 3)
graph = new RectangleOnTri(new DimConstant(1), new DimConstant(this.numLocs)).eval(null, SiteType.Cell);
else
graph = new RectangleOnSquare(new DimConstant(1), new DimConstant(this.numLocs), null, null).eval(null,
SiteType.Cell);
// Add the cells to the topology.
for (int i = 0; i < graph.faces().size(); i++)
{
final Face face = graph.faces().get(i);
final Cell cell = new Cell(face.id() + beginIndex, face.pt().x() + (i * unit), face.pt().y(),
face.pt().z());
cell.setCoord(cell.row(), cell.col(), 0);
cell.setCentroid(face.pt().x(), face.pt().y(), 0);
topology.cells().add(cell);
// We add the vertices of the cells and vice versa.
for (final game.util.graph.Vertex v : face.vertices())
{
final double x = v.pt().x();
final double y = v.pt().y();
final double z = v.pt().z();
final Vertex vertex = new Vertex(Constants.UNDEFINED, x, y, z);
cell.vertices().add(vertex);
}
}
numSites = topology.cells().size();
}
/**
* @return The number of sites on this dice container.
*/
public int numLocs()
{
return this.numLocs;
}
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
concepts.set(Concept.Dice.id(), true);
if (biased != null)
concepts.set(Concept.BiasedDice.id(), true);
if(numFaces == 2)
concepts.set(Concept.DiceD2.id(), true);
if(numFaces == 3)
concepts.set(Concept.DiceD3.id(), true);
if(numFaces == 4)
concepts.set(Concept.DiceD4.id(), true);
if(numFaces == 6)
concepts.set(Concept.DiceD6.id(), true);
return concepts;
}
@Override
public BitSet writesEvalContextRecursive()
{
final BitSet writeEvalContext = new BitSet();
return writeEvalContext;
}
@Override
public BitSet readsEvalContextRecursive()
{
final BitSet readEvalContext = new BitSet();
return readEvalContext;
}
@Override
public boolean missingRequirement(final Game game)
{
boolean missingRequirement = false;
if (role() != null)
{
final int indexOwnerPhase = role().owner();
if (
(
indexOwnerPhase < 1
&&
!role().equals(RoleType.Shared)
&&
!role().equals(RoleType.Neutral)
&&
!role().equals(RoleType.All)
)
||
indexOwnerPhase > game.players().count()
)
{
game.addRequirementToReport(
"A dice is defined in the equipment with an incorrect owner: " + role() + ".");
missingRequirement = true;
}
}
return missingRequirement;
}
} | 9,202 | 24.076294 | 107 | java |
Ludii | Ludii-master/Core/src/game/equipment/container/other/Hand.java | package game.equipment.container.other;
import java.util.BitSet;
import annotations.Name;
import annotations.Opt;
import game.Game;
import game.equipment.container.Container;
import game.functions.dim.DimConstant;
import game.functions.graph.generators.basis.hex.RectangleOnHex;
import game.functions.graph.generators.basis.square.RectangleOnSquare;
import game.functions.graph.generators.basis.tri.RectangleOnTri;
import game.types.board.SiteType;
import game.types.play.RoleType;
import game.util.graph.Face;
import game.util.graph.Graph;
import main.Constants;
import metadata.graphics.util.ContainerStyleType;
import other.ItemType;
import other.concept.Concept;
import other.topology.Cell;
import other.topology.Topology;
import other.topology.Vertex;
/**
* Defines a hand of a player.
*
* @author Eric.Piette
*
* @remarks For any game with components outside of the board.
*/
public class Hand extends Container
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/** The number of locations in this container. */
protected int numLocs;
//-------------------------------------------------------------------------
/**
* @param role The owner of the hand.
* @param size The numbers of sites in the hand.
*
* @example (hand Each size:5)
*/
public Hand
(
final RoleType role,
@Opt @Name final Integer size
)
{
super(null, Constants.UNDEFINED, role);
final String className = this.getClass().toString();
final String containerName = className.substring(className.lastIndexOf('.') + 1, className.length());
if (role.owner() > 0 && role.owner() <= Constants.MAX_PLAYERS)
{
if (name() == null)
this.setName(containerName + role.owner());
}
else if (role == RoleType.Neutral)
{
if (name() == null)
this.setName(containerName + role.owner());
}
else if (role == RoleType.Shared)
{
if (name() == null)
this.setName(containerName + role.owner());
}
this.numLocs = (size == null) ? 1 : size.intValue();
this.style = ContainerStyleType.Hand;
setType(ItemType.Hand);
}
/**
* Copy constructor.
*
* Protected because we do not want the compiler to detect it, this is called
* only in Clone method.
*
* @param other
*/
protected Hand(final Hand other)
{
super(other);
numLocs = other.numLocs;
}
//-------------------------------------------------------------------------
@Override
public void createTopology(final int beginIndex, final int numEdge)
{
final double unit = 1.0 / numLocs;
topology = new Topology();
final int realNumEdge = (numEdge == Constants.UNDEFINED) ? 4 : numEdge;
Graph graph = null;
if (realNumEdge == 6)
graph = new RectangleOnHex(new DimConstant(1), new DimConstant(this.numLocs)).eval(null, SiteType.Cell);
else if (realNumEdge == 3)
graph = new RectangleOnTri(new DimConstant(1), new DimConstant(this.numLocs)).eval(null, SiteType.Cell);
else
graph = new RectangleOnSquare(new DimConstant(1), new DimConstant(this.numLocs), null, null).eval(null,
SiteType.Cell);
// Add the cells to the topology.
for (int i = 0; i < this.numLocs; i++)
{
final Face face = graph.faces().get(i);
final Cell cell = new Cell(face.id() + beginIndex, face.pt().x() + (i * unit), face.pt().y(),
face.pt().z());
cell.setCoord(cell.row(), cell.col(), 0);
cell.setCentroid(face.pt().x(), face.pt().y(), 0);
topology.cells().add(cell);
// We add the vertices of the cells and vice versa.
for (final game.util.graph.Vertex v : face.vertices())
{
final double x = v.pt().x();
final double y = v.pt().y();
final double z = v.pt().z();
final Vertex vertex = new Vertex(Constants.UNDEFINED, x, y, z);
cell.vertices().add(vertex);
}
}
numSites = topology.cells().size();
}
//-------------------------------------------------------------------------
/**
* @return The number of sites on this hand.
*/
public int numLocs()
{
return this.numLocs;
}
//-------------------------------------------------------------------------
@Override
public Hand clone()
{
return new Hand(this);
}
@Override
public boolean isHand()
{
return true;
}
//-------------------------------------------------------------------------
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
concepts.or(super.concepts(game));
concepts.set(Concept.Hand.id(), true);
return concepts;
}
@Override
public BitSet writesEvalContextRecursive()
{
final BitSet writeEvalContext = new BitSet();
writeEvalContext.or(super.writesEvalContextRecursive());
return writeEvalContext;
}
@Override
public BitSet readsEvalContextRecursive()
{
final BitSet readEvalContext = new BitSet();
readEvalContext.or(super.readsEvalContextRecursive());
return readEvalContext;
}
@Override
public boolean missingRequirement(final Game game)
{
boolean missingRequirement = false;
if (role() != null)
{
final int indexOwnerPhase = role().owner();
if (
(
indexOwnerPhase < 1
&&
!role().equals(RoleType.Shared)
&&
!role().equals(RoleType.All)
)
||
indexOwnerPhase > game.players().count()
)
{
game.addRequirementToReport(
"A hand is defined in the equipment with an incorrect owner: " + role() + ".");
missingRequirement = true;
}
}
return missingRequirement;
}
}
| 5,491 | 24.192661 | 107 | java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.