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/Core/src/game/util/graph/Situation.java | package game.util.graph;
import main.math.RCL;
/**
* Graph element positional situation, for coordinate labelling.
* @author cambolbro
*/
public class Situation
{
private final RCL rcl = new RCL();
String label = "";
/**
* @return an RCL coordinate.
*/
public RCL rcl()
{
return rcl;
}
/**
* @return The corresponding label.
*/
public String label()
{
return label;
}
/**
* To set the label.
*
* @param str The new label.
*/
public void setLabel(final String str)
{
label = new String(str);
}
}
| 544 | 12.625 | 64 | java |
Ludii | Ludii-master/Core/src/game/util/graph/Step.java | package game.util.graph;
import java.util.BitSet;
import java.util.List;
import game.util.directions.AbsoluteDirection;
//-----------------------------------------------------------------------------
/**
* Steps from this particular graph element.
*
* @author cambolbro
*/
public class Step
{
protected final GraphElement from;
protected final GraphElement to;
/** Record of AbsoluteDirections that this step agrees with. */
protected final BitSet directions = new BitSet();
//-------------------------------------------------------------------------
/**
* Constructor.
*
* @param from The from graph element.
* @param to The to graph element.
*/
public Step
(
final GraphElement from,
final GraphElement to
)
{
this.from = from;
this.to = to;
}
//-------------------------------------------------------------------------
/**
* @return The from graph element.
*/
public GraphElement from()
{
return from;
}
/**
* @return The to graph element.
*/
public GraphElement to()
{
return to;
}
/**
* @return The bitset of the directions supported by the step.
*/
public BitSet directions()
{
return directions;
}
//-------------------------------------------------------------------------
/**
* @param list A list of steps.
* @return true if the steps in entries are in the steps.
*/
public boolean in(final List<Step> list)
{
for (final Step step : list)
if (from.matches(step.from()) && to.matches(step.to()))
return true;
return false;
}
//-------------------------------------------------------------------------
/**
* @param other The step.
* @return True if the step match.
*/
public boolean matches(final Step other)
{
if (!from.matches(other.from))
return false;
if (!to.matches(other.to))
return false;
if (!directions.equals(other.directions))
return false;
return true;
}
//-------------------------------------------------------------------------
@Override
public String toString()
{
final StringBuilder sb = new StringBuilder();
sb.append(from.label() + " => " + to.label());
if (!directions.isEmpty())
{
sb.append(" (");
for (int d = directions.nextSetBit(0); d >= 0; d = directions.nextSetBit(d + 1))
{
if (d > 0)
sb.append(", ");
sb.append(AbsoluteDirection.values()[d]);
}
sb.append(")");
}
return sb.toString();
}
//-------------------------------------------------------------------------
}
| 2,513 | 18.640625 | 83 | java |
Ludii | Ludii-master/Core/src/game/util/graph/Steps.java | package game.util.graph;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.Collections;
import java.util.List;
import game.types.board.SiteType;
import game.util.directions.AbsoluteDirection;
import main.math.MathRoutines;
//-----------------------------------------------------------------------------
/**
* Record of steps from a given element.
*
* @author cambolbro
*/
public class Steps
{
private final SiteType siteType;
private final int id;
private final List<Step> steps = new ArrayList<Step>();
private List<Step>[] inDirection;
private List<Step>[] toSiteType;
private List<Step>[][] toSiteTypeInDirection;
/** Total directions for these Steps. */
private final BitSet totalDirections = new BitSet();
//-------------------------------------------------------------------------
/**
* Constructor.
*
* @param siteType The graph element type.
* @param id The index of the step.
*/
public Steps(final SiteType siteType, final int id)
{
this.siteType = siteType;
this.id = id;
allocate();
}
//-------------------------------------------------------------------------
/**
* @return The steps.
*/
public List<Step> steps()
{
return steps;
}
/**
* @param toType The graph element.
* @return The steps only for a graph element.
*/
public List<Step> toSiteType(final SiteType toType)
{
return toSiteType[toType.ordinal()];
}
/**
* @param dirn The direction.
* @return The steps only in a direction.
*/
public List<Step> inDirection(final AbsoluteDirection dirn)
{
return inDirection[dirn.ordinal()];
}
/**
* @param toType The graph element.
* @param dirn The direction.
* @return The steps only in a direction and for a graph element type.
*/
public List<Step> toSiteTypeInDirection(final SiteType toType, final AbsoluteDirection dirn)
{
return toSiteTypeInDirection[toType.ordinal()][dirn.ordinal()];
}
/**
* @return The bitset with all the directions.
*/
public BitSet totalDirections()
{
return totalDirections;
}
//-------------------------------------------------------------------------
/**
* Clear the steps in a direction
*
* @param dirn The steps.
*/
public void clearInDirection(final AbsoluteDirection dirn)
{
inDirection[dirn.ordinal()].clear();
}
/**
* Add a step in a direction.
*
* @param dirn The direction.
* @param step The step.
*/
public void addInDirection(final AbsoluteDirection dirn, final Step step)
{
inDirection[dirn.ordinal()].add(step);
}
/**
* Add a step in a direction and for a graph element type.
*
* @param toType The graph element type.
* @param dirn The direction.
* @param step The step.
*/
public void addToSiteTypeInDirection(final SiteType toType, final AbsoluteDirection dirn, final Step step)
{
final List<Step> stepsList = toSiteTypeInDirection[toType.ordinal()][dirn.ordinal()];
for (final Step existing : stepsList)
{
if (step.matches(existing))
return;
}
stepsList.add(step);
}
//-------------------------------------------------------------------------
/**
* Allocate the steps.
*/
@SuppressWarnings("unchecked")
public void allocate()
{
final int numSiteTypes = SiteType.values().length;
final int numDirections = AbsoluteDirection.values().length;
toSiteType = new ArrayList[numSiteTypes];
for (int st = 0; st < numSiteTypes; st++)
toSiteType[st] = new ArrayList<Step>();
inDirection = new ArrayList[numDirections];
for (int dirn = 0; dirn < numDirections; dirn++)
inDirection[dirn] = new ArrayList<Step>();
toSiteTypeInDirection = new ArrayList[numSiteTypes][numDirections];
for (int st = 0; st < numSiteTypes; st++)
for (int dirn = 0; dirn < numDirections; dirn++)
toSiteTypeInDirection[st][dirn] = new ArrayList<Step>();
}
//-------------------------------------------------------------------------
void add(final Step step)
{
for (final Step existing : steps)
if (existing.from().matches(step.from()) && existing.to().matches(step.to()))
{
// Don't add duplicate steps
//System.out.println("Steps.add(): Duplicate steps:\na) " + step + "\nb) " + existing);
existing.directions().or(step.directions()); // keep any unknown directions
return;
}
steps.add(step);
final int toSiteTypeId = step.to().siteType().ordinal();
toSiteType[toSiteTypeId].add(step);
for (int dirn = step.directions().nextSetBit(0); dirn >= 0; dirn = step.directions().nextSetBit(dirn + 1))
{
inDirection[dirn].add(step);
toSiteTypeInDirection[toSiteTypeId][dirn].add(step);
//System.out.println("Adding step to site type " + step.to().siteType() + " in direction " + dirn + "...");
}
totalDirections.or(step.directions());
}
//-------------------------------------------------------------------------
/**
* Sort steps in all lists CW from N.
*/
public void sort()
{
final int numSiteTypes = SiteType.values().length;
final int numDirections = AbsoluteDirection.values().length;
sort(steps);
for (int dirn = 0; dirn < numDirections; dirn++)
sort(inDirection[dirn]);
for (int st = 0; st < numSiteTypes; st++)
sort(toSiteType[st]);
for (int st = 0; st < numSiteTypes; st++)
for (int dirn = 0; dirn < numDirections; dirn++)
sort(toSiteTypeInDirection[st][dirn]);
}
/**
* Sort steps in the specified list CW from N.
*
* @param list The list of the steps.
*/
public static void sort(final List<Step> list)
{
final List<ItemScore> rank = new ArrayList<ItemScore>();
for (int n = 0; n < list.size(); n++)
{
final Step step = list.get(n);
final double theta = MathRoutines.angle(step.from().pt2D(), step.to().pt2D());
double score = Math.PI / 2 - theta + 0.0001;
while (score < 0)
score += 2 * Math.PI;
rank.add(new ItemScore(n, score));
}
Collections.sort(rank);
// Append item references in new order
for (int r = 0; r < rank.size(); r++)
list.add(list.get(rank.get(r).id()));
// Remove initial reference to items
for (int r = 0; r < rank.size(); r++)
list.remove(0);
}
//-------------------------------------------------------------------------
@Override
public String toString()
{
final StringBuilder sb = new StringBuilder();
sb.append("Steps from " + siteType + " " + id + ":\n");
for (final Step step : steps)
sb.append("- " + step.toString() + "\n");
return sb.toString();
}
//-------------------------------------------------------------------------
}
| 6,564 | 24.445736 | 110 | java |
Ludii | Ludii-master/Core/src/game/util/graph/Trajectories.java | package game.util.graph;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.List;
import game.types.board.SiteType;
import game.util.directions.AbsoluteDirection;
import main.math.MathRoutines;
import main.math.Point3D;
import main.math.Vector;
//-----------------------------------------------------------------------------
/**
* Record of relations between elements within a graph.
*
* @author cambolbro
*/
public class Trajectories
{
/** Collections of steps; first indexed by SiteType, second indexed by the from site's ID */
private Steps[][] steps;
/** Collections of radials: first indexed by SiteType, second indexed by site ID */
private Radials[][] radials;
/** Total directions for graph. */
private final BitSet totalDirections = new BitSet();
//-------------------------------------------------------------------------
/**
* Constructor.
*/
public Trajectories()
{
// Do not create relations here!
// Only call create() from the Board class, once, on the final graph object.
}
//-------------------------------------------------------------------------
/**
* @param fromType The graph element type of the from site.
* @param siteId The index of the graph element type.
* @param toType The graph element type of the to site.
* @return The steps according to graph element types for the origin and the
* target.
*/
public List<Step> steps(final SiteType fromType, final int siteId, final SiteType toType)
{
return steps[fromType.ordinal()][siteId].toSiteType(toType);
}
/**
* @param fromType The graph element type of the from site.
* @param siteId The index of the graph element type.
* @param dirn The direction.
* @return The steps according to graph element types for the origin and an
* absolute direction.
*/
public List<Step> steps(final SiteType fromType, final int siteId, final AbsoluteDirection dirn)
{
return steps[fromType.ordinal()][siteId].inDirection(dirn);
}
/**
* @param fromType The graph element type of the from site.
* @param siteId The index of the graph element type.
* @param toType The graph element type of the to site.
* @param dirn The direction.
* @return The steps according to graph element types for the origin and the
* target and for an absolute direction.
*/
public List<Step> steps(final SiteType fromType, final int siteId, final SiteType toType, final AbsoluteDirection dirn)
{
return steps[fromType.ordinal()][siteId].toSiteTypeInDirection(toType, dirn);
}
/**
* @param fromType The graph element type of the from site.
* @param siteId The index of the graph element type.
* @return The radials according to a graph element type for the origin.
*/
public Radials radials(final SiteType fromType, final int siteId)
{
return radials[fromType.ordinal()][siteId];
}
/**
* @param fromType The graph element type of the from site.
* @param siteId The index of the graph element type.
* @param dirn The direction.
* @return The radials according to a graph element type for the origin and for
* an absolute direction.
*/
public List<Radial> radials(final SiteType fromType, final int siteId, final AbsoluteDirection dirn)
{
return radials[fromType.ordinal()][siteId].inDirection(dirn);
}
/**
* @return The bitset of the directions.
*/
public BitSet totalDirections()
{
return totalDirections;
}
//-------------------------------------------------------------------------
/**
* Create the trajectories.
*
* @param graph The graph.
*/
public void create(final Graph graph)
{
// Prepare the arrays
final int numSiteTypes = SiteType.values().length;
steps = new Steps[numSiteTypes][];
radials = new Radials[numSiteTypes][];
for (final SiteType siteType : SiteType.values())
{
final int st = siteType.ordinal();
steps[st] = new Steps[graph.elements(siteType).size()];
radials[st] = new Radials[graph.elements(siteType).size()];
}
generateSteps(graph);
generateRadials(graph);
//System.out.println("===========================================================\n");
//System.out.println(graph);
// report(graph);
}
//-------------------------------------------------------------------------
void generateSteps(final Graph graph)
{
for (final SiteType siteType : SiteType.values())
{
for (final GraphElement from : graph.elements(siteType))
{
final int st = siteType.ordinal();
final int id = from.id();
final Steps stepsFrom = new Steps(siteType, id);
from.stepsTo(stepsFrom);
steps[st][id] = stepsFrom;
}
}
setDirections(graph);
for (int st = 0; st < SiteType.values().length; st++)
for (final Steps stepList : steps[st])
{
totalDirections.or(stepList.totalDirections());
stepList.sort();
}
// // Reorder steps in clockwise order within each relation type
// for (int st = 0; st < SiteType.values().length; st++)
// for (int reln = 0; reln < RelationType.values().length; reln++)
// Collections.sort(stepsTo.steps()[st][reln], new Comparator<StepTo>()
// {
// @Override
// public int compare(final StepTo a, final StepTo b)
// {
// if (a.theta() == b.theta())
// return 0;
// return (a.theta() > b.theta()) ? -1 : 1;
// }
// });
}
//-------------------------------------------------------------------------
/**
* Sets the 'dirn' field of all Steps in the list with unique directions.
*/
void setDirections(final Graph graph)
{
setCompassDirections(graph); // includes pyramidal directions
setCircularDirections(graph);
// Set known directions in each step
for (final SiteType siteType : SiteType.values())
{
final List<? extends GraphElement> elements = graph.elements(siteType);
final int st = siteType.ordinal();
for (int id = 0; id < elements.size(); id++)
for (final AbsoluteDirection dirn : AbsoluteDirection.values())
{
final int dirnIndex = dirn.ordinal();
for (final Step step : steps[st][id].inDirection(AbsoluteDirection.values()[dirnIndex]))
{
step.directions().set(dirnIndex, true);
// steps[st].get(id).toSiteTypeInDirection(step.to.siteType(), dirn).add(step);
steps[st][id].addToSiteTypeInDirection(step.to.siteType(), dirn, step);
totalDirections.set(dirnIndex, true);
}
}
}
}
/**
* Sets the 'dirn' field of all Steps in the list with unique directions.
*/
void setCompassDirections(final Graph graph)
{
for (final SiteType siteType : SiteType.values())
{
final List<? extends GraphElement> elements = graph.elements(siteType);
for (final GraphElement element : elements)
setCompassDirections(graph, element);
}
}
/**
* Sets the 'dirn' field of all Steps in the list with unique directions.
*/
void setCompassDirections(final Graph graph, final GraphElement element)
{
final int st = element.siteType().ordinal();
final List<Step> stepList = steps[st][element.id()].steps();
final double unit = graph.averageEdgeLength();
// Check if only need 8 compass directions
final BitSet used = new BitSet();
boolean collision = false;
for (final Step step : stepList)
{
final int dirn = mapAngleToAbsoluteDirection(step, unit, false).ordinal();
if (used.get(dirn))
{
// More than one step in this direction; use 16 compass directions
collision = true;
break;
}
used.set(dirn, true);
}
// Add new directions
for (final Step step : stepList)
{
final AbsoluteDirection dirn = mapAngleToAbsoluteDirection(step, unit, collision);
// System.out.println("Settings step " + step + " to " + dirn + ".");
// stepsInDirection[st][element.id()][dirn].add(step);
// steps[st].get(element.id()).inDirection(AbsoluteDirection.values()[dirn]).add(step);
steps[st][element.id()].addInDirection(AbsoluteDirection.values()[dirn.ordinal()], step);
if
(
dirn == AbsoluteDirection.N
||
dirn == AbsoluteDirection.E
||
dirn == AbsoluteDirection.S
||
dirn == AbsoluteDirection.W
||
dirn == AbsoluteDirection.NE
||
dirn == AbsoluteDirection.SE
||
dirn == AbsoluteDirection.SW
||
dirn == AbsoluteDirection.NW
||
dirn == AbsoluteDirection.NNE
||
dirn == AbsoluteDirection.ENE
||
dirn == AbsoluteDirection.ESE
||
dirn == AbsoluteDirection.SSE
||
dirn == AbsoluteDirection.SSW
||
dirn == AbsoluteDirection.WSW
||
dirn == AbsoluteDirection.WNW
||
dirn == AbsoluteDirection.NNW
)
steps[st][element.id()].addInDirection(AbsoluteDirection.SameLayer, step);
if
(
dirn == AbsoluteDirection.U
||
dirn == AbsoluteDirection.UN
||
dirn == AbsoluteDirection.UE
||
dirn == AbsoluteDirection.US
||
dirn == AbsoluteDirection.UW
||
dirn == AbsoluteDirection.UNE
||
dirn == AbsoluteDirection.USE
||
dirn == AbsoluteDirection.USW
||
dirn == AbsoluteDirection.UNW
)
steps[st][element.id()].addInDirection(AbsoluteDirection.Upward, step);
if
(
dirn == AbsoluteDirection.D
||
dirn == AbsoluteDirection.DN
||
dirn == AbsoluteDirection.DE
||
dirn == AbsoluteDirection.DS
||
dirn == AbsoluteDirection.DW
||
dirn == AbsoluteDirection.DNE
||
dirn == AbsoluteDirection.DSE
||
dirn == AbsoluteDirection.DSW
||
dirn == AbsoluteDirection.DNW
)
steps[st][element.id()].addInDirection(AbsoluteDirection.Downward, step);
}
}
//-------------------------------------------------------------------------
/**
* @param step The step.
* @param unit The unit.
* @param intercardinal True if the direction has to be intercardinal.
* @return The absolute direction for an angle.
*/
public static AbsoluteDirection mapAngleToAbsoluteDirection
(
final Step step, final double unit, final boolean intercardinal
)
{
final Point3D ptA = step.from().pt();
final Point3D ptB = step.to().pt();
int elevation = 0;
if (ptB.z() - ptA.z() < -0.1 * unit)
elevation = -1; // B is below A
else if (ptB.z() - ptA.z() > 0.1 * unit)
elevation = 1; // B is above A
// Check 2D distance between points
if (elevation != 0 && MathRoutines.distance(ptA.x(), ptA.y(), ptB.x(), ptB.y()) < 0.1 * unit)
{
// Step points are (approximately) on top of each other
return (elevation < 0) ? AbsoluteDirection.D : AbsoluteDirection.U;
}
//double angle = step.theta();
// Get step angle
double angle = Math.atan2(ptB.y() - ptA.y(), ptB.x() - ptA.x());
while (angle < 0)
angle += 2 * Math.PI;
while (angle > 2 * Math.PI)
angle -= 2 * Math.PI;
if (!intercardinal)
{
final double off = 2 * Math.PI / 16;
if (elevation == 0)
{
// On the 2D plane
if (angle < off) return AbsoluteDirection.E;
if (angle < off + 2 * Math.PI / 8) return AbsoluteDirection.NE;
if (angle < off + 4 * Math.PI / 8) return AbsoluteDirection.N;
if (angle < off + 6 * Math.PI / 8) return AbsoluteDirection.NW;
if (angle < off + 8 * Math.PI / 8) return AbsoluteDirection.W;
if (angle < off + 10 * Math.PI / 8) return AbsoluteDirection.SW;
if (angle < off + 12 * Math.PI / 8) return AbsoluteDirection.S;
if (angle < off + 14 * Math.PI / 8) return AbsoluteDirection.SE;
return AbsoluteDirection.E;
}
else if (elevation < 0)
{
// Downwards angle
if (angle < off) return AbsoluteDirection.DE;
if (angle < off + 2 * Math.PI / 8) return AbsoluteDirection.DNE;
if (angle < off + 4 * Math.PI / 8) return AbsoluteDirection.DN;
if (angle < off + 6 * Math.PI / 8) return AbsoluteDirection.DNW;
if (angle < off + 8 * Math.PI / 8) return AbsoluteDirection.DW;
if (angle < off + 10 * Math.PI / 8) return AbsoluteDirection.DSW;
if (angle < off + 12 * Math.PI / 8) return AbsoluteDirection.DS;
if (angle < off + 14 * Math.PI / 8) return AbsoluteDirection.DSE;
return AbsoluteDirection.DE;
}
else
{
// Upwards angle
if (angle < off) return AbsoluteDirection.UE;
if (angle < off + 2 * Math.PI / 8) return AbsoluteDirection.UNE;
if (angle < off + 4 * Math.PI / 8) return AbsoluteDirection.UN;
if (angle < off + 6 * Math.PI / 8) return AbsoluteDirection.UNW;
if (angle < off + 8 * Math.PI / 8) return AbsoluteDirection.UW;
if (angle < off + 10 * Math.PI / 8) return AbsoluteDirection.USW;
if (angle < off + 12 * Math.PI / 8) return AbsoluteDirection.US;
if (angle < off + 14 * Math.PI / 8) return AbsoluteDirection.USE;
return AbsoluteDirection.UE;
}
}
else
{
final double off = 2 * Math.PI / 32;
if (elevation == 0)
{
// On the 2D plane
if (angle < off) return AbsoluteDirection.E;
if (angle < off + 2 * Math.PI / 16) return AbsoluteDirection.ENE;
if (angle < off + 4 * Math.PI / 16) return AbsoluteDirection.NE;
if (angle < off + 6 * Math.PI / 16) return AbsoluteDirection.NNE;
if (angle < off + 8 * Math.PI / 16) return AbsoluteDirection.N;
if (angle < off + 10 * Math.PI / 16) return AbsoluteDirection.NNW;
if (angle < off + 12 * Math.PI / 16) return AbsoluteDirection.NW;
if (angle < off + 14 * Math.PI / 16) return AbsoluteDirection.WNW;
if (angle < off + 16 * Math.PI / 16) return AbsoluteDirection.W;
if (angle < off + 18 * Math.PI / 16) return AbsoluteDirection.WSW;
if (angle < off + 20 * Math.PI / 16) return AbsoluteDirection.SW;
if (angle < off + 22 * Math.PI / 16) return AbsoluteDirection.SSW;
if (angle < off + 24 * Math.PI / 16) return AbsoluteDirection.S;
if (angle < off + 26 * Math.PI / 16) return AbsoluteDirection.SSE;
if (angle < off + 28 * Math.PI / 16) return AbsoluteDirection.SE;
if (angle < off + 30 * Math.PI / 16) return AbsoluteDirection.ESE;
return AbsoluteDirection.E;
}
else if (elevation < 0)
{
// Downwards
if (angle < off) return AbsoluteDirection.DE;
if (angle < off + 2 * Math.PI / 16) return AbsoluteDirection.DNE;
if (angle < off + 4 * Math.PI / 16) return AbsoluteDirection.DNE;
if (angle < off + 6 * Math.PI / 16) return AbsoluteDirection.DNE;
if (angle < off + 8 * Math.PI / 16) return AbsoluteDirection.DN;
if (angle < off + 10 * Math.PI / 16) return AbsoluteDirection.DNW;
if (angle < off + 12 * Math.PI / 16) return AbsoluteDirection.DNW;
if (angle < off + 14 * Math.PI / 16) return AbsoluteDirection.DNW;
if (angle < off + 16 * Math.PI / 16) return AbsoluteDirection.DW;
if (angle < off + 18 * Math.PI / 16) return AbsoluteDirection.DSW;
if (angle < off + 20 * Math.PI / 16) return AbsoluteDirection.DSW;
if (angle < off + 22 * Math.PI / 16) return AbsoluteDirection.DSW;
if (angle < off + 24 * Math.PI / 16) return AbsoluteDirection.DS;
if (angle < off + 26 * Math.PI / 16) return AbsoluteDirection.DSE;
if (angle < off + 28 * Math.PI / 16) return AbsoluteDirection.DSE;
if (angle < off + 30 * Math.PI / 16) return AbsoluteDirection.DSE;
return AbsoluteDirection.DE;
}
else
{
// Upwards
if (angle < off) return AbsoluteDirection.UE;
if (angle < off + 2 * Math.PI / 16) return AbsoluteDirection.UNE;
if (angle < off + 4 * Math.PI / 16) return AbsoluteDirection.UNE;
if (angle < off + 6 * Math.PI / 16) return AbsoluteDirection.UNE;
if (angle < off + 8 * Math.PI / 16) return AbsoluteDirection.UN;
if (angle < off + 10 * Math.PI / 16) return AbsoluteDirection.UNW;
if (angle < off + 12 * Math.PI / 16) return AbsoluteDirection.UNW;
if (angle < off + 14 * Math.PI / 16) return AbsoluteDirection.UNW;
if (angle < off + 16 * Math.PI / 16) return AbsoluteDirection.UW;
if (angle < off + 18 * Math.PI / 16) return AbsoluteDirection.USW;
if (angle < off + 20 * Math.PI / 16) return AbsoluteDirection.USW;
if (angle < off + 22 * Math.PI / 16) return AbsoluteDirection.USW;
if (angle < off + 24 * Math.PI / 16) return AbsoluteDirection.US;
if (angle < off + 26 * Math.PI / 16) return AbsoluteDirection.USE;
if (angle < off + 28 * Math.PI / 16) return AbsoluteDirection.USE;
if (angle < off + 30 * Math.PI / 16) return AbsoluteDirection.USE;
return AbsoluteDirection.UE;
}
}
}
//-------------------------------------------------------------------------
void setCircularDirections(final Graph graph)
{
final int vertexTypeId = SiteType.Vertex.ordinal();
// Find all pivots
final BitSet pivotIds = new BitSet();
for (final Vertex vertex : graph.vertices())
if (vertex.pivot() != null)
pivotIds.set(vertex.pivot().id());
// Store all steps from pivot vertices in 'out' direction
for (int id = pivotIds.nextSetBit(0); id >= 0; id = pivotIds.nextSetBit(id + 1))
for (final Step step : steps[vertexTypeId][id].steps())
{
// steps[vertexTypeId].get(id).inDirection(AbsoluteDirection.Out).add(step);
// steps[vertexTypeId].get(id).inDirection(AbsoluteDirection.Rotational).add(step);
steps[vertexTypeId][id].addInDirection(AbsoluteDirection.Out, step);
steps[vertexTypeId][id].addInDirection(AbsoluteDirection.Rotational, step);
}
// Set circular directions for all other elements
for (final SiteType siteType : SiteType.values())
{
final List<? extends GraphElement> elements = graph.elements(siteType);
final int st = siteType.ordinal();
for (int id = 0; id < elements.size(); id++)
{
if (siteType == SiteType.Vertex && pivotIds.get(id))
continue; // pivot vertices already done
final GraphElement from = elements.get(id);
final Vertex pivot = from.pivot();
if (pivot == null)
continue; // not a pivoted element
for (final Step step : steps[st][id].steps())
{
// Determine circular directions for this pivoted element
final Vector vecAB = new Vector(from.pt(), step.to().pt());
final Vector vecAP = new Vector(from.pt(), pivot.pt());
vecAB.normalise();
vecAP.normalise();
if (step.directions().get(AbsoluteDirection.Diagonal.ordinal()))
continue;
final double dot = vecAB.dotProduct(vecAP);
if (dot > 0.9)
{
// Facing in
// steps[st].get(id).inDirection(AbsoluteDirection.In).add(step);
// steps[st].get(id).inDirection(AbsoluteDirection.Rotational).add(step);
steps[st][id].addInDirection(AbsoluteDirection.In, step);
steps[st][id].addInDirection(AbsoluteDirection.Rotational, step);
}
else if (dot < -0.9)
{
// Facing out
// steps[st].get(id).inDirection(AbsoluteDirection.Out).add(step);
// steps[st].get(id).inDirection(AbsoluteDirection.Rotational).add(step);
steps[st][id].addInDirection(AbsoluteDirection.Out, step);
steps[st][id].addInDirection(AbsoluteDirection.Rotational, step);
}
else
{
final Edge curvedEdge = graph.findEdge(from.id(), step.to().id(), true);
if (curvedEdge == null)
continue;
// Facing left or right
if (MathRoutines.whichSide(from.pt2D(), pivot.pt2D(), step.to().pt2D()) > 0)
{
// steps[st].get(id).inDirection(AbsoluteDirection.CW).add(step);
// steps[st].get(id).inDirection(AbsoluteDirection.Rotational).add(step);
steps[st][id].addInDirection(AbsoluteDirection.CW, step);
steps[st][id].addInDirection(AbsoluteDirection.Rotational, step);
}
else
{
// steps[st].get(id).inDirection(AbsoluteDirection.CCW).add(step);
// steps[st].get(id).inDirection(AbsoluteDirection.Rotational).add(step);
steps[st][id].addInDirection(AbsoluteDirection.CCW, step);
steps[st][id].addInDirection(AbsoluteDirection.Rotational, step);
}
}
}
}
}
}
//-------------------------------------------------------------------------
void generateRadials(final Graph graph)
{
for (final SiteType siteType : SiteType.values())
{
final List<? extends GraphElement> elements = graph.elements(siteType);
final int st = siteType.ordinal();
for (int id = 0; id < elements.size(); id++)
{
//final GraphElement element = elements.get(id);
radials[st][id] = new Radials(siteType, id);
for (final AbsoluteDirection dirn : AbsoluteDirection.values())
{
for (final Step step : steps[st][id].inDirection(dirn))
{
if (step.to().siteType() != siteType)
continue; // don't follow radial to other site types
// Create new radial in this direction
final RadialWIP radial = new RadialWIP(step.from(), dirn);
followRadial(graph, radial, siteType, dirn, step.to());
radials[st][id].addSafe(radial.toRadial());
}
}
}
}
// Remove opposite subsets
for (final SiteType siteType : SiteType.values())
{
final List<? extends GraphElement> elements = graph.elements(siteType);
final int st = siteType.ordinal();
for (int id = 0; id < elements.size(); id++)
for (final Radial radial : radials[st][id].radials())
radial.removeOppositeSubsets();
}
// Reassign Rotational radials
for (final SiteType siteType : SiteType.values())
{
final List<? extends GraphElement> elements = graph.elements(siteType);
final int st = siteType.ordinal();
for (int id = 0; id < elements.size(); id++)
{
// steps[st].get(id).inDirection(AbsoluteDirection.Rotational).clear();
steps[st][id].clearInDirection(AbsoluteDirection.Rotational);
for (final Radial radial : radials[st][id].inDirection(AbsoluteDirection.In))
// radials[st].get(id).inDirection(AbsoluteDirection.Rotational).add(radial);
radials[st][id].addInDirection(AbsoluteDirection.Rotational, radial);
for (final Radial radial : radials[st][id].inDirection(AbsoluteDirection.Out))
// radials[st].get(id).inDirection(AbsoluteDirection.Rotational).add(radial);
radials[st][id].addInDirection(AbsoluteDirection.Rotational, radial);
for (final Radial radial : radials[st][id].inDirection(AbsoluteDirection.CW))
// radials[st].get(id).inDirection(AbsoluteDirection.Rotational).add(radial);
radials[st][id].addInDirection(AbsoluteDirection.Rotational, radial);
for (final Radial radial : radials[st][id].inDirection(AbsoluteDirection.CCW))
// radials[st].get(id).inDirection(AbsoluteDirection.Rotational).add(radial);
radials[st][id].addInDirection(AbsoluteDirection.Rotational, radial);
radials[st][id].removeSubsetsInDirection(AbsoluteDirection.Rotational);
}
}
// Determine distinct radials and sort them CW from N (for Dennis)
for (int st = 0; st < SiteType.values().length; st++)
for (final Radials radialSet : radials[st])
{
radialSet.setDistinct();
radialSet.sort();
}
}
void followRadial
(
final Graph graph, final RadialWIP radial, final SiteType siteType,
final AbsoluteDirection dirn, final GraphElement current
)
{
final double threshold = 0.25; // allowable bend
final double tanThreshold = Math.tan(threshold);
final GraphElement previous = radial.lastStep();
radial.addStep(current);
// Find next step with closest trajectory
//final Vector trajectory = new Vector(previous.pt(), current.pt());
//trajectory.normalise();
if (current.id() >= steps[siteType.ordinal()].length)
{
// Should not happen
System.out.println("** Trajectories.followRadial(): " + siteType + " " + current.id() + " not in steps[][][] array.");
return;
}
final List<Step> nextSteps = steps[siteType.ordinal()][current.id()].inDirection(dirn);
// double bestScore = -100000;
double bestAbsTanDiff = tanThreshold; // initialising this to threshold allows us to always only compare to bestDiff
GraphElement bestNextTo = null;
final int dirnOrdinal = dirn.ordinal();
if
(
dirn == AbsoluteDirection.CW || dirn == AbsoluteDirection.CCW
||
dirn == AbsoluteDirection.In || dirn == AbsoluteDirection.Out
// ||
// dirn == AbsoluteDirection.Rotational
)
{
// Follow circular step
for (final Step next : nextSteps)
{
final GraphElement nextTo = next.to();
if (nextTo.siteType() != siteType)
continue; // only follow radials along same site type
if (next.directions().get(dirnOrdinal))
{
bestNextTo = nextTo;
break;
}
}
}
else
{
// Non-circular steps
for (final Step next : nextSteps)
{
final GraphElement nextTo = next.to();
if (nextTo.siteType() != siteType)
continue; // only follow radials along same site type
if (next.directions().get(dirnOrdinal))
{
// Follow step with smallest deviation in heading
//
// The angle difference computation looks like atan2(y, x) for y and x
// computed based on the three points. Whenever x is negative, we can
// exit early because the angle difference will be either greater than 0.5pi,
// or smaller than -0.5pi; absolute value always bigger than our threshold.
//
// In the case where x is positive, we can compute the same angle difference
// as atan(y / x), instead of atan2(y, x). The absolute value of atan(y / x)
// is a strictly increasing function of the absolute value of (y / x), with
// a minimum of atan(y / x) = 0 if (y / x) = 0.
//
// So, instead of minimising the absolute value of this angle difference, we
// can also just minimise the absolute value of (y / x). The only complication
// now is that we have to adjust the threshold that we compare to; originally,
// we wanted a threshold absolute angle difference of at most 0.25rad. Now,
// we'll have to change that to a threshold of tan(0.25).
final double absTanDiff = MathRoutines.absTanAngleDifferencePosX
(
previous.pt2D(), current.pt2D(), nextTo.pt2D()
);
if (absTanDiff < bestAbsTanDiff) // comparison to threshold is implicit due to init of bestAbsTanDiff
{
bestNextTo = nextTo;
bestAbsTanDiff = absTanDiff;
if (bestAbsTanDiff == 0.0)
break; // We won't be able to improve this anymore
}
}
}
}
if (bestNextTo != null)
{
// if (bestNext.from.siteType() != siteType || bestNext.to.siteType() != siteType)
// System.out.println("** Bad site type in followRadial().");
if (!radial.steps().contains(bestNextTo))
followRadial(graph, radial, siteType, dirn, bestNextTo);
}
}
//-------------------------------------------------------------------------
/**
* Print the trajectories.
*
* @param graph The graph.
*/
public void report(final Graph graph)
{
System.out.println(graph);
System.out.println("\nRadials:");
for (final SiteType siteType : SiteType.values())
{
final List<? extends GraphElement> elements = graph.elements(siteType);
final int st = siteType.ordinal();
for (int id = 0; id < elements.size(); id++)
{
final GraphElement element = elements.get(id);
System.out.println("\nSteps from " + element.label() + ":");
for (final Step step : steps[st][id].steps())
System.out.println(" " + step);
//System.out.println("\nRadials from " + element.label() + ":");
System.out.println("\n" + radials[st][id]);
}
}
System.out.println("\nDirections used:");
for (int d = totalDirections.nextSetBit(0); d >= 0; d = totalDirections.nextSetBit(d + 1))
System.out.println("- " + AbsoluteDirection.values()[d]);
System.out.println();
}
//-------------------------------------------------------------------------
/**
* A "work-in-progress" Radial, which we may still be busy building and adding steps to.
* Can be transformed into a real Radial with fixed-length array of steps when it is finished.
*
* @author Dennis Soemers
*/
private final static class RadialWIP
{
/** The list of steps making up this radial. */
private final List<GraphElement> steps = new ArrayList<GraphElement>();
/**
* Direction of the first step in this radial.
* This is useful to store so that radials can be quickly sorted by direction in Trajectories.
*/
private final AbsoluteDirection direction;
/**
* Constructor.
*
* @param start The starting element of the radial.
* @param direction The absolute direction of the radial.
*/
public RadialWIP(final GraphElement start, final AbsoluteDirection direction)
{
this.direction = direction;
steps.add(start);
}
/**
* @return The list of the graph elements in the steps.
*/
public List<GraphElement> steps()
{
return steps;
}
/**
* Add a element to the steps.
*
* @param to The element.
*/
public void addStep(final GraphElement to)
{
steps.add(to);
}
/**
* @return The last step.
*/
public GraphElement lastStep()
{
return steps.get(steps.size() - 1);
}
/**
* @return A proper Radial, with fixed-length array of steps
*/
public Radial toRadial()
{
return new Radial(steps.toArray(new GraphElement[steps.size()]), direction);
}
}
//-------------------------------------------------------------------------
}
| 29,372 | 31.96633 | 121 | java |
Ludii | Ludii-master/Core/src/game/util/graph/Vertex.java | package game.util.graph;
import java.awt.geom.Point2D;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import game.types.board.SiteType;
import game.util.directions.AbsoluteDirection;
import main.math.MathRoutines;
import main.math.Point3D;
//-----------------------------------------------------------------------------
/**
* Defines a Graph vertex.
*
* @author cambolbro
*/
public class Vertex extends GraphElement
{
private final List<Edge> edges = new ArrayList<Edge>();
private final List<Face> faces = new ArrayList<Face>();
private Vertex pivot = null;
//-------------------------------------------------------------------------
/**
* Constructor.
*
* @param id The index of the vertex.
* @param x The x position of the vertex.
* @param y The y position of the vertex.
*/
public Vertex
(
final int id, final double x, final double y
)
{
this.id = id;
this.pt = new Point3D(x, y);
}
/**
* Constructor.
*
* @param id The index of the vertex.
* @param x The x position of the vertex.
* @param y The y position of the vertex.
* @param z The z position of the vertex.
*/
public Vertex
(
final int id, final double x, final double y, final double z
)
{
this.id = id;
this.pt = new Point3D(x, y, z);
}
/**
* Constructor.
*
* @param id The index of the vertex.
* @param pt The Point3D of the vertex.
*/
public Vertex
(
final int id, final Point3D pt
)
{
this.id = id;
this.pt = new Point3D(pt);
}
/**
* Constructor.
*
* @param id The index of the vertex.
* @param pt The Point2D of the vertex.
*/
public Vertex
(
final int id, final Point2D pt
)
{
this.id = id;
this.pt = new Point3D(pt.getX(), pt.getY());
}
//-------------------------------------------------------------------------
/**
* @return The edges of the vertex.
*/
public List<Edge> edges()
{
return Collections.unmodifiableList(edges);
}
/**
* @return The faces of the vertex.
*/
public List<Face> faces()
{
return faces;
}
@Override
public Vertex pivot()
{
return pivot;
}
/**
* Set the pivot of the vertex.
*
* @param vertex The pivot vertex.
*/
public void setPivot(final Vertex vertex)
{
pivot = vertex;
}
//-------------------------------------------------------------------------
/**
* Clear the edges.
*/
public void clearEdges()
{
edges.clear();
}
/**
* Add an edge.
*
* @param edge The edge.
*/
public void addEdge(final Edge edge)
{
edges.add(edge);
}
/**
* Remove an edge.
*
* @param n the index of the edge.
*/
public void removeEdge(final int n)
{
edges.remove(n);
}
/**
* Clear the faces.
*/
public void clearFaces()
{
faces.clear();
}
/**
* Add a face.
*
* @param face The face.
*/
public void addFace(final Face face)
{
faces.add(face);
}
/**
* Remove a face.
*
* @param n The index of the face.
*/
public void removeFace(final int n)
{
faces.remove(n);
}
//-------------------------------------------------------------------------
@Override
public SiteType siteType()
{
return SiteType.Vertex;
}
//-------------------------------------------------------------------------
/**
* @param edge The edge.
* @return Edge's position in this vertex's list, else -1 if none.
*/
public int edgePosition(final Edge edge)
{
for (int n = 0; n < edges.size(); n++)
if (edges.get(n).matches(edge))
return n;
return -1;
}
/**
* @param face The face.
* @return Face's position in this vertex's list, else -1 if none.
*/
public int facePosition(final Face face)
{
for (int n = 0; n < faces.size(); n++)
if (faces.get(n).id() == face.id())
return n;
return -1;
}
/**
* @param other The other vertex.
* @return Known edge between this vertex and another vertex, else null if none.
*/
public Edge incidentEdge(final Vertex other)
{
for (final Edge edge : edges)
if (edge.matches(this, other))
return edge;
return null;
}
//-------------------------------------------------------------------------
/**
* @param other The other vertex.
* @param tolerance The tolerance.
* @return Vertex at same location within specified tolerance (e.g. 0.1).
*/
public boolean coincident(final Vertex other, final double tolerance)
{
return coincident(other.pt.x(), other.pt.y(), other.pt.z(), tolerance);
}
/**
* @param x The x position.
* @param y The y position.
* @param z The z position.
* @param tolerance The tolerance.
* @return Vertex at same location within specified tolerance (e.g. 0.1).
*/
public boolean coincident(final double x, final double y, final double z, final double tolerance)
{
final double error = Math.abs(x - pt.x()) + Math.abs(y - pt.y()) + Math.abs(z - pt.z());
if (error < tolerance)
return true;
return false;
}
//-------------------------------------------------------------------------
/**
* @param face The face.
* @return Vertex on the other end of the first edge coincident with this vertex
* that is not also on the specified face.
*/
public Vertex edgeAwayFrom(final Face face)
{
for (final Edge edge : edges)
{
if (!face.contains(edge))
return edge.otherVertex(id);
}
return null;
}
//-------------------------------------------------------------------------
/**
* Sort edges by direction in clockwise order around vertex.
*/
public void sortEdges()
{
Collections.sort(edges, new Comparator<Edge>()
{
@Override
public int compare(final Edge a, final Edge b)
{
final Vertex va = a.otherVertex(id());
final Vertex vb = b.otherVertex(id());
final double dirnA = Math.atan2(va.pt.y() - pt.y(), va.pt.x() - pt.x());
final double dirnB = Math.atan2(vb.pt.y() - pt.y(), vb.pt.x() - pt.x());
if (dirnA == dirnB)
return 0;
return (dirnA < dirnB) ? -1 : 1;
}
});
// System.out.print("Edge angles for vertex " + id() + ":");
// for (Edge edge : edges)
// {
// final Vertex v = edge.otherVertex(id());
// final double dirn = Math.atan2(v.y() - y(), v.x() - x());
// System.out.print(" " + dirn);
// }
// System.out.println();
}
//-------------------------------------------------------------------------
/**
* Sort edges by direction in clockwise order around vertex.
*/
void sortFaces()
{
Collections.sort(faces, new Comparator<Face>()
{
@Override
public int compare(final Face a, final Face b)
{
final double dirnA = Math.atan2(a.pt.y() - pt.y(), a.pt.x() - pt.x());
final double dirnB = Math.atan2(b.pt.y() - pt.y(), b.pt.x() - pt.x());
if (dirnA == dirnB)
return 0;
return (dirnA < dirnB) ? -1 : 1;
}
});
// System.out.print("Face angles for vertex " + id() + ":");
// for (final GraphElement ge : faces)
// {
// final double dirn = Math.atan2(ge.pt().y() - pt.y(), ge.pt().x() - pt.x());
// System.out.print(" " + dirn);
// }
// System.out.println();
}
//-------------------------------------------------------------------------
@Override
public List<GraphElement> nbors()
{
final List<GraphElement> nbors = new ArrayList<GraphElement>();
for (final Edge edge : edges)
nbors.add(edge.otherVertex(id));
return nbors;
}
//-------------------------------------------------------------------------
@Override
public void stepsTo(final Steps steps2)
{
//-------------------------------------------------
// Steps to other vertices
// Add orthogonal steps due to edges
for (final Edge edge : edges)
{
final Vertex to = edge.otherVertex(id);
final Step newStep = new Step(this, to);
newStep.directions().set(AbsoluteDirection.Orthogonal.ordinal());
newStep.directions().set(AbsoluteDirection.Adjacent.ordinal());
newStep.directions().set(AbsoluteDirection.All.ordinal());
steps2.add(newStep);
}
//-------------------------------------------------
// Diagonal steps across cell faces
for (final Face face : faces)
{
if (face.vertices().size() < 4)
continue; // no diagonal across a triangle
// Find maximum distance across this diagonal
double bestDist = 1000000;
Vertex bestTo = null;
for (final Vertex to : face.vertices())
{
if (to.id() == id)
continue;
final double dist = MathRoutines.distanceToLine(face.pt2D(), pt2D(), to.pt2D());
if (dist < bestDist)
{
bestDist = dist;
bestTo = to;
}
}
// Create this diagonal 'to' step
final Step newStep = new Step(this, bestTo);
newStep.directions().set(AbsoluteDirection.Diagonal.ordinal());
newStep.directions().set(AbsoluteDirection.All.ordinal());
steps2.add(newStep);
}
//-------------------------------------------------
// Steps to edges
for (final Edge edge : edges)
{
final Step newStep = new Step(this, edge);
newStep.directions().set(AbsoluteDirection.Orthogonal.ordinal());
newStep.directions().set(AbsoluteDirection.Adjacent.ordinal());
newStep.directions().set(AbsoluteDirection.All.ordinal());
steps2.add(newStep);
}
//-------------------------------------------------
// Steps to faces
for (final Face face : faces)
{
final Step newStep = new Step(this, face);
newStep.directions().set(AbsoluteDirection.Orthogonal.ordinal());
newStep.directions().set(AbsoluteDirection.Adjacent.ordinal());
newStep.directions().set(AbsoluteDirection.All.ordinal());
steps2.add(newStep);
}
}
//-------------------------------------------------------------------------
@Override
public String toString()
{
final StringBuilder sb = new StringBuilder();
final DecimalFormat df = new DecimalFormat("#.###");
sb.append("Vertex[" + id + "]: (");
if (pt.x() == (int)pt.x() && pt.y() == (int)pt.y())
sb.append((int)pt.x() + "," + (int)pt.y());
else
sb.append(df.format(pt.x()) + "," + df.format(pt.y()));
if (pt.z() == (int)pt.z())
sb.append("," + (int)pt.z());
else
sb.append("," + df.format(pt.z()));
sb.append(")");
if (pivot != null)
sb.append(" pivot=" + pivot.id());
// List edges
sb.append(" [");
for (int e = 0; e < edges.size(); e++)
{
if (e > 0)
sb.append(" ");
sb.append(edges.get(e).id());
}
sb.append("]");
sb.append(" " + properties);
sb.append(" \"" + situation.label() + "\"");
return sb.toString();
}
//-------------------------------------------------------------------------
}
| 10,673 | 21.145228 | 98 | java |
Ludii | Ludii-master/Core/src/game/util/graph/package-info.java | /**
* Graph utilities are support classes for describing the graph that defines a
* game board.
*/
package game.util.graph;
| 127 | 20.333333 | 78 | java |
Ludii | Ludii-master/Core/src/game/util/math/Count.java | package game.util.math;
import game.functions.ints.IntFunction;
import other.BaseLudeme;
/**
* Associates an item with a count.
*
* @author cambolbro
*
* @remarks This ludeme is used for lists of items with counts, such as (placeRandom ...).
*/
public class Count extends BaseLudeme
{
final String item;
final IntFunction count;
//-------------------------------------------------------------------------
/**
* @param item Item description.
* @param count Number of items.
*
* @example (count "Pawn1" 8)
*/
public Count
(
final String item,
final IntFunction count
)
{
this.item = item;
this.count = count;
}
//-------------------------------------------------------------------------
/**
* @return The item.
*/
public String item()
{
return item;
}
/**
* @return The count.
*/
public IntFunction count()
{
return count;
}
//-------------------------------------------------------------------------
}
| 1,022 | 16.947368 | 92 | java |
Ludii | Ludii-master/Core/src/game/util/math/Pair.java | package game.util.math;
import java.util.BitSet;
import game.Game;
import game.functions.ints.IntConstant;
import game.functions.ints.IntFunction;
import game.types.board.LandmarkType;
import game.types.play.RoleType;
import main.Constants;
import other.BaseLudeme;
/**
* Defines a pair of two integers, two strings or one integer and a string.
*
* @author Eric.Piette
* @remarks This is used for the map ludeme.
*/
public class Pair extends BaseLudeme
{
/** The integer key of the pair. */
final IntFunction intKey;
/** The string key of the pair. */
final String stringKey;
/** The integer value of the pair. */
final IntFunction intValue;
/** The string value of the pair. */
final String stringValue;
/** The landmark of the value. */
final LandmarkType landmark;
/** The key roleType to check in the warning. */
final RoleType roleTypeKey;
/** The value roleType to check in the warning. */
final RoleType roleTypeValue;
/**
* For a pair of integers.
*
* @param key The key of the pair.
* @param value The corresponding value.
*
* @example (pair 5 10)
*/
public Pair
(
final IntFunction key,
final IntFunction value
)
{
this.intKey = key;
this.intValue = value;
this.stringKey = null;
this.stringValue = null;
this.landmark = null;
this.roleTypeKey = null;
this.roleTypeValue = null;
}
/**
* For a pair of a RoleType and an Integer.
*
* @param key The key of the pair.
* @param value The corresponding value.
*
* @example (pair P1 10)
*/
public Pair
(
final RoleType key,
final IntFunction value
)
{
this.intKey = RoleType.toIntFunction(key);
this.intValue = value;
this.stringKey = null;
this.stringValue = null;
this.landmark = null;
this.roleTypeKey = key;
this.roleTypeValue = null;
}
/**
* For a pair of tow RoleTypes.
*
* @param key The key of the pair.
* @param value The corresponding value.
*
* @example (pair P1 P2)
*/
public Pair
(
final RoleType key,
final RoleType value
)
{
this.intKey = RoleType.toIntFunction(key);
this.intValue = RoleType.toIntFunction(value);
this.stringKey = null;
this.stringValue = null;
this.landmark = null;
this.roleTypeKey = key;
this.roleTypeValue = value;
}
/**
* For a pair of two strings.
*
* @param key The key of the pair.
* @param value The corresponding value.
*
* @example (pair "A1" "C3")
*/
public Pair
(
final String key,
final String value
)
{
this.intKey = null;
this.intValue = null;
this.stringKey = key;
this.stringValue = value;
this.landmark = null;
this.roleTypeKey = null;
this.roleTypeValue = null;
}
/**
* For a pair of an integer and a string.
*
* @param key The key of the pair.
* @param value The corresponding value.
*
* @example (pair 0 "A1")
*/
public Pair
(
final IntFunction key,
final String value
)
{
this.intKey = key;
this.intValue = null;
this.stringKey = null;
this.stringValue = value;
this.landmark = null;
this.roleTypeKey = null;
this.roleTypeValue = null;
}
/**
* For a pair of a RoleType and a string.
*
* @param key The key of the pair.
* @param value The corresponding value.
*
* @example (pair P1 "A1")
*/
public Pair
(
final RoleType key,
final String value
)
{
this.intKey = RoleType.toIntFunction(key);
this.intValue = null;
this.stringKey = null;
this.stringValue = value;
this.landmark = null;
this.roleTypeKey = key;
this.roleTypeValue = null;
}
/**
* For a pair of a RoleType and an ordered graph element type.
*
* @param key The key of the pair.
* @param landmark The landmark of the value.
*
* @example (pair P1 LeftSite)
*/
public Pair
(
final RoleType key,
final LandmarkType landmark
)
{
this.intKey = RoleType.toIntFunction(key);
this.intValue = null;
this.stringKey = null;
this.stringValue = null;
this.landmark = landmark;
this.roleTypeKey = key;
this.roleTypeValue = null;
}
/**
* For a pair of a RoleType and a value.
*
* @param key The key of the pair.
* @param value The corresponding value.
*
* @example (pair "A1" P1)
*/
public Pair
(
final String key,
final RoleType value
)
{
this.intKey = null;
this.intValue = RoleType.toIntFunction(value);
this.stringKey = key;
this.stringValue = null;
this.landmark = null;
this.roleTypeKey = null;
this.roleTypeValue = value;
}
/**
* @return The integer value.
*/
public IntFunction intValue()
{
if (intValue != null)
return intValue;
return new IntConstant(Constants.UNDEFINED);
}
/**
* @return The integer key.
*/
public IntFunction intKey()
{
if (intKey != null)
return intKey;
return new IntConstant(Constants.UNDEFINED);
}
/**
* @return The string value.
*/
public String stringValue()
{
return stringValue;
}
/**
* @return The landmark of the value.
*/
public LandmarkType landmarkType()
{
return landmark;
}
/**
* @return The string key.
*/
public String stringKey()
{
return stringKey;
}
/**
* @param game The game.
* @return The corresponding gameFlags.
*/
public long gameFlags(final Game game)
{
long gameFlags = 0l;
if (intKey != null)
gameFlags |= intKey.gameFlags(game);
if (intValue != null)
gameFlags |= intValue.gameFlags(game);
return gameFlags;
}
@Override
public BitSet writesEvalContextRecursive()
{
final BitSet writeEvalContext = new BitSet();
if (intKey != null)
writeEvalContext.or(intKey.writesEvalContextRecursive());
if (intValue != null)
writeEvalContext.or(intValue.writesEvalContextRecursive());
return writeEvalContext;
}
@Override
public BitSet readsEvalContextRecursive()
{
final BitSet readEvalContext = new BitSet();
if (intKey != null)
readEvalContext.or(intKey.readsEvalContextRecursive());
if (intValue != null)
readEvalContext.or(intValue.readsEvalContextRecursive());
return readEvalContext;
}
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
if (intKey != null)
concepts.or(intKey.concepts(game));
if (intValue != null)
concepts.or(intValue.concepts(game));
return concepts;
}
@Override
public boolean missingRequirement(final Game game)
{
boolean missingRequirement = false;
if (intKey != null)
missingRequirement |= intKey.missingRequirement(game);
if (intValue != null)
missingRequirement |= intValue.missingRequirement(game);
// We check if the key roleType is correct.
if (roleTypeKey != null)
{
final int indexOwnerPhase = roleTypeKey.owner();
if (((indexOwnerPhase < 1 && !roleTypeKey.equals(RoleType.Shared)) && !roleTypeKey.equals(RoleType.Neutral)
&& !roleTypeKey.equals(RoleType.All)) || indexOwnerPhase > game.players().count())
{
game.addRequirementToReport(
"The key of a pair in the map is using a wrong roletype which is " + roleTypeKey + ".");
missingRequirement = true;
}
}
// We check if the value roleType is correct.
if (roleTypeValue != null)
{
final int indexOwnerPhase = roleTypeValue.owner();
if (((indexOwnerPhase < 1 && !roleTypeValue.equals(RoleType.Shared))
&& !roleTypeValue.equals(RoleType.Neutral) && !roleTypeKey.equals(RoleType.All))
|| indexOwnerPhase > game.players().count())
{
game.addRequirementToReport(
"The value of a pair in the map is using a wrong roletype which is " + roleTypeValue + ".");
missingRequirement = true;
}
}
return missingRequirement;
}
@Override
public boolean willCrash(final Game game)
{
boolean willCrash = false;
if (intKey != null)
willCrash |= intKey.willCrash(game);
if (intValue != null)
willCrash |= intValue.willCrash(game);
return willCrash;
}
}
| 7,829 | 19.390625 | 110 | java |
Ludii | Ludii-master/Core/src/game/util/math/package-info.java | /**
* Math utilities are support classes for various numerical ludemes.
*/
package game.util.math;
| 101 | 19.4 | 68 | java |
Ludii | Ludii-master/Core/src/game/util/moves/Between.java | package game.util.moves;
import annotations.Name;
import annotations.Opt;
import game.Game;
import game.functions.booleans.BooleanFunction;
import game.functions.ints.IntFunction;
import game.functions.range.RangeFunction;
import game.rules.play.moves.nonDecision.effect.Apply;
import other.BaseLudeme;
/**
* Gets all the conditions or effects related to the location between ``from'' and ``to''.
*
* @author Eric.Piette
*/
public class Between extends BaseLudeme
{
/** The piece to let between the from and to. */
private final IntFunction trail;
/** The condition applied between the from and to. */
private final BooleanFunction cond;
/** The distance before the range locations. */
private final IntFunction before;
/** The range of the middle locations. */
private final RangeFunction range;
/** The distance after the range locations. */
private final IntFunction after;
/** The effect to apply on the locations. */
private final Apply effect;
//-------------------------------------------------------------------------
/**
* @param before Lead distance up to ``between'' section.
* @param range Range of the ``between'' section.
* @param after Trailing distance after ``between'' section.
* @param If The condition on the location.
* @param trail The piece to let on the location.
* @param effect Actions to apply.
*
* @example (between if:(is Enemy (who at:(between))) (apply (remove
* (between))) )
*/
public Between
(
@Opt @Name final IntFunction before,
@Opt final RangeFunction range,
@Opt @Name final IntFunction after,
@Opt @Name final BooleanFunction If,
@Opt @Name final IntFunction trail,
@Opt final Apply effect
)
{
this.trail = trail;
cond = If;
this.before = before;
this.range = range;
this.after = after;
this.effect = effect;
}
//-------------------------------------------------------------------------
/**
* @return The piece to trail
*/
public IntFunction trail()
{
return trail;
}
/**
* @return The effect to apply on the piece in between
*/
public Apply effect()
{
return effect;
}
/**
* @return The distance before the range locations.
*/
public IntFunction before()
{
return before;
}
/**
* @return The range of the middle locations.
*/
public RangeFunction range()
{
return range;
}
/**
* @return The distance after the range locations.
*/
public IntFunction after()
{
return after;
}
/**
* @return The region of the from location.
*/
public BooleanFunction condition()
{
return cond;
}
@Override
public String toEnglish(final Game game)
{
return "for all the between sites where " + cond.toEnglish(game) + " is satisfied, apply " + effect.toEnglish(game);
}
}
| 2,802 | 21.604839 | 118 | java |
Ludii | Ludii-master/Core/src/game/util/moves/Flips.java | package game.util.moves;
import game.Game;
import other.BaseLudeme;
/**
* Sets the flips state of a piece.
*
* @author Eric.Piette
*/
public class Flips extends BaseLudeme
{
/** The first flip value. */
final private int flipA;
/** The second flip value. */
final private int flipB;
//-------------------------------------------------------------------------
/**
* @param flipA The first state of the flip.
* @param flipB The second state of the flip.
* @example (flips 1 2)
*/
public Flips
(
final Integer flipA,
final Integer flipB
)
{
this.flipA = flipA.intValue();
this.flipB = flipB.intValue();
}
//-------------------------------------------------------------------------
/**
* @param currentState
*
* @return The other state.
*/
public int flipState(final int currentState)
{
if (currentState == flipA)
return flipB;
else if (currentState == flipB)
return flipA;
else
return currentState; // no flip state, just return current state
}
//-------------------------------------------------------------------------
/**
* @return The flipA state.
*/
public int flipA()
{
return flipA;
}
/**
* @return The flipB state.
*/
public int flipB()
{
return flipB;
}
//-------------------------------------------------------------------------
@Override
public String toEnglish(final Game game)
{
return "with a " + flipA + " on one side and a " + flipB + " on the other side";
}
}
| 1,479 | 17.5 | 82 | java |
Ludii | Ludii-master/Core/src/game/util/moves/From.java | package game.util.moves;
import annotations.Name;
import annotations.Opt;
import annotations.Or;
import game.functions.booleans.BooleanFunction;
import game.functions.ints.IntFunction;
import game.functions.region.RegionFunction;
import game.types.board.SiteType;
import other.BaseLudeme;
/**
* Specifies operations based on the ``from'' location.
*
* @author cambolbro & Eric.Piette
*/
public class From extends BaseLudeme
{
/** The from location */
private final IntFunction loc;
/** The from region */
private final RegionFunction region;
/** The level of the from location */
private final IntFunction level;
/** The condition on the from location */
private final BooleanFunction cond;
/** The graph element type of the location. */
private final SiteType type;
//-------------------------------------------------------------------------
/**
*
* @param type The graph element type.
* @param region The region of the ``from'' location.
* @param loc The ``from'' location.
* @param level The level of the ``from'' location.
* @param If The condition on the ``from'' location.
*
* @example (from (last To) level:(level))
*/
public From
(
@Opt final SiteType type,
@Opt @Or final RegionFunction region,
@Opt @Or final IntFunction loc,
@Opt @Name final IntFunction level,
@Opt @Name final BooleanFunction If
)
{
this.loc = (region != null) ? null : (loc == null) ? new game.functions.ints.iterator.From(null) : loc;
this.region = region;
this.level = level;
this.cond = If;
this.type = type;
}
//-------------------------------------------------------------------------
/**
* @return The from location.
*/
public IntFunction loc()
{
return loc;
}
/**
* @return The region of the from location.
*/
public RegionFunction region()
{
return region;
}
/**
* @return The level.
*/
public IntFunction level()
{
return level;
}
/**
* @return The condition on the from.
*/
public BooleanFunction cond()
{
return cond;
}
/**
* @return The graph element type of the location.
*/
public SiteType type()
{
return type;
}
}
| 2,198 | 20.144231 | 105 | java |
Ludii | Ludii-master/Core/src/game/util/moves/Piece.java | package game.util.moves;
import annotations.Name;
import annotations.Opt;
import annotations.Or;
import game.functions.ints.IntFunction;
import game.functions.ints.board.Id;
import other.BaseLudeme;
/**
* Specifies operations based on the ``what'' data.
*
* @author Eric.Piette
*/
public class Piece extends BaseLudeme
{
/** The index of the component. */
private final IntFunction component;
/** The indices of the components. */
private final IntFunction[] components;
/** The local state of the site of the component. */
private final IntFunction state;
/** The name of the component. */
private final String name;
/** The names of the components. */
private final String[] names;
//-------------------------------------------------------------------------
/**
* @param nameComponent The name of the component.
* @param component The index of the component [The component with the
* index corresponding to the index of the mover,
* (mover)].
* @param nameComponents The names of the components.
* @param components The indices of the components.
* @param state The local state value to put on the site where the
* piece is placed.
*
* @example (piece (mover))
*/
public Piece
(
@Or final String nameComponent,
@Or final IntFunction component,
@Or final String[] nameComponents,
@Or final IntFunction[] components,
@Opt @Name final IntFunction state
)
{
int numNonNull = 0;
if (component != null)
numNonNull++;
if (components != null)
numNonNull++;
if (nameComponent != null)
numNonNull++;
if (nameComponents != null)
numNonNull++;
if (numNonNull != 1)
throw new IllegalArgumentException(
"Piece(): One nameComponent, component, nameComponents or components parameter must be non-null.");
this.name = nameComponent;
this.names = nameComponents;
this.component = (nameComponent != null) ? new Id(nameComponent,null) : component;
if(nameComponents != null)
{
this.components = new IntFunction[nameComponents.length];
for(int i = 0; i < nameComponents.length;i++)
{
this.components[i] = new Id(nameComponents[i],null);
}
}
else
this.components = components;
this.state = state;
}
//-------------------------------------------------------------------------
/**
* @return The state value.
*/
public IntFunction state()
{
return state;
}
/**
* @return The component index.
*/
public IntFunction component()
{
return component;
}
/**
* @return The indices of the components.
*/
public IntFunction[] components()
{
return components;
}
/**
* @return The name of the component.
*/
public String nameComponent()
{
return name;
}
/**
* @return The names of the components.
*/
public String[] nameComponents()
{
return names;
}
}
| 2,963 | 21.976744 | 104 | java |
Ludii | Ludii-master/Core/src/game/util/moves/Player.java | package game.util.moves;
import game.functions.ints.IntFunction;
import game.functions.ints.state.Mover;
import other.BaseLudeme;
/**
* Specifies operations based on the ``who'' data.
*
* @author Eric.Piette
*/
public class Player extends BaseLudeme
{
/** The index of the player. */
private final IntFunction index;
//-------------------------------------------------------------------------
/** The index function returned by this class. */
private final IntFunction indexReturned;
//-------------------------------------------------------------------------
/**
* @param index The index of the player [(mover)].
*
* @example (player (mover))
* @example (player 2)
*/
public Player
(
final IntFunction index
)
{
this.index = index;
this.indexReturned = (index == null) ? new Mover()
: index;
}
//-------------------------------------------------------------------------
/**
* @return The player index.
*/
public IntFunction originalIndex()
{
return index;
}
/**
* @return The player index returned by the index and the role.
*/
public IntFunction index()
{
return indexReturned;
}
}
| 1,152 | 18.87931 | 76 | java |
Ludii | Ludii-master/Core/src/game/util/moves/To.java | package game.util.moves;
import annotations.Name;
import annotations.Opt;
import annotations.Or;
import game.functions.booleans.BooleanFunction;
import game.functions.intArray.state.Rotations;
import game.functions.ints.IntFunction;
import game.functions.region.RegionFunction;
import game.rules.play.moves.nonDecision.effect.Apply;
import game.types.board.SiteType;
import other.BaseLudeme;
/**
* Specifies operations based on the ``to'' location.
*
* @author cambolbro & Eric.Piette
*/
public class To extends BaseLudeme
{
/** The to location */
private final IntFunction loc;
/** The to region */
private final RegionFunction region;
/** The level of the from location */
private final IntFunction level;
/** The condition on the from location */
private final BooleanFunction cond;
/** The rotations of the to location. */
private final Rotations rotations;
/** The graph element type of the location. */
private final SiteType type;
/** The effect to apply on the locations. */
private final Apply effect;
//-------------------------------------------------------------------------
/**
*
* @param type The graph element type.
* @param region The region of ``to'' the location.
* @param loc The ``to'' location.
* @param level The level of the ``to'' location.
* @param rotations Rotations of the ``to'' location.
* @param If The condition on the ``to'' location.
* @param effect Effect to apply to the ``to'' location.
*
* @example (to (last To) level:(level))
*/
public To
(
@Opt final SiteType type,
@Opt @Or final RegionFunction region,
@Opt @Or final IntFunction loc,
@Opt @Name final IntFunction level,
@Opt final Rotations rotations,
@Opt @Name final BooleanFunction If,
@Opt final Apply effect
)
{
this.loc = (region != null) ? null : (loc == null) ? game.functions.ints.iterator.To.construct() : loc;
this.region = region;
this.level = level;
this.cond = If;
this.rotations = rotations;
this.type = type;
this.effect = effect;
}
//-------------------------------------------------------------------------
/**
* @return The to location.
*/
public IntFunction loc()
{
return loc;
}
/**
* @return The region of the to location.
*/
public RegionFunction region()
{
return region;
}
/**
* @return The level.
*/
public IntFunction level()
{
return level;
}
/**
* @return The condition on the to..
*/
public BooleanFunction cond()
{
return cond;
}
/**
* @return The graph element type of the location.
*/
public SiteType type()
{
return type;
}
/**
* @return The rotation of the to element.
*/
public Rotations rotations()
{
return rotations;
}
/**
* @return The effect.
*/
public Apply effect()
{
return effect;
}
}
| 2,903 | 20.671642 | 105 | java |
Ludii | Ludii-master/Core/src/game/util/moves/package-info.java | /**
* Moves utilities are support classes for defining and generating legal moves.
*/
package game.util.moves;
| 113 | 21.8 | 79 | java |
Ludii | Ludii-master/Core/src/game/util/optimiser/Optimiser.java | package game.util.optimiser;
import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import game.Game;
import game.functions.booleans.BaseBooleanFunction;
import game.functions.booleans.BooleanConstant;
import game.functions.ints.BaseIntFunction;
import game.functions.ints.IntConstant;
import game.functions.region.BaseRegionFunction;
import game.functions.region.RegionConstant;
import main.ReflectionUtils;
import other.Ludeme;
import other.context.Context;
import other.trial.Trial;
/**
* Optimiser which can optimise a compiled game by injecting more efficient ludemes.
*
* @author Dennis Soemers
*/
public class Optimiser
{
//-------------------------------------------------------------------------
/**
* Optimises the given (compiled) game object.
* @param game
*/
public static void optimiseGame(final Game game)
{
final Context dummyContext = new Context(game, new Trial(game));
optimiseLudeme(game, dummyContext, new HashMap<Object, Set<String>>());
}
//-------------------------------------------------------------------------
/**
* Optimises the subtree rooted in the given ludeme
* @param ludeme
* @param dummyContext
* @param visited Map of fields we've already visited, to avoid cycles
*/
private static void optimiseLudeme
(
final Ludeme ludeme, final Context dummyContext, 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))
{
boolean recurse = true;
if (BaseRegionFunction.class.isAssignableFrom(valueClass) && !RegionConstant.class.isAssignableFrom(valueClass))
{
final BaseRegionFunction baseRegion = (BaseRegionFunction) value;
if (baseRegion.isStatic())
{
final RegionConstant constReg = new RegionConstant(baseRegion.eval(dummyContext));
injectLudeme(ludeme, constReg, baseRegion, new HashSet<Object>());
recurse = false;
}
}
else if (BaseIntFunction.class.isAssignableFrom(valueClass) && !IntConstant.class.isAssignableFrom(valueClass))
{
final BaseIntFunction baseInt = (BaseIntFunction) value;
if (baseInt.isStatic())
{
final IntConstant constInt = new IntConstant(baseInt.eval(dummyContext));
injectLudeme(ludeme, constInt, baseInt, new HashSet<Object>());
recurse = false;
}
}
else if (BaseBooleanFunction.class.isAssignableFrom(valueClass) && !BaseBooleanFunction.class.isAssignableFrom(valueClass))
{
final BaseBooleanFunction baseBool = (BaseBooleanFunction) value;
if (baseBool.isStatic())
{
final BooleanConstant constBool = new BooleanConstant(baseBool.eval(dummyContext));
injectLudeme(ludeme, constBool, baseBool, new HashSet<Object>());
recurse = false;
}
}
if (recurse)
optimiseLudeme((Ludeme) value, dummyContext, 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))
{
boolean recurse = true;
if (BaseRegionFunction.class.isAssignableFrom(elementClass) && !RegionConstant.class.isAssignableFrom(elementClass))
{
final BaseRegionFunction baseRegion = (BaseRegionFunction) element;
if (baseRegion.isStatic())
{
final RegionConstant constReg = new RegionConstant(baseRegion.eval(dummyContext));
injectLudeme(ludeme, constReg, baseRegion, new HashSet<Object>());
recurse = false;
}
}
else if (BaseIntFunction.class.isAssignableFrom(elementClass) && !IntConstant.class.isAssignableFrom(elementClass))
{
final BaseIntFunction baseInt = (BaseIntFunction) element;
if (baseInt.isStatic())
{
final IntConstant constInt = new IntConstant(baseInt.eval(dummyContext));
injectLudeme(ludeme, constInt, baseInt, new HashSet<Object>());
recurse = false;
}
}
else if (BaseBooleanFunction.class.isAssignableFrom(elementClass) && !BooleanConstant.class.isAssignableFrom(elementClass))
{
final BaseBooleanFunction baseBool = (BaseBooleanFunction) element;
if (baseBool.isStatic())
{
final BooleanConstant constInt = new BooleanConstant(baseBool.eval(dummyContext));
injectLudeme(ludeme, constInt, baseBool, new HashSet<Object>());
recurse = false;
}
}
if (recurse)
optimiseLudeme((Ludeme) element, dummyContext, 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))
{
boolean recurse = true;
if (BaseRegionFunction.class.isAssignableFrom(elementClass) && !RegionConstant.class.isAssignableFrom(elementClass))
{
final BaseRegionFunction baseRegion = (BaseRegionFunction) element;
if (baseRegion.isStatic())
{
final RegionConstant constReg = new RegionConstant(baseRegion.eval(dummyContext));
injectLudeme(ludeme, constReg, baseRegion, new HashSet<Object>());
recurse = false;
}
}
else if (BaseIntFunction.class.isAssignableFrom(elementClass) && !IntConstant.class.isAssignableFrom(elementClass))
{
final BaseIntFunction baseInt = (BaseIntFunction) element;
if (baseInt.isStatic())
{
final IntConstant constInt = new IntConstant(baseInt.eval(dummyContext));
injectLudeme(ludeme, constInt, baseInt, new HashSet<Object>());
recurse = false;
}
}
else if (BaseBooleanFunction.class.isAssignableFrom(elementClass) && !BooleanConstant.class.isAssignableFrom(elementClass))
{
final BaseBooleanFunction baseBool = (BaseBooleanFunction) element;
if (baseBool.isStatic())
{
final BooleanConstant constInt = new BooleanConstant(baseBool.eval(dummyContext));
injectLudeme(ludeme, constInt, baseBool, new HashSet<Object>());
recurse = false;
}
}
if (recurse)
optimiseLudeme((Ludeme) element, dummyContext, visited);
}
}
}
}
}
}
}
catch (final IllegalArgumentException | IllegalAccessException e)
{
e.printStackTrace();
}
}
//-------------------------------------------------------------------------
/**
* Injects the given new ludeme such that it replaces the original ludeme
* if the original ludeme is a field of the given parent ludeme
*
* @param parentObject
* @param newLudeme
* @param origLudeme
* @param inspectedParentObjects Set of parent objects we already looked at (avoid cycles)
* @throws IllegalAccessException
* @throws IllegalArgumentException
*/
private static void injectLudeme
(
final Object parentObject,
final Ludeme newLudeme,
final Ludeme origLudeme,
final Set<Object> inspectedParentObjects
) throws IllegalArgumentException, IllegalAccessException
{
if (inspectedParentObjects.contains(parentObject))
return;
inspectedParentObjects.add(parentObject);
//System.out.println("injecting " + newLudeme + " as replacement for " + origLudeme + " in " + parentObject);
if (parentObject.getClass().isArray())
{
final int arrLength = Array.getLength(parentObject);
for (int i = 0; i < arrLength; ++i)
{
final Object obj = Array.get(parentObject, i);
if (obj == null)
continue;
if (obj.getClass().isArray() || Iterable.class.isAssignableFrom(obj.getClass()))
injectLudeme(obj, newLudeme, origLudeme, inspectedParentObjects);
else if (obj == origLudeme)
Array.set(parentObject, i, newLudeme);
}
}
else
{
final List<Field> parentFields = ReflectionUtils.getAllFields(parentObject.getClass());
for (final Field field : parentFields)
{
if (field.getName().contains("$"))
continue;
field.setAccessible(true);
if ((field.getModifiers() & Modifier.STATIC) != 0)
continue;
final Object fieldVal = field.get(parentObject);
if (fieldVal == null)
continue;
if (fieldVal.getClass().isArray() || Iterable.class.isAssignableFrom(fieldVal.getClass()))
injectLudeme(fieldVal, newLudeme, origLudeme, inspectedParentObjects);
else if (fieldVal == origLudeme)
field.set(parentObject, newLudeme);
}
}
}
//-------------------------------------------------------------------------
}
| 10,082 | 31.737013 | 132 | java |
Ludii | Ludii-master/Core/src/metadata/Metadata.java | package metadata;
import java.io.Serializable;
import java.util.BitSet;
import annotations.Hide;
import annotations.Opt;
import game.Game;
import metadata.ai.Ai;
import metadata.graphics.Graphics;
import metadata.info.Info;
import metadata.recon.Recon;
/**
* The metadata of a game.
*
* @author cambolbro and Eric.Piette and Dennis Soemers and Matthew.Stephenson
*/
public class Metadata implements MetadataItem, Serializable
{
private static final long serialVersionUID = 1L;
// -----------------------------------------------------------------------
/** The info metadata. */
private final Info info;
/** Our graphics related metadata. */
private final Graphics graphics;
/** Our AI-related metadata (heuristics, features, etc.). */
private final Ai ai;
/** Our Recon-related metadata (heuristics, features, etc.). */
private final Recon recon;
//-----------------------------------------------------------------------
/**
* @param info The info metadata.
* @param graphics The graphics metadata.
* @param ai Metadata for AIs playing this game.
* @param recon The metadata related to reconstruction.
*
* @example (metadata (info { (description "Description of The game") (source
* "Source of the game") (version "1.0.0") (classification
* "board/space/territory") (origin "Origin of the game.") }) (graphics
* { (board Style Go) (player Colour P1 (colour Black)) (player Colour
* P2 (colour White)) }) (ai (bestAgent "UCT")) )
*/
public Metadata
(
@Opt final Info info,
@Opt final Graphics graphics,
@Opt final Ai ai,
@Opt final Recon recon
)
{
// Set info metadata.
if (info != null)
{
this.info = info;
}
else
{
// Initialise an empty info metadata object if non specified.
this.info = new Info(null, null);
}
// Set graphics metadata.
if (graphics != null)
{
this.graphics = graphics;
}
else
{
// Initialise an empty graphics metadata object if non specified.
this.graphics = new Graphics(null, null);
}
// Set AI metadata.
if (ai != null)
this.ai = ai;
else
this.ai = new Ai(null, null, null, null, null, null);
// Set Recon metadata.
if (recon != null)
this.recon = recon;
else
this.recon = new Recon(null, null);
}
/**
* Default constructor for Compiler to call.
*/
@Hide
public Metadata()
{
this.info = new Info(null, null);
this.graphics = new Graphics(null, null);
this.ai = new Ai(null, null, null, null, null, null);
this.recon = new Recon(null, null);
}
//-------------------------------------------------------------------------
/**
* @return The info metadata.
*/
public Info info()
{
return info;
}
/**
* @return The graphics metadata.
*/
public Graphics graphics()
{
return graphics;
}
/**
* @return Our AI metadata
*/
public Ai ai()
{
return ai;
}
/**
* @return Our Recon metadata
*/
public Recon recon()
{
return recon;
}
//-------------------------------------------------------------------------
@Override
public String toString()
{
final StringBuilder sb = new StringBuilder();
sb.append("(metadata\n");
if (info != null)
sb.append(info.toString());
if (graphics != null)
sb.append(graphics.toString());
if (ai != null)
sb.append(ai.toString());
if (recon != null)
sb.append(recon.toString());
sb.append(")\n");
return sb.toString();
}
//-------------------------------------------------------------------------
/**
* @param game The game.
* @return Accumulated concepts.
*/
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
concepts.or(graphics.concepts(game));
return concepts;
}
/**
* @param game The game.
* @return Accumulated game flags.
*/
public long gameFlags(final Game game)
{
long gameFlags = 0l;
gameFlags |= graphics.gameFlags(game);
return gameFlags;
}
}
| 3,983 | 20.191489 | 81 | java |
Ludii | Ludii-master/Core/src/metadata/MetadataItem.java | package metadata;
//-----------------------------------------------------------------------------
/**
* Interface for generic metadata item.
* Classes to be included as metadata should inherit form this.
* @author cambolbro
*/
public interface MetadataItem
{
// Nothing to add, this interface is just for identifying metadata items.
}
| 345 | 23.714286 | 79 | java |
Ludii | Ludii-master/Core/src/metadata/package-info.java | /**
* @chapter Ludii {\it metadata} is additional information about each game that exists outside its core logic.
* Relevant metadata includes general game information, rendering hints, and AI hints
* to improve the playing experience.
*
* @section The {\tt metadata} ludeme is a catch-call for all metadata items.
*/
package metadata;
| 373 | 40.555556 | 112 | java |
Ludii | Ludii-master/Core/src/metadata/ai/AIItem.java | package metadata.ai;
import metadata.MetadataItem;
//-----------------------------------------------------------------------------
/**
* General function hint for this game.Metadata containing hints for AI agents for this game.
* @author cambolbro
*/
public interface AIItem extends MetadataItem
{
// ...
}
| 315 | 20.066667 | 93 | java |
Ludii | Ludii-master/Core/src/metadata/ai/Ai.java | package metadata.ai;
import annotations.Name;
import annotations.Opt;
import metadata.MetadataItem;
import metadata.ai.agents.Agent;
import metadata.ai.features.Features;
import metadata.ai.features.trees.FeatureTrees;
import metadata.ai.heuristics.Heuristics;
//-----------------------------------------------------------------------------
/**
* Defines metadata that can help AIs in the Ludii app to play this game at a
* stronger level.
*
* @remarks Specifying AI metadata for games is not mandatory.
*
* @author Dennis Soemers and cambolbro
*/
public class Ai implements MetadataItem
{
// WARNING: The weird capitalisation of of the class name is INTENTIONAL!
// This makes the type name in the grammar and documentation look better,
// as just "<ai>" instead of the really silly "<aI>" that we would get
// otherwise.
//-------------------------------------------------------------------------
/** The agent */
private final Agent agent;
/** Heuristics */
private final Heuristics heuristics;
/** Automatically trained (or at least generated through some sort of automated process) heuristics */
private final Heuristics trainedHeuristics;
/** Features (could be handcrafted) */
private final Features features;
/** Automatically trained features */
private Features trainedFeatures;
/** Automatically trained feature trees */
private final FeatureTrees trainedFeatureTrees;
//-------------------------------------------------------------------------
/**
* Constructor
* @param agent Can be used to specify the agent that is expected to
* perform best in this game. This algorithm will be used when the ``Ludii AI"
* option is selected in the Ludii app.
* @param heuristics Heuristics to be used by Alpha-Beta agents. These may be
* handcrafted heuristics.
* @param trainedHeuristics Heuristics trained or otherwise generated by some
* sort of automated process. Alpha-Beta agents will only use these if the previous
* parameter (for potentially handcrafted heuristics) is not used.
* @param features Feature sets (possibly handcrafted) to be used for biasing MCTS-based agents.
* If not specified, Biased MCTS will not be available as an AI for this game in Ludii.
* @param trainedFeatures Automatically-trained feature sets. Will be used instead of the
* regular ``features'' parameter if that one is left unspecified.
* @param trainedFeatureTrees Automatically-trained decision trees of features. Will be used
* instead of the regular ``features'' or ``trainedFeatures'' parameters if those are left
* unspecified.
*
* @example (ai (bestAgent "UCT"))
*/
public Ai
(
@Opt final Agent agent,
@Opt final Heuristics heuristics,
@Name @Opt final Heuristics trainedHeuristics,
@Opt final Features features,
@Name @Opt final Features trainedFeatures,
@Name @Opt final FeatureTrees trainedFeatureTrees
)
{
this.agent = agent;
this.heuristics = heuristics;
this.trainedHeuristics = trainedHeuristics;
this.features = features;
this.trainedFeatures = trainedFeatures;
this.trainedFeatureTrees = trainedFeatureTrees;
}
//-------------------------------------------------------------------------
/**
* @return Metadata item describing agent
*/
public Agent agent()
{
return agent;
}
/**
* @return Heuristics for this game
*/
public Heuristics heuristics()
{
if (heuristics == null)
return trainedHeuristics;
return heuristics;
}
/**
* @return Automatically trained / generated heuristics for this game
*/
public Heuristics trainedHeuristics()
{
return trainedHeuristics;
}
/**
* @return Features for this game
*/
public Features features()
{
if (features == null)
return trainedFeatures;
return features;
}
/**
* @return Trained features for this game
*/
public Features trainedFeatures()
{
return trainedFeatures;
}
/**
* @return Trained feature trees for this game
*/
public FeatureTrees trainedFeatureTrees()
{
return trainedFeatureTrees;
}
/**
* Set the trained features
* @param trainedFeatures
*/
public void setTrainedFeatures(final Features trainedFeatures)
{
this.trainedFeatures = trainedFeatures;
}
//-------------------------------------------------------------------------
@Override
public String toString()
{
final StringBuilder sb = new StringBuilder();
sb.append(" (ai\n");
if (agent != null)
sb.append(" " + agent.toString() + "\n");
if (heuristics != null)
sb.append(" " + heuristics.toString() + "\n");
if (trainedHeuristics != null)
sb.append(" trainedHeuristics:" + trainedHeuristics.toString() + "\n");
if (features != null)
sb.append(" " + features.toString() + "\n");
if (trainedFeatures != null)
sb.append(" trainedFeatures:" + trainedFeatures.toString() + "\n");
if (trainedFeatureTrees != null)
sb.append(" trainedFeatureTrees:" + trainedFeatureTrees.toString() + "\n");
sb.append(" )\n");
return sb.toString();
}
//-------------------------------------------------------------------------
}
| 5,168 | 26.641711 | 103 | java |
Ludii | Ludii-master/Core/src/metadata/ai/package-info.java | /**
* @chapter Ludii's {\it artificial intelligence} (AI) agents use hints provided in the {\tt ai} metadata items
* to help them play each game effectively.
* These AI hints can apply to the game as a whole, or be targeted at particular variant rulesets or
* combinations of options within each game.
* Games benefit from the AI metadata but do not depend upon it; that is, Ludii's default AI agents will still
* play each game if no AI metadata is provided, but probably not as well.
*
* @section The {\tt ai} metadata category collects relevant AI-related information.
* This information includes which {\it search algorithm} to use for move planning, what its settings should be,
* which {\it heuristics} are most useful, and which {\it features} (i.e. geometric piece patterns) are most important.
*/
package metadata.ai;
| 849 | 59.714286 | 121 | java |
Ludii | Ludii-master/Core/src/metadata/ai/agents/Agent.java | package metadata.ai.agents;
import metadata.ai.AIItem;
/**
* Describes an agent (either by name of expected best agent, or as a
* complete setup).
*
* @author Dennis Soemers
*/
public interface Agent extends AIItem
{
// Nothing here
}
| 248 | 13.647059 | 70 | java |
Ludii | Ludii-master/Core/src/metadata/ai/agents/BestAgent.java | package metadata.ai.agents;
import main.StringRoutines;
/**
* Describes the name of an algorithm or agent that is typically expected to
* be the best-performing algorithm available in Ludii for this game.
*
* @remarks Some examples of names that Ludii can currently recognise are
* ``Random'', ``Flat MC'', ``Alpha-Beta'', ``UCT'', ``MC-GRAVE'',
* and ``Biased MCTS''.
*
* @author Dennis Soemers
*/
public final class BestAgent implements Agent
{
//-------------------------------------------------------------------------
/** Agent name */
private final String agent;
//-------------------------------------------------------------------------
/**
* Constructor
* @param agent The name of the (expected) best agent for this game.
*
* @example (bestAgent "UCT")
*/
public BestAgent(final String agent)
{
this.agent = agent;
}
//-------------------------------------------------------------------------
/**
* @return The agent string
*/
public String agent()
{
return agent;
}
//-------------------------------------------------------------------------
@Override
public String toString()
{
return "(bestAgent " + StringRoutines.quote(agent) + ")";
}
//-------------------------------------------------------------------------
}
| 1,298 | 21.789474 | 76 | java |
Ludii | Ludii-master/Core/src/metadata/ai/agents/package-info.java | /**
* The {\tt agents} package includes various ways of defining agents.
*/
package metadata.ai.agents;
| 106 | 20.4 | 69 | java |
Ludii | Ludii-master/Core/src/metadata/ai/agents/mcts/Mcts.java | package metadata.ai.agents.mcts;
import annotations.Opt;
import metadata.ai.agents.Agent;
import metadata.ai.agents.mcts.selection.Selection;
import metadata.ai.agents.mcts.selection.Ucb1;
/**
* Describes a Monte-Carlo tree search agent.
*
* @author Dennis Soemers
*/
public class Mcts implements Agent
{
// WARNING: The weird capitalisation of of the class name is INTENTIONAL!
// This makes the type name in the grammar and documentation look better,
// as just "<mcts>" instead of the really silly "<mCTS>" that we would get
// otherwise.
//-------------------------------------------------------------------------
/** Our Selection strategy */
protected final Selection selection;
//-------------------------------------------------------------------------
/**
* Constructor
*
* @param selection The Selection strategy to be used by this MCTS agent [UCB1].
*
* @example (mcts)
*/
public Mcts
(
@Opt final Selection selection
)
{
if (selection != null)
this.selection = selection;
else
this.selection = new Ucb1(null);
if (this.selection.requiresLearnedSelectionPolicy())
{
// TODO check whether a learned selection policy was specified
}
}
//-------------------------------------------------------------------------
@Override
public String toString()
{
return "(mcts " + selection + ")";
}
//-------------------------------------------------------------------------
}
| 1,457 | 22.516129 | 81 | java |
Ludii | Ludii-master/Core/src/metadata/ai/agents/mcts/package-info.java | /**
* The {\tt mcts} package includes agents based on Monte-Carlo tree search.
*/
package metadata.ai.agents.mcts;
| 117 | 22.6 | 75 | java |
Ludii | Ludii-master/Core/src/metadata/ai/agents/mcts/backpropagation/package-info.java | /**
* The {\tt backpropagation} package includes several backpropagation strategies
* for Monte-Carlo tree search.
*/
package metadata.ai.agents.mcts.backpropagation;
| 171 | 27.666667 | 81 | java |
Ludii | Ludii-master/Core/src/metadata/ai/agents/mcts/playout/package-info.java | /**
* The {\tt playout} package includes several play-out strategies
* for Monte-Carlo tree search.
*/
package metadata.ai.agents.mcts.playout;
| 148 | 23.833333 | 66 | java |
Ludii | Ludii-master/Core/src/metadata/ai/agents/mcts/selection/Ag0.java | package metadata.ai.agents.mcts.selection;
import annotations.Opt;
/**
* Describes the selection strategy also used by AlphaGo Zero (and AlphaZero).
* Requires that a learned selection policy (based on features) has been
* described for the MCTS agent that uses this selection strategy.
*
* @author Dennis Soemers
*/
public class Ag0 extends Selection
{
//-------------------------------------------------------------------------
/** The exploration constant */
protected final double explorationConstant;
//-------------------------------------------------------------------------
/**
* Constructor
*
* @param explorationConstant The value to use for the exploration constant [2.5].
*
* @example (ag0)
*/
public Ag0(@Opt final Float explorationConstant)
{
if (explorationConstant == null)
this.explorationConstant = 2.5;
else
this.explorationConstant = explorationConstant.doubleValue();
}
//-------------------------------------------------------------------------
@Override
public String toString()
{
return "(ag0 " + explorationConstant + ")";
}
//-------------------------------------------------------------------------
@Override
public boolean requiresLearnedSelectionPolicy()
{
return true;
}
//-------------------------------------------------------------------------
}
| 1,355 | 23.214286 | 83 | java |
Ludii | Ludii-master/Core/src/metadata/ai/agents/mcts/selection/Selection.java | package metadata.ai.agents.mcts.selection;
import metadata.ai.AIItem;
/**
* Abstract class for Selection strategies for MCTS in AI metadata
*
* @author Dennis Soemers
*/
public abstract class Selection implements AIItem
{
//-------------------------------------------------------------------------
/**
* @return Do we require a learned selection policy?
*/
@SuppressWarnings("static-method")
public boolean requiresLearnedSelectionPolicy()
{
return false;
}
//-------------------------------------------------------------------------
}
| 563 | 19.888889 | 76 | java |
Ludii | Ludii-master/Core/src/metadata/ai/agents/mcts/selection/Ucb1.java | package metadata.ai.agents.mcts.selection;
import annotations.Opt;
/**
* Describes the UCB1 selection strategy, which is one of the most straightforward
* and simple Selection strategies, used by the standard UCT variant of MCTS.
*
* @author Dennis Soemers
*/
public class Ucb1 extends Selection
{
// WARNING: The weird capitalisation of of the class name is INTENTIONAL!
// This makes the type name in the grammar and documentation look better,
// as just "<ucb1>" instead of the really silly "<uCB1>" that we would get
// otherwise.
//-------------------------------------------------------------------------
/** The exploration constant */
protected final double explorationConstant;
//-------------------------------------------------------------------------
/**
* Constructor
*
* @param explorationConstant The value to use for the exploration constant [square root of 2].
*
* @example (ucb1)
* @example (ucb1 0.6)
*/
public Ucb1(@Opt final Float explorationConstant)
{
if (explorationConstant == null)
this.explorationConstant = Math.sqrt(2.0);
else
this.explorationConstant = explorationConstant.doubleValue();
}
//-------------------------------------------------------------------------
@Override
public String toString()
{
return "(ucb1 " + explorationConstant + ")";
}
//-------------------------------------------------------------------------
}
| 1,430 | 26 | 96 | java |
Ludii | Ludii-master/Core/src/metadata/ai/agents/mcts/selection/package-info.java | /**
* The {\tt selection} package includes several selection strategies
* for Monte-Carlo tree search.
*/
package metadata.ai.agents.mcts.selection;
| 153 | 24.666667 | 69 | java |
Ludii | Ludii-master/Core/src/metadata/ai/agents/minimax/AlphaBeta.java | package metadata.ai.agents.minimax;
import annotations.Opt;
import metadata.ai.agents.Agent;
import metadata.ai.heuristics.Heuristics;
/**
* Describes an Alpha-Beta search agent.
*
* @author Dennis Soemers
*/
public class AlphaBeta implements Agent
{
//-------------------------------------------------------------------------
/** The heuristics we want to use. If null, will just use from game file's metadata */
protected final Heuristics heuristics;
//-------------------------------------------------------------------------
/**
* Constructor
*
* @param heuristics The heuristics to be used by this agent. Will default
* to heuristics from the game file's metadata if left unspecified [null].
*
* @example (alphaBeta)
*/
public AlphaBeta
(
@Opt final Heuristics heuristics
)
{
this.heuristics = heuristics;
}
//-------------------------------------------------------------------------
/**
* @return Our heuristics (can be null if we just want to use from game
* file's metadata)
*/
public Heuristics heuristics()
{
return heuristics;
}
//-------------------------------------------------------------------------
@Override
public String toString()
{
if (heuristics == null)
return "(alphaBeta)";
else
return "(alphaBeta " + heuristics.toString() + ")";
}
//-------------------------------------------------------------------------
}
| 1,422 | 21.587302 | 87 | java |
Ludii | Ludii-master/Core/src/metadata/ai/agents/minimax/package-info.java | /**
* The {\tt minimax} package includes minimax-based agents, such as Alpha-Beta.
*/
package metadata.ai.agents.minimax;
| 124 | 24 | 79 | java |
Ludii | Ludii-master/Core/src/metadata/ai/features/FeatureSet.java | package metadata.ai.features;
import annotations.Name;
import annotations.Opt;
import game.types.play.RoleType;
import main.StringRoutines;
import metadata.ai.AIItem;
import metadata.ai.misc.Pair;
/**
* Defines a single feature set, which may be applicable to either a
* single specific player in a game, or to all players in a game.
*
* @remarks Use \\texttt{All} for feature sets that are applicable to all players
* in a game, or \\texttt{P1}, \\texttt{P2}, etc. for feature sets that are
* applicable only to individual players.
*
* @author Dennis Soemers
*/
public class FeatureSet implements AIItem
{
//-------------------------------------------------------------------------
/** Role (should either be All, or a specific Player) */
protected final RoleType role;
/** Array of strings describing features */
protected final String[] featureStrings;
/** Array of weights (one per feature) for Selection */
protected final float[] selectionWeights;
/** Array of weights (one per feature) for Playouts */
protected final float[] playoutWeights;
/** Array of weights (one per feature) for TSPG objective */
protected final float[] tspgWeights;
//-------------------------------------------------------------------------
/**
* For a single collection of features and weights for one role.
*
* @param role The Player (P1, P2, etc.) for which the feature set should apply,
* or All if it is applicable to all players in a game.
* @param features Complete list of all features and weights for this feature
* set.
*
* @example (featureSet All { (pair "rel:to=<{}>:pat=<els=[-{}]>" 1.0) })
* @example (featureSet P1 { (pair "rel:to=<{}>:pat=<els=[-{}]>" 1.0) })
*/
public FeatureSet(final RoleType role, final Pair[] features)
{
this.role = role;
featureStrings = new String[features.length];
selectionWeights = new float[features.length];
for (int i = 0; i < features.length; ++i)
{
featureStrings[i] = features[i].key();
selectionWeights[i] = features[i].floatVal();
}
playoutWeights = null;
tspgWeights = null;
}
/**
* For distinct sets of features and weights for Selection, Playout, and
* TSPG purposes, for a single role.
*
* @param role The Player (P1, P2, etc.) for which the feature set should apply,
* or All if it is applicable to all players in a game.
* @param selectionFeatures Complete list of all features and weights for this feature set,
* for MCTS Selection phase.
* @param playoutFeatures Complete list of all features and weights for this feature set,
* for MCTS Playout phase.
* @param tspgFeatures Complete list of all features and weights for this feature set,
* trained with Tree Search Policy Gradients objective.
*
* @example (featureSet P1 selectionFeatures:{ (pair "rel:to=<{}>:pat=<els=[-{}]>" 1.0) } playoutFeatures:{ (pair "rel:to=<{}>:pat=<els=[-{}]>" 2.0) })
*/
public FeatureSet
(
final RoleType role,
@Opt @Name final Pair[] selectionFeatures,
@Opt @Name final Pair[] playoutFeatures,
@Opt @Name final Pair[] tspgFeatures
)
{
this.role = role;
if (selectionFeatures == null && playoutFeatures == null && tspgFeatures == null)
throw new IllegalArgumentException("At least one of selectionFeatures, playoutFeatures and tspgFeatures must be specified!");
if (selectionFeatures != null && playoutFeatures != null && selectionFeatures.length != playoutFeatures.length)
throw new UnsupportedOperationException("Different feature strings for Selection and Playout currently not supported!");
if (selectionFeatures != null && tspgFeatures != null && selectionFeatures.length != tspgFeatures.length)
throw new UnsupportedOperationException("Different feature strings for Selection and TSPG currently not supported!");
if (playoutFeatures != null && tspgFeatures != null && playoutFeatures.length != tspgFeatures.length)
throw new UnsupportedOperationException("Different feature strings for Playout and TSPG currently not supported!");
assert(selectionFeatures == null || playoutFeatures == null || featureStringsEqual(selectionFeatures, playoutFeatures));
assert(selectionFeatures == null || tspgFeatures == null || featureStringsEqual(selectionFeatures, tspgFeatures));
assert(playoutFeatures == null || tspgFeatures == null || featureStringsEqual(playoutFeatures, tspgFeatures));
// NOTE: we currently just assume that all arrays of pairs
// have exactly the same strings for features
if (selectionFeatures != null)
{
featureStrings = new String[selectionFeatures.length];
for (int i = 0; i < selectionFeatures.length; ++i)
{
featureStrings[i] = selectionFeatures[i].key();
}
}
else if (playoutFeatures != null)
{
featureStrings = new String[playoutFeatures.length];
for (int i = 0; i < playoutFeatures.length; ++i)
{
featureStrings[i] = playoutFeatures[i].key();
}
}
else
{
featureStrings = new String[tspgFeatures.length];
for (int i = 0; i < tspgFeatures.length; ++i)
{
featureStrings[i] = tspgFeatures[i].key();
}
}
if (selectionFeatures != null)
{
selectionWeights = new float[featureStrings.length];
for (int i = 0; i < selectionWeights.length; ++i)
{
selectionWeights[i] = selectionFeatures[i].floatVal();
}
}
else
{
selectionWeights = null;
}
if (playoutFeatures != null)
{
playoutWeights = new float[featureStrings.length];
for (int i = 0; i < playoutWeights.length; ++i)
{
playoutWeights[i] = playoutFeatures[i].floatVal();
}
}
else
{
playoutWeights = null;
}
if (tspgFeatures != null)
{
tspgWeights = new float[featureStrings.length];
for (int i = 0; i < tspgWeights.length; ++i)
{
tspgWeights[i] = tspgFeatures[i].floatVal();
}
}
else
{
tspgWeights = null;
}
}
//-------------------------------------------------------------------------
/**
* @return Role for this feature set
*/
public RoleType role()
{
return role;
}
/**
* @return Array of strings describing features
*/
public String[] featureStrings()
{
return featureStrings;
}
/**
* @return Array of weights for Selection
*/
public float[] selectionWeights()
{
if (selectionWeights != null)
return selectionWeights;
// We'll use playout or TSPG weights as fallback if no selection weights
if (playoutWeights != null)
return playoutWeights;
return tspgWeights;
}
/**
* @return Array of weights for Playout
*/
public float[] playoutWeights()
{
if (playoutWeights != null)
return playoutWeights;
// We'll use selection or TSPG weights as fallback if no selection weights
if (selectionWeights != null)
return selectionWeights;
return tspgWeights;
}
//-------------------------------------------------------------------------
@Override
public String toString()
{
final StringBuilder sb = new StringBuilder();
sb.append(" (featureSet " + role + " ");
if (selectionWeights != null)
{
sb.append("selectionFeatures:{\n");
for (int i = 0; i < featureStrings.length; ++i)
{
sb.append(" (pair ");
sb.append(StringRoutines.quote(featureStrings[i].trim()) + " ");
sb.append(selectionWeights[i]);
sb.append(")\n");
}
sb.append(" }\n");
}
if (playoutWeights != null)
{
sb.append("playoutWeights:{\n");
for (int i = 0; i < featureStrings.length; ++i)
{
sb.append(" (pair ");
sb.append(StringRoutines.quote(featureStrings[i].trim()) + " ");
sb.append(playoutWeights[i]);
sb.append(")\n");
}
sb.append(" }\n");
}
if (tspgWeights != null)
{
sb.append("tspgWeights:{\n");
for (int i = 0; i < featureStrings.length; ++i)
{
sb.append(" (pair ");
sb.append(StringRoutines.quote(featureStrings[i].trim()) + " ");
sb.append(tspgWeights[i]);
sb.append(")\n");
}
sb.append(" }\n");
}
sb.append(" )\n");
return sb.toString();
}
//-------------------------------------------------------------------------
/**
* @param threshold
* @return A string representation of these features, retaining only those for
* which the absolute weights exceed the given threshold.
*/
public String toStringThresholded(final float threshold)
{
final StringBuilder sb = new StringBuilder();
sb.append(" (featureSet " + role + " ");
if (selectionWeights != null)
{
sb.append("selectionFeatures:{\n");
for (int i = 0; i < featureStrings.length; ++i)
{
if (Math.abs(selectionWeights[i]) >= threshold)
{
sb.append(" (pair ");
sb.append(StringRoutines.quote(featureStrings[i].trim()) + " ");
sb.append(selectionWeights[i]);
sb.append(")\n");
}
}
sb.append(" }\n");
}
if (playoutWeights != null)
{
sb.append("playoutWeights:{\n");
for (int i = 0; i < featureStrings.length; ++i)
{
if (Math.abs(playoutWeights[i]) >= threshold)
{
sb.append(" (pair ");
sb.append(StringRoutines.quote(featureStrings[i].trim()) + " ");
sb.append(playoutWeights[i]);
sb.append(")\n");
}
}
sb.append(" }\n");
}
if (tspgWeights != null)
{
sb.append("tspgWeights:{\n");
for (int i = 0; i < featureStrings.length; ++i)
{
if (Math.abs(tspgWeights[i]) >= threshold)
{
sb.append(" (pair ");
sb.append(StringRoutines.quote(featureStrings[i].trim()) + " ");
sb.append(tspgWeights[i]);
sb.append(")\n");
}
}
sb.append(" }\n");
}
sb.append(" )\n");
return sb.toString();
}
//-------------------------------------------------------------------------
/**
* Helper method for asserts, check whether two arrays of Pairs have identical
* feature strings (different weights are allowed).
*
* @param pairsA
* @param pairsB
* @return
*/
private static boolean featureStringsEqual(final Pair[] pairsA, final Pair[] pairsB)
{
if (pairsA.length != pairsB.length)
return false;
for (int i = 0; i < pairsA.length; ++i)
{
if (!pairsA[i].key().equals(pairsB[i].key()))
return false;
}
return true;
}
//-------------------------------------------------------------------------
}
| 10,300 | 26.69086 | 152 | java |
Ludii | Ludii-master/Core/src/metadata/ai/features/Features.java | package metadata.ai.features;
import annotations.Opt;
import metadata.ai.AIItem;
/**
* Describes one or more sets of features (local, geometric patterns) to be used by Biased MCTS agents.
*
* @remarks The basic format of these features is described in: Browne, C., Soemers, D. J. N. J., and Piette, E. (2019).
* ``Strategic features for general games.'' In Proceedings of the 2nd Workshop on Knowledge Extraction from Games (KEG)
* (pp. 70–75).
*
* @author Dennis Soemers
*/
public class Features implements AIItem
{
//-------------------------------------------------------------------------
/** Our array of feature sets */
protected final FeatureSet[] featureSets;
//-------------------------------------------------------------------------
/**
* For just a single feature set shared among players.
* @param featureSet A single feature set.
*
* @example (features (featureSet All {
* (pair "rel:to=<{}>:pat=<refl=true,rots=all,els=[-{}]>" 1.0) }))
*/
public Features(@Opt final FeatureSet featureSet)
{
if (featureSet == null)
this.featureSets = new FeatureSet[]{};
else
this.featureSets = new FeatureSet[]{featureSet};
}
/**
* For multiple feature sets (one per player).
* @param featureSets A sequence of multiple feature sets (typically each
* applying to a different player).
*
* @example (features {
* (featureSet P1 { (pair "rel:to=<{}>:pat=<els=[-{}]>" 1.0) })
* (featureSet P2 { (pair "rel:to=<{}>:pat=<els=[-{}]>" -1.0) })
* })
*/
public Features(@Opt final FeatureSet[] featureSets)
{
if (featureSets == null)
this.featureSets = new FeatureSet[]{};
else
this.featureSets = featureSets;
}
//-------------------------------------------------------------------------
/**
* @return Our array of feature sets
*/
public FeatureSet[] featureSets()
{
return featureSets;
}
//-------------------------------------------------------------------------
@Override
public String toString()
{
final StringBuilder sb = new StringBuilder();
sb.append("(features {\n");
for (final FeatureSet featureSet : featureSets)
{
sb.append(featureSet.toString());
}
sb.append("})\n");
return sb.toString();
}
//-------------------------------------------------------------------------
/**
* @param threshold
* @return A string representation of these features, retaining only those for
* which the absolute weights exceed the given threshold.
*/
public String toStringThresholded(final float threshold)
{
final StringBuilder sb = new StringBuilder();
sb.append("(features {\n");
for (final FeatureSet featureSet : featureSets)
{
sb.append(featureSet.toStringThresholded(threshold));
}
sb.append("})\n");
return sb.toString();
}
//-------------------------------------------------------------------------
}
| 2,881 | 24.504425 | 121 | java |
Ludii | Ludii-master/Core/src/metadata/ai/features/package-info.java | /**
* The {\tt features} package includes information about features used to bias Monte Carlo playouts.
* Each feature describes a geometric pattern of pieces that is relevant to the game, and recommends
* moves to make -- or to not make! -- based on the current game state.
* Biasing random playouts to encourage good moves that intelligent humans would make, and discourage
* moves that they would not make, leads to more realistic playouts and stronger AI play.
*
* For example, a game in which players aim to make line of 5 of their pieces might benefit from a
* feature that encourages the formation of open-ended lines of 4.
* Each feature represents a simple strategy relevant to the game.
*/
package metadata.ai.features;
| 749 | 56.692308 | 102 | java |
Ludii | Ludii-master/Core/src/metadata/ai/features/trees/FeatureTrees.java | package metadata.ai.features.trees;
import annotations.Name;
import annotations.Opt;
import metadata.ai.AIItem;
import metadata.ai.features.trees.classifiers.DecisionTree;
import metadata.ai.features.trees.logits.LogitTree;
/**
* Describes one or more sets of features (local, geometric patterns),
* represented as decision / regression trees.
*
* @author Dennis Soemers
*/
public class FeatureTrees implements AIItem
{
//-------------------------------------------------------------------------
/** Logit trees */
protected LogitTree[] logitTrees;
/** Decision trees for predicting bottom 25% / IQR / top 25% */
protected DecisionTree[] decisionTrees;
//-------------------------------------------------------------------------
/**
* For a variety of different types of trees, each for one or more roles.
*
* @param logitTrees One or more logit trees (each for the All
* role or for a specific player).
* @param decisionTrees One or more decision trees (each for the All
* role or for a specific player).
*
* @example (featureTrees logitTrees:{
* (logitTree P1 (if "rel:to=<{}>:pat=<els=[f{0}]>" then:(leaf { (pair "Intercept" 1.0) }) else:(leaf { (pair "Intercept" -1.0) })))
* })
*/
public FeatureTrees
(
@Name @Opt final LogitTree[] logitTrees,
@Name @Opt final DecisionTree[] decisionTrees
)
{
this.logitTrees = logitTrees;
this.decisionTrees = decisionTrees;
}
//-------------------------------------------------------------------------
/**
* @return Array of logit trees.
*/
public LogitTree[] logitTrees()
{
return logitTrees;
}
/**
* @return Array of decision trees.
*/
public DecisionTree[] decisionTrees()
{
return decisionTrees;
}
//-------------------------------------------------------------------------
@Override
public String toString()
{
final StringBuilder sb = new StringBuilder();
sb.append("(featureTrees \n");
if (logitTrees != null)
{
sb.append("logitTrees:{\n");
for (final LogitTree tree : logitTrees)
{
sb.append(tree.toString() + "\n");
}
sb.append("}\n");
}
if (decisionTrees != null)
{
sb.append("decisionTrees:{\n");
for (final DecisionTree tree : decisionTrees)
{
sb.append(tree.toString() + "\n");
}
sb.append("}\n");
}
sb.append(")");
return sb.toString();
}
//-------------------------------------------------------------------------
}
| 2,448 | 22.32381 | 134 | java |
Ludii | Ludii-master/Core/src/metadata/ai/features/trees/classifiers/BinaryLeaf.java | package metadata.ai.features.trees.classifiers;
import java.util.Set;
/**
* Describes a leaf node in a binary classification tree for features; it contains
* only a predicted probability for "top move".
*
* @author Dennis Soemers
*/
public class BinaryLeaf extends DecisionTreeNode
{
//-------------------------------------------------------------------------
/** Predicted probability of being the/a top move */
protected final float prob;
//-------------------------------------------------------------------------
/**
* Defines the feature (condition) and the predicted probability of being a top move.
* @param prob Predicted probability of being a top move.
*
* @example (binaryLeaf 0.6)
*/
public BinaryLeaf
(
final Float prob
)
{
this.prob = prob.floatValue();
}
//-------------------------------------------------------------------------
@Override
public void collectFeatureStrings(final Set<String> outFeatureStrings)
{
// Do nothing
}
//-------------------------------------------------------------------------
/**
* @return Move probability predicted by this leaf.
*/
public float prob()
{
return prob;
}
//-------------------------------------------------------------------------
@Override
public String toString()
{
return toString(0);
}
@Override
public String toString(final int indent)
{
return "(binaryLeaf " + prob + ")";
}
//-------------------------------------------------------------------------
}
| 1,510 | 20.585714 | 86 | java |
Ludii | Ludii-master/Core/src/metadata/ai/features/trees/classifiers/DecisionTree.java | package metadata.ai.features.trees.classifiers;
import game.types.play.RoleType;
import metadata.ai.AIItem;
/**
* Describes a Decision Tree for features (a decision tree representation of a feature set,
* which outputs class predictions).
*
* @author Dennis Soemers
*/
public class DecisionTree implements AIItem
{
//-------------------------------------------------------------------------
/** Role (should either be All, or a specific Player) */
protected final RoleType role;
/** Root node of the tree */
protected final DecisionTreeNode root;
//-------------------------------------------------------------------------
/**
* For a single decision tree for one role.
*
* @param role The Player (P1, P2, etc.) for which the logit tree should apply,
* or All if it is applicable to all players in a game.
* @param root The root node of the tree.
*
* @example (decisionTree P1 (if "rel:to=<{}>:pat=<els=[f{0}]>" then:(leaf bottom25:0.0 iqr:0.2 top25:0.8) else:(leaf bottom25:0.6 iqr:0.35 top25:0.05)))
*/
public DecisionTree(final RoleType role, final DecisionTreeNode root)
{
this.role = role;
this.root = root;
}
//-------------------------------------------------------------------------
/**
* @return The role that this tree was built for.
*/
public RoleType role()
{
return role;
}
/**
* @return The root node of this tree
*/
public DecisionTreeNode root()
{
return root;
}
//-------------------------------------------------------------------------
@Override
public String toString()
{
final StringBuilder sb = new StringBuilder();
sb.append("(decisionTree " + role + "\n");
sb.append(root.toString(1) + "\n");
sb.append(")");
return sb.toString();
}
//-------------------------------------------------------------------------
}
| 1,841 | 23.56 | 154 | java |
Ludii | Ludii-master/Core/src/metadata/ai/features/trees/classifiers/DecisionTreeNode.java | package metadata.ai.features.trees.classifiers;
import java.util.Set;
import metadata.ai.AIItem;
/**
* Describes a node in a decision tree for features. May either be a condition
* node (internal node), or a node with class predictions (leaf node).
*
* @author Dennis Soemers
*/
public abstract class DecisionTreeNode implements AIItem
{
//-------------------------------------------------------------------------
/**
* Collect strings for all features under this node.
* @param outFeatureStrings Set to put all the feature strings in.
*/
public abstract void collectFeatureStrings(final Set<String> outFeatureStrings);
//-------------------------------------------------------------------------
/**
* @param indent Number of tabs (assuming four spaces) to indent
* @return String representation of this node.
*/
public abstract String toString(final int indent);
//-------------------------------------------------------------------------
}
| 981 | 27.057143 | 81 | java |
Ludii | Ludii-master/Core/src/metadata/ai/features/trees/classifiers/If.java | package metadata.ai.features.trees.classifiers;
import java.util.Set;
import annotations.Name;
import main.StringRoutines;
/**
* Describes a decision node in a decision tree for features; it contains one
* feature (the condition we check), and two branches; one for the case
* where the condition is true, and one for the case where the condition is false.
*
* @author Dennis Soemers
*/
public class If extends DecisionTreeNode
{
//-------------------------------------------------------------------------
/** String description of the feature we want to evaluate as condition */
protected final String feature;
/** Node we navigate to when the condition is satisfied */
protected final DecisionTreeNode thenNode;
/** Node we navigate to when condition is not satisfied */
protected final DecisionTreeNode elseNode;
//-------------------------------------------------------------------------
/**
* Defines the feature (condition), and the two branches.
* @param feature The feature to evaluate (the condition).
* @param then The branch to take if the feature is active.
* @param Else The branch to take if the feature is not active.
*
* @example (if "rel:to=<{}>:pat=<els=[f{0}]>" then:(leaf bottom25:0.0 iqr:0.2 top25:0.8) else:(leaf bottom25:0.6 iqr:0.35 top25:0.05))
*/
public If
(
final String feature,
@Name final DecisionTreeNode then,
@Name final DecisionTreeNode Else
)
{
this.feature = feature;
this.thenNode = then;
this.elseNode = Else;
}
//-------------------------------------------------------------------------
@Override
public void collectFeatureStrings(final Set<String> outFeatureStrings)
{
outFeatureStrings.add(feature);
thenNode.collectFeatureStrings(outFeatureStrings);
elseNode.collectFeatureStrings(outFeatureStrings);
}
//-------------------------------------------------------------------------
/**
* @return String of our feature
*/
public String featureString()
{
return feature;
}
/**
* @return Node we traverse to if condition holds
*/
public DecisionTreeNode thenNode()
{
return thenNode;
}
/**
* @return Node we traverse to if condition does not hold
*/
public DecisionTreeNode elseNode()
{
return elseNode;
}
//-------------------------------------------------------------------------
@Override
public String toString()
{
return toString(0);
}
@Override
public String toString(final int indent)
{
final StringBuilder sb = new StringBuilder();
final String outerIndentStr = StringRoutines.indent(4, indent);
final String innerIndentStr = StringRoutines.indent(4, indent + 1);
sb.append("(if " + StringRoutines.quote(feature) + "\n");
sb.append(innerIndentStr + "then:" + thenNode.toString(indent + 1) + "\n");
sb.append(innerIndentStr + "else:" + elseNode.toString(indent + 1) + "\n");
sb.append(outerIndentStr + ")");
return sb.toString();
}
//-------------------------------------------------------------------------
}
| 3,015 | 25.690265 | 136 | java |
Ludii | Ludii-master/Core/src/metadata/ai/features/trees/classifiers/Leaf.java | package metadata.ai.features.trees.classifiers;
import java.util.Set;
import annotations.Name;
/**
* Describes a leaf node in a binary classification tree for features; it contains
* only a predicted probability for "best move".
*
* @author Dennis Soemers
*/
public class Leaf extends DecisionTreeNode
{
//-------------------------------------------------------------------------
/** Predicted probability of being a bottom-25% move */
protected final float bottom25Prob;
/** Predicted probability of being a move in the Interquartile Range */
protected final float iqrProb;
/** Predicted probability of being a top-25% move */
protected final float top25Prob;
//-------------------------------------------------------------------------
/**
* Defines the feature (condition) and the predicted probabilities for different classes.
* @param bottom25 Predicted probability of being a bottom-25% move.
* @param iqr Predicted probability of being a move in the Interquartile Range.
* @param top25 Predicted probability of being a top-25% move.
*
* @example (leaf bottom25:0.0 iqr:0.2 top25:0.8)
*/
public Leaf
(
@Name final Float bottom25,
@Name final Float iqr,
@Name final Float top25
)
{
bottom25Prob = bottom25.floatValue();
iqrProb = iqr.floatValue();
top25Prob = top25.floatValue();
}
//-------------------------------------------------------------------------
@Override
public void collectFeatureStrings(final Set<String> outFeatureStrings)
{
// Do nothing
}
//-------------------------------------------------------------------------
/**
* @return Predicted probability for the bottom-25% class
*/
public float bottom25Prob()
{
return bottom25Prob;
}
/**
* @return Predicted probability for the IQR class
*/
public float iqrProb()
{
return iqrProb;
}
/**
* @return Predicted probability for the top-25% class
*/
public float top25Prob()
{
return top25Prob;
}
//-------------------------------------------------------------------------
@Override
public String toString()
{
return toString(0);
}
@Override
public String toString(final int indent)
{
return "(leaf bottom25:" + bottom25Prob + " iqr:" + iqrProb + " top25:" + top25Prob + ")";
}
//-------------------------------------------------------------------------
}
| 2,358 | 22.59 | 92 | java |
Ludii | Ludii-master/Core/src/metadata/ai/features/trees/classifiers/package-info.java | /**
* This package contains various types of classifier trees, which produce various
* types of classifications for moves, based on features.
*/
package metadata.ai.features.trees.classifiers;
| 196 | 31.833333 | 81 | java |
Ludii | Ludii-master/Core/src/metadata/ai/features/trees/logits/If.java | package metadata.ai.features.trees.logits;
import java.util.Set;
import annotations.Name;
import main.StringRoutines;
/**
* Describes a decision node in a logit tree for features; it contains one
* feature (the condition we check), and two branches; one for the case
* where the condition is true, and one for the case where the condition is false.
*
* @author Dennis Soemers
*/
public class If extends LogitNode
{
//-------------------------------------------------------------------------
/** String description of the feature we want to evaluate as condition */
protected final String feature;
/** Node we navigate to when the condition is satisfied */
protected final LogitNode thenNode;
/** Node we navigate to when condition is not satisfied */
protected final LogitNode elseNode;
//-------------------------------------------------------------------------
/**
* Defines the feature (condition), and the two branches.
* @param feature The feature to evaluate (the condition).
* @param then The branch to take if the feature is active.
* @param Else The branch to take if the feature is not active.
*
* @example (if "rel:to=<{}>:pat=<els=[f{0}]>" then:(leaf { (pair "Intercept" 1.0) }) else:(leaf { (pair "Intercept" -1.0) }))
*/
public If
(
final String feature,
@Name final LogitNode then,
@Name final LogitNode Else
)
{
this.feature = feature;
this.thenNode = then;
this.elseNode = Else;
}
//-------------------------------------------------------------------------
@Override
public void collectFeatureStrings(final Set<String> outFeatureStrings)
{
outFeatureStrings.add(feature);
thenNode.collectFeatureStrings(outFeatureStrings);
elseNode.collectFeatureStrings(outFeatureStrings);
}
//-------------------------------------------------------------------------
/**
* @return The feature string
*/
public String featureString()
{
return feature;
}
/**
* @return The then node
*/
public LogitNode thenNode()
{
return thenNode;
}
/**
* @return The else node
*/
public LogitNode elseNode()
{
return elseNode;
}
//-------------------------------------------------------------------------
@Override
public String toString()
{
return toString(0);
}
@Override
public String toString(final int indent)
{
final StringBuilder sb = new StringBuilder();
final String outerIndentStr = StringRoutines.indent(4, indent);
final String innerIndentStr = StringRoutines.indent(4, indent + 1);
sb.append("(if " + StringRoutines.quote(feature) + "\n");
sb.append(innerIndentStr + "then:" + thenNode.toString(indent + 1) + "\n");
sb.append(innerIndentStr + "else:" + elseNode.toString(indent + 1) + "\n");
sb.append(outerIndentStr + ")");
return sb.toString();
}
//-------------------------------------------------------------------------
}
| 2,888 | 24.566372 | 127 | java |
Ludii | Ludii-master/Core/src/metadata/ai/features/trees/logits/Leaf.java | package metadata.ai.features.trees.logits;
import java.util.Set;
import main.StringRoutines;
import metadata.ai.misc.Pair;
/**
* Describes a leaf node in a logit tree for features; it contains an array
* of features and weights, describing a linear function to use to compute the
* logit in this node. An intercept feature should collect all the weights
* inferred from features evaluated in decision nodes leading up to this leaf.
*
* @author Dennis Soemers
*/
public class Leaf extends LogitNode
{
//-------------------------------------------------------------------------
/** Remaining features to evaluate in our model */
protected final String[] featureStrings;
/** Array of weights for our remaining features */
protected final float[] weights;
//-------------------------------------------------------------------------
/**
* Defines the remaining features (used in linear model) and their weights.
* @param features List of remaining features to evaluate and their weights.
*
* @example (leaf { (pair "Intercept" 1.0) })
*/
public Leaf(final Pair[] features)
{
featureStrings = new String[features.length];
weights = new float[features.length];
for (int i = 0; i < features.length; ++i)
{
featureStrings[i] = features[i].key();
weights[i] = features[i].floatVal();
}
}
//-------------------------------------------------------------------------
@Override
public void collectFeatureStrings(final Set<String> outFeatureStrings)
{
for (final String s : featureStrings)
{
outFeatureStrings.add(s);
}
}
//-------------------------------------------------------------------------
/**
* @return Array of strings of features used in model
*/
public String[] featureStrings()
{
return featureStrings;
}
/**
* @return Array of weights used in model
*/
public float[] weights()
{
return weights;
}
//-------------------------------------------------------------------------
@Override
public String toString()
{
return toString(0);
}
@Override
public String toString(final int indent)
{
final StringBuilder sb = new StringBuilder();
sb.append("(leaf { ");
for (int i = 0; i < featureStrings.length; ++i)
{
sb.append("(pair " + StringRoutines.quote(featureStrings[i]) + " " + weights[i] + ") ");
}
sb.append( "})");
return sb.toString();
}
//-------------------------------------------------------------------------
}
| 2,463 | 23.156863 | 91 | java |
Ludii | Ludii-master/Core/src/metadata/ai/features/trees/logits/LogitNode.java | package metadata.ai.features.trees.logits;
import java.util.Set;
import metadata.ai.AIItem;
/**
* Describes a node in a logit tree for features. May either be a condition
* node (internal node), or a node with a linear model (a leaf node).
*
* @author Dennis Soemers
*/
public abstract class LogitNode implements AIItem
{
//-------------------------------------------------------------------------
/**
* Collect strings for all features under this node.
* @param outFeatureStrings Set to put all the feature strings in.
*/
public abstract void collectFeatureStrings(final Set<String> outFeatureStrings);
//-------------------------------------------------------------------------
/**
* @param indent Number of tabs (assuming four spaces) to indent
* @return String representation of this node.
*/
public abstract String toString(final int indent);
//-------------------------------------------------------------------------
}
| 965 | 26.6 | 81 | java |
Ludii | Ludii-master/Core/src/metadata/ai/features/trees/logits/LogitTree.java | package metadata.ai.features.trees.logits;
import game.types.play.RoleType;
import metadata.ai.AIItem;
/**
* Describes a Logit Tree for features (a regression tree representation of a feature set,
* which outputs logits).
*
* @author Dennis Soemers
*/
public class LogitTree implements AIItem
{
//-------------------------------------------------------------------------
/** Role (should either be All, or a specific Player) */
protected final RoleType role;
/** Root node of the tree */
protected final LogitNode root;
//-------------------------------------------------------------------------
/**
* For a single logit tree for one role.
*
* @param role The Player (P1, P2, etc.) for which the logit tree should apply,
* or All if it is applicable to all players in a game.
* @param root The root node of the tree.
*
* @example (logitTree P1 (if "rel:to=<{}>:pat=<els=[f{0}]>" then:(leaf { (pair "Intercept" 1.0) }) else:(leaf { (pair "Intercept" -1.0) })))
*/
public LogitTree(final RoleType role, final LogitNode root)
{
this.role = role;
this.root = root;
}
//-------------------------------------------------------------------------
/**
* @return Root node of this logit tree
*/
public LogitNode root()
{
return root;
}
/**
* @return The role that this tree belongs to
*/
public RoleType role()
{
return role;
}
//-------------------------------------------------------------------------
@Override
public String toString()
{
final StringBuilder sb = new StringBuilder();
sb.append("(logitTree " + role + "\n");
sb.append(root.toString(1) + "\n");
sb.append(")");
return sb.toString();
}
//-------------------------------------------------------------------------
}
| 1,777 | 22.706667 | 142 | java |
Ludii | Ludii-master/Core/src/metadata/ai/features/trees/logits/package-info.java | /**
* This package contains logit regression trees, which produce
* logit predictions for moves, based on features.
*/
package metadata.ai.features.trees.logits;
| 166 | 26.833333 | 63 | java |
Ludii | Ludii-master/Core/src/metadata/ai/heuristics/HeuristicUtil.java | package metadata.ai.heuristics;
import annotations.Hide;
import metadata.ai.heuristics.terms.HeuristicTerm;
/**
* Utility functions for heuristic manipulation.
*
* @author Matthew.Stephenson
*/
@Hide
public class HeuristicUtil
{
//-------------------------------------------------------------------------
/**
* @param heuristic
* @return Normalises all weights on heuristic between -1 and 1.
*/
public static Heuristics normaliseHeuristic(final Heuristics heuristic)
{
double maxWeight = 0.0;
for (final HeuristicTerm term : heuristic.heuristicTerms())
maxWeight = Math.max(maxWeight, term.maxAbsWeight());
return new Heuristics(multiplyHeuristicTerms(heuristic.heuristicTerms(), 1.0/maxWeight));
}
//-------------------------------------------------------------------------
/**
* @param heuristicTerms
* @param multiplier
* @return Multiplies the weights for an array of heuristicTerms by the specified multiplier.
*/
public static HeuristicTerm[] multiplyHeuristicTerms(final HeuristicTerm[] heuristicTerms, final double multiplier)
{
final HeuristicTerm[] heuristicTermsMultiplied = new HeuristicTerm[heuristicTerms.length];
for (int i = 0; i < heuristicTermsMultiplied.length; i++)
{
final HeuristicTerm halvedHeuristicTerm = heuristicTerms[i].copy();
halvedHeuristicTerm.setWeight((float) (heuristicTerms[i].weight()*multiplier));
heuristicTermsMultiplied[i] = halvedHeuristicTerm;
}
return heuristicTermsMultiplied;
}
//-------------------------------------------------------------------------
/**
* @param weight
* @return Converts a (normalised) weight to a string by binning it.
*/
public static String convertWeightToString(final double weight)
{
if (weight < 0.2)
return "very low importance";
else if (weight < 0.4)
return "low importance";
else if (weight < 0.6)
return "moderate importance";
else if (weight < 0.8)
return "high importance";
else
return "very high importance";
}
//-------------------------------------------------------------------------
}
| 2,087 | 28.408451 | 116 | java |
Ludii | Ludii-master/Core/src/metadata/ai/heuristics/Heuristics.java | package metadata.ai.heuristics;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import annotations.Opt;
import game.Game;
import main.FileHandling;
import main.StringRoutines;
import main.collections.FVector;
import main.grammar.Report;
import metadata.ai.AIItem;
import metadata.ai.heuristics.terms.HeuristicTerm;
import other.context.Context;
/**
* Defines a collection of heuristics, which can be used by Alpha-Beta agent in
* Ludii for their heuristics state evaluations.
*
* @author Dennis Soemers
*/
public class Heuristics implements AIItem
{
//-------------------------------------------------------------------------
/** Our array of heuristic terms */
protected final HeuristicTerm[] heuristicTerms;
//-------------------------------------------------------------------------
/**
* For a single heuristic term.
*
* @param term A single heuristic term.
*
* @example (heuristics (score))
*/
public Heuristics(@Opt final HeuristicTerm term)
{
if (term == null)
heuristicTerms = new HeuristicTerm[]{};
else
heuristicTerms = new HeuristicTerm[]{term};
}
/**
* For a collection of multiple heuristic terms.
*
* @param terms A sequence of multiple heuristic terms, which will all
* be linearly combined based on their weights.
*
* @example (heuristics { (material) (mobilitySimple weight:0.01) })
*/
public Heuristics(@Opt final HeuristicTerm[] terms)
{
if (terms == null)
heuristicTerms = new HeuristicTerm[]{};
else
heuristicTerms = terms;
}
/**
* Copy constructor (written as static method so it's not picked up by grammar)
* @param other
* @return Copy of heuristics
*/
public static Heuristics copy(final Heuristics other)
{
if (other == null)
return null;
return new Heuristics(other);
}
/**
* Copy constructor (private, not visible to grammar)
* @param other
*/
private Heuristics(final Heuristics other)
{
heuristicTerms = new HeuristicTerm[other.heuristicTerms.length];
for (int i = 0; i < heuristicTerms.length; ++i)
{
heuristicTerms[i] = other.heuristicTerms[i].copy();
}
}
//-------------------------------------------------------------------------
/**
* Computes heuristic value estimate for the given state
* from the perspective of the given player.
*
* @param context
* @param player
* @param absWeightThreshold We skip terms with an absolute weight below this value
* (negative for no skipping)
* @return Heuristic value estimate
*/
public float computeValue(final Context context, final int player, final float absWeightThreshold)
{
float value = 0.f;
for (final HeuristicTerm term : heuristicTerms)
{
final float weight = term.weight();
final float absWeight = Math.abs(weight);
if (absWeight >= absWeightThreshold)
{
float termOutput = term.computeValue(context, player, absWeightThreshold / absWeight);
if (term.transformation() != null)
termOutput = term.transformation().transform(context, termOutput);
value += weight * termOutput;
}
}
return value;
}
/**
* Initialises all terms for given game
* @param game
*/
public void init(final Game game)
{
for (final HeuristicTerm term : heuristicTerms)
{
term.init(game);
}
}
//-------------------------------------------------------------------------
/**
* @param context
* @param player
* @return Heuristics feature vector in given state, from perspective of given player
*/
public FVector computeStateFeatureVector(final Context context, final int player)
{
final Game game = context.game();
final int numPlayers = game.players().count();
FVector featureVector = new FVector(0);
for (final HeuristicTerm term : heuristicTerms)
{
final FVector vec = term.computeStateFeatureVector(context, player);
for (int p = 1; p <= numPlayers; ++p)
{
if (p != player)
{
final FVector oppVector = term.computeStateFeatureVector(context, p);
vec.subtract(oppVector);
}
}
for (int j = 0; j < vec.dim(); ++j)
{
if (term.transformation() != null)
vec.set(j, term.transformation().transform(context, vec.get(j)));
}
featureVector = FVector.concat(featureVector, vec);
}
return featureVector;
}
/**
* @return Vector of parameters (weights including "internal" weights of nested heuristics)
*/
public FVector paramsVector()
{
// TODO our math here is only going to be correct for now because
// we don't use non-linear transformations with any heuristics
// that have internal pieceWeights vectors...
FVector paramsVector = new FVector(0);
for (final HeuristicTerm term : heuristicTerms)
{
final float weight = term.weight();
final FVector vec = term.paramsVector();
if (vec == null)
{
paramsVector = paramsVector.append(weight);
}
else
{
final FVector weightedVec = new FVector(vec);
weightedVec.mult(weight);
paramsVector = FVector.concat(paramsVector, weightedVec);
}
}
return paramsVector;
}
/**
* Updates weights in heuristics based on given vector of params
* @param game
* @param newParams
* @param startIdx Index at which to start reading params
*/
public void updateParams(final Game game, final FVector newParams, final int startIdx)
{
int currentIdx = startIdx;
for (final HeuristicTerm term : heuristicTerms)
{
currentIdx = term.updateParams(game, newParams, currentIdx);
}
}
//-------------------------------------------------------------------------
/**
* @return Our array of Heuristic Terms
*/
public HeuristicTerm[] heuristicTerms()
{
return heuristicTerms;
}
/**
* Writes these heuristics to a text file
* @param game
* @param filepath
*/
public void toFile(final Game game, final String filepath)
{
try (final PrintWriter writer = new PrintWriter(filepath, "UTF-8"))
{
writer.println("(heuristics { \n");
for (final HeuristicTerm term : heuristicTerms)
{
writer.println(" " + term.toString());
}
writer.println("} )");
}
catch (final FileNotFoundException | UnsupportedEncodingException e)
{
e.printStackTrace();
}
}
//-------------------------------------------------------------------------
@Override
public String toString()
{
final StringBuilder sb = new StringBuilder();
sb.append("(heuristics {\n");
for (final HeuristicTerm term : heuristicTerms)
sb.append(" " + term.toString() + "\n");
sb.append("})\n");
return sb.toString();
}
//-------------------------------------------------------------------------
/**
* @param thresholdWeight
* @return A string representation of these heuristics, with any terms
* for which the absolute weight does not exceed the given threshold removed.
*/
public String toStringThresholded(final float thresholdWeight)
{
final StringBuilder sb = new StringBuilder();
sb.append("(heuristics {\n");
for (final HeuristicTerm term : heuristicTerms)
{
final String termStr = term.toStringThresholded(thresholdWeight);
if (termStr != null)
sb.append(" " + termStr + "\n");
}
sb.append("})\n");
return sb.toString();
}
@Override
public boolean equals(final Object o)
{
return o.toString().equals(toString());
}
@Override
public int hashCode()
{
return toString().hashCode();
}
//-------------------------------------------------------------------------
/**
* Builds heuristics as described by a given array of lines.
* @param lines
* @return Built heuristics
*/
public static Heuristics fromLines(final String[] lines)
{
if (!lines[0].startsWith("heuristics="))
{
System.err.println("Error: Heuristics::fromLines() expects first line to start with heuristics=");
}
else
{
final String str = lines[0].substring("heuristics=".length());
if (str.startsWith("value-func-dir-"))
{
final File valueFuncDir = new File(str.substring("value-func-dir-".length()));
if (valueFuncDir.exists() && valueFuncDir.isDirectory())
{
final File[] files = valueFuncDir.listFiles();
int latestCheckpoint = -1;
File latestCheckpointFile = null;
for (final File file : files)
{
final String filename = file.getName();
if (filename.startsWith("ValueFunction_") && filename.endsWith(".txt"))
{
final int checkpoint =
Integer.parseInt
(
filename.split
(
java.util.regex.Pattern.quote("_")
)[1].replaceAll(java.util.regex.Pattern.quote(".txt"), "")
);
if (checkpoint > latestCheckpoint)
{
latestCheckpoint = checkpoint;
latestCheckpointFile = file;
}
}
}
if (latestCheckpointFile != null)
{
try
{
final String contents = FileHandling.loadTextContentsFromFile(latestCheckpointFile.getAbsolutePath());
// Compile heuristic
final Heuristics heuristic =
(Heuristics)compiler.Compiler.compileObject
(
StringRoutines.join("\n", contents),
"metadata.ai.heuristics.Heuristics",
new Report()
);
return heuristic;
}
catch (final IOException e)
{
e.printStackTrace();
}
}
}
}
else if (new File(str).exists())
{
try
{
final String contents = FileHandling.loadTextContentsFromFile(str);
// Compile heuristic
final Heuristics heuristic =
(Heuristics)compiler.Compiler.compileObject
(
StringRoutines.join("\n", contents),
"metadata.ai.heuristics.Heuristics",
new Report()
);
return heuristic;
}
catch (final IOException e)
{
e.printStackTrace();
}
}
else
{
System.err.println("Heuristics::fromLines() does not know how to interpret: " + str);
}
}
return null;
}
//-------------------------------------------------------------------------
}
| 10,170 | 23.567633 | 109 | java |
Ludii | Ludii-master/Core/src/metadata/ai/heuristics/package-info.java | /**
* The {\tt heuristics} package includes information about which heuristics are relevant to the current game,
* and their optimal settings and weights.
* Heuristics are simple rules of thumb for estimating the positional strength of players in a given game state.
* Each heuristic focusses on a particular aspect of the game, e.g. material piece count, piece mobility, etc.
*/
package metadata.ai.heuristics;
| 420 | 51.625 | 113 | java |
Ludii | Ludii-master/Core/src/metadata/ai/heuristics/terms/CentreProximity.java | package metadata.ai.heuristics.terms;
import java.util.Arrays;
import java.util.List;
import annotations.Name;
import annotations.Opt;
import game.Game;
import game.equipment.component.Component;
import main.Constants;
import main.StringRoutines;
import main.collections.FVector;
import metadata.ai.heuristics.HeuristicUtil;
import metadata.ai.heuristics.transformations.HeuristicTransformation;
import metadata.ai.misc.Pair;
import other.context.Context;
import other.location.Location;
import other.state.owned.Owned;
/**
* Defines a heuristic term based on the proximity of pieces to the centre of
* a game's board.
*
* @author Dennis Soemers
*/
public class CentreProximity extends HeuristicTerm
{
//-------------------------------------------------------------------------
/** Array of names specified for piece types */
private String[] pieceWeightNames;
/**
* Array of weights as specified in metadata. Will be used to initialise
* a weight vector for a specific game when init() is called.
*/
private float[] gameAgnosticWeightsArray;
/** Vector with weights for every piece type */
private FVector pieceWeights = null;
/** The maximum distance that exists in our Centres distance table */
private int maxDistance = -1;
//-------------------------------------------------------------------------
/**
* Constructor
*
* @param transformation An optional transformation to be applied to any
* raw heuristic score outputs.
* @param weight The weight for this term in a linear combination of multiple terms.
* If not specified, a default weight of $1.0$ is used.
* @param pieceWeights Weights for different piece types. If no piece weights are
* specified at all, all piece types are given an equal weight of $1.0$. If piece
* weights are only specified for some piece types, all other piece types get a
* weight of $0$.
*
* @example (centreProximity pieceWeights:{ (pair "Queen" 1.0) (pair "King" -1.0) })
*/
public CentreProximity
(
@Name @Opt final HeuristicTransformation transformation,
@Name @Opt final Float weight,
@Name @Opt final Pair[] pieceWeights
)
{
super(transformation, weight);
if (pieceWeights == null)
{
// We want a weight of 1.0 for everything
pieceWeightNames = new String[]{""};
gameAgnosticWeightsArray = new float[]{1.f};
}
else
{
pieceWeightNames = new String[pieceWeights.length];
gameAgnosticWeightsArray = new float[pieceWeights.length];
for (int i = 0; i < pieceWeights.length; ++i)
{
pieceWeightNames[i] = pieceWeights[i].key();
gameAgnosticWeightsArray[i] = pieceWeights[i].floatVal();
}
}
}
@Override
public HeuristicTerm copy()
{
return new CentreProximity(this);
}
/**
* Copy constructor (private, so not visible to grammar)
* @param other
*/
private CentreProximity(final CentreProximity other)
{
super(other.transformation, Float.valueOf(other.weight));
pieceWeightNames = Arrays.copyOf(other.pieceWeightNames, other.pieceWeightNames.length);
gameAgnosticWeightsArray = Arrays.copyOf(other.gameAgnosticWeightsArray, other.gameAgnosticWeightsArray.length);
}
//-------------------------------------------------------------------------
@Override
public float computeValue(final Context context, final int player, final float absWeightThreshold)
{
if (maxDistance == 0)
return 0.f;
final int[] distances = context.game().distancesToCentre();
final Owned owned = context.state().owned();
final List<? extends Location>[] pieces = owned.positions(player);
float value = 0.f;
for (int i = 0; i < pieces.length; ++i)
{
if (pieces[i].isEmpty())
continue;
final float pieceWeight = pieceWeights.get(owned.reverseMap(player, i));
if (Math.abs(pieceWeight) >= absWeightThreshold)
{
for (final Location position : pieces[i])
{
final int site = position.site();
if (site >= distances.length) // Different container, skip it
continue;
final int dist = distances[site];
final float proximity = 1.f - ((float) dist / maxDistance);
value += pieceWeight * proximity;
}
}
}
return value;
}
@Override
public FVector computeStateFeatureVector(final Context context, final int player)
{
final FVector featureVector = new FVector(pieceWeights.dim());
if (maxDistance != 0.f)
{
final int[] distances = context.game().distancesToCentre();
final Owned owned = context.state().owned();
final List<? extends Location>[] pieces = owned.positions(player);
for (int i = 0; i < pieces.length; ++i)
{
if (pieces[i].isEmpty())
continue;
final int compIdx = owned.reverseMap(player, i);
for (final Location position : pieces[i])
{
final int site = position.site();
if (site >= distances.length) // Different container, skip it
continue;
final int dist = distances[site];
final float proximity = 1.f - ((float) dist / maxDistance);
featureVector.addToEntry(compIdx, proximity);
}
}
}
return featureVector;
}
@Override
public FVector paramsVector()
{
return pieceWeights;
}
@Override
public void init(final Game game)
{
// Compute vector of piece weights
pieceWeights = HeuristicTerm.pieceWeightsVector(game, pieceWeightNames, gameAgnosticWeightsArray);
// Precompute maximum distance for this game
computeMaxDist(game);
}
@Override
public int updateParams(final Game game, final FVector newParams, final int startIdx)
{
final int retVal = super.updateParams(game, newParams, startIdx);
// Need to update the array of weights we were passed in constructor
// in case we decide to write ourselves to a file
final Object[] returnArrays = updateGameAgnosticWeights(game, pieceWeights, pieceWeightNames, gameAgnosticWeightsArray);
pieceWeightNames = (String[]) returnArrays[0];
gameAgnosticWeightsArray = (float[]) returnArrays[1];
return retVal;
}
//-------------------------------------------------------------------------
/**
* Helper method for constructors
* @param game
*/
private final void computeMaxDist(final Game game)
{
final int[] distances = game.distancesToCentre();
if (distances != null)
{
int max = 0;
for (int i = 0; i < distances.length; ++i)
{
if (distances[i] > max)
max = distances[i];
}
maxDistance = max;
}
else
{
maxDistance = 0;
}
}
//-------------------------------------------------------------------------
/**
* @param game
* @return True if heuristic of this type could be applicable to given game
*/
public static boolean isApplicableToGame(final Game game)
{
final Component[] components = game.equipment().components();
if (components.length <= 1)
return false;
if (game.distancesToCentre() == null)
return false;
return true;
}
/**
* @param game
* @return True if the heuristic of this type is sensible for the given game
* (must be applicable, but even some applicable heuristics may be considered
* to be not sensible).
*/
public static boolean isSensibleForGame(final Game game)
{
return isApplicableToGame(game);
}
@Override
public boolean isApplicable(final Game game)
{
return isApplicableToGame(game);
}
//-------------------------------------------------------------------------
@Override
public String toString()
{
final StringBuilder sb = new StringBuilder();
sb.append("(centreProximity");
if (transformation != null)
sb.append(" transformation:" + transformation.toString());
if (weight != 1.f)
sb.append(" weight:" + weight);
if (pieceWeightNames.length > 1 || (pieceWeightNames.length == 1 && pieceWeightNames[0].length() > 0))
{
sb.append(" pieceWeights:{\n");
for (int i = 0; i < pieceWeightNames.length; ++i)
{
if (gameAgnosticWeightsArray[i] != 0.f)
sb.append(" (pair " + StringRoutines.quote(pieceWeightNames[i]) + " " + gameAgnosticWeightsArray[i] + ")\n");
}
sb.append(" }");
}
sb.append(")");
return sb.toString();
}
//-------------------------------------------------------------------------
@Override
public String toStringThresholded(final float threshold)
{
boolean shouldPrint = false;
boolean haveRelevantPieces = false;
final StringBuilder pieceWeightsSb = new StringBuilder();
if (pieceWeightNames.length > 1 || (pieceWeightNames.length == 1 && pieceWeightNames[0].length() > 0))
{
for (int i = 0; i < pieceWeightNames.length; ++i)
{
if (Math.abs(weight * gameAgnosticWeightsArray[i]) >= threshold)
{
pieceWeightsSb.append(" (pair " + StringRoutines.quote(pieceWeightNames[i]) + " " + gameAgnosticWeightsArray[i] + ")\n");
haveRelevantPieces = true;
shouldPrint = true;
}
}
}
else if (Math.abs(weight) >= threshold)
{
// No manually specified weights, so they will all default to 1.0,
// and we have a large enough term-wide weight
shouldPrint = true;
}
if (shouldPrint)
{
final StringBuilder sb = new StringBuilder();
sb.append("(centreProximity");
if (transformation != null)
sb.append(" transformation:" + transformation.toString());
if (weight != 1.f)
sb.append(" weight:" + weight);
if (haveRelevantPieces)
{
sb.append(" pieceWeights:{\n");
sb.append(pieceWeightsSb);
sb.append(" }");
}
sb.append(")");
return sb.toString();
}
else
{
return null;
}
}
//-------------------------------------------------------------------------
@Override
public void merge(final HeuristicTerm term)
{
final CentreProximity castTerm = (CentreProximity) term;
for (int i = 0; i < pieceWeightNames.length; i++)
for (int j = 0; j < castTerm.pieceWeightNames.length; j++)
if (pieceWeightNames[i].equals(castTerm.pieceWeightNames[j]))
gameAgnosticWeightsArray[i] = gameAgnosticWeightsArray[i] + castTerm.gameAgnosticWeightsArray[j] * (castTerm.weight()/weight());
}
@Override
public void simplify()
{
if (Math.abs(weight() - 1.f) > Constants.EPSILON)
{
for (int i = 0; i < gameAgnosticWeightsArray.length; i++)
gameAgnosticWeightsArray[i] *= weight();
setWeight(1.f);
}
}
@Override
public float maxAbsWeight()
{
float maxWeight = Math.abs(weight());
for (final float f : gameAgnosticWeightsArray)
maxWeight = Math.max(maxWeight, Math.abs(f));
return maxWeight;
}
//-------------------------------------------------------------------------
@Override
public String description()
{
return "Sum of owned pieces, weighted by proximity to centre.";
}
@Override
public String toEnglishString(final Context context, final int playerIndex)
{
final StringBuilder sb = new StringBuilder();
if (pieceWeightNames.length > 1 || (pieceWeightNames.length == 1 && pieceWeightNames[0].length() > 0))
{
for (int i = 0; i < pieceWeightNames.length; ++i)
{
if (gameAgnosticWeightsArray[i] != 0.f)
{
final String pieceTrailingNumbers = StringRoutines.getTrailingNumbers(pieceWeightNames[i]);
if (pieceTrailingNumbers.length() == 0 || playerIndex < 0 || Integer.valueOf(pieceTrailingNumbers).intValue() == playerIndex)
{
if (weight > 0)
sb.append("You should try to move your " + StringRoutines.removeTrailingNumbers(pieceWeightNames[i]) + "(s) towards the center of the board");
else
sb.append("You should try to move your " + StringRoutines.removeTrailingNumbers(pieceWeightNames[i]) + "(s) away from the center of the board");
sb.append(" (" + HeuristicUtil.convertWeightToString(gameAgnosticWeightsArray[i]) + ")\n");
}
}
}
}
else
{
if (weight > 0)
sb.append("You should try to move your piece(s) towards the center of the board");
else
sb.append("You should try to move your piece(s) away from the center of the board");
sb.append(" (" + HeuristicUtil.convertWeightToString(weight) + ")\n");
}
return sb.toString();
}
//-------------------------------------------------------------------------
@Override
public float[] gameAgnosticWeightsArray() {
return gameAgnosticWeightsArray;
}
@Override
public FVector pieceWeights() {
return pieceWeights;
}
}
| 12,338 | 26.238411 | 151 | java |
Ludii | Ludii-master/Core/src/metadata/ai/heuristics/terms/ComponentValues.java | package metadata.ai.heuristics.terms;
import java.util.Arrays;
import java.util.List;
import annotations.Name;
import annotations.Opt;
import game.Game;
import game.equipment.component.Component;
import game.equipment.container.Container;
import game.types.board.SiteType;
import game.types.state.GameType;
import main.Constants;
import main.StringRoutines;
import main.collections.FVector;
import metadata.ai.heuristics.HeuristicUtil;
import metadata.ai.heuristics.transformations.HeuristicTransformation;
import metadata.ai.misc.Pair;
import other.context.Context;
import other.location.Location;
import other.state.container.ContainerState;
import other.state.owned.Owned;
/**
* Defines a heuristic term based on the values of sites that contain
* components owned by a player.
*
* @author Dennis Soemers
*/
public class ComponentValues extends HeuristicTerm
{
//-------------------------------------------------------------------------
/** Array of names specified for piece types */
private String[] pieceWeightNames;
/**
* Array of weights as specified in metadata. Will be used to initialise
* a weight vector for a specific game when init() is called.
*/
private float[] gameAgnosticWeightsArray;
/** If true, only count pieces on the main board (i.e., container 0) */
private final boolean boardOnly;
/** Vector with weights for every piece type */
private FVector pieceWeights = null;
/** Indices of hand containers per player */
private int[] handIndices = null;
/** Does our current game have more than 1 container? */
private boolean gameHasMultipleContainers = false;
//-------------------------------------------------------------------------
/**
* Constructor
*
* @param transformation An optional transformation to be applied to any
* raw heuristic score outputs.
* @param weight The weight for this term in a linear combination of multiple terms.
* If not specified, a default weight of $1.0$ is used.
* @param pieceWeights Weights for different piece types. If no piece weights are
* specified at all, all piece types are given an equal weight of $1.0$. If piece
* weights are only specified for some piece types, all other piece types get a
* weight of $0$. These weights are multiplied with the values on sites where these
* pieces are present.
* @param boardOnly If true, only pieces that are on the game's main board are counted,
* and pieces that are, for instance, in players' hands are excluded. False by default.
*
* @example (componentValues boardOnly:True)
*/
public ComponentValues
(
@Name @Opt final HeuristicTransformation transformation,
@Name @Opt final Float weight,
@Name @Opt final Pair[] pieceWeights,
@Name @Opt final Boolean boardOnly
)
{
super(transformation, weight);
if (pieceWeights == null)
{
// We want a weight of 1.0 for everything
pieceWeightNames = new String[]{""};
gameAgnosticWeightsArray = new float[]{1.f};
}
else
{
pieceWeightNames = new String[pieceWeights.length];
gameAgnosticWeightsArray = new float[pieceWeights.length];
for (int i = 0; i < pieceWeights.length; ++i)
{
pieceWeightNames[i] = pieceWeights[i].key();
gameAgnosticWeightsArray[i] = pieceWeights[i].floatVal();
}
}
this.boardOnly = (boardOnly == null) ? false : boardOnly.booleanValue();
}
@Override
public HeuristicTerm copy()
{
return new ComponentValues(this);
}
/**
* Copy constructor (private, so not visible to grammar)
* @param other
*/
private ComponentValues(final ComponentValues other)
{
super(other.transformation, Float.valueOf(other.weight));
pieceWeightNames = Arrays.copyOf(other.pieceWeightNames, other.pieceWeightNames.length);
gameAgnosticWeightsArray = Arrays.copyOf(other.gameAgnosticWeightsArray, other.gameAgnosticWeightsArray.length);
boardOnly = other.boardOnly;
}
//-------------------------------------------------------------------------
@Override
public float computeValue(final Context context, final int player, final float absWeightThreshold)
{
final Owned owned = context.state().owned();
final List<? extends Location>[] pieces = owned.positions(player);
float value = 0.f;
if (!boardOnly || !gameHasMultipleContainers)
{
for (int i = 0; i < pieces.length; ++i)
{
if (pieces[i].isEmpty())
continue;
final float pieceWeight = pieceWeights.get(owned.reverseMap(player, i));
if (Math.abs(pieceWeight) >= absWeightThreshold)
{
for (final Location loc : pieces[i])
{
final int cid = loc.siteType() != SiteType.Cell ? 0 : context.containerId()[loc.site()];
value += pieceWeight * context.containerState(cid).value(loc.site(), loc.level(), loc.siteType());
}
}
}
}
else
{
for (int i = 0; i < pieces.length; ++i)
{
if (pieces[i].isEmpty())
continue;
final float pieceWeight = pieceWeights.get(owned.reverseMap(player, i));
if (Math.abs(pieceWeight) >= absWeightThreshold)
{
for (final Location loc : pieces[i])
{
if (loc.siteType() != SiteType.Cell || context.containerId()[loc.site()] == 0)
value += pieceWeight * context.containerState(0).value(loc.site(), loc.level(), loc.siteType());
}
}
}
}
if (!boardOnly && handIndices != null)
{
final List<? extends Location>[] neutralPieces = owned.positions(0);
for (int i = 0; i < neutralPieces.length; ++i)
{
if (neutralPieces[i].isEmpty())
continue;
final float pieceWeight = pieceWeights.get(owned.reverseMap(0, i));
if (Math.abs(pieceWeight) >= absWeightThreshold)
{
for (final Location pos : neutralPieces[i])
{
final int site = pos.site();
final int cid = handIndices[player];
if (pos.siteType() == SiteType.Cell && context.containerId()[site] == cid)
{
final ContainerState cs = context.containerState(cid);
value += pieceWeight * cs.countCell(site) * cs.valueCell(site);
}
}
}
}
}
return value;
}
@Override
public FVector computeStateFeatureVector(final Context context, final int player)
{
final FVector featureVector = new FVector(pieceWeights.dim());
final Owned owned = context.state().owned();
final List<? extends Location>[] pieces = owned.positions(player);
if (!boardOnly || !gameHasMultipleContainers)
{
for (int i = 0; i < pieces.length; ++i)
{
if (pieces[i].isEmpty())
continue;
final int compIdx = owned.reverseMap(player, i);
for (final Location loc : pieces[i])
{
final int cid = loc.siteType() != SiteType.Cell ? 0 : context.containerId()[loc.site()];
featureVector.addToEntry(compIdx, context.containerState(cid).value(loc.site(), loc.level(), loc.siteType()));
}
}
if (handIndices != null)
{
final List<? extends Location>[] neutralPieces = owned.positions(0);
for (int i = 0; i < neutralPieces.length; ++i)
{
if (neutralPieces[i].isEmpty())
continue;
final int compIdx = owned.reverseMap(player, i);
for (final Location pos : neutralPieces[i])
{
final int site = pos.site();
final int cid = handIndices[player];
if (pos.siteType() == SiteType.Cell && context.containerId()[site] == cid)
{
final ContainerState cs = context.containerState(cid);
featureVector.addToEntry(compIdx, cs.countCell(site) * cs.valueCell(site));
}
}
}
}
}
else
{
for (int i = 0; i < pieces.length; ++i)
{
if (pieces[i].isEmpty())
continue;
final int compIdx = owned.reverseMap(player, i);
for (final Location loc : pieces[i])
{
if (loc.siteType() != SiteType.Cell || context.containerId()[loc.site()] == 0)
featureVector.addToEntry(compIdx, context.containerState(0).value(loc.site(), loc.level(), loc.siteType()));
}
}
}
return featureVector;
}
@Override
public FVector paramsVector()
{
return pieceWeights;
}
@Override
public void init(final Game game)
{
// Compute vector of piece weights
pieceWeights = HeuristicTerm.pieceWeightsVector(game, pieceWeightNames, gameAgnosticWeightsArray);
// Precompute hand indices for this game
computeHandIndices(game);
gameHasMultipleContainers = (game.equipment().containers().length > 1);
}
@Override
public int updateParams(final Game game, final FVector newParams, final int startIdx)
{
final int retVal = super.updateParams(game, newParams, startIdx);
// Need to update the array of weights we were passed in constructor
// in case we decide to write ourselves to a file
final Object[] returnArrays = updateGameAgnosticWeights(game, pieceWeights, pieceWeightNames, gameAgnosticWeightsArray);
pieceWeightNames = (String[]) returnArrays[0];
gameAgnosticWeightsArray = (float[]) returnArrays[1];
return retVal;
}
//-------------------------------------------------------------------------
/**
* @param game
*/
private void computeHandIndices(final Game game)
{
boolean foundHands = false;
final int[] handContainerIndices = new int[game.players().count() + 1];
for (final Container c : game.equipment().containers())
{
if (c instanceof game.equipment.container.other.Hand)
{
final int owner = ((game.equipment.container.other.Hand)c).owner();
if (owner > 0 && owner < handContainerIndices.length && handContainerIndices[owner] == 0)
{
foundHands = true;
handContainerIndices[owner] = c.index();
}
}
}
if (!foundHands)
handIndices = null;
else
handIndices = handContainerIndices;
}
//-------------------------------------------------------------------------
/**
* @param game
* @return True if heuristic of this type could be applicable to given game
*/
public static boolean isApplicableToGame(final Game game)
{
if ((game.gameFlags() & GameType.Value) == 0L)
return false;
final Component[] components = game.equipment().components();
if (components.length <= 1)
return false;
return true;
}
/**
* @param game
* @return True if the heuristic of this type is sensible for the given game
* (must be applicable, but even some applicable heuristics may be considered
* to be not sensible).
*/
public static boolean isSensibleForGame(final Game game)
{
return isApplicableToGame(game);
}
@Override
public boolean isApplicable(final Game game)
{
return isApplicableToGame(game);
}
//-------------------------------------------------------------------------
@Override
public String toString()
{
final StringBuilder sb = new StringBuilder();
sb.append("(componentValues");
if (transformation != null)
sb.append(" transformation:" + transformation.toString());
if (weight != 1.f)
sb.append(" weight:" + weight);
if (pieceWeightNames.length > 1 || (pieceWeightNames.length == 1 && pieceWeightNames[0].length() > 0))
{
sb.append(" pieceWeights:{\n");
for (int i = 0; i < pieceWeightNames.length; ++i)
{
if (gameAgnosticWeightsArray[i] != 0.f)
sb.append(" (pair " + StringRoutines.quote(pieceWeightNames[i]) + " " + gameAgnosticWeightsArray[i] + ")\n");
}
sb.append(" }");
if (boardOnly)
sb.append("\n boardOnly:True\n");
}
else if (boardOnly)
{
sb.append(" boardOnly:True");
}
sb.append(")");
return sb.toString();
}
//-------------------------------------------------------------------------
@Override
public String toStringThresholded(final float threshold)
{
boolean shouldPrint = false;
boolean haveRelevantPieces = false;
final StringBuilder pieceWeightsSb = new StringBuilder();
if (pieceWeightNames.length > 1 || (pieceWeightNames.length == 1 && pieceWeightNames[0].length() > 0))
{
for (int i = 0; i < pieceWeightNames.length; ++i)
{
if (Math.abs(weight * gameAgnosticWeightsArray[i]) >= threshold)
{
pieceWeightsSb.append(" (pair " + StringRoutines.quote(pieceWeightNames[i]) + " " + gameAgnosticWeightsArray[i] + ")\n");
haveRelevantPieces = true;
shouldPrint = true;
}
}
}
else if (Math.abs(weight) >= threshold)
{
// No manually specified weights, so they will all default to 1.0,
// and we have a large enough term-wide weight
shouldPrint = true;
}
if (shouldPrint)
{
final StringBuilder sb = new StringBuilder();
sb.append("(componentValues");
if (transformation != null)
sb.append(" transformation:" + transformation.toString());
if (weight != 1.f)
sb.append(" weight:" + weight);
if (haveRelevantPieces)
{
sb.append(" pieceWeights:{\n");
sb.append(pieceWeightsSb);
sb.append(" }");
if (boardOnly)
sb.append("\n boardOnly:True\n");
}
else if (boardOnly)
{
sb.append(" boardOnly:True");
}
sb.append(")");
return sb.toString();
}
else
{
return null;
}
}
//-------------------------------------------------------------------------
@Override
public void merge(final HeuristicTerm term)
{
final ComponentValues castTerm = (ComponentValues) term;
for (int i = 0; i < pieceWeightNames.length; i++)
for (int j = 0; j < castTerm.pieceWeightNames.length; j++)
if (pieceWeightNames[i].equals(castTerm.pieceWeightNames[j]))
gameAgnosticWeightsArray[i] = gameAgnosticWeightsArray[i] + castTerm.gameAgnosticWeightsArray[j] * (castTerm.weight()/weight());
}
@Override
public void simplify()
{
if (Math.abs(weight() - 1.f) > Constants.EPSILON)
{
for (int i = 0; i < gameAgnosticWeightsArray.length; i++)
gameAgnosticWeightsArray[i] *= weight();
setWeight(1.f);
}
}
@Override
public float maxAbsWeight()
{
float maxWeight = Math.abs(weight());
for (final float f : gameAgnosticWeightsArray)
maxWeight = Math.max(maxWeight, Math.abs(f));
return maxWeight;
}
//-------------------------------------------------------------------------
@Override
public String description()
{
return "Sum of values of sites occupied by owned pieces.";
}
@Override
public String toEnglishString(final Context context, final int playerIndex)
{
final StringBuilder sb = new StringBuilder();
final String extraString = boardOnly ? " on the board" : "";
if (pieceWeightNames.length > 1 || (pieceWeightNames.length == 1 && pieceWeightNames[0].length() > 0))
{
for (int i = 0; i < pieceWeightNames.length; ++i)
{
if (gameAgnosticWeightsArray[i] != 0.f)
{
final String pieceTrailingNumbers = StringRoutines.getTrailingNumbers(pieceWeightNames[i]);
if (pieceTrailingNumbers.length() == 0 || playerIndex < 0 || Integer.valueOf(pieceTrailingNumbers).intValue() == playerIndex)
{
if (weight > 0)
sb.append("You should try to maximise the value of your " + StringRoutines.removeTrailingNumbers(pieceWeightNames[i]) + "(s)");
else
sb.append("You should try to minimise the value of your " + StringRoutines.removeTrailingNumbers(pieceWeightNames[i]) + "(s)");
sb.append(extraString + " (" + HeuristicUtil.convertWeightToString(gameAgnosticWeightsArray[i]) + ")\n");
}
}
}
}
else
{
if (weight > 0)
sb.append("You should try to maximise the value of your piece(s)");
else
sb.append("You should try to minimise the value of your piece(s)");
sb.append(extraString + " (" + HeuristicUtil.convertWeightToString(weight) + ")\n");
}
return sb.toString();
}
//-------------------------------------------------------------------------
@Override
public float[] gameAgnosticWeightsArray() {
return gameAgnosticWeightsArray;
}
@Override
public FVector pieceWeights() {
return pieceWeights;
}
}
| 15,821 | 27.354839 | 134 | java |
Ludii | Ludii-master/Core/src/metadata/ai/heuristics/terms/CornerProximity.java | package metadata.ai.heuristics.terms;
import java.util.Arrays;
import java.util.List;
import annotations.Name;
import annotations.Opt;
import game.Game;
import game.equipment.component.Component;
import main.Constants;
import main.StringRoutines;
import main.collections.FVector;
import metadata.ai.heuristics.HeuristicUtil;
import metadata.ai.heuristics.transformations.HeuristicTransformation;
import metadata.ai.misc.Pair;
import other.context.Context;
import other.location.Location;
import other.state.owned.Owned;
/**
* Defines a heuristic term based on the proximity of pieces to the corners of
* a game's board.
*
* @author Dennis Soemers
*/
public class CornerProximity extends HeuristicTerm
{
//-------------------------------------------------------------------------
/** Array of names specified for piece types */
private String[] pieceWeightNames;
/**
* Array of weights as specified in metadata. Will be used to initialise
* a weight vector for a specific game when init() is called.
*/
private float[] gameAgnosticWeightsArray;
/** Vector with weights for every piece type */
private FVector pieceWeights = null;
/** The maximum distance that exists in our Corners distance table */
private int maxDistance = -1;
//-------------------------------------------------------------------------
/**
* Constructor
*
* @param transformation An optional transformation to be applied to any
* raw heuristic score outputs.
* @param weight The weight for this term in a linear combination of multiple terms.
* If not specified, a default weight of $1.0$ is used.
* @param pieceWeights Weights for different piece types. If no piece weights are
* specified at all, all piece types are given an equal weight of $1.0$. If piece
* weights are only specified for some piece types, all other piece types get a
* weight of $0$.
*
* @example (cornerProximity pieceWeights:{ (pair "Queen" -1.0) (pair "King" 1.0) })
*/
public CornerProximity
(
@Name @Opt final HeuristicTransformation transformation,
@Name @Opt final Float weight,
@Name @Opt final Pair[] pieceWeights
)
{
super(transformation, weight);
if (pieceWeights == null)
{
// We want a weight of 1.0 for everything
pieceWeightNames = new String[]{""};
gameAgnosticWeightsArray = new float[]{1.f};
}
else
{
pieceWeightNames = new String[pieceWeights.length];
gameAgnosticWeightsArray = new float[pieceWeights.length];
for (int i = 0; i < pieceWeights.length; ++i)
{
pieceWeightNames[i] = pieceWeights[i].key();
gameAgnosticWeightsArray[i] = pieceWeights[i].floatVal();
}
}
}
@Override
public HeuristicTerm copy()
{
return new CornerProximity(this);
}
/**
* Copy constructor (private, so not visible to grammar)
* @param other
*/
private CornerProximity(final CornerProximity other)
{
super(other.transformation, Float.valueOf(other.weight));
pieceWeightNames = Arrays.copyOf(other.pieceWeightNames, other.pieceWeightNames.length);
gameAgnosticWeightsArray = Arrays.copyOf(other.gameAgnosticWeightsArray, other.gameAgnosticWeightsArray.length);
}
//-------------------------------------------------------------------------
@Override
public float computeValue(final Context context, final int player, final float absWeightThreshold)
{
// if (maxDistance == 0)
// return 0.f;
final int[] distances = context.game().distancesToCorners();
final Owned owned = context.state().owned();
final List<? extends Location>[] pieces = owned.positions(player);
float value = 0.f;
for (int i = 0; i < pieces.length; ++i)
{
if (pieces[i].isEmpty())
continue;
final float pieceWeight = pieceWeights.get(owned.reverseMap(player, i));
if (Math.abs(pieceWeight) >= absWeightThreshold)
{
for (final Location position : pieces[i])
{
final int site = position.site();
if (site >= distances.length) // Different container, skip it
continue;
final int dist = distances[site];
final float proximity = 1.f - ((float) dist / maxDistance);
value += pieceWeight * proximity;
}
}
}
return value;
}
@Override
public FVector computeStateFeatureVector(final Context context, final int player)
{
final FVector featureVector = new FVector(pieceWeights.dim());
if (maxDistance != 0.f)
{
final int[] distances = context.game().distancesToCorners();
final Owned owned = context.state().owned();
final List<? extends Location>[] pieces = owned.positions(player);
for (int i = 0; i < pieces.length; ++i)
{
if (pieces[i].isEmpty())
continue;
final int compIdx = owned.reverseMap(player, i);
for (final Location position : pieces[i])
{
final int site = position.site();
if (site >= distances.length) // Different container, skip it
continue;
final int dist = distances[site];
final float proximity = 1.f - ((float) dist / maxDistance);
featureVector.addToEntry(compIdx, proximity);
}
}
}
return featureVector;
}
@Override
public FVector paramsVector()
{
return pieceWeights;
}
@Override
public void init(final Game game)
{
// Compute vector of piece weights
pieceWeights = HeuristicTerm.pieceWeightsVector(game, pieceWeightNames, gameAgnosticWeightsArray);
// Precompute maximum distance for this game
computeMaxDist(game);
}
@Override
public int updateParams(final Game game, final FVector newParams, final int startIdx)
{
final int retVal = super.updateParams(game, newParams, startIdx);
// Need to update the array of weights we were passed in constructor
// in case we decide to write ourselves to a file
final Object[] returnArrays = updateGameAgnosticWeights(game, pieceWeights, pieceWeightNames, gameAgnosticWeightsArray);
pieceWeightNames = (String[]) returnArrays[0];
gameAgnosticWeightsArray = (float[]) returnArrays[1];
return retVal;
}
//-------------------------------------------------------------------------
/**
* Helper method for constructors
* @param game
*/
private final void computeMaxDist(final Game game)
{
final int[] distances = game.distancesToCorners();
if (distances != null)
{
int max = 0;
for (int i = 0; i < distances.length; ++i)
{
if (distances[i] > max)
max = distances[i];
}
maxDistance = max;
}
else
{
maxDistance = 0;
}
}
//-------------------------------------------------------------------------
/**
* @param game
* @return True if heuristic of this type could be applicable to given game
*/
public static boolean isApplicableToGame(final Game game)
{
final Component[] components = game.equipment().components();
if (components.length <= 1)
return false;
if (game.distancesToCorners() == null)
return false;
return true;
}
/**
* @param game
* @return True if the heuristic of this type is sensible for the given game
* (must be applicable, but even some applicable heuristics may be considered
* to be not sensible).
*/
public static boolean isSensibleForGame(final Game game)
{
return isApplicableToGame(game);
}
@Override
public boolean isApplicable(final Game game)
{
return isApplicableToGame(game);
}
//-------------------------------------------------------------------------
@Override
public String toString()
{
final StringBuilder sb = new StringBuilder();
sb.append("(cornerProximity");
if (transformation != null)
sb.append(" transformation:" + transformation.toString());
if (weight != 1.f)
sb.append(" weight:" + weight);
if (pieceWeightNames.length > 1 || (pieceWeightNames.length == 1 && pieceWeightNames[0].length() > 0))
{
sb.append(" pieceWeights:{\n");
for (int i = 0; i < pieceWeightNames.length; ++i)
{
if (gameAgnosticWeightsArray[i] != 0.f)
sb.append(" (pair " + StringRoutines.quote(pieceWeightNames[i]) + " " + gameAgnosticWeightsArray[i] + ")\n");
}
sb.append(" }");
}
sb.append(")");
return sb.toString();
}
//-------------------------------------------------------------------------
@Override
public String toStringThresholded(final float threshold)
{
boolean shouldPrint = false;
boolean haveRelevantPieces = false;
final StringBuilder pieceWeightsSb = new StringBuilder();
if (pieceWeightNames.length > 1 || (pieceWeightNames.length == 1 && pieceWeightNames[0].length() > 0))
{
for (int i = 0; i < pieceWeightNames.length; ++i)
{
if (Math.abs(weight * gameAgnosticWeightsArray[i]) >= threshold)
{
pieceWeightsSb.append(" (pair " + StringRoutines.quote(pieceWeightNames[i]) + " " + gameAgnosticWeightsArray[i] + ")\n");
haveRelevantPieces = true;
shouldPrint = true;
}
}
}
else if (Math.abs(weight) >= threshold)
{
// No manually specified weights, so they will all default to 1.0,
// and we have a large enough term-wide weight
shouldPrint = true;
}
if (shouldPrint)
{
final StringBuilder sb = new StringBuilder();
sb.append("(cornerProximity");
if (transformation != null)
sb.append(" transformation:" + transformation.toString());
if (weight != 1.f)
sb.append(" weight:" + weight);
if (haveRelevantPieces)
{
sb.append(" pieceWeights:{\n");
sb.append(pieceWeightsSb);
sb.append(" }");
}
sb.append(")");
return sb.toString();
}
else
{
return null;
}
}
//-------------------------------------------------------------------------
@Override
public void merge(final HeuristicTerm term)
{
final CornerProximity castTerm = (CornerProximity) term;
for (int i = 0; i < pieceWeightNames.length; i++)
for (int j = 0; j < castTerm.pieceWeightNames.length; j++)
if (pieceWeightNames[i].equals(castTerm.pieceWeightNames[j]))
gameAgnosticWeightsArray[i] = gameAgnosticWeightsArray[i] + castTerm.gameAgnosticWeightsArray[j] * (castTerm.weight()/weight());
}
@Override
public void simplify()
{
if (Math.abs(weight() - 1.f) > Constants.EPSILON)
{
for (int i = 0; i < gameAgnosticWeightsArray.length; i++)
gameAgnosticWeightsArray[i] *= weight();
setWeight(1.f);
}
}
@Override
public float maxAbsWeight()
{
float maxWeight = Math.abs(weight());
for (final float f : gameAgnosticWeightsArray)
maxWeight = Math.max(maxWeight, Math.abs(f));
return maxWeight;
}
//-------------------------------------------------------------------------
@Override
public String description()
{
return "Sum of owned pieces, weighted by proximity to nearest corner.";
}
@Override
public String toEnglishString(final Context context, final int playerIndex)
{
final StringBuilder sb = new StringBuilder();
if (pieceWeightNames.length > 1 || (pieceWeightNames.length == 1 && pieceWeightNames[0].length() > 0))
{
for (int i = 0; i < pieceWeightNames.length; ++i)
{
if (gameAgnosticWeightsArray[i] != 0.f)
{
final String pieceTrailingNumbers = StringRoutines.getTrailingNumbers(pieceWeightNames[i]);
if (pieceTrailingNumbers.length() == 0 || playerIndex < 0 || Integer.valueOf(pieceTrailingNumbers).intValue() == playerIndex)
{
if (weight > 0)
sb.append("You should try to move your " + StringRoutines.removeTrailingNumbers(pieceWeightNames[i]) + "(s) towards the corners of the board");
else
sb.append("You should try to move your " + StringRoutines.removeTrailingNumbers(pieceWeightNames[i]) + "(s) away from the corners of the board");
sb.append(" (" + HeuristicUtil.convertWeightToString(gameAgnosticWeightsArray[i]) + ")\n");
}
}
}
}
else
{
if (weight > 0)
sb.append("You should try to move your piece(s) towards the corners of the board");
else
sb.append("You should try to move your piece(s) away from the corners of the board");
sb.append(" (" + HeuristicUtil.convertWeightToString(weight) + ")\n");
}
return sb.toString();
}
//-------------------------------------------------------------------------
@Override
public float[] gameAgnosticWeightsArray() {
return gameAgnosticWeightsArray;
}
@Override
public FVector pieceWeights() {
return pieceWeights;
}
}
| 12,360 | 26.347345 | 152 | java |
Ludii | Ludii-master/Core/src/metadata/ai/heuristics/terms/CurrentMoverHeuristic.java | package metadata.ai.heuristics.terms;
import annotations.Name;
import annotations.Opt;
import game.Game;
import main.collections.FVector;
import metadata.ai.heuristics.transformations.HeuristicTransformation;
import other.context.Context;
/**
* Defines a heuristic term that adds its weight only for the player
* whose turn it is in any given game state.
*
* @author Dennis Soemers
*/
public class CurrentMoverHeuristic extends HeuristicTerm
{
//-------------------------------------------------------------------------
/**
* Constructor
*
* @param transformation An optional transformation to be applied to any
* raw heuristic score outputs.
* @param weight The weight for this term in a linear combination of multiple terms.
* If not specified, a default weight of $1.0$ is used.
*
* @example (currentMoverHeuristic weight:1.0)
*/
public CurrentMoverHeuristic
(
@Name @Opt final HeuristicTransformation transformation,
@Name @Opt final Float weight
)
{
super(transformation, weight);
}
@Override
public HeuristicTerm copy()
{
return new CurrentMoverHeuristic(this);
}
/**
* Copy constructor (private, so not visible to grammar)
* @param other
*/
private CurrentMoverHeuristic(final CurrentMoverHeuristic other)
{
super(other.transformation, Float.valueOf(other.weight));
}
//-------------------------------------------------------------------------
@Override
public float computeValue(final Context context, final int player, final float absWeightThreshold)
{
if (context.state().mover() == player)
return 1.f;
else
return 0.f;
}
@Override
public FVector computeStateFeatureVector(final Context context, final int player)
{
if (context.state().mover() == player)
return FVector.ones(1);
else
return FVector.zeros(1);
}
@Override
public FVector paramsVector()
{
return null;
}
//-------------------------------------------------------------------------
/**
* @param game
* @return True if heuristic of this type could be applicable to given game
*/
public static boolean isApplicableToGame(final Game game)
{
return game.isAlternatingMoveGame();
}
/**
* @param game
* @return True if the heuristic of this type is sensible for the given game
* (must be applicable, but even some applicable heuristics may be considered
* to be not sensible).
*/
public static boolean isSensibleForGame(final Game game)
{
return isApplicableToGame(game);
}
@Override
public boolean isApplicable(final Game game)
{
return isApplicableToGame(game);
}
//-------------------------------------------------------------------------
@Override
public String toString()
{
final StringBuilder sb = new StringBuilder();
sb.append("(currentMoverHeuristic");
if (transformation != null)
sb.append(" transformation:" + transformation.toString());
if (weight != 1.f)
sb.append(" weight:" + weight);
sb.append(")");
return sb.toString();
}
//-------------------------------------------------------------------------
@Override
public String toStringThresholded(final float threshold)
{
boolean shouldPrint = false;
if (Math.abs(weight) >= threshold)
{
// No manually specified weights, so they will all default to 1.0,
// and we have a large enough term-wide weight
shouldPrint = true;
}
if (shouldPrint)
{
final StringBuilder sb = new StringBuilder();
sb.append("(currentMoverHeuristic");
if (transformation != null)
sb.append(" transformation:" + transformation.toString());
if (weight != 1.f)
sb.append(" weight:" + weight);
sb.append(")");
return sb.toString();
}
else
{
return null;
}
}
//-------------------------------------------------------------------------
@Override
public String description()
{
return "TODO.";
}
@Override
public String toEnglishString(final Context context, final int playerIndex)
{
return "TODO.";
}
//-------------------------------------------------------------------------
}
| 4,067 | 22.113636 | 99 | java |
Ludii | Ludii-master/Core/src/metadata/ai/heuristics/terms/HeuristicTerm.java | package metadata.ai.heuristics.terms;
import java.util.ArrayList;
import java.util.List;
import game.Game;
import game.equipment.component.Component;
import gnu.trove.list.array.TFloatArrayList;
import main.collections.FVector;
import metadata.ai.AIItem;
import metadata.ai.heuristics.transformations.HeuristicTransformation;
import other.context.Context;
/**
* Abstract class for heuristic terms. Every heuristic term is expected to implement
* a function that outputs a score for a given game state and player, and every term
* has a weight that is used for computing linear combinations of multiple terms.
*
* @author Dennis Soemers and matthew.stephenson
*/
public abstract class HeuristicTerm implements AIItem
{
//-------------------------------------------------------------------------
/** The weight of this term in linear combinations */
protected float weight;
/** Transformation to apply to heuristic score (before multiplying with weight!) */
protected final HeuristicTransformation transformation;
//-------------------------------------------------------------------------
/**
* Constructor
*
* @param transformation An optional transformation to be applied to any raw heuristic
* score outputs.
* @param weight The weight for this term in a linear combination of multiple terms.
* If not specified, a default weight of 1.0 is used.
*/
public HeuristicTerm(final HeuristicTransformation transformation, final Float weight)
{
if (weight == null)
this.weight = 1.f;
else
this.weight = weight.floatValue();
this.transformation = transformation;
}
/**
* Copy method (not copy constructor, so not visible to grammar)
* @return Copy of the heuristic term
*/
public abstract HeuristicTerm copy();
//-------------------------------------------------------------------------
/**
* @return English description of this heuristic.
*/
public abstract String description();
/**
* @param context
* @param playerIndex
* @return toString of this Heuristic in an English language format.
*/
public abstract String toEnglishString(final Context context, final int playerIndex);
//-------------------------------------------------------------------------
/**
* @param term
* @return if this HeuristicTerm can be merged with the parameter term.
*/
public boolean canBeMerged(final HeuristicTerm term)
{
return this.getClass().getName().equals(term.getClass().getName());
}
/**
* Merges this HeuristicTerm with the parameter term. Make sure that all pieceWeightNames are the same.
* @param term
*/
public void merge(final HeuristicTerm term)
{
setWeight(weight() + term.weight());
}
/**
* Simplifies this heuristic, usually by combining weights.
*/
public void simplify()
{
// do nothing
}
/**
* @return the maximum weight value for any aspect of this heuristic.
*/
public float maxAbsWeight()
{
return Math.abs(weight());
}
//-------------------------------------------------------------------------
/**
* Computes heuristic value estimate for the given state
* from the perspective of the given player. This should NOT
* apply any transformations.
*
* @param context
* @param player
* @param absWeightThreshold We skip terms with an absolute weight below this value
* (negative for no skipping)
* @return Heuristic value estimate
*/
public abstract float computeValue(final Context context, final int player, final float absWeightThreshold);
/**
* Allows for initialisation / precomputation of data for a given game.
* Default implementation does nothing.
*
* @param game
*/
public void init(final Game game)
{
// Do nothing
}
//-------------------------------------------------------------------------
/**
* @param context
* @param player
* @return Heuristic's feature vector in given state, from perspective of given player
*/
public abstract FVector computeStateFeatureVector(final Context context, final int player);
/**
* @return Vector of parameters (weights including "internal" weights of nested heuristics).
* Should return null if this term does not have any internal weights (other than the single
* weight for use in the linear combination of multiple terms).
*/
public abstract FVector paramsVector();
/**
* Updates weights in heuristic based on given vector of params.
*
* @param game
* @param newParams
* @param startIdx Index at which to start reading params
* @return Index in vector at which the next heuristic term is allowed to start reading
*/
public int updateParams(final Game game, final FVector newParams, final int startIdx)
{
final FVector internalParams = paramsVector();
if (internalParams == null)
{
weight = newParams.get(startIdx);
return startIdx + 1;
}
else
{
internalParams.copyFrom(newParams, startIdx, 0, internalParams.dim());
// We let our inner heuristic terms completely absorb the weights,
// so must ensure to only have a weight of exactly 1.f ourselves
weight = 1.f;
return startIdx + internalParams.dim();
}
}
//-------------------------------------------------------------------------
/**
* @return A transformation to be applied to output values (null for no transformation)
*/
public HeuristicTransformation transformation()
{
return transformation;
}
/**
* @return Weight for this term in linear combination of multiple heuristic terms
*/
public float weight()
{
return weight;
}
//-------------------------------------------------------------------------
/**
* A helper method that a variety of heuristic term classes can use to convert
* input they were given in a constructor into a game-specific vector of piece
* weights.
*
* @param game
* @param pieceWeightNames
* @param gameAgnosticWeightsArray
* @return Vector of piece weights for given game
*/
protected static FVector pieceWeightsVector
(
final Game game,
final String[] pieceWeightNames,
final float[] gameAgnosticWeightsArray
)
{
final Component[] components = game.equipment().components();
final FVector pieceWeights = new FVector(components.length);
for (int nameIdx = 0; nameIdx < pieceWeightNames.length; ++nameIdx)
{
final String s = pieceWeightNames[nameIdx].trim();
for (int i = 1; i < components.length; ++i)
{
final String compName = components[i].name();
if (compName.startsWith(s))
{
boolean match = true;
if (s.length() > 0)
{
if (Character.isDigit(s.charAt(s.length() - 1)))
{
if (!s.equals(compName))
match = false;
}
else
{
for (int j = s.length(); j < compName.length(); ++j)
{
if (!Character.isDigit(compName.charAt(j)))
{
match = false;
break;
}
}
}
}
if (match)
{
pieceWeights.set(i, gameAgnosticWeightsArray[nameIdx]);
}
}
}
}
return pieceWeights;
}
/**
* Helper method to update our array of game-agnostic weights
* based on our current vector of piece weights for a current
* game (which may have been modified due to training)
*
* @param game
* @param pieceWeights
* @param pieceWeightNames
* @param gameAgnosticWeightsArray
* @return Array of two elements: first is a new array of piece names, second a new array of weights
*/
protected static Object[] updateGameAgnosticWeights
(
final Game game,
final FVector pieceWeights,
final String[] pieceWeightNames,
final float[] gameAgnosticWeightsArray
)
{
final List<String> newPieceWeightNames = new ArrayList<String>();
final TFloatArrayList newPieceWeights = new TFloatArrayList();
final Component[] components = game.equipment().components();
for (int i = 1; i < pieceWeights.dim(); ++i)
{
newPieceWeightNames.add(components[i].name());
newPieceWeights.add(pieceWeights.get(i));
}
return new Object[]{newPieceWeightNames.toArray(new String[0]), newPieceWeights.toArray()};
}
//-------------------------------------------------------------------------
/**
* @param game
* @return True if heuristic of this type could be applicable to given game
*/
public abstract boolean isApplicable(final Game game);
//-------------------------------------------------------------------------
/**
* @param threshold
* @return A string representation of this heuristic term, with any components
* for which the absolute weight does not exceed the given threshold removed.
* Should return null if there are no components remaining after thresholding.
*/
public abstract String toStringThresholded(final float threshold);
//-------------------------------------------------------------------------
/**
* @param weight
*/
public void setWeight(final float weight)
{
this.weight = weight;
}
/**
* Used for term reconstruction using a genetic code
* @return The array of game-agnostic weights
*/
@SuppressWarnings("static-method")
public float[] gameAgnosticWeightsArray()
{
return null;
}
/**
* Used for term reconstruction using a genetic code
* @return The vector of piece weights
*/
@SuppressWarnings("static-method")
public FVector pieceWeights()
{
return null;
}
//-------------------------------------------------------------------------
}
| 9,446 | 26.382609 | 109 | java |
Ludii | Ludii-master/Core/src/metadata/ai/heuristics/terms/Influence.java | package metadata.ai.heuristics.terms;
import annotations.Name;
import annotations.Opt;
import game.Game;
import game.types.state.GameType;
import gnu.trove.set.hash.TIntHashSet;
import main.collections.FVector;
import main.collections.FastArrayList;
import metadata.ai.heuristics.HeuristicUtil;
import metadata.ai.heuristics.transformations.HeuristicTransformation;
import other.context.Context;
import other.move.Move;
/**
* Defines a heuristic term that multiplies its weight by the number
* of moves with distinct "to" positions that a player has in a current game state,
* divided by the number of playable positions that exist in the game.
*
* @remarks Always produces a score of $0$ for players who are not the current mover.
*
* @author Dennis Soemers
*/
public class Influence extends HeuristicTerm
{
//-------------------------------------------------------------------------
/**
* Constructor
*
* @param transformation An optional transformation to be applied to any
* raw heuristic score outputs.
* @param weight The weight for this term in a linear combination of multiple terms.
* If not specified, a default weight of $1.0$ is used.
*
* @example (influence weight:0.5)
*/
public Influence
(
@Name @Opt final HeuristicTransformation transformation,
@Name @Opt final Float weight
)
{
super(transformation, weight);
}
@Override
public HeuristicTerm copy()
{
return new Influence(this);
}
/**
* Copy constructor (private, so not visible to grammar)
* @param other
*/
private Influence(final Influence other)
{
super(other.transformation, Float.valueOf(other.weight));
}
//-------------------------------------------------------------------------
@Override
public float computeValue(final Context context, final int player, final float absWeightThreshold)
{
if (context.state().mover() == player)
{
final FastArrayList<Move> moves = context.game().moves(context).moves();
final TIntHashSet toPositions = new TIntHashSet();
for (final Move move : moves)
{
final int to = move.to();
if (to >= 0)
toPositions.add(to);
}
return ((float) toPositions.size()) / context.game().equipment().totalDefaultSites();
}
else
{
return 0.f;
}
}
@Override
public FVector computeStateFeatureVector(final Context context, final int player)
{
final FVector featureVector = new FVector(1);
featureVector.set(0, computeValue(context, player, -1.f));
return featureVector;
}
@Override
public FVector paramsVector()
{
return null;
}
//-------------------------------------------------------------------------
/**
* @param game
* @return True if heuristic of this type could be applicable to given game
*/
public static boolean isApplicableToGame(final Game game)
{
// Note: we only allow this heuristic in games that also use from-positions, because
// otherwise the number of moves with distinct to-positions is almost always meaningless
// (with some exceptions, like if moves have same to-position but different consequents)
return game.isAlternatingMoveGame() && ((game.gameFlags() & GameType.UsesFromPositions) != 0L);
}
/**
* @param game
* @return True if the heuristic of this type is sensible for the given game
* (must be applicable, but even some applicable heuristics may be considered
* to be not sensible).
*/
public static boolean isSensibleForGame(final Game game)
{
return isApplicableToGame(game);
}
@Override
public boolean isApplicable(final Game game)
{
return isApplicableToGame(game);
}
//-------------------------------------------------------------------------
@Override
public String toString()
{
final StringBuilder sb = new StringBuilder();
sb.append("(influence");
if (transformation != null)
sb.append(" transformation:" + transformation.toString());
if (weight != 1.f)
sb.append(" weight:" + weight);
sb.append(")");
return sb.toString();
}
//-------------------------------------------------------------------------
@Override
public String toStringThresholded(final float threshold)
{
boolean shouldPrint = false;
if (Math.abs(weight) >= threshold)
{
// No manually specified weights, so they will all default to 1.0,
// and we have a large enough term-wide weight
shouldPrint = true;
}
if (shouldPrint)
{
final StringBuilder sb = new StringBuilder();
sb.append("(influence");
if (transformation != null)
sb.append(" transformation:" + transformation.toString());
if (weight != 1.f)
sb.append(" weight:" + weight);
sb.append(")");
return sb.toString();
}
else
{
return null;
}
}
//-------------------------------------------------------------------------
@Override
public String description()
{
return "Number of legal moves with distinct destination positions.";
}
@Override
public String toEnglishString(final Context context, final int playerIndex)
{
final StringBuilder sb = new StringBuilder();
if (weight > 0)
sb.append("You should try to maximise the number of spaces you can move to");
else
sb.append("You should try to minimise the number of spaces you can move to");
sb.append(" (" + HeuristicUtil.convertWeightToString(weight) + ")\n");
return sb.toString();
}
//-------------------------------------------------------------------------
}
| 5,421 | 25.193237 | 99 | java |
Ludii | Ludii-master/Core/src/metadata/ai/heuristics/terms/InfluenceAdvanced.java | package metadata.ai.heuristics.terms;
import annotations.Name;
import annotations.Opt;
import game.Game;
import game.types.state.GameType;
import gnu.trove.set.hash.TIntHashSet;
import main.collections.FVector;
import main.collections.FastArrayList;
import metadata.ai.heuristics.HeuristicUtil;
import metadata.ai.heuristics.transformations.HeuristicTransformation;
import other.context.Context;
import other.context.TempContext;
import other.move.Move;
/**
* Defines a heuristic term that multiplies its weight by the number
* of moves with distinct "to" positions that a player has in a current game state,
* divided by the number of playable positions that exist in the game.
* In comparison to Influence, this is a more advanced version that will also attempt
* to gain non-zero estimates of the influence of players other than the current
* player to move.
*
* @author Dennis Soemers
*/
public class InfluenceAdvanced extends HeuristicTerm
{
//-------------------------------------------------------------------------
/**
* Constructor
*
* @param transformation An optional transformation to be applied to any
* raw heuristic score outputs.
* @param weight The weight for this term in a linear combination of multiple terms.
* If not specified, a default weight of $1.0$ is used.
*
* @example (influenceAdvanced weight:0.5)
*/
public InfluenceAdvanced
(
@Name @Opt final HeuristicTransformation transformation,
@Name @Opt final Float weight
)
{
super(transformation, weight);
}
@Override
public HeuristicTerm copy()
{
return new InfluenceAdvanced(this);
}
/**
* Copy constructor (private, so not visible to grammar)
* @param other
*/
private InfluenceAdvanced(final InfluenceAdvanced other)
{
super(other.transformation, Float.valueOf(other.weight));
}
//-------------------------------------------------------------------------
@Override
public float computeValue(final Context context, final int player, final float absWeightThreshold)
{
final Context computeContext;
if (context.state().mover() == player)
{
computeContext = context;
}
else
{
computeContext = new TempContext(context);
computeContext.state().setPrev(context.state().mover());
computeContext.state().setMover(player);
computeContext.trial().clearLegalMoves();
}
final FastArrayList<Move> legalMoves = computeContext.game().moves(computeContext).moves();
final TIntHashSet toPositions = new TIntHashSet();
for (final Move move : legalMoves)
{
final int to = move.to();
if (to >= 0)
toPositions.add(to);
}
return ((float) toPositions.size()) / computeContext.game().equipment().totalDefaultSites();
}
@Override
public FVector computeStateFeatureVector(final Context context, final int player)
{
final FVector featureVector = new FVector(1);
featureVector.set(0, computeValue(context, player, -1.f));
return featureVector;
}
@Override
public FVector paramsVector()
{
return null;
}
//-------------------------------------------------------------------------
/**
* @param game
* @return True if heuristic of this type could be applicable to given game
*/
public static boolean isApplicableToGame(final Game game)
{
// Note: we only allow this heuristic in games that also use from-positions, because
// otherwise the number of moves with distinct to-positions is almost always meaningless
// (with some exceptions, like if moves have same to-position but different consequents)
return game.isAlternatingMoveGame() && ((game.gameFlags() & GameType.UsesFromPositions) != 0L);
}
/**
* @param game
* @return True if the heuristic of this type is sensible for the given game
* (must be applicable, but even some applicable heuristics may be considered
* to be not sensible).
*/
public static boolean isSensibleForGame(final Game game)
{
return isApplicableToGame(game);
}
@Override
public boolean isApplicable(final Game game)
{
return isApplicableToGame(game);
}
//-------------------------------------------------------------------------
@Override
public String toString()
{
final StringBuilder sb = new StringBuilder();
sb.append("(influenceAdvanced");
if (transformation != null)
sb.append(" transformation:" + transformation.toString());
if (weight != 1.f)
sb.append(" weight:" + weight);
sb.append(")");
return sb.toString();
}
//-------------------------------------------------------------------------
@Override
public String toStringThresholded(final float threshold)
{
boolean shouldPrint = false;
if (Math.abs(weight) >= threshold)
{
// No manually specified weights, so they will all default to 1.0,
// and we have a large enough term-wide weight
shouldPrint = true;
}
if (shouldPrint)
{
final StringBuilder sb = new StringBuilder();
sb.append("(influenceAdvanced");
if (transformation != null)
sb.append(" transformation:" + transformation.toString());
if (weight != 1.f)
sb.append(" weight:" + weight);
sb.append(")");
return sb.toString();
}
else
{
return null;
}
}
//-------------------------------------------------------------------------
@Override
public String description()
{
return "Number of legal moves with distinct destination positions.";
}
@Override
public String toEnglishString(final Context context, final int playerIndex)
{
final StringBuilder sb = new StringBuilder();
if (weight > 0)
sb.append("You should try to maximise the number of spaces you can move to");
else
sb.append("You should try to minimise the number of spaces you can move to");
sb.append(" (" + HeuristicUtil.convertWeightToString(weight) + ")\n");
return sb.toString();
}
//-------------------------------------------------------------------------
}
| 5,887 | 26.133641 | 99 | java |
Ludii | Ludii-master/Core/src/metadata/ai/heuristics/terms/Intercept.java | package metadata.ai.heuristics.terms;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import annotations.Name;
import annotations.Opt;
import game.Game;
import game.types.play.RoleType;
import gnu.trove.list.array.TFloatArrayList;
import main.Constants;
import main.StringRoutines;
import main.collections.FVector;
import metadata.ai.heuristics.transformations.HeuristicTransformation;
import metadata.ai.misc.Pair;
import other.context.Context;
/**
* Defines an intercept term for heuristic-based value functions, with one
* weight per player.
*
* @author Dennis Soemers
*/
public class Intercept extends HeuristicTerm
{
//-------------------------------------------------------------------------
/** Array of names specified for piece types */
private RoleType[] players;
/**
* Array of weights as specified in metadata. Will be used to initialise
* a weight vector for a specific game when init() is called.
*/
private float[] gameAgnosticWeightsArray;
/** Vector with weights for every player */
private FVector playerWeightsVector = null;
//-------------------------------------------------------------------------
/**
* Constructor
*
* @param transformation An optional transformation to be applied to any
* raw heuristic score outputs.
* @param playerWeights Weights for different players. Players for which no
* weights are specified are given a weight of 0.0. Player names must be
* one of the following: "P1", "P2", ..., "P16".
*
* @example (intercept playerWeights:{ (pair "P1" 1.0) (pair "P2" 0.5) })
*/
public Intercept
(
@Name @Opt final HeuristicTransformation transformation,
@Name final Pair[] playerWeights
)
{
super(transformation, Float.valueOf(1.f));
players = new RoleType[playerWeights.length];
gameAgnosticWeightsArray = new float[playerWeights.length];
for (int i = 0; i < playerWeights.length; ++i)
{
players[i] = RoleType.valueOf(playerWeights[i].key());
gameAgnosticWeightsArray[i] = playerWeights[i].floatVal();
}
}
@Override
public HeuristicTerm copy()
{
return new Intercept(this);
}
/**
* Copy constructor (private, so not visible to grammar)
* @param other
*/
private Intercept(final Intercept other)
{
super(other.transformation, Float.valueOf(other.weight));
players = Arrays.copyOf(other.players, other.players.length);
gameAgnosticWeightsArray = Arrays.copyOf(other.gameAgnosticWeightsArray, other.gameAgnosticWeightsArray.length);
}
//-------------------------------------------------------------------------
@Override
public float computeValue(final Context context, final int player, final float absWeightThreshold)
{
return playerWeightsVector.get(player);
}
@Override
public FVector computeStateFeatureVector(final Context context, final int player)
{
final FVector featureVector = new FVector(playerWeightsVector.dim());
featureVector.set(player, 1.f);
return featureVector;
}
@Override
public FVector paramsVector()
{
return playerWeightsVector;
}
@Override
public void init(final Game game)
{
// Compute vector of player weights
playerWeightsVector = new FVector(game.players().count() + 1);
for (int i = 0; i < players.length; ++i)
{
playerWeightsVector.set(players[i].owner(), gameAgnosticWeightsArray[i]);
}
}
@Override
public int updateParams(final Game game, final FVector newParams, final int startIdx)
{
final int retVal = super.updateParams(game, newParams, startIdx);
// Need to update the array of weights we were passed in constructor
// in case we decide to write ourselves to a file
final List<RoleType> roleTypes = new ArrayList<RoleType>();
final TFloatArrayList nonZeroWeights = new TFloatArrayList();
for (int i = 1; i < newParams.dim(); ++i)
{
if (newParams.get(i) != 0.f)
{
roleTypes.add(RoleType.roleForPlayerId(i));
nonZeroWeights.add(newParams.get(i));
}
}
players = roleTypes.toArray(new RoleType[roleTypes.size()]);
gameAgnosticWeightsArray = nonZeroWeights.toArray();
return retVal;
}
//-------------------------------------------------------------------------
/**
* @param game
* @return True if heuristic of this type could be applicable to given game
*/
public static boolean isApplicableToGame(final Game game)
{
return true;
}
/**
* @param game
* @return True if the heuristic of this type is sensible for the given game
* (must be applicable, but even some applicable heuristics may be considered
* to be not sensible).
*/
public static boolean isSensibleForGame(final Game game)
{
return isApplicableToGame(game);
}
@Override
public boolean isApplicable(final Game game)
{
return isApplicableToGame(game);
}
//-------------------------------------------------------------------------
@Override
public String toString()
{
final StringBuilder sb = new StringBuilder();
sb.append("(intercept");
if (transformation != null)
sb.append(" transformation:" + transformation.toString());
if (weight != 1.f)
System.err.println("Intercept heuristic does not support weight other than 1.f!");
if (players.length >= 1)
{
sb.append(" playerWeights:{\n");
for (int i = 0; i < players.length; ++i)
{
if (gameAgnosticWeightsArray[i] != 0.f)
sb.append(" (pair " + StringRoutines.quote(players[i].name()) + " " + gameAgnosticWeightsArray[i] + ")\n");
}
sb.append(" }");
}
sb.append(")");
return sb.toString();
}
//-------------------------------------------------------------------------
@Override
public String toStringThresholded(final float threshold)
{
boolean shouldPrint = false;
boolean haveRelevantPlayers = false;
final StringBuilder playerWeightsSb = new StringBuilder();
if (players.length >= 1)
{
for (int i = 0; i < players.length; ++i)
{
if (Math.abs(weight * gameAgnosticWeightsArray[i]) >= threshold)
{
playerWeightsSb.append(" (pair " + StringRoutines.quote(players[i].name()) + " " + gameAgnosticWeightsArray[i] + ")\n");
haveRelevantPlayers = true;
shouldPrint = true;
}
}
}
if (shouldPrint)
{
final StringBuilder sb = new StringBuilder();
sb.append("(intercept");
if (transformation != null)
sb.append(" transformation:" + transformation.toString());
if (weight != 1.f)
System.err.println("Intercept heuristic does not support weight other than 1.f!");
if (haveRelevantPlayers)
{
sb.append(" pieceWeights:{\n");
sb.append(playerWeightsSb);
sb.append(" }");
}
sb.append(")");
return sb.toString();
}
else
{
return null;
}
}
//-------------------------------------------------------------------------
@Override
public void merge(final HeuristicTerm term)
{
final Intercept castTerm = (Intercept) term;
for (int i = 0; i < players.length; i++)
for (int j = 0; j < castTerm.players.length; j++)
if (players[i].equals(castTerm.players[j]))
gameAgnosticWeightsArray[i] = gameAgnosticWeightsArray[i] + castTerm.gameAgnosticWeightsArray[j] * (castTerm.weight()/weight());
}
@Override
public void simplify()
{
if (Math.abs(weight() - 1.f) > Constants.EPSILON)
{
for (int i = 0; i < gameAgnosticWeightsArray.length; i++)
gameAgnosticWeightsArray[i] *= weight();
setWeight(1.f);
}
}
@Override
public float maxAbsWeight()
{
float maxWeight = Math.abs(weight());
for (final float f : gameAgnosticWeightsArray)
maxWeight = Math.max(maxWeight, Math.abs(f));
return maxWeight;
}
//-------------------------------------------------------------------------
@Override
public String description()
{
return "Intercept terms per player, for heuristic-based value functions.";
}
@Override
public String toEnglishString(final Context context, final int playerIndex)
{
return "";
}
//-------------------------------------------------------------------------
@Override
public float[] gameAgnosticWeightsArray() {
return gameAgnosticWeightsArray;
}
}
| 8,138 | 25.170418 | 133 | java |
Ludii | Ludii-master/Core/src/metadata/ai/heuristics/terms/LineCompletionHeuristic.java | package metadata.ai.heuristics.terms;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import annotations.Name;
import annotations.Opt;
import game.Game;
import game.equipment.component.Component;
import game.functions.booleans.is.line.IsLine;
import game.functions.ints.IntFunction;
import game.rules.phase.Phase;
import game.types.board.SiteType;
import game.util.directions.AbsoluteDirection;
import game.util.graph.GraphElement;
import game.util.graph.Radial;
import gnu.trove.list.array.TFloatArrayList;
import main.Constants;
import main.ReflectionUtils;
import main.collections.FVector;
import main.collections.ListUtils;
import metadata.ai.heuristics.HeuristicUtil;
import metadata.ai.heuristics.transformations.HeuristicTransformation;
import other.Ludeme;
import other.context.Context;
import other.location.Location;
import other.state.container.ContainerState;
import other.state.owned.Owned;
import other.topology.TopologyElement;
import other.trial.Trial;
/**
* Defines a heuristic state value based on a player's potential to
* complete lines up to a given target length.
* This mostly follows the description of the N-in-a-Row advisor as
* described on pages 82-84 of:
* ``Browne, C.B. (2009) Automatic generation and evaluation of recombination games.
* PhD thesis, Queensland University of Technology''.
*
* @author Dennis Soemers
*/
public class LineCompletionHeuristic extends HeuristicTerm
{
//-------------------------------------------------------------------------
/** If true, we want to automatically determine a default target length per game board */
private final boolean autoComputeTargetLength;
/** Our target length */
private int targetLength;
//-------------------------------------------------------------------------
/**
* Constructor
*
* @param transformation An optional transformation to be applied to any
* raw heuristic score outputs.
* @param weight The weight for this term in a linear combination of multiple terms.
* If not specified, a default weight of $1.0$ is used.
* @param targetLength The target length for line completions. If not specified,
* we automatically determine a target length based on properties of the game
* rules or board.
*
* @example (lineCompletionHeuristic targetLength:3)
*/
public LineCompletionHeuristic
(
@Name @Opt final HeuristicTransformation transformation,
@Name @Opt final Float weight,
@Name @Opt final Integer targetLength
)
{
super(transformation, weight);
if (targetLength == null)
{
autoComputeTargetLength = true;
}
else
{
autoComputeTargetLength = false;
this.targetLength = targetLength.intValue();
}
}
@Override
public HeuristicTerm copy()
{
return new LineCompletionHeuristic(this);
}
/**
* Copy constructor (private, so not visible to grammar)
* @param other
*/
private LineCompletionHeuristic(final LineCompletionHeuristic other)
{
super(other.transformation, Float.valueOf(other.weight));
autoComputeTargetLength = other.autoComputeTargetLength;
targetLength = other.targetLength;
}
//-------------------------------------------------------------------------
@Override
public float computeValue(final Context context, final int player, final float absWeightThreshold)
{
final Game game = context.game();
final Owned owned = context.state().owned();
final List<? extends Location>[] pieces = owned.positions(player);
final List<? extends TopologyElement> sites = game.graphPlayElements();
final boolean[] ignore = new boolean[sites.size()];
final SiteType siteType = game.board().defaultSite();
final TFloatArrayList lineValues = new TFloatArrayList();
for (final List<? extends Location> piecesList : pieces)
{
for (final Location piecePos : piecesList)
{
final int pieceSite = piecePos.site();
if (context.containerId()[pieceSite] > 0)
continue; // we only support the main board
final ContainerState state = context.state().containerStates()[0];
final List<Radial> radials = game.board().graph().trajectories().radials(piecePos.siteType(), pieceSite).distinctInDirection(AbsoluteDirection.Adjacent);
for (final Radial radial : radials)
{
final GraphElement[] path = radial.steps();
final List<Radial> opposites = radial.opposites();
final GraphElement[][] oppositePaths;
if (opposites != null)
{
oppositePaths = new GraphElement[opposites.size()][];
for (int i = 0; i < opposites.size(); ++i)
{
oppositePaths[i] = opposites.get(i).steps();
}
}
else
{
oppositePaths = new GraphElement[1][0];
}
// Index 0 is the "current" location; we already know
// we have a piece there, so can skip checking that
// and directly add it to our counts
final int indexBound = Math.min(path.length, targetLength + 1);
final boolean[] endPathsBlocked = new boolean[targetLength];
final int[] potentialLineLengths = new int[targetLength];
final int[] realPieces = new int[targetLength];
// Fill all the counts up starting with 1, since we know
// there's at least 1 piece (the one we're starting from)
Arrays.fill(potentialLineLengths, 1);
Arrays.fill(realPieces, 1);
for (int indexPath = 1; indexPath < indexBound; ++indexPath)
{
final int site = path[indexPath].id();
final int who = state.who(site, siteType);
if (ignore[site])
{
// We've already been here, skip this
break;
}
else if (who != Constants.NOBODY && who != player)
{
// An enemy piece
assert (endPathsBlocked[targetLength - indexPath] == false);
endPathsBlocked[targetLength - indexPath] = true;
break;
}
else
{
for (int j = 0; j < targetLength - indexPath; ++j)
{
potentialLineLengths[j] += 1;
if (who == player)
realPieces[j] += 1;
}
}
}
for (final GraphElement[] oppositePath : oppositePaths)
{
// At best there can be targetLength lines for this radial + opposite combo;
// There's:
// - one line starting in piece pos and following direction
// - one line with one piece in opposite direction, and rest in direction
// - one line with two pieces in opposite direction, and rest in direction
// - etc.
final boolean[] endOppositePathsBlocked = new boolean[targetLength];
final boolean[] endPathsBlockedInner = Arrays.copyOf(endPathsBlocked, targetLength);
final int[] potentialLineLengthsInner = Arrays.copyOf(potentialLineLengths, targetLength);
final int[] realPiecesInner = Arrays.copyOf(realPieces, targetLength);
// Now the same thing, but in opposite radial
final int oppositeIndexBound = Math.min(oppositePath.length, targetLength + 1);
for (int indexPath = 1; indexPath < oppositeIndexBound; ++indexPath)
{
final int site = oppositePath[indexPath].id();
final int who = state.who(site, siteType);
if (ignore[site])
{
// We've already been here, skip this
break;
}
else if (who != Constants.NOBODY && who != player)
{
// An enemy piece
assert (endOppositePathsBlocked[indexPath - 1] == false);
endOppositePathsBlocked[indexPath - 1] = true;
break;
}
else
{
for (int j = indexPath; j < targetLength; ++j)
{
potentialLineLengthsInner[j] += 1;
if (who == player)
realPiecesInner[j] += 1;
}
}
}
// Compute values for all potential lines along this radial
for (int j = 0; j < potentialLineLengthsInner.length; ++j)
{
if (potentialLineLengthsInner[j] == targetLength)
{
// This is a potential line
float value = (float) realPiecesInner[j] / (float) potentialLineLengthsInner[j];
if (endPathsBlockedInner[j])
value *= 0.5f;
if (endOppositePathsBlocked[j])
value *= 0.5f;
lineValues.add(value);
}
}
}
}
// From now on we should ignore any lines including this piece;
// we've already counted all of them!
ignore[pieceSite] = true;
}
}
// Union of probabilities takes way too long to compute, so we just
// take average of the top 2 line values
final int argMax = ListUtils.argMax(lineValues);
final float maxVal = lineValues.getQuick(argMax);
lineValues.setQuick(argMax, -1.f);
final int secondArgMax = ListUtils.argMax(lineValues);
final float secondMaxVal = lineValues.getQuick(secondArgMax);
return maxVal + secondMaxVal / 2.f;
// compute "union of probabilities" from all line values
//return MathRoutines.unionOfProbabilities(lineValues);
}
@Override
public FVector computeStateFeatureVector(final Context context, final int player)
{
final FVector featureVector = new FVector(1);
featureVector.set(0, computeValue(context, player, -1.f));
return featureVector;
}
@Override
public FVector paramsVector()
{
return null;
}
@Override
public void init(final Game game)
{
if (autoComputeTargetLength)
{
// We need to compute target length for this game automatically
final List<IsLine> lineLudemes = new ArrayList<IsLine>();
if (game.rules().end() != null)
collectLineLudemes(lineLudemes, game.rules().end(), new HashMap<Object, Set<String>>());
for (final Phase phase : game.rules().phases())
{
if (phase != null && phase.end() != null)
collectLineLudemes(lineLudemes, phase.end(), new HashMap<Object, Set<String>>());
}
int maxTargetLength = 2; // anything less than 2 makes no sense
if (lineLudemes.isEmpty())
{
// // we'll take the longest distance of any single site to the
// // centre region (or 2 if that's bigger)
// final Topology graph = game.board().topology();
// final SiteType siteType = game.board().defaultSite();
// final int[] distancesToCentre = graph.distancesToCentre(siteType);
//
// if (distancesToCentre != null)
// {
// for (final int dist : distancesToCentre)
// {
// maxTargetLength = Math.max(maxTargetLength, dist);
// }
// }
// else
// {
// // Centres don't exist, instead we'll just pick a large number
// maxTargetLength = 15;
// }
// We'll just pick 3 (nice number, but also low, so relatively cheap)
maxTargetLength = 3;
}
else
{
final Context dummyContext = new Context(game, new Trial(game));
for (final IsLine line : lineLudemes)
{
maxTargetLength = Math.max(maxTargetLength, line.length().eval(dummyContext));
}
}
targetLength = maxTargetLength;
}
}
//-------------------------------------------------------------------------
/**
* @param game
* @return True if heuristic of this type could be applicable to given game
*/
public static boolean isApplicableToGame(final Game game)
{
if (game.isEdgeGame())
return false;
final Component[] components = game.equipment().components();
if (components.length <= 1)
return false;
return true;
}
/**
* @param game
* @return True if the heuristic of this type is sensible for the given game
* (must be applicable, but even some applicable heuristics may be considered
* to be not sensible).
*/
public static boolean isSensibleForGame(final Game game)
{
return isApplicableToGame(game);
}
@Override
public boolean isApplicable(final Game game)
{
return isApplicableToGame(game);
}
//-------------------------------------------------------------------------
/**
* Helper method to recursively collect all (line x) ludemes in the subtree
* rooted in a given ludeme.
*
* @param outList
* @param ludeme
* @param visited
*/
private static void collectLineLudemes
(
final List<IsLine> outList,
final Ludeme ludeme,
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))
{
if (IsLine.class.isAssignableFrom(valueClass))
{
final IsLine line = (IsLine) value;
final IntFunction length = line.length();
if (length.isStatic())
outList.add(line);
}
collectLineLudemes(outList, (Ludeme) value, 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))
{
if (IsLine.class.isAssignableFrom(elementClass))
{
final IsLine line = (IsLine) element;
final IntFunction length = line.length();
if (length.isStatic())
outList.add(line);
}
collectLineLudemes(outList, (Ludeme) element, 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))
{
if (IsLine.class.isAssignableFrom(elementClass))
{
final IsLine line = (IsLine) element;
final IntFunction length = line.length();
if (length.isStatic())
outList.add(line);
}
collectLineLudemes(outList, (Ludeme) element, visited);
}
}
}
}
}
}
}
catch (final IllegalArgumentException | IllegalAccessException e)
{
e.printStackTrace();
}
}
//-------------------------------------------------------------------------
@Override
public String toString()
{
final StringBuilder sb = new StringBuilder();
sb.append("(lineCompletionHeuristic");
if (transformation != null)
sb.append(" transformation:" + transformation.toString());
if (weight != 1.f)
sb.append(" weight:" + weight);
if (!autoComputeTargetLength)
sb.append(" targetLength:" + targetLength);
sb.append(")");
return sb.toString();
}
//-------------------------------------------------------------------------
@Override
public String toStringThresholded(final float threshold)
{
boolean shouldPrint = false;
if (Math.abs(weight) >= threshold)
{
// No manually specified weights, so they will all default to 1.0,
// and we have a large enough term-wide weight
shouldPrint = true;
}
if (shouldPrint)
{
final StringBuilder sb = new StringBuilder();
sb.append("(lineCompletionHeuristic");
if (transformation != null)
sb.append(" transformation:" + transformation.toString());
if (weight != 1.f)
sb.append(" weight:" + weight);
if (!autoComputeTargetLength)
sb.append(" targetLength:" + targetLength);
sb.append(")");
return sb.toString();
}
else
{
return null;
}
}
//-------------------------------------------------------------------------
@Override
public String description()
{
return "Measure of potential to complete line(s) of owned pieces.";
}
@Override
public String toEnglishString(final Context context, final int playerIndex)
{
final StringBuilder sb = new StringBuilder();
if (weight > 0)
sb.append("You should try to make piece line(s) of length " + targetLength);
else
sb.append("You should try to avoid making piece line(s) of length " + targetLength);
sb.append(" (" + HeuristicUtil.convertWeightToString(weight) + ")\n");
return sb.toString();
}
//-------------------------------------------------------------------------
}
| 17,024 | 27.613445 | 157 | java |
Ludii | Ludii-master/Core/src/metadata/ai/heuristics/terms/Material.java | package metadata.ai.heuristics.terms;
import java.util.Arrays;
import java.util.List;
import annotations.Name;
import annotations.Opt;
import game.Game;
import game.equipment.component.Component;
import game.equipment.container.Container;
import game.types.board.SiteType;
import main.Constants;
import main.StringRoutines;
import main.collections.FVector;
import metadata.ai.heuristics.HeuristicUtil;
import metadata.ai.heuristics.transformations.HeuristicTransformation;
import metadata.ai.misc.Pair;
import other.context.Context;
import other.location.Location;
import other.state.owned.Owned;
/**
* Defines a heuristic term based on the material that a player has on
* the board and in their hand.
*
* @author Dennis Soemers
*/
public class Material extends HeuristicTerm
{
//-------------------------------------------------------------------------
/** Array of names specified for piece types */
private String[] pieceWeightNames;
/**
* Array of weights as specified in metadata. Will be used to initialise
* a weight vector for a specific game when init() is called.
*/
private float[] gameAgnosticWeightsArray;
/** If true, only count pieces on the main board (i.e., container 0) */
private final boolean boardOnly;
/** Vector with weights for every piece type */
private FVector pieceWeights = null;
/** Indices of hand containers per player */
private int[] handIndices = null;
/** Does our current game have more than 1 container? */
private boolean gameHasMultipleContainers = false;
//-------------------------------------------------------------------------
/**
* Constructor
*
* @param transformation An optional transformation to be applied to any
* raw heuristic score outputs.
* @param weight The weight for this term in a linear combination of multiple terms.
* If not specified, a default weight of $1.0$ is used.
* @param pieceWeights Weights for different piece types. If no piece weights are
* specified at all, all piece types are given an equal weight of $1.0$. If piece
* weights are only specified for some piece types, all other piece types get a
* weight of $0$.
* @param boardOnly If true, only pieces that are on the game's main board are counted,
* and pieces that are, for instance, in players' hands are excluded. False by default.
*
* @example (material pieceWeights:{ (pair "Pawn" 1.0) (pair "Bishop" 3.0) })
*/
public Material
(
@Name @Opt final HeuristicTransformation transformation,
@Name @Opt final Float weight,
@Name @Opt final Pair[] pieceWeights,
@Name @Opt final Boolean boardOnly
)
{
super(transformation, weight);
if (pieceWeights == null)
{
// We want a weight of 1.0 for everything
pieceWeightNames = new String[]{""};
gameAgnosticWeightsArray = new float[]{1.f};
}
else
{
pieceWeightNames = new String[pieceWeights.length];
gameAgnosticWeightsArray = new float[pieceWeights.length];
for (int i = 0; i < pieceWeights.length; ++i)
{
pieceWeightNames[i] = pieceWeights[i].key();
gameAgnosticWeightsArray[i] = pieceWeights[i].floatVal();
}
}
this.boardOnly = (boardOnly == null) ? false : boardOnly.booleanValue();
}
@Override
public HeuristicTerm copy()
{
return new Material(this);
}
/**
* Copy constructor (private, so not visible to grammar)
* @param other
*/
private Material(final Material other)
{
super(other.transformation, Float.valueOf(other.weight));
pieceWeightNames = Arrays.copyOf(other.pieceWeightNames, other.pieceWeightNames.length);
gameAgnosticWeightsArray = Arrays.copyOf(other.gameAgnosticWeightsArray, other.gameAgnosticWeightsArray.length);
boardOnly = other.boardOnly;
}
//-------------------------------------------------------------------------
@Override
public float computeValue(final Context context, final int player, final float absWeightThreshold)
{
final Owned owned = context.state().owned();
final List<? extends Location>[] pieces = owned.positions(player);
float value = 0.f;
if (!boardOnly || !gameHasMultipleContainers)
{
for (int i = 0; i < pieces.length; ++i)
{
if (pieces[i].isEmpty())
continue;
final float pieceWeight = pieceWeights.get(owned.reverseMap(player, i));
if (Math.abs(pieceWeight) >= absWeightThreshold)
value += pieceWeight * pieces[i].size();
}
if (handIndices != null)
{
final List<? extends Location>[] neutralPieces = owned.positions(0);
for (int i = 0; i < neutralPieces.length; ++i)
{
if (neutralPieces[i].isEmpty())
continue;
final float pieceWeight = pieceWeights.get(owned.reverseMap(0, i));
if (Math.abs(pieceWeight) >= absWeightThreshold)
{
for (final Location pos : neutralPieces[i])
{
final int site = pos.site();
if (pos.siteType() == SiteType.Cell && context.containerId()[site] == handIndices[player])
value += pieceWeight * context.state().containerStates()[handIndices[player]].countCell(site);
}
}
}
}
}
else
{
for (int i = 0; i < pieces.length; ++i)
{
if (pieces[i].isEmpty())
continue;
final float pieceWeight = pieceWeights.get(owned.reverseMap(player, i));
if (Math.abs(pieceWeight) >= absWeightThreshold)
{
for (final Location loc : pieces[i])
{
if (loc.siteType() != SiteType.Cell || context.containerId()[loc.site()] == 0)
value += pieceWeight;
}
}
}
}
return value;
}
@Override
public FVector computeStateFeatureVector(final Context context, final int player)
{
final FVector featureVector = new FVector(pieceWeights.dim());
final Owned owned = context.state().owned();
final List<? extends Location>[] pieces = owned.positions(player);
if (!boardOnly || !gameHasMultipleContainers)
{
for (int i = 0; i < pieces.length; ++i)
{
final int compIdx = owned.reverseMap(player, i);
featureVector.addToEntry(compIdx, pieces[i].size());
}
if (handIndices != null)
{
final List<? extends Location>[] neutralPieces = owned.positions(0);
for (int i = 0; i < neutralPieces.length; ++i)
{
final int compIdx = owned.reverseMap(player, i);
for (final Location pos : neutralPieces[i])
{
final int site = pos.site();
if (pos.siteType() == SiteType.Cell && context.containerId()[site] == handIndices[player])
featureVector.addToEntry(compIdx, context.state().containerStates()[handIndices[player]].countCell(site));
}
}
}
}
else
{
for (int i = 0; i < pieces.length; ++i)
{
final int compIdx = owned.reverseMap(player, i);
for (final Location loc : pieces[i])
{
if (loc.siteType() != SiteType.Cell || context.containerId()[loc.site()] == 0)
featureVector.addToEntry(compIdx, 1.f);
}
}
}
return featureVector;
}
@Override
public FVector paramsVector()
{
return pieceWeights;
}
@Override
public void init(final Game game)
{
// Compute vector of piece weights
pieceWeights = HeuristicTerm.pieceWeightsVector(game, pieceWeightNames, gameAgnosticWeightsArray);
// Precompute hand indices for this game
computeHandIndices(game);
gameHasMultipleContainers = (game.equipment().containers().length > 1);
}
@Override
public int updateParams(final Game game, final FVector newParams, final int startIdx)
{
final int retVal = super.updateParams(game, newParams, startIdx);
// Need to update the array of weights we were passed in constructor
// in case we decide to write ourselves to a file
final Object[] returnArrays = updateGameAgnosticWeights(game, pieceWeights, pieceWeightNames, gameAgnosticWeightsArray);
pieceWeightNames = (String[]) returnArrays[0];
gameAgnosticWeightsArray = (float[]) returnArrays[1];
return retVal;
}
//-------------------------------------------------------------------------
/**
* @param game
*/
private void computeHandIndices(final Game game)
{
boolean foundHands = false;
final int[] handContainerIndices = new int[game.players().count() + 1];
for (final Container c : game.equipment().containers())
{
if (c instanceof game.equipment.container.other.Hand)
{
final int owner = ((game.equipment.container.other.Hand)c).owner();
if (owner > 0 && owner < handContainerIndices.length && handContainerIndices[owner] == 0)
{
foundHands = true;
handContainerIndices[owner] = c.index();
}
}
}
if (!foundHands)
handIndices = null;
else
handIndices = handContainerIndices;
}
//-------------------------------------------------------------------------
/**
* @param game
* @return True if heuristic of this type could be applicable to given game
*/
public static boolean isApplicableToGame(final Game game)
{
final Component[] components = game.equipment().components();
if (components.length <= 1)
return false;
return true;
}
/**
* @param game
* @return True if the heuristic of this type is sensible for the given game
* (must be applicable, but even some applicable heuristics may be considered
* to be not sensible).
*/
public static boolean isSensibleForGame(final Game game)
{
return isApplicableToGame(game);
}
@Override
public boolean isApplicable(final Game game)
{
return isApplicableToGame(game);
}
//-------------------------------------------------------------------------
@Override
public String toString()
{
final StringBuilder sb = new StringBuilder();
sb.append("(material");
if (transformation != null)
sb.append(" transformation:" + transformation.toString());
if (weight != 1.f)
sb.append(" weight:" + weight);
if (pieceWeightNames.length > 1 || (pieceWeightNames.length == 1 && pieceWeightNames[0].length() > 0))
{
sb.append(" pieceWeights:{\n");
boolean allZeros = true;
for (int i = 0; i < pieceWeightNames.length; ++i)
{
if (gameAgnosticWeightsArray[i] != 0.f)
{
break;
}
}
for (int i = 0; i < pieceWeightNames.length; ++i)
{
if (allZeros || (gameAgnosticWeightsArray[i] != 0.f))
sb.append(" (pair " + StringRoutines.quote(pieceWeightNames[i]) + " " + gameAgnosticWeightsArray[i] + ")\n");
}
sb.append(" }");
if (boardOnly)
sb.append("\n boardOnly:True\n");
}
else if (boardOnly)
{
sb.append(" boardOnly:True");
}
sb.append(")");
return sb.toString();
}
//-------------------------------------------------------------------------
@Override
public String toStringThresholded(final float threshold)
{
boolean shouldPrint = false;
boolean haveRelevantPieces = false;
final StringBuilder pieceWeightsSb = new StringBuilder();
if (pieceWeightNames.length > 1 || (pieceWeightNames.length == 1 && pieceWeightNames[0].length() > 0))
{
for (int i = 0; i < pieceWeightNames.length; ++i)
{
if (Math.abs(weight * gameAgnosticWeightsArray[i]) >= threshold)
{
pieceWeightsSb.append(" (pair " + StringRoutines.quote(pieceWeightNames[i]) + " " + gameAgnosticWeightsArray[i] + ")\n");
haveRelevantPieces = true;
shouldPrint = true;
}
}
}
else if (Math.abs(weight) >= threshold)
{
// No manually specified weights, so they will all default to 1.0,
// and we have a large enough term-wide weight
shouldPrint = true;
}
if (shouldPrint)
{
final StringBuilder sb = new StringBuilder();
sb.append("(material");
if (transformation != null)
sb.append(" transformation:" + transformation.toString());
if (weight != 1.f)
sb.append(" weight:" + weight);
if (haveRelevantPieces)
{
sb.append(" pieceWeights:{\n");
sb.append(pieceWeightsSb);
sb.append(" }");
if (boardOnly)
sb.append("\n boardOnly:True\n");
}
else if (boardOnly)
{
sb.append(" boardOnly:True");
}
sb.append(")");
return sb.toString();
}
else
{
return null;
}
}
//-------------------------------------------------------------------------
@Override
public void merge(final HeuristicTerm term)
{
final Material castTerm = (Material) term;
for (int i = 0; i < pieceWeightNames.length; i++)
for (int j = 0; j < castTerm.pieceWeightNames.length; j++)
if (pieceWeightNames[i].equals(castTerm.pieceWeightNames[j]))
gameAgnosticWeightsArray[i] = gameAgnosticWeightsArray[i] + castTerm.gameAgnosticWeightsArray[j] * (castTerm.weight()/weight());
}
@Override
public void simplify()
{
if (Math.abs(weight() - 1.f) > Constants.EPSILON)
{
for (int i = 0; i < gameAgnosticWeightsArray.length; i++)
gameAgnosticWeightsArray[i] *= weight();
setWeight(1.f);
}
}
@Override
public float maxAbsWeight()
{
float maxWeight = Math.abs(weight());
for (final float f : gameAgnosticWeightsArray)
maxWeight = Math.max(maxWeight, Math.abs(f));
return maxWeight;
}
//-------------------------------------------------------------------------
@Override
public String description()
{
return "Sum of owned pieces.";
}
@Override
public String toEnglishString(final Context context, final int playerIndex)
{
final StringBuilder sb = new StringBuilder();
final String extraString = boardOnly ? " on the board" : "";
if (pieceWeightNames.length > 1 || (pieceWeightNames.length == 1 && pieceWeightNames[0].length() > 0))
{
for (int i = 0; i < pieceWeightNames.length; ++i)
{
if (gameAgnosticWeightsArray[i] != 0.f)
{
final String pieceTrailingNumbers = StringRoutines.getTrailingNumbers(pieceWeightNames[i]);
if (pieceTrailingNumbers.length() == 0 || playerIndex < 0 || Integer.valueOf(pieceTrailingNumbers).intValue() == playerIndex)
{
if (gameAgnosticWeightsArray[i] > 0)
sb.append("You should try to maximise the number of " + StringRoutines.removeTrailingNumbers(pieceWeightNames[i]) + "(s) you control");
else
sb.append("You should try to minimise the number of " + StringRoutines.removeTrailingNumbers(pieceWeightNames[i]) + "(s) you control");
sb.append(extraString + " (" + HeuristicUtil.convertWeightToString(gameAgnosticWeightsArray[i]) + ")\n");
}
}
}
}
else
{
if (weight > 0)
sb.append("You should try to maximise the number of piece(s) you control");
else
sb.append("You should try to maximise the number of piece(s) you control");
sb.append(extraString + " (" + HeuristicUtil.convertWeightToString(weight) + ")\n");
}
return sb.toString();
}
//-------------------------------------------------------------------------
@Override
public float[] gameAgnosticWeightsArray() {
return gameAgnosticWeightsArray;
}
@Override
public FVector pieceWeights() {
return pieceWeights;
}
}
| 14,902 | 26.9606 | 142 | java |
Ludii | Ludii-master/Core/src/metadata/ai/heuristics/terms/MobilityAdvanced.java | package metadata.ai.heuristics.terms;
import annotations.Name;
import annotations.Opt;
import game.Game;
import main.collections.FVector;
import metadata.ai.heuristics.HeuristicUtil;
import metadata.ai.heuristics.transformations.HeuristicTransformation;
import other.context.Context;
import other.context.TempContext;
/**
* Defines a more advanced Mobility heuristic that attempts to also compute
* non-zero mobility values for players other than the current mover (by
* modifying the game state temporarily such that it thinks the current mover
* is any other player).
*
* @author Dennis Soemers
*/
public class MobilityAdvanced extends HeuristicTerm
{
//-------------------------------------------------------------------------
/**
* Constructor
*
* @param transformation An optional transformation to be applied to any
* raw heuristic score outputs.
* @param weight The weight for this term in a linear combination of multiple terms.
* If not specified, a default weight of $1.0$ is used.
*
* @example (mobilityAdvanced weight:0.5)
*/
public MobilityAdvanced
(
@Name @Opt final HeuristicTransformation transformation,
@Name @Opt final Float weight
)
{
super(transformation, weight);
}
@Override
public MobilityAdvanced copy()
{
return new MobilityAdvanced(this);
}
/**
* Copy constructor (private, so not visible to grammar)
* @param other
*/
private MobilityAdvanced(final MobilityAdvanced other)
{
super(other.transformation, Float.valueOf(other.weight));
}
//-------------------------------------------------------------------------
@Override
public float computeValue(final Context context, final int player, final float absWeightThreshold)
{
if (context.state().mover() == player)
{
return context.game().moves(context).count();
}
else
{
final TempContext copy = new TempContext(context);
copy.state().setPrev(context.state().mover());
copy.state().setMover(player);
copy.trial().clearLegalMoves();
return copy.game().moves(copy).count();
}
}
@Override
public FVector computeStateFeatureVector(final Context context, final int player)
{
final FVector featureVector = new FVector(1);
featureVector.set(0, computeValue(context, player, -1.f));
return featureVector;
}
@Override
public FVector paramsVector()
{
return null;
}
//-------------------------------------------------------------------------
/**
* @param game
* @return True if heuristic of this type could be applicable to given game
*/
public static boolean isApplicableToGame(final Game game)
{
return game.isAlternatingMoveGame();
}
/**
* @param game
* @return True if the heuristic of this type is sensible for the given game
* (must be applicable, but even some applicable heuristics may be considered
* to be not sensible).
*/
public static boolean isSensibleForGame(final Game game)
{
return isApplicableToGame(game);
}
@Override
public boolean isApplicable(final Game game)
{
return isApplicableToGame(game);
}
//-------------------------------------------------------------------------
@Override
public String toString()
{
final StringBuilder sb = new StringBuilder();
sb.append("(mobilityAdvanced");
if (transformation != null)
sb.append(" transformation:" + transformation.toString());
if (weight != 1.f)
sb.append(" weight:" + weight);
sb.append(")");
return sb.toString();
}
//-------------------------------------------------------------------------
@Override
public String toStringThresholded(final float threshold)
{
boolean shouldPrint = false;
if (Math.abs(weight) >= threshold)
{
// No manually specified weights, so they will all default to 1.0,
// and we have a large enough term-wide weight
shouldPrint = true;
}
if (shouldPrint)
{
final StringBuilder sb = new StringBuilder();
sb.append("(mobilityAdvanced");
if (transformation != null)
sb.append(" transformation:" + transformation.toString());
if (weight != 1.f)
sb.append(" weight:" + weight);
sb.append(")");
return sb.toString();
}
else
{
return null;
}
}
@Override
public String description()
{
return "Number of legal moves.";
}
//-------------------------------------------------------------------------
@Override
public String toEnglishString(final Context context, final int playerIndex)
{
final StringBuilder sb = new StringBuilder();
if (weight > 0)
sb.append("You should try to maximise the number of moves you can make");
else
sb.append("You should try to minimise the number of moves you can make");
sb.append(" (" + HeuristicUtil.convertWeightToString(weight) + ")\n");
return sb.toString();
}
//-------------------------------------------------------------------------
}
| 4,859 | 23.795918 | 99 | java |
Ludii | Ludii-master/Core/src/metadata/ai/heuristics/terms/MobilitySimple.java | package metadata.ai.heuristics.terms;
import annotations.Name;
import annotations.Opt;
import game.Game;
import main.collections.FVector;
import metadata.ai.heuristics.HeuristicUtil;
import metadata.ai.heuristics.transformations.HeuristicTransformation;
import other.context.Context;
/**
* Defines a simple heuristic term that multiplies its weight by the number
* of moves that a player has in a current game state.
*
* @remarks Always produces a score of $0$ for players who are not the current mover.
*
* @author Dennis Soemers
*/
public class MobilitySimple extends HeuristicTerm
{
//-------------------------------------------------------------------------
/**
* Constructor
*
* @param transformation An optional transformation to be applied to any
* raw heuristic score outputs.
* @param weight The weight for this term in a linear combination of multiple terms.
* If not specified, a default weight of $1.0$ is used.
*
* @example (mobilitySimple weight:0.5)
*/
public MobilitySimple
(
@Name @Opt final HeuristicTransformation transformation,
@Name @Opt final Float weight
)
{
super(transformation, weight);
}
@Override
public MobilitySimple copy()
{
return new MobilitySimple(this);
}
/**
* Copy constructor (private, so not visible to grammar)
* @param other
*/
private MobilitySimple(final MobilitySimple other)
{
super(other.transformation, Float.valueOf(other.weight));
}
//-------------------------------------------------------------------------
@Override
public float computeValue(final Context context, final int player, final float absWeightThreshold)
{
if (context.state().mover() == player)
return context.game().moves(context).count();
else
return 0.f;
}
@Override
public FVector computeStateFeatureVector(final Context context, final int player)
{
final FVector featureVector = new FVector(1);
featureVector.set(0, computeValue(context, player, -1.f));
return featureVector;
}
@Override
public FVector paramsVector()
{
return null;
}
//-------------------------------------------------------------------------
/**
* @param game
* @return True if heuristic of this type could be applicable to given game
*/
public static boolean isApplicableToGame(final Game game)
{
return game.isAlternatingMoveGame();
}
/**
* @param game
* @return True if the heuristic of this type is sensible for the given game
* (must be applicable, but even some applicable heuristics may be considered
* to be not sensible).
*/
public static boolean isSensibleForGame(final Game game)
{
return isApplicableToGame(game);
}
@Override
public boolean isApplicable(final Game game)
{
return isApplicableToGame(game);
}
//-------------------------------------------------------------------------
@Override
public String toString()
{
final StringBuilder sb = new StringBuilder();
sb.append("(mobilitySimple");
if (transformation != null)
sb.append(" transformation:" + transformation.toString());
if (weight != 1.f)
sb.append(" weight:" + weight);
sb.append(")");
return sb.toString();
}
//-------------------------------------------------------------------------
@Override
public String toStringThresholded(final float threshold)
{
boolean shouldPrint = false;
if (Math.abs(weight) >= threshold)
{
// No manually specified weights, so they will all default to 1.0,
// and we have a large enough term-wide weight
shouldPrint = true;
}
if (shouldPrint)
{
final StringBuilder sb = new StringBuilder();
sb.append("(mobilitySimple");
if (transformation != null)
sb.append(" transformation:" + transformation.toString());
if (weight != 1.f)
sb.append(" weight:" + weight);
sb.append(")");
return sb.toString();
}
else
{
return null;
}
}
@Override
public String description()
{
return "Number of legal moves.";
}
//-------------------------------------------------------------------------
@Override
public String toEnglishString(final Context context, final int playerIndex)
{
final StringBuilder sb = new StringBuilder();
if (weight > 0)
sb.append("You should try to maximise the number of moves you can make");
else
sb.append("You should try to minimise the number of moves you can make");
sb.append(" (" + HeuristicUtil.convertWeightToString(weight) + ")\n");
return sb.toString();
}
//-------------------------------------------------------------------------
}
| 4,560 | 23.390374 | 99 | java |
Ludii | Ludii-master/Core/src/metadata/ai/heuristics/terms/NullHeuristic.java | package metadata.ai.heuristics.terms;
import game.Game;
import main.collections.FVector;
import other.context.Context;
/**
* Defines a null heuristic term that always returns a value of 0.
*
* @author Dennis Soemers
*/
public class NullHeuristic extends HeuristicTerm
{
//-------------------------------------------------------------------------
/**
* Constructor
*
* @example (nullHeuristic)
*/
public NullHeuristic()
{
super(null, null);
}
@Override
public NullHeuristic copy()
{
return new NullHeuristic();
}
//-------------------------------------------------------------------------
@Override
public float computeValue(final Context context, final int player, final float absWeightThreshold)
{
return 0.f;
}
@Override
public FVector computeStateFeatureVector(final Context context, final int player)
{
final FVector featureVector = new FVector(1);
featureVector.set(0, computeValue(context, player, -1.f));
return featureVector;
}
@Override
public FVector paramsVector()
{
return null;
}
//-------------------------------------------------------------------------
/**
* @param game
* @return True if heuristic of this type could be applicable to given game
*/
public static boolean isApplicableToGame(final Game game)
{
return true;
}
/**
* @param game
* @return True if the heuristic of this type is sensible for the given game
* (must be applicable, but even some applicable heuristics may be considered
* to be not sensible).
*/
public static boolean isSensibleForGame(final Game game)
{
return isApplicableToGame(game);
}
@Override
public boolean isApplicable(final Game game)
{
return isApplicableToGame(game);
}
//-------------------------------------------------------------------------
@Override
public String toString()
{
return "(nullHeuristic)";
}
//-------------------------------------------------------------------------
@Override
public String toStringThresholded(final float threshold)
{
return null;
}
//-------------------------------------------------------------------------
@Override
public String description()
{
return "Null.";
}
@Override
public String toEnglishString(final Context context, final int playerIndex)
{
return "Null.";
}
//-------------------------------------------------------------------------
}
| 2,400 | 19.698276 | 99 | java |
Ludii | Ludii-master/Core/src/metadata/ai/heuristics/terms/OwnRegionsCount.java | package metadata.ai.heuristics.terms;
import annotations.Name;
import annotations.Opt;
import game.Game;
import game.equipment.other.Regions;
import gnu.trove.list.array.TIntArrayList;
import main.collections.FVector;
import metadata.ai.heuristics.HeuristicUtil;
import metadata.ai.heuristics.transformations.HeuristicTransformation;
import other.context.Context;
/**
* Defines a heuristic term based on the sum of all counts of sites
* in a player's owned regions.
*
* @author Dennis Soemers
*/
public class OwnRegionsCount extends HeuristicTerm
{
//-------------------------------------------------------------------------
/** Regions over which to sum up counts (per player) */
private int[][] regionIndices = null;
//-------------------------------------------------------------------------
/**
* Constructor
*
* @param transformation An optional transformation to be applied to any
* raw heuristic score outputs.
* @param weight The weight for this term in a linear combination of multiple terms.
* If not specified, a default weight of $1.0$ is used.
*
* @example (ownRegionsCount weight:1.0)
*/
public OwnRegionsCount
(
@Name @Opt final HeuristicTransformation transformation,
@Name @Opt final Float weight
)
{
super(transformation, weight);
}
@Override
public HeuristicTerm copy()
{
return new OwnRegionsCount(this);
}
/**
* Copy constructor (private, so not visible to grammar)
* @param other
*/
private OwnRegionsCount(final OwnRegionsCount other)
{
super(other.transformation, Float.valueOf(other.weight));
}
//-------------------------------------------------------------------------
@Override
public float computeValue(final Context context, final int player, final float absWeightThreshold)
{
if (regionIndices[player].length == 0)
return 0.f;
final Regions[] regions = context.game().equipment().regions();
int sumCounts = 0;
for (int i = 0; i < regionIndices[player].length; ++i)
{
final int regionIdx = regionIndices[player][i];
final Regions region = regions[regionIdx];
final int[] sites = region.eval(context);
for (final int site : sites)
{
sumCounts += context.containerState(0).count(site, context.game().equipment().containers()[0].defaultSite());
}
}
return sumCounts;
}
@Override
public FVector computeStateFeatureVector(final Context context, final int player)
{
final FVector featureVector = new FVector(1);
featureVector.set(0, computeValue(context, player, -1.f));
return featureVector;
}
@Override
public FVector paramsVector()
{
return null;
}
@Override
public void init(final Game game)
{
regionIndices = new int[game.players().count() + 1][];
for (int p = 1; p <= game.players().count(); ++p)
{
final TIntArrayList relevantIndices = new TIntArrayList();
for (int i = 0; i < game.equipment().regions().length; ++i)
{
final Regions region = game.equipment().regions()[i];
if (region.owner() == p)
{
final int[] distances = game.distancesToRegions()[i];
if (distances != null) // This means it's a static region
{
relevantIndices.add(i);
}
}
}
regionIndices[p] = relevantIndices.toArray();
}
}
//-------------------------------------------------------------------------
/**
* @param game
* @return True if heuristic of this type could be applicable to given game
*/
public static boolean isApplicableToGame(final Game game)
{
if (game.distancesToRegions() == null)
return false;
final Regions[] regions = game.equipment().regions();
if (regions.length == 1)
return false;
boolean foundOwnedRegion = false;
for (final Regions region : regions)
{
if (region.owner() > 0 && region.owner() <= game.players().count())
{
foundOwnedRegion = true;
break;
}
}
return foundOwnedRegion;
}
/**
* @param game
* @return True if the heuristic of this type is sensible for the given game
* (must be applicable, but even some applicable heuristics may be considered
* to be not sensible).
*/
public static boolean isSensibleForGame(final Game game)
{
return isApplicableToGame(game);
}
@Override
public boolean isApplicable(final Game game)
{
return isApplicableToGame(game);
}
//-------------------------------------------------------------------------
@Override
public String toString()
{
final StringBuilder sb = new StringBuilder();
sb.append("(ownRegionsCount");
if (transformation != null)
sb.append(" transformation:" + transformation.toString());
if (weight != 1.f)
sb.append(" weight:" + weight);
sb.append(")");
return sb.toString();
}
//-------------------------------------------------------------------------
@Override
public String toStringThresholded(final float threshold)
{
boolean shouldPrint = false;
if (Math.abs(weight) >= threshold)
{
// No manually specified weights, so they will all default to 1.0,
// and we have a large enough term-wide weight
shouldPrint = true;
}
if (shouldPrint)
{
final StringBuilder sb = new StringBuilder();
sb.append("(ownRegionsCount");
if (transformation != null)
sb.append(" transformation:" + transformation.toString());
if (weight != 1.f)
sb.append(" weight:" + weight);
sb.append(")");
return sb.toString();
}
else
{
return null;
}
}
//-------------------------------------------------------------------------
@Override
public String description()
{
return "Sum of (piece) counts in owned regions.";
}
@Override
public String toEnglishString(final Context context, final int playerIndex)
{
final StringBuilder sb = new StringBuilder();
if (weight > 0)
sb.append("You should try to maximise the number of pieces in the regions you own");
else
sb.append("You should try to minimise the number of pieces in the regions you own");
sb.append(" (" + HeuristicUtil.convertWeightToString(weight) + ")\n");
return sb.toString();
}
//-------------------------------------------------------------------------
}
| 6,177 | 23.322835 | 113 | java |
Ludii | Ludii-master/Core/src/metadata/ai/heuristics/terms/PlayerRegionsProximity.java | package metadata.ai.heuristics.terms;
import java.util.Arrays;
import java.util.List;
import annotations.Name;
import annotations.Opt;
import game.Game;
import game.equipment.other.Regions;
import gnu.trove.list.array.TIntArrayList;
import main.Constants;
import main.StringRoutines;
import main.collections.FVector;
import metadata.ai.heuristics.HeuristicUtil;
import metadata.ai.heuristics.transformations.HeuristicTransformation;
import metadata.ai.misc.Pair;
import other.context.Context;
import other.location.Location;
import other.state.owned.Owned;
/**
* Defines a heuristic term based on the proximity of pieces to the regions
* owned by a particular player.
*
* @author Dennis Soemers
*/
public class PlayerRegionsProximity extends HeuristicTerm
{
//-------------------------------------------------------------------------
/** Array of names specified for piece types. */
private String[] pieceWeightNames;
/**
* Array of weights as specified in metadata. Will be used to initialise
* a weight vector for a specific game when init() is called.
*/
private float[] gameAgnosticWeightsArray;
/** Vector with weights for every piece type */
private FVector pieceWeights = null;
/** The maximum distance that exists in our Centres distance table */
private int maxDistance = -1;
/** Player for which we use the regions */
private final int regionPlayer;
/** Regions across which to compute best proximity */
private int[] regionIndices = null;
//-------------------------------------------------------------------------
/**
* Constructor
*
* @param transformation An optional transformation to be applied to any
* raw heuristic score outputs.
* @param weight The weight for this term in a linear combination of multiple terms.
* If not specified, a default weight of $1.0$ is used.
* @param player The player whose owned regions we compute proximity to.
* @param pieceWeights Weights for different piece types. If no piece weights are
* specified at all, all piece types are given an equal weight of $1.0$. If piece
* weights are only specified for some piece types, all other piece types get a
* weight of $0$.
*
* @example (playerRegionsProximity player:2)
*/
public PlayerRegionsProximity
(
@Name @Opt final HeuristicTransformation transformation,
@Name @Opt final Float weight,
@Name final Integer player,
@Name @Opt final Pair[] pieceWeights
)
{
super(transformation, weight);
regionPlayer = player.intValue();
if (pieceWeights == null)
{
// We want a weight of 1.0 for everything
pieceWeightNames = new String[]{""};
gameAgnosticWeightsArray = new float[]{1.f};
}
else
{
pieceWeightNames = new String[pieceWeights.length];
gameAgnosticWeightsArray = new float[pieceWeights.length];
for (int i = 0; i < pieceWeights.length; ++i)
{
pieceWeightNames[i] = pieceWeights[i].key();
gameAgnosticWeightsArray[i] = pieceWeights[i].floatVal();
}
}
}
@Override
public HeuristicTerm copy()
{
return new PlayerRegionsProximity(this);
}
/**
* Copy constructor (private, so not visible to grammar)
* @param other
*/
private PlayerRegionsProximity(final PlayerRegionsProximity other)
{
super(other.transformation, Float.valueOf(other.weight));
pieceWeightNames = Arrays.copyOf(other.pieceWeightNames, other.pieceWeightNames.length);
gameAgnosticWeightsArray = Arrays.copyOf(other.gameAgnosticWeightsArray, other.gameAgnosticWeightsArray.length);
regionPlayer = other.regionPlayer;
}
//-------------------------------------------------------------------------
@Override
public float computeValue(final Context context, final int player, final float absWeightThreshold)
{
if (maxDistance == 0)
return 0.f;
final int[][] distances = context.game().distancesToRegions();
final Owned owned = context.state().owned();
final List<? extends Location>[] pieces = owned.positions(player);
float value = 0.f;
for (int i = 0; i < pieces.length; ++i)
{
if (pieces[i].isEmpty())
continue;
final float pieceWeight = pieceWeights.get(owned.reverseMap(player, i));
if (Math.abs(pieceWeight) >= absWeightThreshold)
{
for (final Location position : pieces[i])
{
final int site = position.site();
int minDist = Integer.MAX_VALUE;
for (final int regionIdx : regionIndices)
{
if (site >= distances[regionIdx].length) // Different container, skip it
continue;
final int dist = distances[regionIdx][site];
if (dist < minDist)
minDist = dist;
}
final float proximity = 1.f - ((float) minDist / maxDistance);
value += pieceWeight * proximity;
}
}
}
return value;
}
@Override
public FVector computeStateFeatureVector(final Context context, final int player)
{
final FVector featureVector = new FVector(pieceWeights.dim());
if (maxDistance != 0)
{
final int[][] distances = context.game().distancesToRegions();
final Owned owned = context.state().owned();
final List<? extends Location>[] pieces = owned.positions(player);
for (int i = 0; i < pieces.length; ++i)
{
if (pieces[i].isEmpty())
continue;
final int compIdx = owned.reverseMap(player, i);
for (final Location position : pieces[i])
{
final int site = position.site();
if (site >= distances.length) // Different container, skip it
continue;
int minDist = Integer.MAX_VALUE;
for (final int regionIdx : regionIndices)
{
final int dist = distances[regionIdx][site];
if (dist < minDist)
minDist = dist;
}
final float proximity = 1.f - ((float) minDist / maxDistance);
featureVector.addToEntry(compIdx, proximity);
}
}
}
return featureVector;
}
@Override
public FVector paramsVector()
{
return pieceWeights;
}
@Override
public void init(final Game game)
{
// Compute vector of piece weights
pieceWeights = HeuristicTerm.pieceWeightsVector(game, pieceWeightNames, gameAgnosticWeightsArray);
final TIntArrayList relevantIndices = new TIntArrayList();
int max = 0;
for (int i = 0; i < game.equipment().regions().length; ++i)
{
final Regions region = game.equipment().regions()[i];
if (region.owner() == regionPlayer)
{
final int[] distances = game.distancesToRegions()[i];
if (distances != null)
{
relevantIndices.add(i);
for (int j = 0; j < distances.length; ++j)
{
if (distances[j] > max)
max = distances[j];
}
}
}
}
maxDistance = max;
regionIndices = relevantIndices.toArray();
}
@Override
public int updateParams(final Game game, final FVector newParams, final int startIdx)
{
final int retVal = super.updateParams(game, newParams, startIdx);
// Need to update the array of weights we were passed in constructor
// in case we decide to write ourselves to a file
final Object[] returnArrays = updateGameAgnosticWeights(game, pieceWeights, pieceWeightNames, gameAgnosticWeightsArray);
pieceWeightNames = (String[]) returnArrays[0];
gameAgnosticWeightsArray = (float[]) returnArrays[1];
return retVal;
}
//-------------------------------------------------------------------------
/**
* @param game
* @return True if heuristic of this type could be applicable to given game
*/
public static boolean isApplicableToGame(final Game game)
{
if (game.distancesToRegions() == null)
return false;
if (game.equipment().components().length <= 1)
return false;
final Regions[] regions = game.equipment().regions();
if (regions.length == 0)
return false;
boolean foundOwnedRegion = false;
for (final Regions region : regions)
{
if (region.owner() > 0 && region.owner() <= game.players().count())
{
foundOwnedRegion = true;
break;
}
}
return foundOwnedRegion;
}
/**
* @param game
* @return True if the heuristic of this type is sensible for the given game
* (must be applicable, but even some applicable heuristics may be considered
* to be not sensible).
*/
public static boolean isSensibleForGame(final Game game)
{
return isApplicableToGame(game);
}
@Override
public boolean isApplicable(final Game game)
{
return isApplicableToGame(game);
}
//-------------------------------------------------------------------------
/**
* @return Player whose owned regions we compute proximity to
*/
public int regionPlayer()
{
return regionPlayer;
}
//-------------------------------------------------------------------------
@Override
public String toString()
{
final StringBuilder sb = new StringBuilder();
sb.append("(playerRegionsProximity");
if (transformation != null)
sb.append(" transformation:" + transformation.toString());
if (weight != 1.f)
sb.append(" weight:" + weight);
sb.append(" player:" + regionPlayer);
if (pieceWeightNames.length > 1 || (pieceWeightNames.length == 1 && pieceWeightNames[0].length() > 0))
{
sb.append(" pieceWeights:{\n");
for (int i = 0; i < pieceWeightNames.length; ++i)
{
if (gameAgnosticWeightsArray[i] != 0.f)
sb.append(" (pair " + StringRoutines.quote(pieceWeightNames[i]) + " " + gameAgnosticWeightsArray[i] + ")\n");
}
sb.append(" }");
}
sb.append(")");
return sb.toString();
}
//-------------------------------------------------------------------------
@Override
public String toStringThresholded(final float threshold)
{
boolean shouldPrint = false;
boolean haveRelevantPieces = false;
final StringBuilder pieceWeightsSb = new StringBuilder();
if (pieceWeightNames.length > 1 || (pieceWeightNames.length == 1 && pieceWeightNames[0].length() > 0))
{
for (int i = 0; i < pieceWeightNames.length; ++i)
{
if (Math.abs(weight * gameAgnosticWeightsArray[i]) >= threshold)
{
pieceWeightsSb.append(" (pair " + StringRoutines.quote(pieceWeightNames[i]) + " " + gameAgnosticWeightsArray[i] + ")\n");
haveRelevantPieces = true;
shouldPrint = true;
}
}
}
else if (Math.abs(weight) >= threshold)
{
// No manually specified weights, so they will all default to 1.0,
// and we have a large enough term-wide weight
shouldPrint = true;
}
if (shouldPrint)
{
final StringBuilder sb = new StringBuilder();
sb.append("(playerRegionsProximity");
if (transformation != null)
sb.append(" transformation:" + transformation.toString());
if (weight != 1.f)
sb.append(" weight:" + weight);
sb.append(" player:" + regionPlayer);
if (haveRelevantPieces)
{
sb.append(" pieceWeights:{\n");
sb.append(pieceWeightsSb);
sb.append(" }");
}
sb.append(")");
return sb.toString();
}
else
{
return null;
}
}
//-------------------------------------------------------------------------
@Override
public boolean canBeMerged(final HeuristicTerm term)
{
return (this.getClass().getName().equals(term.getClass().getName()) && regionPlayer() == ((PlayerRegionsProximity) term).regionPlayer());
}
@Override
public void merge(final HeuristicTerm term)
{
final PlayerRegionsProximity castTerm = (PlayerRegionsProximity) term;
for (int i = 0; i < pieceWeightNames.length; i++)
for (int j = 0; j < castTerm.pieceWeightNames.length; j++)
if (pieceWeightNames[i].equals(castTerm.pieceWeightNames[j]))
gameAgnosticWeightsArray[i] = gameAgnosticWeightsArray[i] + castTerm.gameAgnosticWeightsArray[j] * (castTerm.weight()/weight());
}
@Override
public void simplify()
{
if (Math.abs(weight() - 1.f) > Constants.EPSILON)
{
for (int i = 0; i < gameAgnosticWeightsArray.length; i++)
gameAgnosticWeightsArray[i] *= weight();
setWeight(1.f);
}
}
@Override
public float maxAbsWeight()
{
float maxWeight = Math.abs(weight());
for (final float f : gameAgnosticWeightsArray)
maxWeight = Math.max(maxWeight, Math.abs(f));
return maxWeight;
}
//-------------------------------------------------------------------------
@Override
public String description()
{
return "Sum of owned pieces, weighted by proximity to owned region(s).";
}
@Override
public String toEnglishString(final Context context, final int playerIndex)
{
final StringBuilder sb = new StringBuilder();
if (pieceWeightNames.length > 1 || (pieceWeightNames.length == 1 && pieceWeightNames[0].length() > 0))
{
for (int i = 0; i < pieceWeightNames.length; ++i)
{
if (gameAgnosticWeightsArray[i] != 0.f)
{
final String pieceTrailingNumbers = StringRoutines.getTrailingNumbers(pieceWeightNames[i]);
if (pieceTrailingNumbers.length() == 0 || playerIndex < 0 || Integer.valueOf(pieceTrailingNumbers).intValue() == playerIndex)
{
if (gameAgnosticWeightsArray[i] > 0)
sb.append("You should try to move your " + StringRoutines.removeTrailingNumbers(pieceWeightNames[i]) + "(s) towards the regions owned by Player " + regionPlayer);
else
sb.append("You should try to move your " + StringRoutines.removeTrailingNumbers(pieceWeightNames[i]) + "(s) away from the regions owned by Player " + regionPlayer);
sb.append(" (" + HeuristicUtil.convertWeightToString(gameAgnosticWeightsArray[i]) + ")\n");
}
}
}
}
else
{
if (weight > 0)
sb.append("You should try to move your piece(s) towards the regions owned by Player " + regionPlayer);
else
sb.append("You should try to move your piece(s) away from the regions owned by Player " + regionPlayer);
sb.append(" (" + HeuristicUtil.convertWeightToString(weight) + ")\n");
}
return sb.toString();
}
//-------------------------------------------------------------------------
@Override
public float[] gameAgnosticWeightsArray() {
return gameAgnosticWeightsArray;
}
@Override
public FVector pieceWeights() {
return pieceWeights;
}
}
| 14,040 | 26.69428 | 171 | java |
Ludii | Ludii-master/Core/src/metadata/ai/heuristics/terms/PlayerSiteMapCount.java | package metadata.ai.heuristics.terms;
import annotations.Name;
import annotations.Opt;
import game.Game;
import game.equipment.other.Map;
import main.Constants;
import main.collections.FVector;
import metadata.ai.heuristics.HeuristicUtil;
import metadata.ai.heuristics.transformations.HeuristicTransformation;
import other.context.Context;
/**
* Defines a heuristic term that adds up the counts in sites
* corresponding to values in Maps where Player IDs (e.g. $1$, $2$, etc.)
* may be used as keys.
*
* @author Dennis Soemers
*/
public class PlayerSiteMapCount extends HeuristicTerm
{
//-------------------------------------------------------------------------
/** Num sites in the main container in the game for which we initialise */
private int numSites = Constants.UNDEFINED;
//-------------------------------------------------------------------------
/**
* Constructor
*
* @param transformation An optional transformation to be applied to any
* raw heuristic score outputs.
* @param weight The weight for this term in a linear combination of multiple terms.
* If not specified, a default weight of $1.0$ is used.
*
* @example (playerSiteMapCount weight:1.0)
*/
public PlayerSiteMapCount
(
@Name @Opt final HeuristicTransformation transformation,
@Name @Opt final Float weight
)
{
super(transformation, weight);
}
@Override
public PlayerSiteMapCount copy()
{
return new PlayerSiteMapCount(this);
}
/**
* Copy constructor (private, so not visible to grammar)
* @param other
*/
private PlayerSiteMapCount(final PlayerSiteMapCount other)
{
super(other.transformation, Float.valueOf(other.weight));
}
//-------------------------------------------------------------------------
@Override
public float computeValue(final Context context, final int player, final float absWeightThreshold)
{
int sumCounts = 0;
final Map[] maps = context.game().equipment().maps();
for (final Map map : maps)
{
final int playerVal = map.to(player);
if (playerVal != Constants.OFF && playerVal != map.noEntryValue() && playerVal < numSites && playerVal >= 0)
{
sumCounts += context.containerState(0).count(playerVal, context.game().equipment().containers()[0].defaultSite());
}
}
return sumCounts;
}
@Override
public FVector computeStateFeatureVector(final Context context, final int player)
{
final FVector featureVector = new FVector(1);
featureVector.set(0, computeValue(context, player, -1.f));
return featureVector;
}
@Override
public FVector paramsVector()
{
return null;
}
//-------------------------------------------------------------------------
@Override
public void init(final Game game)
{
numSites = game.equipment().containers()[0].numSites();
}
/**
* @param game
* @return True if heuristic of this type could be applicable to given game
*/
public static boolean isApplicableToGame(final Game game)
{
final Map[] maps = game.equipment().maps();
if (maps.length == 0)
return false;
final int numPlayers = game.players().count();
boolean foundPlayerMapping = false;
final int numSites = game.equipment().containers()[0].numSites();
for (final Map map : maps)
{
for (int p = 1; p <= numPlayers; ++p)
{
final int val = map.to(p);
if (val != Constants.OFF && val != map.noEntryValue() && val < numSites)
{
foundPlayerMapping = true;
break;
}
}
if (foundPlayerMapping)
break;
}
return foundPlayerMapping;
}
/**
* @param game
* @return True if the heuristic of this type is sensible for the given game
* (must be applicable, but even some applicable heuristics may be considered
* to be not sensible).
*/
public static boolean isSensibleForGame(final Game game)
{
return isApplicableToGame(game);
}
@Override
public boolean isApplicable(final Game game)
{
return isApplicableToGame(game);
}
//-------------------------------------------------------------------------
@Override
public String toString()
{
final StringBuilder sb = new StringBuilder();
sb.append("(playerSiteMapCount");
if (transformation != null)
sb.append(" transformation:" + transformation.toString());
if (weight != 1.f)
sb.append(" weight:" + weight);
sb.append(")");
return sb.toString();
}
//-------------------------------------------------------------------------
@Override
public String toStringThresholded(final float threshold)
{
boolean shouldPrint = false;
if (Math.abs(weight) >= threshold)
{
// No manually specified weights, so they will all default to 1.0,
// and we have a large enough term-wide weight
shouldPrint = true;
}
if (shouldPrint)
{
final StringBuilder sb = new StringBuilder();
sb.append("(playerSiteMapCount");
if (transformation != null)
sb.append(" transformation:" + transformation.toString());
if (weight != 1.f)
sb.append(" weight:" + weight);
sb.append(")");
return sb.toString();
}
else
{
return null;
}
}
//-------------------------------------------------------------------------
@Override
public String description()
{
return "Sum of (piece) counts in sites mapped to by player ID.";
}
@Override
public String toEnglishString(final Context context, final int playerIndex)
{
final StringBuilder sb = new StringBuilder();
if (weight > 0)
sb.append("You should try to maximise the number of pieces in sites mapped to your player ID.");
else
sb.append("You should try to minimise the number of pieces in sites mapped to your player ID.");
sb.append(" (" + HeuristicUtil.convertWeightToString(weight) + ")\n");
return sb.toString();
}
//-------------------------------------------------------------------------
}
| 5,836 | 23.838298 | 118 | java |
Ludii | Ludii-master/Core/src/metadata/ai/heuristics/terms/RegionProximity.java | package metadata.ai.heuristics.terms;
import java.util.Arrays;
import java.util.List;
import annotations.Name;
import annotations.Opt;
import game.Game;
import game.equipment.other.Regions;
import main.Constants;
import main.StringRoutines;
import main.collections.FVector;
import metadata.ai.heuristics.HeuristicUtil;
import metadata.ai.heuristics.transformations.HeuristicTransformation;
import metadata.ai.misc.Pair;
import other.context.Context;
import other.location.Location;
import other.state.owned.Owned;
/**
* Defines a heuristic term based on the proximity of pieces to a particular region.
*
* @author Dennis Soemers
*/
public class RegionProximity extends HeuristicTerm
{
//-------------------------------------------------------------------------
/** Array of names specified for piece types */
private String[] pieceWeightNames;
/**
* Array of weights as specified in metadata. Will be used to initialise
* a weight vector for a specific game when init() is called.
*/
private float[] gameAgnosticWeightsArray;
/** Vector with weights for every piece type */
private FVector pieceWeights = null;
/** The maximum distance that exists in our Centres distance table */
private int maxDistance = -1;
/** Region for which to compute proximity */
private final int region;
//-------------------------------------------------------------------------
/**
* Constructor
*
* @param transformation An optional transformation to be applied to any
* raw heuristic score outputs.
* @param weight The weight for this term in a linear combination of multiple terms.
* If not specified, a default weight of $1.0$ is used.
* @param region Index of the region to which we wish to compute proximity.
* @param pieceWeights Weights for different piece types. If no piece weights are
* specified at all, all piece types are given an equal weight of $1.0$. If piece
* weights are only specified for some piece types, all other piece types get a
* weight of $0$.
*
* @example (regionProximity weight:-1.0 region:0)
*/
public RegionProximity
(
@Name @Opt final HeuristicTransformation transformation,
@Name @Opt final Float weight,
@Name final Integer region,
@Name @Opt final Pair[] pieceWeights
)
{
super(transformation, weight);
this.region = region.intValue();
if (pieceWeights == null)
{
// We want a weight of 1.0 for everything
pieceWeightNames = new String[]{""};
gameAgnosticWeightsArray = new float[]{1.f};
}
else
{
pieceWeightNames = new String[pieceWeights.length];
gameAgnosticWeightsArray = new float[pieceWeights.length];
for (int i = 0; i < pieceWeights.length; ++i)
{
pieceWeightNames[i] = pieceWeights[i].key();
gameAgnosticWeightsArray[i] = pieceWeights[i].floatVal();
}
}
}
@Override
public HeuristicTerm copy()
{
return new RegionProximity(this);
}
/**
* Copy constructor (private, so not visible to grammar)
* @param other
*/
private RegionProximity(final RegionProximity other)
{
super(other.transformation, Float.valueOf(other.weight));
pieceWeightNames = Arrays.copyOf(other.pieceWeightNames, other.pieceWeightNames.length);
gameAgnosticWeightsArray = Arrays.copyOf(other.gameAgnosticWeightsArray, other.gameAgnosticWeightsArray.length);
region = other.region;
}
//-------------------------------------------------------------------------
@Override
public float computeValue(final Context context, final int player, final float absWeightThreshold)
{
if (maxDistance == 0)
return 0.f;
final int[] distances = context.game().distancesToRegions()[region];
final Owned owned = context.state().owned();
final List<? extends Location>[] pieces = owned.positions(player);
float value = 0.f;
for (int i = 0; i < pieces.length; ++i)
{
if (pieces[i].isEmpty())
continue;
final float pieceWeight = pieceWeights.get(owned.reverseMap(player, i));
if (Math.abs(pieceWeight) >= absWeightThreshold)
{
for (final Location position : pieces[i])
{
final int site = position.site();
if (site >= distances.length) // Different container, skip it
continue;
final int dist = distances[site];
final float proximity = 1.f - ((float) dist / maxDistance);
value += pieceWeight * proximity;
}
}
}
return value;
}
@Override
public FVector computeStateFeatureVector(final Context context, final int player)
{
final FVector featureVector = new FVector(pieceWeights.dim());
if (maxDistance != 0)
{
final int[] distances = context.game().distancesToRegions()[region];
final Owned owned = context.state().owned();
final List<? extends Location>[] pieces = owned.positions(player);
for (int i = 0; i < pieces.length; ++i)
{
final int compIdx = owned.reverseMap(player, i);
for (final Location position : pieces[i])
{
final int site = position.site();
if (site >= distances.length) // Different container, skip it
continue;
final int dist = distances[site];
final float proximity = 1.f - ((float) dist / maxDistance);
featureVector.addToEntry(compIdx, proximity);
}
}
}
return featureVector;
}
@Override
public FVector paramsVector()
{
return pieceWeights;
}
@Override
public void init(final Game game)
{
// Compute vector of piece weights
pieceWeights = HeuristicTerm.pieceWeightsVector(game, pieceWeightNames, gameAgnosticWeightsArray);
// Precompute maximum distance for this game
computeMaxDist(game);
}
@Override
public int updateParams(final Game game, final FVector newParams, final int startIdx)
{
final int retVal = super.updateParams(game, newParams, startIdx);
// Need to update the array of weights we were passed in constructor
// in case we decide to write ourselves to a file
final Object[] returnArrays = updateGameAgnosticWeights(game, pieceWeights, pieceWeightNames, gameAgnosticWeightsArray);
pieceWeightNames = (String[]) returnArrays[0];
gameAgnosticWeightsArray = (float[]) returnArrays[1];
return retVal;
}
//-------------------------------------------------------------------------
/**
* Helper method for constructors
* @param game
*/
private final void computeMaxDist(final Game game)
{
final int[] distances = game.distancesToRegions()[region];
if (distances != null)
{
int max = 0;
for (int i = 0; i < distances.length; ++i)
{
if (distances[i] > max)
max = distances[i];
}
maxDistance = max;
}
else
{
maxDistance = 0;
}
}
//-------------------------------------------------------------------------
/**
* @param game
* @return True if heuristic of this type could be applicable to given game
*/
public static boolean isApplicableToGame(final Game game)
{
if (game.distancesToRegions() == null)
return false;
if (game.equipment().components().length <= 1)
return false;
final Regions[] regions = game.equipment().regions();
if (regions.length == 0)
return false;
for (int i = 0; i < regions.length; ++i)
{
if (game.distancesToRegions()[i] != null)
return true;
}
return false;
}
/**
* @param game
* @return True if the heuristic of this type is sensible for the given game
* (must be applicable, but even some applicable heuristics may be considered
* to be not sensible).
*/
public static boolean isSensibleForGame(final Game game)
{
return isApplicableToGame(game);
}
@Override
public boolean isApplicable(final Game game)
{
return isApplicableToGame(game);
}
//-------------------------------------------------------------------------
/**
* @return The index of the region for which we compute proximity
*/
public int region()
{
return region;
}
//-------------------------------------------------------------------------
@Override
public String toString()
{
final StringBuilder sb = new StringBuilder();
sb.append("(regionProximity");
if (transformation != null)
sb.append(" transformation:" + transformation.toString());
if (weight != 1.f)
sb.append(" weight:" + weight);
sb.append(" region:" + region);
if (pieceWeightNames.length > 1 || (pieceWeightNames.length == 1 && pieceWeightNames[0].length() > 0))
{
sb.append(" pieceWeights:{\n");
for (int i = 0; i < pieceWeightNames.length; ++i)
{
if (gameAgnosticWeightsArray[i] != 0.f)
sb.append(" (pair " + StringRoutines.quote(pieceWeightNames[i]) + " " + gameAgnosticWeightsArray[i] + ")\n");
}
sb.append(" }");
}
sb.append(")");
return sb.toString();
}
//-------------------------------------------------------------------------
@Override
public String toStringThresholded(final float threshold)
{
boolean shouldPrint = false;
boolean haveRelevantPieces = false;
final StringBuilder pieceWeightsSb = new StringBuilder();
if (pieceWeightNames.length > 1 || (pieceWeightNames.length == 1 && pieceWeightNames[0].length() > 0))
{
for (int i = 0; i < pieceWeightNames.length; ++i)
{
if (Math.abs(weight * gameAgnosticWeightsArray[i]) >= threshold)
{
pieceWeightsSb.append(" (pair " + StringRoutines.quote(pieceWeightNames[i]) + " " + gameAgnosticWeightsArray[i] + ")\n");
haveRelevantPieces = true;
shouldPrint = true;
}
}
}
else if (Math.abs(weight) >= threshold)
{
// No manually specified weights, so they will all default to 1.0,
// and we have a large enough term-wide weight
shouldPrint = true;
}
if (shouldPrint)
{
final StringBuilder sb = new StringBuilder();
sb.append("(regionProximity");
if (transformation != null)
sb.append(" transformation:" + transformation.toString());
if (weight != 1.f)
sb.append(" weight:" + weight);
sb.append(" region:" + region);
if (haveRelevantPieces)
{
sb.append(" pieceWeights:{\n");
sb.append(pieceWeightsSb);
sb.append(" }");
}
sb.append(")");
return sb.toString();
}
else
{
return null;
}
}
//-------------------------------------------------------------------------
@Override
public boolean canBeMerged(final HeuristicTerm term)
{
return (this.getClass().getName().equals(term.getClass().getName()) && region() == ((RegionProximity) term).region());
}
@Override
public void merge(final HeuristicTerm term)
{
final RegionProximity castTerm = (RegionProximity) term;
for (int i = 0; i < pieceWeightNames.length; i++)
for (int j = 0; j < castTerm.pieceWeightNames.length; j++)
if (pieceWeightNames[i].equals(castTerm.pieceWeightNames[j]))
gameAgnosticWeightsArray[i] = gameAgnosticWeightsArray[i] + castTerm.gameAgnosticWeightsArray[j] * (castTerm.weight()/weight());
}
@Override
public void simplify()
{
if (Math.abs(weight() - 1.f) > Constants.EPSILON)
{
for (int i = 0; i < gameAgnosticWeightsArray.length; i++)
gameAgnosticWeightsArray[i] *= weight();
setWeight(1.f);
}
}
@Override
public float maxAbsWeight()
{
float maxWeight = Math.abs(weight());
for (final float f : gameAgnosticWeightsArray)
maxWeight = Math.max(maxWeight, Math.abs(f));
return maxWeight;
}
//-------------------------------------------------------------------------
@Override
public String description()
{
return "Sum of owned pieces, weighted by proximity to a predefined region.";
}
@Override
public String toEnglishString(final Context context, final int playerIndex)
{
final StringBuilder sb = new StringBuilder();
if (pieceWeightNames.length > 1 || (pieceWeightNames.length == 1 && pieceWeightNames[0].length() > 0))
{
for (int i = 0; i < pieceWeightNames.length; ++i)
{
if (gameAgnosticWeightsArray[i] != 0.f)
{
final String pieceTrailingNumbers = StringRoutines.getTrailingNumbers(pieceWeightNames[i]);
if (pieceTrailingNumbers.length() == 0 || playerIndex < 0 || Integer.valueOf(pieceTrailingNumbers).intValue() == playerIndex)
{
if (gameAgnosticWeightsArray[i] > 0)
sb.append("You should try to move your " + StringRoutines.removeTrailingNumbers(pieceWeightNames[i]) + "(s) towards the region " + context.game().equipment().regions()[region].name());
else
sb.append("You should try to move your " + StringRoutines.removeTrailingNumbers(pieceWeightNames[i]) + "(s) away from the region " + context.game().equipment().regions()[region].name());
sb.append(" (" + HeuristicUtil.convertWeightToString(gameAgnosticWeightsArray[i]) + ")\n");
}
}
}
}
else
{
if (weight > 0)
sb.append("You should try to move your piece(s) towards the region " + context.game().equipment().regions()[region].name());
else
sb.append("You should try to move your piece(s) away from the region " + context.game().equipment().regions()[region].name());
sb.append(" (" + HeuristicUtil.convertWeightToString(weight) + ")\n");
}
return sb.toString();
}
//-------------------------------------------------------------------------
@Override
public float[] gameAgnosticWeightsArray() {
return gameAgnosticWeightsArray;
}
@Override
public FVector pieceWeights() {
return pieceWeights;
}
}
| 13,349 | 26.582645 | 193 | java |
Ludii | Ludii-master/Core/src/metadata/ai/heuristics/terms/Score.java | package metadata.ai.heuristics.terms;
import annotations.Name;
import annotations.Opt;
import game.Game;
import main.collections.FVector;
import metadata.ai.heuristics.HeuristicUtil;
import metadata.ai.heuristics.transformations.HeuristicTransformation;
import other.context.Context;
/**
* Defines a heuristic term based on a Player's score in a game.
*
* @author Dennis Soemers
*/
public class Score extends HeuristicTerm
{
//-------------------------------------------------------------------------
/**
* Constructor
*
* @param transformation An optional transformation to be applied to any
* raw heuristic score outputs.
* @param weight The weight for this term in a linear combination of multiple terms.
* If not specified, a default weight of $1.0$ is used.
*
* @example (score)
*/
public Score
(
@Name @Opt final HeuristicTransformation transformation,
@Name @Opt final Float weight
)
{
super(transformation, weight);
}
@Override
public Score copy()
{
return new Score(this);
}
/**
* Copy constructor (private, so not visible to grammar)
* @param other
*/
private Score(final Score other)
{
super(other.transformation, Float.valueOf(other.weight));
}
//-------------------------------------------------------------------------
@Override
public float computeValue(final Context context, final int player, final float absWeightThreshold)
{
if (context.game().requiresScore())
return context.score(player);
return 0.f;
}
@Override
public FVector computeStateFeatureVector(final Context context, final int player)
{
final FVector featureVector = new FVector(1);
featureVector.set(0, computeValue(context, player, -1.f));
return featureVector;
}
@Override
public FVector paramsVector()
{
return null;
}
//-------------------------------------------------------------------------
/**
* @param game
* @return True if heuristic of this type could be applicable to given game
*/
public static boolean isApplicableToGame(final Game game)
{
return game.requiresScore();
}
/**
* @param game
* @return True if the heuristic of this type is sensible for the given game
* (must be applicable, but even some applicable heuristics may be considered
* to be not sensible).
*/
public static boolean isSensibleForGame(final Game game)
{
return isApplicableToGame(game);
}
@Override
public boolean isApplicable(final Game game)
{
return isApplicableToGame(game);
}
//-------------------------------------------------------------------------
@Override
public String toString()
{
final StringBuilder sb = new StringBuilder();
sb.append("(score");
if (transformation != null)
sb.append(" transformation:" + transformation.toString());
if (weight != 1.f)
sb.append(" weight:" + weight);
sb.append(")");
return sb.toString();
}
//-------------------------------------------------------------------------
@Override
public String toStringThresholded(final float threshold)
{
boolean shouldPrint = false;
if (Math.abs(weight) >= threshold)
{
// No manually specified weights, so they will all default to 1.0,
// and we have a large enough term-wide weight
shouldPrint = true;
}
if (shouldPrint)
{
final StringBuilder sb = new StringBuilder();
sb.append("(score");
if (transformation != null)
sb.append(" transformation:" + transformation.toString());
if (weight != 1.f)
sb.append(" weight:" + weight);
sb.append(")");
return sb.toString();
}
else
{
return null;
}
}
//-------------------------------------------------------------------------
@Override
public String description()
{
return "Score variable of game state corresponding to player.";
}
@Override
public String toEnglishString(final Context context, final int playerIndex)
{
final StringBuilder sb = new StringBuilder();
if (weight > 0)
sb.append("You should try to maximise your score");
else
sb.append("You should try to minimise your score");
sb.append(" (" + HeuristicUtil.convertWeightToString(weight) + ")\n");
return sb.toString();
}
//-------------------------------------------------------------------------
}
| 4,271 | 21.967742 | 99 | java |
Ludii | Ludii-master/Core/src/metadata/ai/heuristics/terms/SidesProximity.java | package metadata.ai.heuristics.terms;
import java.util.Arrays;
import java.util.List;
import annotations.Name;
import annotations.Opt;
import game.Game;
import game.equipment.component.Component;
import main.Constants;
import main.StringRoutines;
import main.collections.FVector;
import metadata.ai.heuristics.HeuristicUtil;
import metadata.ai.heuristics.transformations.HeuristicTransformation;
import metadata.ai.misc.Pair;
import other.context.Context;
import other.location.Location;
import other.state.owned.Owned;
/**
* Defines a heuristic term based on the proximity of pieces to the sides of
* a game's board.
*
* @author Dennis Soemers
*/
public class SidesProximity extends HeuristicTerm
{
//-------------------------------------------------------------------------
/** Array of names specified for piece types */
private String[] pieceWeightNames;
/**
* Array of weights as specified in metadata. Will be used to initialise
* a weight vector for a specific game when init() is called.
*/
private float[] gameAgnosticWeightsArray;
/** Vector with weights for every piece type */
private FVector pieceWeights = null;
/** The maximum distance that exists in our Sides distance table */
private int maxDistance = -1;
//-------------------------------------------------------------------------
/**
* Constructor
*
* @param transformation An optional transformation to be applied to any
* raw heuristic score outputs.
* @param weight The weight for this term in a linear combination of multiple terms.
* If not specified, a default weight of $1.0$ is used.
* @param pieceWeights Weights for different piece types. If no piece weights are
* specified at all, all piece types are given an equal weight of $1.0$. If piece
* weights are only specified for some piece types, all other piece types get a
* weight of $0$.
*
* @example (sidesProximity weight:-1.0)
*/
public SidesProximity
(
@Name @Opt final HeuristicTransformation transformation,
@Name @Opt final Float weight,
@Name @Opt final Pair[] pieceWeights
)
{
super(transformation, weight);
if (pieceWeights == null)
{
// We want a weight of 1.0 for everything
pieceWeightNames = new String[]{""};
gameAgnosticWeightsArray = new float[]{1.f};
}
else
{
pieceWeightNames = new String[pieceWeights.length];
gameAgnosticWeightsArray = new float[pieceWeights.length];
for (int i = 0; i < pieceWeights.length; ++i)
{
pieceWeightNames[i] = pieceWeights[i].key();
gameAgnosticWeightsArray[i] = pieceWeights[i].floatVal();
}
}
}
@Override
public HeuristicTerm copy()
{
return new SidesProximity(this);
}
/**
* Copy constructor (private, so not visible to grammar)
* @param other
*/
private SidesProximity(final SidesProximity other)
{
super(other.transformation, Float.valueOf(other.weight));
pieceWeightNames = Arrays.copyOf(other.pieceWeightNames, other.pieceWeightNames.length);
gameAgnosticWeightsArray = Arrays.copyOf(other.gameAgnosticWeightsArray, other.gameAgnosticWeightsArray.length);
}
//-------------------------------------------------------------------------
@Override
public float computeValue(final Context context, final int player, final float absWeightThreshold)
{
if (maxDistance == 0)
return 0.f;
final int[] distances = context.game().distancesToSides();
final Owned owned = context.state().owned();
final List<? extends Location>[] pieces = owned.positions(player);
float value = 0.f;
for (int i = 0; i < pieces.length; ++i)
{
if (pieces[i].isEmpty())
continue;
final float pieceWeight = pieceWeights.get(owned.reverseMap(player, i));
if (Math.abs(pieceWeight) >= absWeightThreshold)
{
for (final Location position : pieces[i])
{
final int site = position.site();
if (site >= distances.length) // Different container, skip it
continue;
final int dist = distances[site];
final float proximity = 1.f - ((float) dist / maxDistance);
value += pieceWeight * proximity;
}
}
}
return value;
}
//-------------------------------------------------------------------------
@Override
public FVector computeStateFeatureVector(final Context context, final int player)
{
final FVector featureVector = new FVector(pieceWeights.dim());
if (maxDistance != 0.f)
{
final int[] distances = context.game().distancesToSides();
final Owned owned = context.state().owned();
final List<? extends Location>[] pieces = owned.positions(player);
for (int i = 0; i < pieces.length; ++i)
{
final int compIdx = owned.reverseMap(player, i);
for (final Location position : pieces[i])
{
final int site = position.site();
if (site >= distances.length) // Different container, skip it
continue;
final int dist = distances[site];
final float proximity = 1.f - ((float) dist / maxDistance);
featureVector.addToEntry(compIdx, proximity);
}
}
}
return featureVector;
}
//-------------------------------------------------------------------------
@Override
public FVector paramsVector()
{
return pieceWeights;
}
@Override
public void init(final Game game)
{
// Compute vector of piece weights
pieceWeights = HeuristicTerm.pieceWeightsVector(game, pieceWeightNames, gameAgnosticWeightsArray);
// Precompute maximum distance for this game
computeMaxDist(game);
}
@Override
public int updateParams(final Game game, final FVector newParams, final int startIdx)
{
final int retVal = super.updateParams(game, newParams, startIdx);
// Need to update the array of weights we were passed in constructor
// in case we decide to write ourselves to a file
final Object[] returnArrays = updateGameAgnosticWeights(game, pieceWeights, pieceWeightNames, gameAgnosticWeightsArray);
pieceWeightNames = (String[]) returnArrays[0];
gameAgnosticWeightsArray = (float[]) returnArrays[1];
return retVal;
}
//-------------------------------------------------------------------------
/**
* Helper method for constructors
* @param game
*/
private final void computeMaxDist(final Game game)
{
final int[] distances = game.distancesToSides();
if (distances != null)
{
int max = 0;
for (int i = 0; i < distances.length; ++i)
{
if (distances[i] > max)
max = distances[i];
}
maxDistance = max;
}
else
{
maxDistance = 0;
}
}
//-------------------------------------------------------------------------
/**
* @param game
* @return True if heuristic of this type could be applicable to given game
*/
public static boolean isApplicableToGame(final Game game)
{
final Component[] components = game.equipment().components();
if (components.length <= 1)
return false;
if (game.distancesToSides() == null)
return false;
return true;
}
/**
* @param game
* @return True if the heuristic of this type is sensible for the given game
* (must be applicable, but even some applicable heuristics may be considered
* to be not sensible).
*/
public static boolean isSensibleForGame(final Game game)
{
return isApplicableToGame(game);
}
@Override
public boolean isApplicable(final Game game)
{
return isApplicableToGame(game);
}
//-------------------------------------------------------------------------
@Override
public String toString()
{
final StringBuilder sb = new StringBuilder();
sb.append("(sidesProximity");
if (transformation != null)
sb.append(" transformation:" + transformation.toString());
if (weight != 1.f)
sb.append(" weight:" + weight);
if (pieceWeightNames.length > 1 || (pieceWeightNames.length == 1 && pieceWeightNames[0].length() > 0))
{
sb.append(" pieceWeights:{\n");
for (int i = 0; i < pieceWeightNames.length; ++i)
{
if (gameAgnosticWeightsArray[i] != 0.f)
sb.append(" (pair " + StringRoutines.quote(pieceWeightNames[i]) + " " + gameAgnosticWeightsArray[i] + ")\n");
}
sb.append(" }");
}
sb.append(")");
return sb.toString();
}
//-------------------------------------------------------------------------
@Override
public String toStringThresholded(final float threshold)
{
boolean shouldPrint = false;
boolean haveRelevantPieces = false;
final StringBuilder pieceWeightsSb = new StringBuilder();
if (pieceWeightNames.length > 1 || (pieceWeightNames.length == 1 && pieceWeightNames[0].length() > 0))
{
for (int i = 0; i < pieceWeightNames.length; ++i)
{
if (Math.abs(weight * gameAgnosticWeightsArray[i]) >= threshold)
{
pieceWeightsSb.append(" (pair " + StringRoutines.quote(pieceWeightNames[i]) + " " + gameAgnosticWeightsArray[i] + ")\n");
haveRelevantPieces = true;
shouldPrint = true;
}
}
}
else if (Math.abs(weight) >= threshold)
{
// No manually specified weights, so they will all default to 1.0,
// and we have a large enough term-wide weight
shouldPrint = true;
}
if (shouldPrint)
{
final StringBuilder sb = new StringBuilder();
sb.append("(sidesProximity");
if (transformation != null)
sb.append(" transformation:" + transformation.toString());
if (weight != 1.f)
sb.append(" weight:" + weight);
if (haveRelevantPieces)
{
sb.append(" pieceWeights:{\n");
sb.append(pieceWeightsSb);
sb.append(" }");
}
sb.append(")");
return sb.toString();
}
else
{
return null;
}
}
//-------------------------------------------------------------------------
@Override
public void merge(final HeuristicTerm term)
{
final SidesProximity castTerm = (SidesProximity) term;
for (int i = 0; i < pieceWeightNames.length; i++)
for (int j = 0; j < castTerm.pieceWeightNames.length; j++)
if (pieceWeightNames[i].equals(castTerm.pieceWeightNames[j]))
gameAgnosticWeightsArray[i] = gameAgnosticWeightsArray[i] + castTerm.gameAgnosticWeightsArray[j] * (castTerm.weight()/weight());
}
@Override
public void simplify()
{
if (Math.abs(weight() - 1.f) > Constants.EPSILON)
{
for (int i = 0; i < gameAgnosticWeightsArray.length; i++)
gameAgnosticWeightsArray[i] *= weight();
setWeight(1.f);
}
}
@Override
public float maxAbsWeight()
{
float maxWeight = Math.abs(weight());
for (final float f : gameAgnosticWeightsArray)
maxWeight = Math.max(maxWeight, Math.abs(f));
return maxWeight;
}
@Override
public String description()
{
return "Sum of owned pieces, weighted by proximity to nearest side.";
}
//-------------------------------------------------------------------------
@Override
public String toEnglishString(final Context context, final int playerIndex)
{
final StringBuilder sb = new StringBuilder();
if (pieceWeightNames.length > 1 || (pieceWeightNames.length == 1 && pieceWeightNames[0].length() > 0))
{
for (int i = 0; i < pieceWeightNames.length; ++i)
{
if (gameAgnosticWeightsArray[i] != 0.f)
{
final String pieceTrailingNumbers = StringRoutines.getTrailingNumbers(pieceWeightNames[i]);
if (pieceTrailingNumbers.length() == 0 || playerIndex < 0 || Integer.valueOf(pieceTrailingNumbers).intValue() == playerIndex)
{
if (gameAgnosticWeightsArray[i] > 0)
sb.append("You should try to move your " + StringRoutines.removeTrailingNumbers(pieceWeightNames[i]) + "(s) towards the sides of the board");
else
sb.append("You should try to move your " + StringRoutines.removeTrailingNumbers(pieceWeightNames[i]) + "(s) away from the sides of the board");
sb.append(" (" + HeuristicUtil.convertWeightToString(gameAgnosticWeightsArray[i]) + ")\n");
}
}
}
}
else
{
if (weight > 0)
sb.append("You should try to move your piece(s) towards the sides of the board");
else
sb.append("You should try to move your piece(s) away from the sides of the board");
sb.append(" (" + HeuristicUtil.convertWeightToString(weight) + ")\n");
}
return sb.toString();
}
//-------------------------------------------------------------------------
@Override
public float[] gameAgnosticWeightsArray() {
return gameAgnosticWeightsArray;
}
@Override
public FVector pieceWeights() {
return pieceWeights;
}
}
| 12,405 | 26.446903 | 150 | java |
Ludii | Ludii-master/Core/src/metadata/ai/heuristics/terms/UnthreatenedMaterial.java | package metadata.ai.heuristics.terms;
import java.util.Arrays;
import java.util.List;
import annotations.Name;
import annotations.Opt;
import game.Game;
import game.equipment.component.Component;
import game.types.board.SiteType;
import gnu.trove.set.hash.TIntHashSet;
import main.Constants;
import main.StringRoutines;
import main.collections.FVector;
import main.collections.FastArrayList;
import metadata.ai.heuristics.HeuristicUtil;
import metadata.ai.heuristics.transformations.HeuristicTransformation;
import metadata.ai.misc.Pair;
import other.action.Action;
import other.action.ActionType;
import other.action.move.remove.ActionRemove;
import other.action.move.remove.ActionRemoveTopPiece;
import other.concept.Concept;
import other.context.Context;
import other.context.TempContext;
import other.location.Location;
import other.move.Move;
import other.state.owned.Owned;
/**
* Defines a heuristic term based on the unthreatened material (which
* opponents cannot threaten with their legal moves).
*
* @author Dennis Soemers
*/
public class UnthreatenedMaterial extends HeuristicTerm
{
//-------------------------------------------------------------------------
/** Array of names specified for piece types */
private String[] pieceWeightNames;
/**
* Array of weights as specified in metadata. Will be used to initialise
* a weight vector for a specific game when init() is called.
*/
private float[] gameAgnosticWeightsArray;
/** Vector with weights for every piece type */
private FVector pieceWeights = null;
//-------------------------------------------------------------------------
/**
* Constructor
*
* @param transformation An optional transformation to be applied to any
* raw heuristic score outputs.
* @param weight The weight for this term in a linear combination of multiple terms.
* If not specified, a default weight of $1.0$ is used.
* @param pieceWeights Weights for different piece types. If no piece weights are
* specified at all, all piece types are given an equal weight of $1.0$. If piece
* weights are only specified for some piece types, all other piece types get a
* weight of $0$.
*
* @example (unthreatenedMaterial pieceWeights:{ (pair "Pawn" 1.0) (pair "Bishop" 3.0) })
*/
public UnthreatenedMaterial
(
@Name @Opt final HeuristicTransformation transformation,
@Name @Opt final Float weight,
@Name @Opt final Pair[] pieceWeights
)
{
super(transformation, weight);
if (pieceWeights == null)
{
// We want a weight of 1.0 for everything
pieceWeightNames = new String[]{""};
gameAgnosticWeightsArray = new float[]{1.f};
}
else
{
pieceWeightNames = new String[pieceWeights.length];
gameAgnosticWeightsArray = new float[pieceWeights.length];
for (int i = 0; i < pieceWeights.length; ++i)
{
pieceWeightNames[i] = pieceWeights[i].key();
gameAgnosticWeightsArray[i] = pieceWeights[i].floatVal();
}
}
}
@Override
public HeuristicTerm copy()
{
return new UnthreatenedMaterial(this);
}
/**
* Copy constructor (private, so not visible to grammar)
* @param other
*/
private UnthreatenedMaterial(final UnthreatenedMaterial other)
{
super(other.transformation, Float.valueOf(other.weight));
pieceWeightNames = Arrays.copyOf(other.pieceWeightNames, other.pieceWeightNames.length);
gameAgnosticWeightsArray = Arrays.copyOf(other.gameAgnosticWeightsArray, other.gameAgnosticWeightsArray.length);
}
//-------------------------------------------------------------------------
@Override
public float computeValue(final Context context, final int player, final float absWeightThreshold)
{
final Game game = context.game();
final Owned owned = context.state().owned();
// First find all threatened positions by any opposing players
final TIntHashSet threatenedSites = new TIntHashSet();
for (int p = 1; p <= game.players().count(); ++p)
{
if (p == player)
continue;
final FastArrayList<Move> oppLegalMoves;
if (context.state().mover() == p)
{
oppLegalMoves = game.moves(context).moves();
}
else
{
final TempContext temp = new TempContext(context);
temp.state().setPrev(context.state().mover());
temp.state().setMover(p);
temp.trial().clearLegalMoves();
oppLegalMoves = game.moves(temp).moves();
for (final Move move : oppLegalMoves)
{
for (final Action action : move.actions())
{
if (action != null && action.actionType() != null && action.actionType().equals(ActionType.Remove))
{
if (action instanceof ActionRemove)
{
final ActionRemove removeAction = (ActionRemove) action;
final int removeSite = removeAction.to();
final int contID = removeSite >= context.containerId().length ? -1 : context.containerId()[removeSite];
if (contID == 0)
{
threatenedSites.add(removeSite);
}
}
else if (action instanceof ActionRemoveTopPiece)
{
final ActionRemoveTopPiece removeAction = (ActionRemoveTopPiece) action;
final int removeSite = removeAction.to();
final int contID = removeSite >= context.containerId().length ? -1 : context.containerId()[removeSite];
if (contID == 0)
{
threatenedSites.add(removeSite);
}
}
else
{
System.err.println("ERROR: UnthreatenedMaterial does not recognise Remove action: " + action.getClass());
}
}
}
// Also assume we threaten the site we move to, regardless of whether or not there are Remove actions
if (move.to() >= 0)
threatenedSites.add(move.to());
}
}
}
// Now count material value, but only for unthreatened sites
final List<? extends Location>[] pieces = owned.positions(player);
float value = 0.f;
for (int i = 0; i < pieces.length; ++i)
{
if (pieces[i].isEmpty())
continue;
final float pieceWeight = pieceWeights.get(owned.reverseMap(player, i));
if (Math.abs(pieceWeight) >= absWeightThreshold)
{
for (final Location loc : pieces[i])
{
if (loc.siteType() != SiteType.Cell || context.containerId()[loc.site()] == 0)
{
if (!threatenedSites.contains(loc.site()))
value += pieceWeight;
}
}
}
}
return value;
}
@Override
public FVector computeStateFeatureVector(final Context context, final int player)
{
final FVector featureVector = new FVector(pieceWeights.dim());
final Game game = context.game();
final Owned owned = context.state().owned();
// First find all threatened positions by any opposing players
final TIntHashSet threatenedSites = new TIntHashSet();
for (int p = 1; p <= game.players().count(); ++p)
{
if (p == player)
continue;
final FastArrayList<Move> oppLegalMoves;
if (context.state().mover() == p)
{
oppLegalMoves = game.moves(context).moves();
}
else
{
final TempContext temp = new TempContext(context);
temp.state().setMover(player);
temp.trial().clearLegalMoves();
oppLegalMoves = game.moves(temp).moves();
for (final Move move : oppLegalMoves)
{
for (final Action action : move.actions())
{
if (action != null && action.actionType().equals(ActionType.Remove))
{
final ActionRemove removeAction = (ActionRemove) action;
final int removeSite = removeAction.to();
final int contID = removeSite >= context.containerId().length ? -1 : context.containerId()[removeSite];
if (contID == 0)
{
threatenedSites.add(removeSite);
}
}
}
// Also assume we threaten the site we move to, regardless of whether or not there are Remove actions
if (move.to() >= 0)
threatenedSites.add(move.to());
}
}
}
final List<? extends Location>[] pieces = owned.positions(player);
for (int i = 0; i < pieces.length; ++i)
{
if (pieces[i].isEmpty())
continue;
final int compIdx = owned.reverseMap(player, i);
for (final Location loc : pieces[i])
{
if (loc.siteType() != SiteType.Cell || context.containerId()[loc.site()] == 0)
{
if (!threatenedSites.contains(loc.site()))
featureVector.addToEntry(compIdx, 1.f);
}
}
}
return featureVector;
}
@Override
public FVector paramsVector()
{
return pieceWeights;
}
@Override
public void init(final Game game)
{
// Compute vector of piece weights
pieceWeights = HeuristicTerm.pieceWeightsVector(game, pieceWeightNames, gameAgnosticWeightsArray);
}
@Override
public int updateParams(final Game game, final FVector newParams, final int startIdx)
{
final int retVal = super.updateParams(game, newParams, startIdx);
// Need to update the array of weights we were passed in constructor
// in case we decide to write ourselves to a file
final Object[] returnArrays = updateGameAgnosticWeights(game, pieceWeights, pieceWeightNames, gameAgnosticWeightsArray);
pieceWeightNames = (String[]) returnArrays[0];
gameAgnosticWeightsArray = (float[]) returnArrays[1];
return retVal;
}
//-------------------------------------------------------------------------
/**
* @param game
* @return True if heuristic of this type could be applicable to given game
*/
public static boolean isApplicableToGame(final Game game)
{
final Component[] components = game.equipment().components();
if (components.length <= 1)
return false;
return true;
}
/**
* @param game
* @return True if the heuristic of this type is sensible for the given game
* (must be applicable, but even some applicable heuristics may be considered
* to be not sensible).
*/
public static boolean isSensibleForGame(final Game game)
{
return isApplicableToGame(game) && game.booleanConcepts().get(Concept.Capture.id());
}
@Override
public boolean isApplicable(final Game game)
{
return isApplicableToGame(game);
}
//-------------------------------------------------------------------------
@Override
public String toString()
{
final StringBuilder sb = new StringBuilder();
sb.append("(unthreatenedMaterial");
if (transformation != null)
sb.append(" transformation:" + transformation.toString());
if (weight != 1.f)
sb.append(" weight:" + weight);
if (pieceWeightNames.length > 1 || (pieceWeightNames.length == 1 && pieceWeightNames[0].length() > 0))
{
sb.append(" pieceWeights:{\n");
for (int i = 0; i < pieceWeightNames.length; ++i)
{
if (gameAgnosticWeightsArray[i] != 0.f)
sb.append(" (pair " + StringRoutines.quote(pieceWeightNames[i]) + " " + gameAgnosticWeightsArray[i] + ")\n");
}
sb.append(" }");
}
sb.append(")");
return sb.toString();
}
//-------------------------------------------------------------------------
@Override
public String toStringThresholded(final float threshold)
{
boolean shouldPrint = false;
boolean haveRelevantPieces = false;
final StringBuilder pieceWeightsSb = new StringBuilder();
if (pieceWeightNames.length > 1 || (pieceWeightNames.length == 1 && pieceWeightNames[0].length() > 0))
{
for (int i = 0; i < pieceWeightNames.length; ++i)
{
if (Math.abs(weight * gameAgnosticWeightsArray[i]) >= threshold)
{
pieceWeightsSb.append(" (pair " + StringRoutines.quote(pieceWeightNames[i]) + " " + gameAgnosticWeightsArray[i] + ")\n");
haveRelevantPieces = true;
shouldPrint = true;
}
}
}
else if (Math.abs(weight) >= threshold)
{
// No manually specified weights, so they will all default to 1.0,
// and we have a large enough term-wide weight
shouldPrint = true;
}
if (shouldPrint)
{
final StringBuilder sb = new StringBuilder();
sb.append("(unthreatenedMaterial");
if (transformation != null)
sb.append(" transformation:" + transformation.toString());
if (weight != 1.f)
sb.append(" weight:" + weight);
if (haveRelevantPieces)
{
sb.append(" pieceWeights:{\n");
sb.append(pieceWeightsSb);
sb.append(" }");
}
sb.append(")");
return sb.toString();
}
else
{
return null;
}
}
//-------------------------------------------------------------------------
@Override
public void merge(final HeuristicTerm term)
{
final UnthreatenedMaterial castTerm = (UnthreatenedMaterial) term;
for (int i = 0; i < pieceWeightNames.length; i++)
for (int j = 0; j < castTerm.pieceWeightNames.length; j++)
if (pieceWeightNames[i].equals(castTerm.pieceWeightNames[j]))
gameAgnosticWeightsArray[i] = gameAgnosticWeightsArray[i] + castTerm.gameAgnosticWeightsArray[j] * (castTerm.weight()/weight());
}
@Override
public void simplify()
{
if (Math.abs(weight() - 1.f) > Constants.EPSILON)
{
for (int i = 0; i < gameAgnosticWeightsArray.length; i++)
gameAgnosticWeightsArray[i] *= weight();
setWeight(1.f);
}
}
@Override
public float maxAbsWeight()
{
float maxWeight = Math.abs(weight());
for (final float f : gameAgnosticWeightsArray)
maxWeight = Math.max(maxWeight, Math.abs(f));
return maxWeight;
}
//-------------------------------------------------------------------------
@Override
public String description()
{
return "Sum of unthreatened owned pieces.";
}
@Override
public String toEnglishString(final Context context, final int playerIndex)
{
final StringBuilder sb = new StringBuilder();
if (pieceWeightNames.length > 1 || (pieceWeightNames.length == 1 && pieceWeightNames[0].length() > 0))
{
for (int i = 0; i < pieceWeightNames.length; ++i)
{
if (gameAgnosticWeightsArray[i] != 0.f)
{
final String pieceTrailingNumbers = StringRoutines.getTrailingNumbers(pieceWeightNames[i]);
if (pieceTrailingNumbers.length() == 0 || playerIndex < 0 || Integer.valueOf(pieceTrailingNumbers).intValue() == playerIndex)
{
if (gameAgnosticWeightsArray[i] > 0)
sb.append("You should try to maximise the number of unthreatened " + StringRoutines.removeTrailingNumbers(pieceWeightNames[i]) + "(s) you control");
else
sb.append("You should try to minimise the number of unthreatened " + StringRoutines.removeTrailingNumbers(pieceWeightNames[i]) + "(s) you control");
sb.append(" (" + HeuristicUtil.convertWeightToString(gameAgnosticWeightsArray[i]) + ")\n");
}
}
}
}
else
{
if (weight > 0)
sb.append("You should try to maximise the number of unthreatened piece(s) you control");
else
sb.append("You should try to maximise the number of unthreatened piece(s) you control");
sb.append(" (" + HeuristicUtil.convertWeightToString(weight) + ")\n");
}
return sb.toString();
}
//-------------------------------------------------------------------------
@Override
public float[] gameAgnosticWeightsArray() {
return gameAgnosticWeightsArray;
}
@Override
public FVector pieceWeights() {
return pieceWeights;
}
}
| 15,048 | 28.052124 | 155 | java |
Ludii | Ludii-master/Core/src/metadata/ai/heuristics/terms/package-info.java | /**
* The {\tt terms} package includes the actual heuristic metrics that can be applied and their settings.
*/
package metadata.ai.heuristics.terms;
| 151 | 29.4 | 104 | java |
Ludii | Ludii-master/Core/src/metadata/ai/heuristics/transformations/DivNumBoardSites.java | package metadata.ai.heuristics.transformations;
import other.context.Context;
/**
* Transforms heuristic scores by dividing them by the number of sites
* in a game's board.
*
* @remarks Can be used to approximately standardise heuristic values across
* games with different board sizes.
*
* @author Dennis Soemers
*/
public class DivNumBoardSites implements HeuristicTransformation
{
//-------------------------------------------------------------------------
/**
* @example (divNumBoardSites)
*/
public DivNumBoardSites()
{
// Do nothing
}
//-------------------------------------------------------------------------
@Override
public float transform(final Context context, final float heuristicScore)
{
return heuristicScore / context.game().board().numSites();
}
//-------------------------------------------------------------------------
@Override
public String toString()
{
return "(divNumBoardSites)";
}
//-------------------------------------------------------------------------
}
| 1,039 | 21.608696 | 76 | java |
Ludii | Ludii-master/Core/src/metadata/ai/heuristics/transformations/DivNumInitPlacement.java | package metadata.ai.heuristics.transformations;
import other.context.Context;
/**
* Transforms heuristic scores by dividing them by the number of pieces
* placed in a game's initial game state.
*
* @remarks Can be used to approximately standardise heuristic values across
* games with different initial numbers of pieces.
*
* @author Dennis Soemers
*/
public class DivNumInitPlacement implements HeuristicTransformation
{
//-------------------------------------------------------------------------
/**
* @example (divNumInitPlacement)
*/
public DivNumInitPlacement()
{
// Do nothing
}
//-------------------------------------------------------------------------
@Override
public float transform(final Context context, final float heuristicScore)
{
final int numInitPlacement = Math.max(1, context.trial().numInitPlacement());
return heuristicScore / numInitPlacement;
}
//-------------------------------------------------------------------------
@Override
public String toString()
{
return "(divNumInitPlacement)";
}
//-------------------------------------------------------------------------
}
| 1,148 | 23.446809 | 79 | java |
Ludii | Ludii-master/Core/src/metadata/ai/heuristics/transformations/HeuristicTransformation.java | package metadata.ai.heuristics.transformations;
import metadata.ai.AIItem;
import other.context.Context;
/**
* Interface for transformations of heuristics (generally functions
* intended to map the scores of a heuristic to some different range).
*
* @author Dennis Soemers
*/
public interface HeuristicTransformation extends AIItem
{
//-------------------------------------------------------------------------
/**
* @param context
* @param heuristicScore
* @return Transformed version of given score
*/
public float transform(final Context context, final float heuristicScore);
//-------------------------------------------------------------------------
}
| 682 | 24.296296 | 76 | java |
Ludii | Ludii-master/Core/src/metadata/ai/heuristics/transformations/LogisticFunction.java | package metadata.ai.heuristics.transformations;
import other.context.Context;
/**
* Transforms heuristic scores by applying the logistic function to them:
* $f(x) = \\frac{1}{1 + \\exp(x)}$.
*
* @remarks This guarantees that all transformed heuristic scores will lie
* in $[0, 1]$. May map too many different values only to the limits of this
* interval in practice.
*
* @author Dennis Soemers
*/
public class LogisticFunction implements HeuristicTransformation
{
//-------------------------------------------------------------------------
/**
* @example (logisticFunction)
*/
public LogisticFunction()
{
// Do nothing
}
//-------------------------------------------------------------------------
@Override
public float transform(final Context context, final float heuristicScore)
{
return (float) (1.0 / (1.0 + Math.exp(heuristicScore)));
}
//-------------------------------------------------------------------------
@Override
public String toString()
{
return "(logisticFunction)";
}
//-------------------------------------------------------------------------
}
| 1,118 | 22.808511 | 76 | java |
Ludii | Ludii-master/Core/src/metadata/ai/heuristics/transformations/Tanh.java | package metadata.ai.heuristics.transformations;
import other.context.Context;
/**
* Transforms heuristic scores by applying the $\\tanh$ to them:
* $f(x) = \\tanh(x)$.
*
* @remarks This guarantees that all transformed heuristic scores will lie
* in $[-1, 1]$. May map too many different values only to the limits of this
* interval in practice.
*
* @author Dennis Soemers
*/
public class Tanh implements HeuristicTransformation
{
//-------------------------------------------------------------------------
/**
* @example (tanh)
*/
public Tanh()
{
// Do nothing
}
//-------------------------------------------------------------------------
@Override
public float transform(final Context context, final float heuristicScore)
{
return (float) Math.tanh(heuristicScore);
}
//-------------------------------------------------------------------------
@Override
public String toString()
{
return "(tanh)";
}
//-------------------------------------------------------------------------
}
| 1,033 | 21 | 77 | java |
Ludii | Ludii-master/Core/src/metadata/ai/heuristics/transformations/package-info.java | /**
* The {\it transformations} metadata items specify how to normalise the heuristics results into a useful range.
*/
package metadata.ai.heuristics.transformations;
| 169 | 33 | 112 | java |
Ludii | Ludii-master/Core/src/metadata/ai/misc/Pair.java | package metadata.ai.misc;
import main.StringRoutines;
import metadata.MetadataItem;
/**
* Defines a pair of a String and a floating point value. Typically used
* in AI metadata to assign a numeric value (such as a heuristic score, or
* some other weight) to a specific piece name.
*
* @author Dennis Soemers
*/
public class Pair implements MetadataItem
{
//-------------------------------------------------------------------------
/** Our key */
protected final String key;
/** Our float value */
protected final float floatVal;
//-------------------------------------------------------------------------
/**
* @param key The String value.
* @param floatVal The floating point value.
*
* @example (pair "Pawn" 1.0)
*/
public Pair
(
final String key,
final Float floatVal
)
{
this.key = key;
this.floatVal = floatVal.floatValue();
}
//-------------------------------------------------------------------------
/**
* @return Our key
*/
public final String key()
{
return key;
}
/**
* @return Our float value
*/
public final float floatVal()
{
return floatVal;
}
//-------------------------------------------------------------------------
@Override
public String toString()
{
return "(pair " + StringRoutines.quote(key) + " " + floatVal + ")";
}
//-------------------------------------------------------------------------
@Override
public int hashCode()
{
final int prime = 31;
int result = 1;
result = prime * result + Float.floatToIntBits(floatVal);
result = prime * result + ((key == null) ? 0 : key.hashCode());
return result;
}
@Override
public boolean equals(final Object obj)
{
if (this == obj)
return true;
if (!(obj instanceof Pair))
return false;
final Pair other = (Pair) obj;
if (floatVal != other.floatVal)
return false;
if (key == null)
{
if (other.key != null)
return false;
}
else if (!key.equals(other.key))
{
return false;
}
return true;
}
//-------------------------------------------------------------------------
}
| 2,098 | 18.256881 | 76 | java |
Ludii | Ludii-master/Core/src/metadata/ai/misc/package-info.java | /**
* The {\tt misc} package includes miscellaneous items relevant to the AI settings.
*/
package metadata.ai.misc;
| 118 | 22.8 | 83 | java |
Ludii | Ludii-master/Core/src/metadata/graphics/Graphics.java | package metadata.graphics;
import java.awt.Color;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.BitSet;
import java.util.List;
import annotations.Or;
import game.Game;
import game.equipment.container.Container;
import game.equipment.other.Regions;
import game.functions.ints.board.Id;
import game.functions.region.RegionFunction;
import game.types.board.RelationType;
import game.types.board.ShapeType;
import game.types.board.SiteType;
import game.types.component.SuitType;
import game.types.play.RoleType;
import main.Constants;
import main.StringRoutines;
import metadata.graphics.board.Boolean.BoardCheckered;
import metadata.graphics.board.colour.BoardColour;
import metadata.graphics.board.curvature.BoardCurvature;
import metadata.graphics.board.ground.BoardBackground;
import metadata.graphics.board.ground.BoardForeground;
import metadata.graphics.board.placement.BoardPlacement;
import metadata.graphics.board.shape.BoardShape;
import metadata.graphics.board.style.BoardStyle;
import metadata.graphics.board.styleThickness.BoardStyleThickness;
import metadata.graphics.hand.placement.HandPlacement;
import metadata.graphics.no.Boolean.NoAnimation;
import metadata.graphics.no.Boolean.NoBoard;
import metadata.graphics.no.Boolean.NoCurves;
import metadata.graphics.no.Boolean.NoDicePips;
import metadata.graphics.no.Boolean.NoSunken;
import metadata.graphics.others.HiddenImage;
import metadata.graphics.others.StackType;
import metadata.graphics.others.SuitRanking;
import metadata.graphics.piece.colour.PieceColour;
import metadata.graphics.piece.families.PieceFamilies;
import metadata.graphics.piece.ground.PieceBackground;
import metadata.graphics.piece.ground.PieceForeground;
import metadata.graphics.piece.name.PieceAddStateToName;
import metadata.graphics.piece.name.PieceExtendName;
import metadata.graphics.piece.name.PieceRename;
import metadata.graphics.piece.rotate.PieceRotate;
import metadata.graphics.piece.scale.PieceScale;
import metadata.graphics.piece.style.PieceStyle;
import metadata.graphics.player.colour.PlayerColour;
import metadata.graphics.player.name.PlayerName;
import metadata.graphics.puzzle.AdversarialPuzzle;
import metadata.graphics.puzzle.DrawHint;
import metadata.graphics.puzzle.HintLocation;
import metadata.graphics.region.colour.RegionColour;
import metadata.graphics.show.Boolean.ShowCost;
import metadata.graphics.show.Boolean.ShowCurvedEdges;
import metadata.graphics.show.Boolean.ShowEdgeDirections;
import metadata.graphics.show.Boolean.ShowLocalStateHoles;
import metadata.graphics.show.Boolean.ShowPits;
import metadata.graphics.show.Boolean.ShowPlayerHoles;
import metadata.graphics.show.Boolean.ShowPossibleMoves;
import metadata.graphics.show.Boolean.ShowRegionOwner;
import metadata.graphics.show.Boolean.ShowStraightEdges;
import metadata.graphics.show.check.ShowCheck;
import metadata.graphics.show.component.ShowPieceState;
import metadata.graphics.show.component.ShowPieceValue;
import metadata.graphics.show.edges.ShowEdges;
import metadata.graphics.show.line.ShowLine;
import metadata.graphics.show.score.ShowScore;
import metadata.graphics.show.sites.ShowSitesAsHoles;
import metadata.graphics.show.sites.ShowSitesIndex;
import metadata.graphics.show.sites.ShowSitesShape;
import metadata.graphics.show.symbol.ShowSymbol;
import metadata.graphics.util.BoardGraphicsType;
import metadata.graphics.util.ComponentStyleType;
import metadata.graphics.util.ContainerStyleType;
import metadata.graphics.util.CurveType;
import metadata.graphics.util.EdgeInfoGUI;
import metadata.graphics.util.EdgeType;
import metadata.graphics.util.HoleType;
import metadata.graphics.util.LineStyle;
import metadata.graphics.util.MetadataFunctions;
import metadata.graphics.util.MetadataImageInfo;
import metadata.graphics.util.PieceColourType;
import metadata.graphics.util.PieceStackType;
import metadata.graphics.util.PuzzleDrawHintType;
import metadata.graphics.util.PuzzleHintLocationType;
import metadata.graphics.util.ScoreDisplayInfo;
import metadata.graphics.util.StackPropertyType;
import metadata.graphics.util.ValueDisplayInfo;
import metadata.graphics.util.colour.Colour;
import other.context.Context;
import other.topology.TopologyElement;
/**
* Graphics hints for rendering the game.
*
* @author matthew.stephenson and cambolbro
*/
public class Graphics implements Serializable
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/** All metadata graphics items. */
final List<GraphicsItem> items = new ArrayList<GraphicsItem>();
/** Report detailing any errors when attempting to process metadata. */
String errorReport = "";
/** If the graphics need to be redrawn after each move. */
private boolean needRedraw = false;
//-------------------------------------------------------------------------
/**
* Graphics hints for rendering the game.
*
* @param item The graphic item of the game.
* @param items The graphic items of the game.
*/
public Graphics
(
@Or final GraphicsItem item,
@Or final GraphicsItem[] items
)
{
int numNonNull = 0;
if (item != null)
numNonNull++;
if (items != null)
numNonNull++;
if (numNonNull > 1)
throw new IllegalArgumentException("Only one of @Or should be different to null");
if(items != null)
for (final GraphicsItem i : items)
this.items.add(i);
else
this.items.add(item);
}
//-------------------------------------------------------------------------
/**
* @param context The context.
* @param playerIndexCond The index of the player.
* @param pieceNameCond The name of the piece
* @param containerIndexCond The index of the container.
* @param stateCond The state.
* @param valueCond The value.
* @return If the piece's state should be added to its name.
*/
public boolean addStateToName(final Context context, final int playerIndexCond, final String pieceNameCond, final int containerIndexCond, final int stateCond, final int valueCond)
{
for (final GraphicsItem graphicsItem : items)
if (graphicsItem instanceof PieceAddStateToName)
{
final PieceAddStateToName pieceAddStateToName = (PieceAddStateToName) graphicsItem;
final RoleType roleType = pieceAddStateToName.roleType();
final String pieceName = pieceAddStateToName.pieceName();
final Integer containerIndex = pieceAddStateToName.container();
final Integer state = pieceAddStateToName.state();
final Integer value = pieceAddStateToName.value();
if (roleType == null || MetadataFunctions.getRealOwner(context, roleType) == playerIndexCond)
if (state == null || state.intValue() == stateCond)
if (value == null || value.intValue() == valueCond)
if (containerIndex == null || containerIndex.intValue() == containerIndexCond)
if (pieceName == null || pieceName.equals(pieceNameCond) || pieceName.equals(StringRoutines.removeTrailingNumbers(pieceNameCond)))
return true;
}
return false;
}
//-------------------------------------------------------------------------
/**
* @param context The context.
* @param playerIndexCond The index of the player.
* @param pieceNameCond The name of the piece.
* @return The component style type.
*/
public ComponentStyleType componentStyle(final Context context, final int playerIndexCond, final String pieceNameCond)
{
for (final GraphicsItem graphicsItem : items)
if (graphicsItem instanceof PieceStyle)
{
final PieceStyle pieceStyle = (PieceStyle) graphicsItem;
final RoleType roleType = pieceStyle.roleType();
final String pieceName = pieceStyle.pieceName();
if (roleType == null || MetadataFunctions.getRealOwner(context, roleType) == playerIndexCond)
if (pieceName == null || pieceName.equals(pieceNameCond) || pieceName.equals(StringRoutines.removeTrailingNumbers(pieceNameCond)))
return pieceStyle.componentStyleType();
}
return null;
}
//-------------------------------------------------------------------------
/**
* @param context The context.
* @param playerIndexCond The index of the player.
* @param pieceNameCond The name of the piece.
* @return The ValueDisplayInfo for the local state.
*/
public ValueDisplayInfo displayPieceState(final Context context, final int playerIndexCond, final String pieceNameCond)
{
final float MAX_SCALE = 100f; // multiplication factor on original size
final float MIN_OFFSET = -1f; // decimal percentage of board size
final float MAX_OFFSET = 1f; // decimal percentage of board size
for (final GraphicsItem graphicsItem : items)
if (graphicsItem instanceof ShowPieceState)
{
final ShowPieceState showPieceState = (ShowPieceState) graphicsItem;
final RoleType roleType = showPieceState.roleType();
final String pieceName = showPieceState.pieceName();
final float offsetX = showPieceState.offsetX();
final float offsetY = showPieceState.offsetY();
final float scale = showPieceState.scale();
if (roleType == null || MetadataFunctions.getRealOwner(context, roleType) == playerIndexCond)
if (pieceName == null || pieceName.equals(pieceNameCond) || pieceName.equals(StringRoutines.removeTrailingNumbers(pieceNameCond)))
if (scale >= 0 && scale <= MAX_SCALE)
if (offsetX >= MIN_OFFSET && offsetX <= MAX_OFFSET)
if (offsetY >= MIN_OFFSET && offsetY <= MAX_OFFSET)
return new ValueDisplayInfo
(
showPieceState.location(),
showPieceState.offsetImage(),
showPieceState.valueOutline(),
scale,
offsetX,
offsetY
);
else
addError("Offset Y for piece state was equal to " + offsetY + ", offset must be between " + MIN_OFFSET + " and " + MAX_OFFSET);
else
addError("Offset X for piece state was equal to " + offsetX + ", offset must be between " + MIN_OFFSET + " and " + MAX_OFFSET);
else
addError("Scale for piece state was equal to " + scale + ", scale must be between 0 and " + MAX_SCALE);
}
return new ValueDisplayInfo();
}
//-------------------------------------------------------------------------
/**
* @param context The context.
* @param playerIndexCond The index of the player.
* @param pieceNameCond The name of the piece.
* @return The ValueDisplayInfo for the value.
*/
public ValueDisplayInfo displayPieceValue(final Context context, final int playerIndexCond, final String pieceNameCond)
{
final float MAX_SCALE = 100f; // multiplication factor on original size
final float MIN_OFFSET = -1f; // decimal percentage of board size
final float MAX_OFFSET = 1f; // decimal percentage of board size
for (final GraphicsItem graphicsItem : items)
if (graphicsItem instanceof ShowPieceValue)
{
final ShowPieceValue showPieceValue = (ShowPieceValue) graphicsItem;
final RoleType roleType = showPieceValue.roleType();
final String pieceName = showPieceValue.pieceName();
final float offsetX = showPieceValue.offsetX();
final float offsetY = showPieceValue.offsetY();
final float scale = showPieceValue.scale();
if (roleType == null || MetadataFunctions.getRealOwner(context, roleType) == playerIndexCond)
if (pieceName == null || pieceName.equals(pieceNameCond) || pieceName.equals(StringRoutines.removeTrailingNumbers(pieceNameCond)))
if (scale >= 0 && scale <= MAX_SCALE)
if (offsetX >= MIN_OFFSET && offsetX <= MAX_OFFSET)
if (offsetY >= MIN_OFFSET && offsetY <= MAX_OFFSET)
return new ValueDisplayInfo
(
showPieceValue.location(),
showPieceValue.offsetImage(),
showPieceValue.valueOutline(),
scale,
offsetX,
offsetY
);
else
addError("Offset Y for piece value was equal to " + offsetY + ", offset must be between " + MIN_OFFSET + " and " + MAX_OFFSET);
else
addError("Offset X for piece value was equal to " + offsetX + ", offset must be between " + MIN_OFFSET + " and " + MAX_OFFSET);
else
addError("Scale for piece value was equal to " + scale + ", scale must be between 0 and " + MAX_SCALE);
}
return new ValueDisplayInfo();
}
//-------------------------------------------------------------------------
/**
* @param context The context.
* @return The metadataImageInfo.
*/
public ArrayList<MetadataImageInfo> boardBackground(final Context context)
{
final float MAX_SCALE = 100f; // multiplication factor on original size
final int MAX_ROTATION = 360; // degrees
final float MIN_OFFSET = -1f; // decimal percentage of board size
final float MAX_OFFSET = 1f; // decimal percentage of board size
final ArrayList<MetadataImageInfo> allBackgrounds = new ArrayList<>();
for (final GraphicsItem graphicsItem : items)
if (graphicsItem instanceof BoardBackground)
{
final BoardBackground boardBackground = (BoardBackground)graphicsItem;
final int rotation = boardBackground.rotation();
final float offsetX = boardBackground.offsetX();
final float offsetY = boardBackground.offsetY();
final Colour fillColourMeta = boardBackground.fillColour();
final Colour edgeColourMeta = boardBackground.edgeColour();
final Color fillColour = (fillColourMeta == null) ? null : fillColourMeta.colour();
final Color edgeColour = (edgeColourMeta == null) ? null : edgeColourMeta.colour();
final float scale = boardBackground.scale();
float scaleX, scaleY;
if (Math.abs(scale - 1.0) > Constants.EPSILON)
{
scaleX = scale;
scaleY = scale;
}
else
{
scaleX = boardBackground.scaleX();
scaleY = boardBackground.scaleY();
}
if (scaleX >= 0 && scaleX <= MAX_SCALE && scaleY >= 0 && scaleY <= MAX_SCALE)
if (rotation >= 0 && rotation <= MAX_ROTATION)
if (offsetX >= MIN_OFFSET && offsetX <= MAX_OFFSET)
if (offsetY >= MIN_OFFSET && offsetY <= MAX_OFFSET)
allBackgrounds.add
(
new MetadataImageInfo
(
-1,
null,
boardBackground.image(),
scaleX,
scaleY,
fillColour,
edgeColour,
rotation,
offsetX,
offsetY
)
);
else
addError("Offset Y for board background was equal to " + offsetY + ", offset must be between " + MIN_OFFSET + " and " + MAX_OFFSET);
else
addError("Offset X for board background was equal to " + offsetX + ", offset must be between " + MIN_OFFSET + " and " + MAX_OFFSET);
else
addError("Rotation for board background was equal to " + rotation + ", rotation must be between 0 and " + MAX_ROTATION);
else
addError("Scale for board background was equal to " + scale + ", scale must be between 0 and " + MAX_SCALE);
}
return allBackgrounds;
}
//-------------------------------------------------------------------------
/**
* @param context The context.
* @return The metadataImageInfo.
*/
public ArrayList<MetadataImageInfo> boardForeground(final Context context)
{
final float MAX_SCALE = 100f; // multiplication factor on original size
final int MAX_ROTATION = 360; // degrees
final float MIN_OFFSET = -1f; // decimal percentage of board size
final float MAX_OFFSET = 1f; // decimal percentage of board size
final ArrayList<MetadataImageInfo> allForegrounds = new ArrayList<>();
for (final GraphicsItem graphicsItem : items)
if (graphicsItem instanceof BoardForeground)
{
final BoardForeground boardForeground = (BoardForeground)graphicsItem;
final int rotation = boardForeground.rotation();
final float offsetX = boardForeground.offsetX();
final float offsetY = boardForeground.offsetY();
final Colour fillColourMeta = boardForeground.fillColour();
final Color fillColour = (fillColourMeta == null) ? null : fillColourMeta.colour();
final Colour edgeColourMeta = boardForeground.edgeColour();
final Color edgeColour = (edgeColourMeta == null) ? null : edgeColourMeta.colour();
final float scale = boardForeground.scale();
float scaleX, scaleY;
if (Math.abs(scale - 1.0) > Constants.EPSILON)
{
scaleX = scale;
scaleY = scale;
}
else
{
scaleX = boardForeground.scaleX();
scaleY = boardForeground.scaleY();
}
if (scaleX >= 0 && scaleX <= MAX_SCALE && scaleY >= 0 && scaleY <= MAX_SCALE)
if (rotation >= 0 && rotation <= MAX_ROTATION)
if (offsetX >= MIN_OFFSET && offsetX <= MAX_OFFSET)
if (offsetY >= MIN_OFFSET && offsetY <= MAX_OFFSET)
allForegrounds.add
(
new MetadataImageInfo
(
-1,
null,
boardForeground.image(),
scaleX,
scaleY,
fillColour,
edgeColour,
boardForeground.rotation(),
boardForeground.offsetX(),
boardForeground.offsetY()
)
);
else
addError("Offset Y for board foreground was equal to " + offsetY + ", offset must be between " + MIN_OFFSET + " and " + MAX_OFFSET);
else
addError("Offset X for board foreground was equal to " + offsetX + ", offset must be between " + MIN_OFFSET + " and " + MAX_OFFSET);
else
addError("Rotation for board foreground was equal to " + rotation + ", rotation must be between 0 and " + MAX_ROTATION);
else
addError("Scale for board foreground was equal to " + scale + ", scale must be between 0 and " + MAX_SCALE);
}
return allForegrounds;
}
//-------------------------------------------------------------------------
/**
* @param context The context.
* @param playerIndexCond The index of the player.
* @param pieceNameCond The name of the piece.
* @param containerIndexCond The index of the container.
* @param stateCond The state.
* @param valueCond The value.
* @return The metadataImageInfo.
*/
public ArrayList<MetadataImageInfo> pieceBackground(final Context context, final int playerIndexCond, final String pieceNameCond, final int containerIndexCond, final int stateCond, final int valueCond)
{
final float MAX_SCALE = 100f; // multiplication factor on original size
final int MAX_ROTATION = 360; // degrees
final ArrayList<MetadataImageInfo> allBackground = new ArrayList<>();
for (final GraphicsItem graphicsItem : items)
if (graphicsItem instanceof PieceBackground)
{
final PieceBackground pieceBackground = (PieceBackground)graphicsItem;
final RoleType roleType = pieceBackground.roleType();
final String pieceName = pieceBackground.pieceName();
final Integer containerIndex = pieceBackground.container();
final Integer value = pieceBackground.value();
final Integer state = pieceBackground.state();
final int rotation = pieceBackground.rotation();
final Colour fillColourMeta = pieceBackground.fillColour();
final Color fillColour = (fillColourMeta == null) ? null : fillColourMeta.colour();
final Colour edgeColourMeta = pieceBackground.edgeColour();
final Color edgeColour = (edgeColourMeta == null) ? null : edgeColourMeta.colour();
final float scale = pieceBackground.scale();
float scaleX, scaleY;
if (Math.abs(scale - 1.0) > Constants.EPSILON)
{
scaleX = scale;
scaleY = scale;
}
else
{
scaleX = pieceBackground.scaleX();
scaleY = pieceBackground.scaleY();
}
if (roleType == null || MetadataFunctions.getRealOwner(context, roleType) == playerIndexCond)
if (state == null || state.intValue() == stateCond)
if (value == null || value.intValue() == valueCond)
if (containerIndex == null || containerIndex.intValue() == containerIndexCond)
if (pieceName == null || pieceName.equals(pieceNameCond) || pieceName.equals(StringRoutines.removeTrailingNumbers(pieceNameCond)))
if (scaleX >= 0 && scaleX <= MAX_SCALE && scaleY >= 0 && scaleY <= MAX_SCALE)
if (rotation >= 0 && rotation <= MAX_ROTATION)
allBackground.add
(
new MetadataImageInfo
(
-1,
null,
pieceBackground.image(),
pieceBackground.text(),
scaleX,
scaleY,
fillColour,
edgeColour,
pieceBackground.rotation(),
pieceBackground.offsetX(),
pieceBackground.offsetY()
)
);
else
addError("Rotation for background of piece " + pieceName + " was equal to " + rotation + ", rotation must be between 0 and " + MAX_ROTATION);
else
addError("Scale for background of piece " + pieceName + " was equal to " + scale + ", scale must be between 0 and " + MAX_SCALE);
}
return allBackground;
}
//-------------------------------------------------------------------------
/**
* @param context The context.
* @param playerIndexCond The index of the player.
* @param pieceNameCond The name of the piece.
* @param containerIndexCond The index of the container.
* @param stateCond The state.
* @param valueCond The value.
* @return The MetadataImageInfo
*/
public ArrayList<MetadataImageInfo> pieceForeground(final Context context, final int playerIndexCond, final String pieceNameCond, final int containerIndexCond, final int stateCond, final int valueCond)
{
final float MAX_SCALE = 100f; // multiplication factor on original size
final int MAX_ROTATION = 360; // degrees
final ArrayList<MetadataImageInfo> allForeground = new ArrayList<>();
for (final GraphicsItem graphicsItem : items)
if (graphicsItem instanceof PieceForeground)
{
final PieceForeground pieceForeground = (PieceForeground)graphicsItem;
final RoleType roleType = pieceForeground.roleType();
final String pieceName = pieceForeground.pieceName();
final Integer containerIndex = pieceForeground.container();
final Integer value = pieceForeground.value();
final Integer state = pieceForeground.state();
final int rotation = pieceForeground.rotation();
final Colour fillColourMeta = pieceForeground.fillColour();
final Color fillColour = (fillColourMeta == null) ? null : fillColourMeta.colour();
final Colour edgeColourMeta = pieceForeground.edgeColour();
final Color edgeColour = (edgeColourMeta == null) ? null : edgeColourMeta.colour();
final float scale = pieceForeground.scale();
float scaleX, scaleY;
if (Math.abs(scale - 1.0) > Constants.EPSILON)
{
scaleX = scale;
scaleY = scale;
}
else
{
scaleX = pieceForeground.scaleX();
scaleY = pieceForeground.scaleY();
}
if (roleType == null || MetadataFunctions.getRealOwner(context, roleType) == playerIndexCond)
if (state == null || state.intValue() == stateCond)
if (value == null || value.intValue() == valueCond)
if (containerIndex == null || containerIndex.intValue() == containerIndexCond)
if (pieceName == null || pieceName.equals(pieceNameCond) || pieceName.equals(StringRoutines.removeTrailingNumbers(pieceNameCond)))
if (scaleX >= 0 && scaleX <= MAX_SCALE && scaleY >= 0 && scaleY <= MAX_SCALE)
if (rotation >= 0 && rotation <= MAX_ROTATION)
allForeground.add
(
new MetadataImageInfo
(
-1,
null,
pieceForeground.image(),
pieceForeground.text(),
scaleX,
scaleY,
fillColour,
edgeColour,
pieceForeground.rotation(),
pieceForeground.offsetX(),
pieceForeground.offsetY()
)
);
else
addError("Rotation for foreground of piece " + pieceName + " was equal to " + rotation + ", rotation must be between 0 and " + MAX_ROTATION);
else
addError("Scale for foreground of piece " + pieceName + " was equal to " + scale + ", scale must be between 0 and " + MAX_SCALE);
}
return allForeground;
}
//-------------------------------------------------------------------------
/**
* @return The hidden image name.
*/
public String pieceHiddenImage()
{
for (final GraphicsItem graphicsItem : items)
if (graphicsItem instanceof HiddenImage)
return ((HiddenImage) graphicsItem).hiddenImage();
return null;
}
//-------------------------------------------------------------------------
/**
* @param context The context.
* @param playerIndexCond The index of the player.
* @param pieceNameCond The name of the piece.
* @param containerIndexCond The index of the container.
* @param stateCond The state.
* @param valueCond The value.
* @param pieceColourType The aspect of the piece that is being coloured.
* @return The colour.
*/
public Color pieceColour(final Context context, final int playerIndexCond, final String pieceNameCond, final int containerIndexCond, final int stateCond, final int valueCond, final PieceColourType pieceColourType)
{
for (final GraphicsItem graphicsItem : items)
if (graphicsItem instanceof PieceColour)
{
final PieceColour pieceColour = (PieceColour) graphicsItem;
final RoleType roleType = pieceColour.roleType();
final String pieceName = pieceColour.pieceName();
final Integer containerIndex = pieceColour.container();
final Integer state = pieceColour.state();
final Integer value = pieceColour.value();
final Colour fillColour = pieceColour.fillColour();
final Colour strokeColour = pieceColour.strokeColour();
final Colour secondaryColour = pieceColour.secondaryColour();
if (roleType == null || MetadataFunctions.getRealOwner(context, roleType) == playerIndexCond)
if (state == null || state.intValue() == stateCond)
if (value == null || value.intValue() == valueCond)
if (containerIndex == null || containerIndex.intValue() == containerIndexCond)
if (pieceName == null || pieceName.equals(pieceNameCond) || pieceName.equals(StringRoutines.removeTrailingNumbers(pieceNameCond)))
{
if (pieceColourType.equals(PieceColourType.Fill))
return (fillColour == null) ? null : fillColour.colour();
else if (pieceColourType.equals(PieceColourType.Edge))
return (strokeColour == null) ? null : strokeColour.colour();
else if (pieceColourType.equals(PieceColourType.Secondary))
return (secondaryColour == null) ? null : secondaryColour.colour();
}
}
return null;
}
//-------------------------------------------------------------------------
/**
* @return The list of the families pieces.
*/
public String[] pieceFamilies()
{
for (final GraphicsItem graphicsItem : items)
if (graphicsItem instanceof PieceFamilies)
return ((PieceFamilies) graphicsItem).pieceFamilies();
return null;
}
//-------------------------------------------------------------------------
/**
* @param context The context.
* @param playerIndexCond The index of the player.
* @param pieceNameCond The name of the piece.
* @param containerIndexCond The index of the container.
* @param stateCond The state.
* @param valueCond The value.
* @return The degrees to rotate the piece image (clockwise).
*/
public int pieceRotate(final Context context, final int playerIndexCond, final String pieceNameCond, final int containerIndexCond, final int stateCond, final int valueCond)
{
final int MAX_ROTATION = 360; // degrees
for (final GraphicsItem graphicsItem : items)
if (graphicsItem instanceof PieceRotate)
{
final PieceRotate pieceRotate = (PieceRotate)graphicsItem;
final RoleType roleType = pieceRotate.roleType();
final String pieceName = pieceRotate.pieceName();
final Integer containerIndex = pieceRotate.container();
final Integer value = pieceRotate.value();
final Integer state = pieceRotate.state();
final int rotation = pieceRotate.rotation();
if (roleType == null || MetadataFunctions.getRealOwner(context, roleType) == playerIndexCond)
if (state == null || state.intValue() == stateCond)
if (value == null || value.intValue() == valueCond)
if (containerIndex == null || containerIndex.intValue() == containerIndexCond)
if (pieceName == null || pieceName.equals(pieceNameCond) || pieceName.equals(StringRoutines.removeTrailingNumbers(pieceNameCond)))
if (rotation >= 0 && rotation <= MAX_ROTATION)
return rotation;
else
addError("Rotation for piece" + pieceNameCond + "was equal to " + rotation + ", rotation must be between 0 and " + MAX_ROTATION);
}
return 0;
}
//-------------------------------------------------------------------------
/**
* @param context The context
* @param playerIndexCond The index of the player.
* @param pieceNameCond The name of the piece.
* @param containerIndexCond The index of the container.
* @param stateCond The state.
* @param valueCond The state.
* @return The piece name extended.
*/
public String pieceNameExtension(final Context context, final int playerIndexCond, final String pieceNameCond, final int containerIndexCond, final int stateCond, final int valueCond)
{
for (final GraphicsItem graphicsItem : items)
if (graphicsItem instanceof PieceExtendName)
{
final PieceExtendName pieceExtendName = (PieceExtendName)graphicsItem;
final RoleType roleType = pieceExtendName.roleType();
final String pieceName = pieceExtendName.pieceName();
final Integer containerIndex = pieceExtendName.container();
final Integer value = pieceExtendName.value();
final Integer state = pieceExtendName.state();
if (roleType == null || MetadataFunctions.getRealOwner(context, roleType) == playerIndexCond)
if (state == null || state.intValue() == stateCond)
if (value == null || value.intValue() == valueCond)
if (containerIndex == null || containerIndex.intValue() == containerIndexCond)
if (pieceName == null || pieceName.equals(pieceNameCond) || pieceName.equals(StringRoutines.removeTrailingNumbers(pieceNameCond)))
return pieceExtendName.nameExtension();
}
return "";
}
//-------------------------------------------------------------------------
/**
* @param context The context.
* @param playerIndexCond The index of the player.
* @param pieceNameCond The name of the piece.
* @param containerIndexCond The index of the container.
* @param stateCond The state.
* @param valueCond The value.
* @return The new name.
*/
public String pieceNameReplacement(final Context context, final int playerIndexCond, final String pieceNameCond, final int containerIndexCond, final int stateCond, final int valueCond)
{
for (final GraphicsItem graphicsItem : items)
if (graphicsItem instanceof PieceRename)
{
final PieceRename pieceRename = (PieceRename)graphicsItem;
final RoleType roleType = pieceRename.roleType();
final String pieceName = pieceRename.pieceName();
final Integer containerIndex = pieceRename.container();
final Integer value = pieceRename.value();
final Integer state = pieceRename.state();
if (roleType == null || MetadataFunctions.getRealOwner(context, roleType) == playerIndexCond)
if (state == null || state.intValue() == stateCond)
if (value == null || value.intValue() == valueCond)
if (containerIndex == null || containerIndex.intValue() == containerIndexCond)
if (pieceName == null || pieceName.equals(pieceNameCond) || pieceName.equals(StringRoutines.removeTrailingNumbers(pieceNameCond)))
return pieceRename.nameReplacement();
}
return null;
}
//-------------------------------------------------------------------------
/**
* @param context The context.
* @param playerIndexCond The index of the player.
* @param pieceNameCond The name of the piece.
* @param containerIndexCond The index of the container.
* @param stateCond The state.
* @param valueCond The value.
* @return The new scale.
*/
public Point2D.Float pieceScale(final Context context, final int playerIndexCond, final String pieceNameCond, final int containerIndexCond, final int stateCond, final int valueCond)
{
for (final GraphicsItem graphicsItem : items)
if (graphicsItem instanceof PieceScale)
{
final PieceScale pieceScale = (PieceScale)graphicsItem;
final RoleType roleType = pieceScale.roleType();
final String pieceName = pieceScale.pieceName();
final Integer containerIndex = pieceScale.container();
final Integer value = pieceScale.value();
final Integer state = pieceScale.state();
final float scale = pieceScale.scale();
float scaleX, scaleY;
if (Math.abs(scale - 1.0) > Constants.EPSILON)
{
scaleX = scale;
scaleY = scale;
}
else
{
scaleX = pieceScale.scaleX();
scaleY = pieceScale.scaleY();
}
if (roleType == null || MetadataFunctions.getRealOwner(context, roleType) == playerIndexCond)
if (state == null || state.intValue() == stateCond)
if (value == null || value.intValue() == valueCond)
if (containerIndex == null || containerIndex.intValue() == containerIndexCond)
if (pieceName == null || pieceName.equals(pieceNameCond) || pieceName.equals(StringRoutines.removeTrailingNumbers(pieceNameCond)))
return new Point2D.Float(scaleX, scaleY);
}
return new Point2D.Float((float)0.9, (float)0.9);
}
//-------------------------------------------------------------------------
/**
* @param context The context.
* @param playerIndexCond The index of the player.
* @param pieceNameCond The name of the piece.
* @return True if check is used.
*/
public boolean checkUsed(final Context context, final int playerIndexCond, final String pieceNameCond)
{
for (final GraphicsItem graphicsItem : items)
if (graphicsItem instanceof ShowCheck)
{
final ShowCheck showCheck = (ShowCheck)graphicsItem;
final RoleType roleType = showCheck.roleType();
final String pieceName = showCheck.pieceName();
if (roleType == null || MetadataFunctions.getRealOwner(context, roleType) == playerIndexCond)
if (pieceName == null || pieceName.equals(pieceNameCond) || pieceName.equals(StringRoutines.removeTrailingNumbers(pieceNameCond)))
return true;
}
return false;
}
//-------------------------------------------------------------------------
/**
* @param context The context.
* @return The list of the MetadataImageInfo.
*/
public ArrayList<MetadataImageInfo> drawSymbol(final Context context)
{
final int MAX_ROTATION = 360; // degrees
final ArrayList<MetadataImageInfo> allSymbols = new ArrayList<>();
for (final GraphicsItem graphicsItem : items)
{
if (graphicsItem instanceof ShowSymbol)
{
final ShowSymbol showSymbol = (ShowSymbol)graphicsItem;
final RoleType roleType = showSymbol.roleType();
final String imageName = showSymbol.imageName();
final String text = showSymbol.text();
final int rotation = showSymbol.rotation();
final float offsetX = showSymbol.getOffsetX();
final float offsetY = showSymbol.getOffsetY();
final String region = showSymbol.region();
final RegionFunction regionFunction = showSymbol.regionFunction();
final Integer[] sites = showSymbol.sites();
final SiteType graphElementType = showSymbol.graphElementType(context);
final Colour fillColourMeta = showSymbol.fillColour();
final Color fillColour = (fillColourMeta == null) ? null : fillColourMeta.colour();
final Colour edgeColourMeta = showSymbol.edgeColour();
final Color edgeColour = (edgeColourMeta == null) ? null : edgeColourMeta.colour();
final float scale = showSymbol.scale();
float scaleX, scaleY;
if (Math.abs(scale - 1.0) > Constants.EPSILON)
{
scaleX = scale;
scaleY = scale;
}
else
{
scaleX = showSymbol.scaleX();
scaleY = showSymbol.scaleY();
}
if (rotation < 0 || rotation > MAX_ROTATION)
{
addError("Rotation for symbol" + imageName + "was equal to " + rotation + ", rotation must be between 0 and " + MAX_ROTATION);
continue;
}
if (sites != null)
{
for (final Integer site : sites)
{
if (context.game().board().topology().getGraphElements(graphElementType).size() > site.intValue())
allSymbols.add(new MetadataImageInfo(site.intValue(), graphElementType, imageName, text, scaleX, scaleY, fillColour, edgeColour, rotation, offsetX, offsetY));
else
addError("Failed to add symbol " + imageName + " at site " + site.intValue() + " with graphElementType " + graphElementType);
}
}
else if (region != null)
{
for (final ArrayList<Integer> regionSites : MetadataFunctions.convertRegionToSiteArray(context, region, roleType))
{
for (final Integer site : regionSites)
{
if (context.game().board().topology().getGraphElements(graphElementType).size() > site.intValue())
allSymbols.add(new MetadataImageInfo(site.intValue(),graphElementType, imageName, text, scaleX, scaleY, fillColour, edgeColour, rotation, offsetX, offsetY));
else
addError("Failed to add symbol " + imageName + " at region site " + site.intValue() + " with graphElementType " + graphElementType);
}
}
}
else if (regionFunction != null)
{
regionFunction.preprocess(context.game());
for(final int site : regionFunction.eval(context).sites())
{
if (context.game().board().topology().getGraphElements(graphElementType).size() > site)
allSymbols.add(new MetadataImageInfo(site, graphElementType, imageName, text, scaleX, scaleY, fillColour, edgeColour, rotation, offsetX, offsetY));
else
addError("Failed to add symbol " + imageName + " at region site " + site + " with graphElementType " + graphElementType);
}
}
}
}
return allSymbols;
}
//-------------------------------------------------------------------------
/**
* @param context The context.
* @return The list of the MetadataImageInfo.
*/
public ArrayList<MetadataImageInfo> drawLines(final Context context)
{
final ArrayList<MetadataImageInfo> allLines = new ArrayList<>();
for (final GraphicsItem graphicsItem : items)
if (graphicsItem instanceof ShowLine)
{
final ShowLine showLine = (ShowLine)graphicsItem;
final Integer[][] lines = showLine.lines();
final Float[] curve = showLine.curve();
final float scale = showLine.scale();
final SiteType siteType = showLine.siteType();
final CurveType curveType = showLine.curveType();
final LineStyle lineStyle = showLine.style();
final Colour colourMeta = showLine.colour();
final Color colour = (colourMeta == null) ? null : colourMeta.colour();
if (lines != null)
{
for (final Integer[] line : lines)
{
if (context.game().board().topology().vertices().size() > Math.max(line[0].intValue(), line[1].intValue()))
if (curve == null || curve.length == 4)
allLines.add(new MetadataImageInfo(line, colour, scale, curve, siteType, curveType, lineStyle));
else
addError("Exactly 4 values must be specified for the curve between " + line[0] + " and " + line[1]);
else
addError("Failed to draw line between vertices " + line[0] + " and " + line[1]);
}
}
}
return allLines;
}
//-------------------------------------------------------------------------
/**
* @param boardGraphicsTypeCond The BoardGraphicsType.
* @return The colour of the board.
*/
public Color boardColour(final BoardGraphicsType boardGraphicsTypeCond)
{
for (final GraphicsItem graphicsItem : items)
if (graphicsItem instanceof BoardColour)
{
final BoardColour boardColour = (BoardColour)graphicsItem;
final BoardGraphicsType boardGraphicsType = boardColour.boardGraphicsType();
final Colour colourMeta = boardColour.colour();
if (boardGraphicsType == boardGraphicsTypeCond)
return (colourMeta == null) ? null : colourMeta.colour();
}
return null;
}
//-------------------------------------------------------------------------
/**
* @return True if the board is hidden.
*/
public boolean boardHidden()
{
for (final GraphicsItem graphicsItem : items)
if (graphicsItem instanceof NoBoard)
return ((NoBoard) graphicsItem).boardHidden();
return false;
}
//-------------------------------------------------------------------------
/**
* @return True if the region owned has to be showed.
*/
public boolean showRegionOwner()
{
for (final GraphicsItem graphicsItem : items)
if (graphicsItem instanceof ShowRegionOwner)
return ((ShowRegionOwner) graphicsItem).show();
return false;
}
//-------------------------------------------------------------------------
/**
* @return The ContainerStyleType.
*/
public ContainerStyleType boardStyle()
{
for (final GraphicsItem graphicsItem : items)
if (graphicsItem instanceof BoardStyle)
return ((BoardStyle) graphicsItem).containerStyleType();
return null;
}
//-------------------------------------------------------------------------
/**
* @return If the container is supposed to only render Edges in a special way (pen and paper style).
*/
public boolean replaceComponentsWithFilledCells()
{
for (final GraphicsItem graphicsItem : items)
if (graphicsItem instanceof BoardStyle)
return ((BoardStyle) graphicsItem).replaceComponentsWithFilledCells();
return false;
}
//-------------------------------------------------------------------------
/**
* @return True if the board is checkered.
*/
public boolean checkeredBoard()
{
for (final GraphicsItem graphicsItem : items)
if (graphicsItem instanceof BoardCheckered)
return ((BoardCheckered) graphicsItem).checkeredBoard();
return false;
}
//-------------------------------------------------------------------------
/**
* @param context The context.
* @return True if the regions have to be filled.
*/
public ArrayList<ArrayList<MetadataImageInfo>> regionsToFill(final Context context)
{
final ArrayList<ArrayList<MetadataImageInfo>> allRegions = new ArrayList<>();
for (final GraphicsItem graphicsItem : items)
if (graphicsItem instanceof RegionColour)
{
final RegionColour regionColour = (RegionColour)graphicsItem;
final RoleType roleType = regionColour.roleType();
final String region = regionColour.region();
final RegionFunction regionFunction = regionColour.regionFunction();
final Integer[] sites = regionColour.sites();
final SiteType graphElementType = regionColour.graphElementType(context);
final SiteType regionSiteType = regionColour.regionSiteType(context);
final Colour colourMeta = regionColour.colour();
final Color colour = (colourMeta == null) ? null : colourMeta.colour();
final float scale = regionColour.getScale();
if (sites != null)
{
allRegions.add(new ArrayList<>());
for (final Integer site : sites)
{
if (context.game().board().topology().getGraphElements(graphElementType).size() > site.intValue())
{
allRegions.get(allRegions.size()-1).add(new MetadataImageInfo(site.intValue(), graphElementType, regionSiteType, colour, scale));
}
else
addError("Failed to fill site " + site.intValue() + " with graphElementType " + graphElementType);
}
}
else if (region != null)
{
for (final ArrayList<Integer> regionSiteList : MetadataFunctions.convertRegionToSiteArray(context, region, roleType))
{
allRegions.add(new ArrayList<>());
for (final int site : regionSiteList)
{
if (context.game().board().topology().getGraphElements(graphElementType).size() > site)
allRegions.get(allRegions.size()-1).add(new MetadataImageInfo(site, graphElementType, regionSiteType, colour, scale));
else
addError("Failed to fill region " + region + "at site " + site + " with graphElementType " + graphElementType);
}
}
}
else if (regionFunction != null)
{
allRegions.add(new ArrayList<>());
regionFunction.preprocess(context.game());
for (final int site : regionFunction.eval(context).sites())
{
if (context.game().board().topology().getGraphElements(graphElementType).size() > site)
allRegions.get(allRegions.size()-1).add(new MetadataImageInfo(site, graphElementType, regionSiteType, colour, scale));
else
addError("Failed to fill region " + region + "at site " + site + " with graphElementType " + graphElementType);
}
}
}
return allRegions;
}
//-------------------------------------------------------------------------
/**
* @param boardGraphicsTypeCond The BoardGraphicsType.
* @return The new thickness.
*/
public float boardThickness(final BoardGraphicsType boardGraphicsTypeCond)
{
final float MAX_THICKNESS = 100f; // multiplication factor on original size
for (final GraphicsItem graphicsItem : items)
if (graphicsItem instanceof BoardStyleThickness)
{
final BoardStyleThickness boardStyleThickness = (BoardStyleThickness)graphicsItem;
final BoardGraphicsType boardGraphicsType = boardStyleThickness.boardGraphicsType();
final float thickness = boardStyleThickness.thickness();
if (boardGraphicsType.equals(boardGraphicsTypeCond))
if (thickness >= 0 && thickness <= MAX_THICKNESS)
return thickness;
else addError("Scale for board thickness " + boardGraphicsTypeCond.name() + " was equal to " + thickness + ", scale must be between 0 and " + MAX_THICKNESS);
}
return (float) 1.0;
}
//-------------------------------------------------------------------------
/**
* @return The new thickness.
*/
public float boardCurvature()
{
for (final GraphicsItem graphicsItem : items)
if (graphicsItem instanceof BoardCurvature)
return ((BoardCurvature) graphicsItem).curveOffset();
return (float) 0.333;
}
//-------------------------------------------------------------------------
/**
* @return True if the puzzle is adversarial.
*/
public boolean adversarialPuzzle()
{
for (final GraphicsItem graphicsItem : items)
if (graphicsItem instanceof AdversarialPuzzle)
return ((AdversarialPuzzle) graphicsItem).adversarialPuzzle();
return false;
}
//-------------------------------------------------------------------------
/**
* @param context The context.
* @param playerId The player Id
* @return When to show the score.
*/
public ScoreDisplayInfo scoreDisplayInfo(final Context context, final int playerId)
{
for (final GraphicsItem graphicsItem : items)
if (graphicsItem instanceof ShowScore)
{
final ShowScore showScore = (ShowScore)graphicsItem;
final RoleType roleType = showScore.roleType();
if (roleType == RoleType.All || MetadataFunctions.getRealOwner(context, roleType) == playerId)
return new ScoreDisplayInfo(showScore.showScore(), roleType, showScore.scoreReplacement(), showScore.scoreSuffix());
}
return new ScoreDisplayInfo();
}
//-------------------------------------------------------------------------
/**
* @return True if no animation.
*/
public boolean noAnimation()
{
for (final GraphicsItem graphicsItem : items)
if (graphicsItem instanceof NoAnimation)
return ((NoAnimation) graphicsItem).noAnimation();
return false;
}
//-------------------------------------------------------------------------
/**
* @return True if no sunken visuals.
*/
public boolean noSunken()
{
for (final GraphicsItem graphicsItem : items)
if (graphicsItem instanceof NoSunken)
return ((NoSunken) graphicsItem).noSunken();
return false;
}
//-------------------------------------------------------------------------
/**
* @return True if pips on the dice should be always drawn as a single number.
*/
public boolean noDicePips()
{
for (final GraphicsItem graphicsItem : items)
if (graphicsItem instanceof NoDicePips)
return ((NoDicePips) graphicsItem).noDicePips();
return false;
}
//-------------------------------------------------------------------------
/**
* @return The list of the suit ranking.
*/
public SuitType[] suitRanking()
{
for (final GraphicsItem graphicsItem : items)
if (graphicsItem instanceof SuitRanking)
return ((SuitRanking) graphicsItem).suitRanking();
return null;
}
//-------------------------------------------------------------------------
/**
* @param context The context.
* @param containerCond The container.
* @param siteCond The site.
* @param siteTypeCond The graph element type.
* @param stateCond The state site.
* @param valueCond The value site.
* @param stackPropertyType The property of the stack being checked.
* @return The piece stack scale.
*/
public double stackMetadata(final Context context, final Container containerCond, final int siteCond, final SiteType siteTypeCond, final int stateCond, final int valueCond, final StackPropertyType stackPropertyType)
{
final float MAX_SCALE = 100f; // multiplication factor on original size.
final int MAX_LIMIT = 10; // max height of stack.
for (final GraphicsItem graphicsItem : items)
if (graphicsItem instanceof StackType)
{
final StackType stackType = (StackType)graphicsItem;
final RoleType roleType = stackType.roleType();
final String containerName = stackType.name();
final Integer containerIndex = stackType.index();
final Integer[] sites = stackType.sites();
final SiteType graphElementType = stackType.graphElementType();
final Integer state = stackType.state();
final Integer value = stackType.value();
final float scale = stackType.scale();
final float limit = stackType.limit();
final PieceStackType pieceStackType = stackType.stackType();
if (roleType == null || MetadataFunctions.getRealOwner(context, roleType) == containerCond.owner())
if (containerName == null || containerName.equals(containerCond.name()) || containerName.equals(StringRoutines.removeTrailingNumbers(containerCond.name())))
if (containerIndex == null || containerIndex.equals(Integer.valueOf(containerCond.index())))
if (sites == null || Arrays.asList(sites).contains(Integer.valueOf(siteCond)) )
if (graphElementType == null || graphElementType.equals(siteTypeCond))
if (state == null || state.equals(Integer.valueOf(stateCond)))
if (value == null || value.equals(Integer.valueOf(valueCond)))
{
if (stackPropertyType.equals(StackPropertyType.Scale))
if (scale >= 0 && scale <= MAX_SCALE)
return scale;
else
addError("Stack scale for role " + roleType + " name " + containerName + " was equal to " + scale + ", scale must be between 0 and " + MAX_SCALE);
else if (stackPropertyType.equals(StackPropertyType.Limit))
if (limit >= 1 && limit <= MAX_LIMIT)
return limit;
else
addError("Stack scale for role " + roleType + " name " + containerName + " was equal to " + limit + ", limit must be between 1 and " + MAX_LIMIT);
else if (stackPropertyType.equals(StackPropertyType.Type))
return pieceStackType.ordinal();
}
}
if (stackPropertyType.equals(StackPropertyType.Scale))
return 1.0;
else if (stackPropertyType.equals(StackPropertyType.Limit))
return 5;
else if (stackPropertyType.equals(StackPropertyType.Type))
return PieceStackType.Default.ordinal();
return 0;
}
//-------------------------------------------------------------------------
/**
* @param context The context.
* @param playerIndex The index of the player.
* @return The colour of a given player index.
*/
public Color playerColour(final Context context, final int playerIndex)
{
for (final GraphicsItem graphicsItem : items)
if (graphicsItem instanceof PlayerColour)
{
final PlayerColour playerColour = ((PlayerColour) graphicsItem);
final RoleType roleType = playerColour.roleType();
final Colour colourMeta = playerColour.colour();
if (MetadataFunctions.getRealOwner(context, roleType) == playerIndex)
return (colourMeta == null) ? null : colourMeta.colour();
}
return null;
}
//-------------------------------------------------------------------------
/**
*
* @param context The context.
* @param playerIndex The index of the player.
* @return The name of a given player index.
*/
public String playerName(final Context context, final int playerIndex)
{
for (final GraphicsItem graphicsItem : items)
if (graphicsItem instanceof PlayerName)
{
final PlayerName playerName = ((PlayerName) graphicsItem);
final RoleType roleType = playerName.roleType();
if (MetadataFunctions.getRealOwner(context, roleType) == playerIndex)
return playerName.name();
}
return null;
}
//-------------------------------------------------------------------------
/**
* @return True if the sites has to be drawn like a hole.
*/
public int[] sitesAsSpecialHoles()
{
for (final GraphicsItem graphicsItem : items)
if (graphicsItem instanceof ShowSitesAsHoles)
return ((ShowSitesAsHoles) graphicsItem).indices();
return new int[0];
}
/**
* @return The shape of the holes.
*/
public HoleType shapeSpecialHole()
{
for (final GraphicsItem graphicsItem : items)
if (graphicsItem instanceof ShowSitesAsHoles)
return ((ShowSitesAsHoles) graphicsItem).type();
return null;
}
//-------------------------------------------------------------------------
/**
* @param game The game.
* @param element The topology element.
* @return Returns the additional value to add to this sites index when displayed, Null if no value to be shown.
*/
public Integer showSiteIndex(final Game game, final TopologyElement element)
{
for (final GraphicsItem graphicsItem : items)
if (graphicsItem instanceof ShowSitesIndex)
if (((ShowSitesIndex) graphicsItem).type().equals(element.elementType()))
return ((ShowSitesIndex) graphicsItem).additionalValue();
return null;
}
//-------------------------------------------------------------------------
/**
* @return True If the player holes have to be showed.
*/
public boolean showPlayerHoles()
{
for (final GraphicsItem graphicsItem : items)
if (graphicsItem instanceof ShowPlayerHoles)
return ((ShowPlayerHoles) graphicsItem).showPlayerHoles();
return false;
}
//-------------------------------------------------------------------------
/**
* @return True If the holes with a local state of zero should be marked.
*/
public boolean holesUseLocalState()
{
for (final GraphicsItem graphicsItem : items)
if (graphicsItem instanceof ShowLocalStateHoles)
return ((ShowLocalStateHoles) graphicsItem).useLocalState();
return false;
}
//-------------------------------------------------------------------------
/**
* @param edgeTypeCond The edge type.
* @param relationTypeCond The relation type.
* @param connectionCond True if this is a connection.
* @return The EdgeInfoGUI.
*/
public EdgeInfoGUI drawEdge(final EdgeType edgeTypeCond, final RelationType relationTypeCond, final boolean connectionCond)
{
for (final GraphicsItem graphicsItem : items)
if (graphicsItem instanceof ShowEdges)
{
final ShowEdges showEdges = ((ShowEdges) graphicsItem);
final EdgeType edgeType = showEdges.edgeType();
final RelationType relationType = showEdges.relationType();
final Boolean connection = showEdges.connection();
if (edgeType.supersetOf(edgeTypeCond))
if (relationType.supersetOf(relationTypeCond))
if (connection.booleanValue() == connectionCond)
return new EdgeInfoGUI(showEdges.style(), showEdges.colour().colour());
}
return null;
}
//-------------------------------------------------------------------------
/**
* @return true to show the pits.
*/
public boolean showPits()
{
for (final GraphicsItem graphicsItem : items)
if (graphicsItem instanceof ShowPits)
return ((ShowPits) graphicsItem).showPits();
return false;
}
//-------------------------------------------------------------------------
/**
* @return True to show the costs.
*/
public boolean showCost()
{
for (final GraphicsItem graphicsItem : items)
if (graphicsItem instanceof ShowCost)
return ((ShowCost) graphicsItem).showCost();
return false;
}
//-------------------------------------------------------------------------
/**
* @return True to show the hints.
*/
public PuzzleHintLocationType hintLocationType()
{
for (final GraphicsItem graphicsItem : items)
if (graphicsItem instanceof HintLocation)
return ((HintLocation) graphicsItem).hintLocation();
return null;
}
//-------------------------------------------------------------------------
/**
* @return True to show the hints.
*/
public PuzzleDrawHintType drawHintType()
{
for (final GraphicsItem graphicsItem : items)
if (graphicsItem instanceof DrawHint)
return ((DrawHint) graphicsItem).drawHint();
return null;
}
//-------------------------------------------------------------------------
/**
* @return True to show the costs.
*/
public boolean showEdgeDirections()
{
for (final GraphicsItem graphicsItem : items)
if (graphicsItem instanceof ShowEdgeDirections)
return ((ShowEdgeDirections) graphicsItem).showEdgeDirections();
return false;
}
//-------------------------------------------------------------------------
/**
* @return True to show curved edges.
*/
public boolean showCurvedEdges()
{
for (final GraphicsItem graphicsItem : items)
if (graphicsItem instanceof ShowCurvedEdges)
return ((ShowCurvedEdges) graphicsItem).showCurvedEdges();
return true;
}
//-------------------------------------------------------------------------
/**
* @return True to show straight edges.
*/
public boolean showStraightEdges()
{
for (final GraphicsItem graphicsItem : items)
if (graphicsItem instanceof ShowStraightEdges)
return ((ShowStraightEdges) graphicsItem).showStraightEdges();
return true;
}
//-------------------------------------------------------------------------
/**
* @return True to show the costs.
*/
public boolean showPossibleMoves()
{
for (final GraphicsItem graphicsItem : items)
if (graphicsItem instanceof ShowPossibleMoves)
return ((ShowPossibleMoves) graphicsItem).showPossibleMoves();
return false;
}
//-------------------------------------------------------------------------
/**
* @return True to draw the lines of the ring with straight lines.
*/
public boolean straightRingLines()
{
for (final GraphicsItem graphicsItem : items)
if (graphicsItem instanceof NoCurves)
return ((NoCurves) graphicsItem).straightRingLines();
return false;
}
//-------------------------------------------------------------------------
/**
* @return The shape of the cell.
*/
public ShapeType cellShape()
{
for (final GraphicsItem graphicsItem : items)
if (graphicsItem instanceof ShowSitesShape)
return ((ShowSitesShape) graphicsItem).shape();
return null;
}
//-------------------------------------------------------------------------
/**
* @return The shape of the board.
*/
public ShapeType boardShape()
{
for (final GraphicsItem graphicsItem : items)
if (graphicsItem instanceof BoardShape)
return ((BoardShape) graphicsItem).shape();
return null;
}
//-------------------------------------------------------------------------
/**
* @return The placement of the board.
*/
public Rectangle2D boardPlacement()
{
for (final GraphicsItem graphicsItem : items)
if (graphicsItem instanceof BoardPlacement)
{
final BoardPlacement boardPlacement = ((BoardPlacement) graphicsItem);
return (new Rectangle2D.Double(boardPlacement.offsetX(), boardPlacement.offsetY(), boardPlacement.scale(), boardPlacement.scale()));
}
return null;
}
//-------------------------------------------------------------------------
/**
* @param context
* @param playerId
* @return The placement of the hand.
*/
public Rectangle2D handPlacement(final Context context, final int playerId)
{
for (final GraphicsItem graphicsItem : items)
if (graphicsItem instanceof HandPlacement)
{
final HandPlacement handPlacement = ((HandPlacement) graphicsItem);
if (new Id(null,handPlacement.getPlayer()).eval(context) == playerId)
return (new Rectangle2D.Double(handPlacement.offsetX(), handPlacement.offsetY(), handPlacement.scale(), handPlacement.scale()));
}
return null;
}
//-------------------------------------------------------------------------
/**
* @param context
* @param playerId
* @return If orientation of a hand is vertical.
*/
public boolean handVertical(final Context context, final int playerId)
{
for (final GraphicsItem graphicsItem : items)
if (graphicsItem instanceof HandPlacement)
{
final HandPlacement handPlacement = ((HandPlacement) graphicsItem);
if (new Id(null,handPlacement.getPlayer()).eval(context) == playerId)
return handPlacement.isVertical();
}
return false;
}
//-------------------------------------------------------------------------
@Override
public String toString()
{
final StringBuilder sb = new StringBuilder();
final String open = (items.size() <= 1) ? "" : "{";
final String close = (items.size() <= 1) ? "" : "}";
sb.append(" (graphics " + open + "\n");
for (final GraphicsItem item : items)
if (item != null)
sb.append(" " + item.toString());
sb.append(" " + close + ")\n");
return sb.toString();
}
//-------------------------------------------------------------------------
/**
* Add error to errorReport.
*/
private void addError(final String string)
{
errorReport += "Error: " + string + "\n";
}
/**
* @return errorReport.
*/
public String getErrorReport()
{
return errorReport;
}
/**
* Set errorReport.
*
* @param s The report.
*/
public void setErrorReport(final String s)
{
errorReport = s;
}
//-------------------------------------------------------------------------
/**
* @param game The game.
* @return Accumulated concepts.
*/
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
for (final GraphicsItem item : items)
if (item != null)
concepts.or(item.concepts(game));
return concepts;
}
/**
* @param game The game.
* @return Accumulated concepts.
*/
public long gameFlags(final Game game)
{
long gameFlags = 0l;
for (final GraphicsItem item : items)
if (item != null)
gameFlags |= item.gameFlags(game);
return gameFlags;
}
/**
* Compute if the game needs to be redrawn.
* @param game The game.
*/
public void computeNeedRedraw(final Game game)
{
for (final Regions region : game.equipment().regions())
if (!region.isStatic())
needRedraw = true;
for (final GraphicsItem item : items)
if (item != null && item.needRedraw())
needRedraw = true;
}
/**
* @return True if the graphics need to be redrawn after each move.
*/
public boolean needRedrawn()
{
return needRedraw;
}
}
| 64,477 | 34.505507 | 216 | java |
Ludii | Ludii-master/Core/src/metadata/graphics/GraphicsItem.java | package metadata.graphics;
import java.util.BitSet;
import game.Game;
import metadata.MetadataItem;
/**
* Metadata containing graphics hints.
* @author cambolbro
*/
public interface GraphicsItem extends MetadataItem
{
/**
* @param game The game.
* @return Accumulated concepts.
*/
public BitSet concepts(final Game game);
/**
* @param game The game.
* @return Accumulated game flags.
*/
public long gameFlags(final Game game);
/**
* @return True if this ludeme needs to be redrawn after each move.
*/
public boolean needRedraw();
}
| 563 | 17.193548 | 68 | java |
Ludii | Ludii-master/Core/src/metadata/graphics/package-info.java | /**
* @chapter The {\tt graphics} metadata items give hints for rendering the board and components, as well as custom UI behaviour,
* to customise the interface for specific games and improve the playing experience.
*/
package metadata.graphics;
| 250 | 40.833333 | 129 | java |
Ludii | Ludii-master/Core/src/metadata/graphics/board/Board.java | package metadata.graphics.board;
import java.util.BitSet;
import annotations.Name;
import annotations.Opt;
import game.Game;
import metadata.graphics.GraphicsItem;
import metadata.graphics.board.Boolean.BoardCheckered;
import metadata.graphics.board.colour.BoardColour;
import metadata.graphics.board.curvature.BoardCurvature;
import metadata.graphics.board.ground.BoardBackground;
import metadata.graphics.board.ground.BoardForeground;
import metadata.graphics.board.placement.BoardPlacement;
import metadata.graphics.board.style.BoardStyle;
import metadata.graphics.board.styleThickness.BoardStyleThickness;
import metadata.graphics.piece.PieceGroundType;
import metadata.graphics.util.BoardGraphicsType;
import metadata.graphics.util.ContainerStyleType;
import metadata.graphics.util.colour.Colour;
/**
* Sets a graphic data to the board.
*
* @author Eric.Piette
*/
public class Board implements GraphicsItem
{
/**
* For setting the style of a board.
*
* @param boardType The type of data.
* @param containerStyleType Container style wanted for the board.
* @param replaceComponentsWithFilledCells True if cells should be filled instead of component drawn [False].
*
* @example (board Style Chess)
*/
@SuppressWarnings("javadoc")
public static GraphicsItem construct
(
final BoardStyleType boardType,
final ContainerStyleType containerStyleType,
@Opt @Name final Boolean replaceComponentsWithFilledCells
)
{
switch (boardType)
{
case Style:
return new BoardStyle(containerStyleType, replaceComponentsWithFilledCells);
default:
break;
}
// We should never reach that except if we forget some codes.
throw new IllegalArgumentException("Board(): A BoardStyleType is not implemented.");
}
//-------------------------------------------------------------------------------
/**
* For setting the thickness style.
*
* @param boardType The type of data.
* @param boardGraphicsType The board graphics type to which the colour is to be
* applied (must be InnerEdge or OuterEdge).
* @param thickness The assigned thickness scale for the specified
* boardGraphicsType.
*
* @example (board StyleThickness OuterEdges 2.0)
*/
@SuppressWarnings("javadoc")
public static GraphicsItem construct
(
final BoardStyleThicknessType boardType,
final BoardGraphicsType boardGraphicsType,
final Float thickness
)
{
switch (boardType)
{
case StyleThickness:
return new BoardStyleThickness(boardGraphicsType, thickness);
default:
break;
}
// We should never reach that except if we forget some codes.
throw new IllegalArgumentException("Board(): A BoardStyleThicknessType is not implemented.");
}
//-------------------------------------------------------------------------------
/**
* For setting the board to be checkered.
*
* @param boardType The type of data.
* @param value Whether the graphic data should be applied or not [True].
*
* @example (board Checkered)
*/
@SuppressWarnings("javadoc")
public static GraphicsItem construct
(
final BoardBooleanType boardType,
@Opt final Boolean value
)
{
switch (boardType)
{
case Checkered:
return new BoardCheckered(value);
default:
break;
}
// We should never reach that except if we forget some codes.
throw new IllegalArgumentException("Board(): A BoardBooleanType is not implemented.");
}
//-------------------------------------------------------------------------------
/**
* For setting the background or the foreground of a board.
*
* @param boardType The type of data to apply to the board.
* @param image Name of the image to draw. Default value is an outline around the board.
* @param fillColour Colour for the inner sections of the image. Default value
* is the phase 0 colour of the board.
* @param edgeColour Colour for the edges of the image. Default value is the
* outer edge colour of the board.
* @param scale Scale for the drawn image relative to the size of the
* board [1.0].
* @param scaleX Scale for the drawn image, relative to the cell size of the container, along x-axis [1.0].
* @param scaleY Scale for the drawn image, relative to the cell size of the container, along y-axis [1.0].
* @param rotation Rotation of the drawn image (clockwise).
* @param offsetX Offset distance as percentage of board size to push the image to the right [0].
* @param offsetY Offset distance as percentage of board size to push the image to the down [0].
*
* @example (board Background image:"octagon" fillColour:(colour White)
* edgeColour:(colour White) scale:1.2)
*/
@SuppressWarnings("javadoc")
public static GraphicsItem construct
(
final PieceGroundType boardType,
@Opt @Name final String image,
@Opt @Name final Colour fillColour,
@Opt @Name final Colour edgeColour,
@Opt @Name final Float scale,
@Opt @Name final Float scaleX,
@Opt @Name final Float scaleY,
@Opt @Name final Integer rotation,
@Opt @Name final Float offsetX,
@Opt @Name final Float offsetY
)
{
switch (boardType)
{
case Background:
return new BoardBackground(image, fillColour, edgeColour, scale, scaleX, scaleY, rotation, offsetX, offsetY);
case Foreground:
return new BoardForeground(image, fillColour, edgeColour, scale, scaleX, scaleY, rotation, offsetX, offsetY);
default:
break;
}
// We should never reach that except if we forget some codes.
throw new IllegalArgumentException("Piece(): A PieceGroundType is not implemented.");
}
//-------------------------------------------------------------------------------
/**
* For setting the colour of the board.
*
* @param boardType The type of data.
* @param boardGraphicsType The board graphics type to which the colour is to be
* applied.
* @param colour The assigned colour for the specified
* boardGraphicsType.
*
* @example (board Colour Phase2 (colour Cyan))
*/
@SuppressWarnings("javadoc")
public static GraphicsItem construct
(
final BoardColourType boardType,
final BoardGraphicsType boardGraphicsType,
final Colour colour
)
{
switch (boardType)
{
case Colour:
return new BoardColour(boardGraphicsType,colour);
default:
break;
}
// We should never reach that except if we forget some codes.
throw new IllegalArgumentException("Board(): A BoardColourType is not implemented.");
}
//-------------------------------------------------------------------------------
/**
* For setting the placement of the board.
*
* @param BoardPlacementType The type of data.
* @param scale scale for the board.
* @param offsetX X offset for board center.
* @param offsetY Y offset for board center.
*
* @example (board Placement scale:0.8)
*/
@SuppressWarnings("javadoc")
public static GraphicsItem construct
(
final BoardPlacementType boardType,
@Opt @Name final Float scale,
@Opt @Name final Float offsetX,
@Opt @Name final Float offsetY
)
{
switch (boardType)
{
case Placement:
return new BoardPlacement(scale, offsetX, offsetY);
default:
break;
}
// We should never reach that except if we forget some codes.
throw new IllegalArgumentException("Board(): A BoardShapeType is not implemented.");
}
//-------------------------------------------------------------------------------
/**
* For setting the curvature of the board.
*
* @param boardType The type of data.
* @param curveOffset The curve offset.
*
* @example (board Curvature 0.45)
*/
@SuppressWarnings("javadoc")
public static GraphicsItem construct
(
final BoardCurvatureType boardType,
final Float curveOffset
)
{
switch (boardType)
{
case Curvature:
return new BoardCurvature(curveOffset);
default:
break;
}
// We should never reach that except if we forget some codes.
throw new IllegalArgumentException("Board(): A BoardCurvatureType is not implemented.");
}
//-------------------------------------------------------------------------------
private Board()
{
// Ensure that compiler does not pick up default constructor
}
//-------------------------------------------------------------------------
@Override
public BitSet concepts(final Game game)
{
throw new UnsupportedOperationException("Board.concepts(...): Should never be called directly.");
}
@Override
public long gameFlags(final Game game)
{
throw new UnsupportedOperationException("Board.gameFlags(...): Should never be called directly.");
}
@Override
public boolean needRedraw()
{
throw new UnsupportedOperationException("Board.gameFlags(...): Should never be called directly.");
}
}
| 8,928 | 29.474403 | 112 | java |
Ludii | Ludii-master/Core/src/metadata/graphics/board/BoardBooleanType.java | package metadata.graphics.board;
/**
* Defines the types of Board metadata depending only of a boolean.
*
* @author Eric.Piette
*/
public enum BoardBooleanType
{
/** To indicate whether the board should be drawn in a checkered pattern. */
Checkered,
} | 259 | 20.666667 | 77 | java |
Ludii | Ludii-master/Core/src/metadata/graphics/board/BoardColourType.java | package metadata.graphics.board;
/**
* Defines the types of Board metadata related to the colour.
*
* @author Eric.Piette
*/
public enum BoardColourType
{
/** To set the colour of a specific aspect of the board. */
Colour,
} | 232 | 18.416667 | 61 | java |
Ludii | Ludii-master/Core/src/metadata/graphics/board/BoardCurvatureType.java | package metadata.graphics.board;
/**
* Defines the types of Board metadata related to the curvature style.
*
* @author Matthew.Stephenson
*/
public enum BoardCurvatureType
{
/** To set the curve offset when drawing curves. */
Curvature,
} | 246 | 19.583333 | 70 | java |
Ludii | Ludii-master/Core/src/metadata/graphics/board/BoardPlacementType.java | package metadata.graphics.board;
/**
* Defines the types of Board metadata related to the placement.
*
* @author Eric.Piette
*/
public enum BoardPlacementType
{
/** To set the placement of the board. */
Placement,
} | 223 | 17.666667 | 64 | java |
Ludii | Ludii-master/Core/src/metadata/graphics/board/BoardStyleThicknessType.java | package metadata.graphics.board;
/**
* Defines the types of Board metadata related to the thickness style.
*
* @author Eric.Piette
*/
public enum BoardStyleThicknessType
{
/** To set the preferred scale for the thickness of a specific aspect of the board. */
StyleThickness,
} | 284 | 22.75 | 87 | java |
Ludii | Ludii-master/Core/src/metadata/graphics/board/BoardStyleType.java | package metadata.graphics.board;
/**
* Defines the types of Board metadata related to the style.
*
* @author Eric.Piette
*/
public enum BoardStyleType
{
/** To set the style of the board. */
Style,
} | 207 | 16.333333 | 60 | java |
Ludii | Ludii-master/Core/src/metadata/graphics/board/package-info.java | /**
* The {\tt (board ...)} `super' metadata ludeme is used modify a graphic
* property of a board.
*/
package metadata.graphics.board;
| 139 | 22.333333 | 73 | java |
Ludii | Ludii-master/Core/src/metadata/graphics/board/Boolean/BoardCheckered.java | package metadata.graphics.board.Boolean;
import java.util.BitSet;
import annotations.Hide;
import annotations.Opt;
import game.Game;
import metadata.graphics.GraphicsItem;
/**
* Indicates whether the board should be drawn in a checkered pattern.
*
* @author Matthew.Stephenson
*
* @remarks Colouring is done based on the board's phases.
*/
@Hide
public class BoardCheckered implements GraphicsItem
{
/** If the board should be checkered. */
private final boolean checkeredBoard;
//-------------------------------------------------------------------------
/**
* @param checkeredBoard Whether the board should be checkered or not [True].
*/
public BoardCheckered
(
@Opt final Boolean checkeredBoard
)
{
this.checkeredBoard = (checkeredBoard == null) ? true : checkeredBoard.booleanValue();
}
//-------------------------------------------------------------------------
/**
* @return If the board should be checkered.
*/
public boolean checkeredBoard()
{
return checkeredBoard;
}
//-------------------------------------------------------------------------
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
return concepts;
}
@Override
public long gameFlags(final Game game)
{
final long gameFlags = 0l;
return gameFlags;
}
@Override
public boolean needRedraw()
{
return false;
}
}
| 1,390 | 19.455882 | 88 | java |
Ludii | Ludii-master/Core/src/metadata/graphics/board/colour/BoardColour.java | package metadata.graphics.board.colour;
import java.util.BitSet;
import annotations.Hide;
import game.Game;
import metadata.graphics.GraphicsItem;
import metadata.graphics.util.BoardGraphicsType;
import metadata.graphics.util.colour.Colour;
/**
* Sets the colour of a specific aspect of the board.
*
* @author Matthew.Stephenson
*
* @remarks Different aspects of the board that can be specified are defined in BoardGraphicsType.
*/
@Hide
public class BoardColour implements GraphicsItem
{
/** boardGraphicsType to colour. */
private final BoardGraphicsType boardGraphicsType;
/** Colour to apply. */
private final Colour colour;
//-------------------------------------------------------------------------
/**
* @param boardGraphicsType The board graphics type to which the colour is to be
* applied.
* @param colour The assigned colour for the specified
* boardGraphicsType.
*/
public BoardColour
(
final BoardGraphicsType boardGraphicsType,
final Colour colour
)
{
this.boardGraphicsType = boardGraphicsType;
this.colour = colour;
}
//-------------------------------------------------------------------------
/**
* @return BoardGraphicsType that the colour is applied to.
*/
public BoardGraphicsType boardGraphicsType()
{
return boardGraphicsType;
}
//-------------------------------------------------------------------------
/**
* @return Colour to apply onto the specified boardGraphicsType.
*/
public Colour colour()
{
return colour;
}
//-------------------------------------------------------------------------
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
return concepts;
}
@Override
public long gameFlags(final Game game)
{
final long gameFlags = 0l;
return gameFlags;
}
@Override
public boolean needRedraw()
{
return false;
}
}
| 1,945 | 21.113636 | 98 | java |
Ludii | Ludii-master/Core/src/metadata/graphics/board/curvature/BoardCurvature.java | package metadata.graphics.board.curvature;
import java.util.BitSet;
import annotations.Hide;
import game.Game;
import metadata.graphics.GraphicsItem;
/**
* Sets the preferred curve offset for the board.
*
* @author Matthew.Stephenson
*/
@Hide
public class BoardCurvature implements GraphicsItem
{
/** curve offset (used by BoardDesign.curvePath). */
private final float curveOffset;
//-------------------------------------------------------------------------
/**
* @param curveOffset curve offset when drawing curves.
*
* @example (board Curvature 0.45)
*/
public BoardCurvature
(
final Float curveOffset
)
{
this.curveOffset = curveOffset.floatValue();
}
//-------------------------------------------------------------------------
/**
* @return curve offset when drawing curves.
*/
public float curveOffset()
{
return curveOffset;
}
//-------------------------------------------------------------------------
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
return concepts;
}
@Override
public long gameFlags(final Game game)
{
final long gameFlags = 0l;
return gameFlags;
}
@Override
public boolean needRedraw()
{
return false;
}
}
| 1,266 | 17.632353 | 76 | java |
Ludii | Ludii-master/Core/src/metadata/graphics/board/ground/BoardBackground.java | package metadata.graphics.board.ground;
import java.util.BitSet;
import annotations.Hide;
import annotations.Name;
import annotations.Opt;
import game.Game;
import metadata.graphics.GraphicsItem;
import metadata.graphics.util.colour.Colour;
/**
* Draws a specified image behind the game board.
*
* @author Matthew.Stephenson
*/
@Hide
public class BoardBackground implements GraphicsItem
{
/** Background image to draw. */
private final String image;
/** Fill colour of drawn image. */
private final Colour fillColour;
/** Edge colour of drawn image. */
private final Colour edgeColour;
/** Scale of drawn image. */
private final float scale;
/** Scale of drawn image along x-axis. */
private final float scaleX;
/** Scale of drawn image along y-axis. */
private final float scaleY;
/** Rotation of drawn image. */
private final int rotation;
/** Offset right for drawn image. */
private final float offsetX;
/** Offset down for drawn image. */
private final float offsetY;
//-------------------------------------------------------------------------
/**
* @param image Name of the background image to draw. Default value is an outline around the board.
* @param fillColour Colour for the inner sections of the image. Default value is the fill colour of the component.
* @param edgeColour Colour for the edges of the image. Default value is the edge colour of the component.
* @param scale Scale for the drawn image, relative to the cell size of the container [1.0].
* @param scaleX Scale for the drawn image, relative to the cell size of the container, along x-axis [1.0].
* @param scaleY Scale for the drawn image, relative to the cell size of the container, along y-axis [1.0].
* @param rotation Rotation for the drawn image [0].
* @param offsetX Offset distance percentage to push the image to the right [0].
* @param offsetY Offset distance percentage to push the image down [0].
*/
public BoardBackground
(
@Opt @Name final String image,
@Opt @Name final Colour fillColour,
@Opt @Name final Colour edgeColour,
@Opt @Name final Float scale,
@Opt @Name final Float scaleX,
@Opt @Name final Float scaleY,
@Opt @Name final Integer rotation,
@Opt @Name final Float offsetX,
@Opt @Name final Float offsetY
)
{
this.image = image;
this.fillColour = fillColour;
this.edgeColour = edgeColour;
this.scale = (scale == null) ? (float)1.0 : scale.floatValue();
this.scaleX = (scaleX == null) ? (float)1.0 : scaleX.floatValue();
this.scaleY = (scaleY == null) ? (float)1.0 : scaleY.floatValue();
this.rotation = (rotation == null) ? 0 : rotation.intValue();
this.offsetX = (offsetX == null) ? 0 : offsetX.floatValue();
this.offsetY = (offsetY == null) ? 0 : offsetY.floatValue();
}
//-------------------------------------------------------------------------
/**
* @return Background image to draw.
*/
public String image()
{
return image;
}
//-------------------------------------------------------------------------
/**
* @return Fill colour of drawn image.
*/
public Colour fillColour()
{
return fillColour;
}
//-------------------------------------------------------------------------
/**
* @return Edge colour of drawn image.
*/
public Colour edgeColour()
{
return edgeColour;
}
//-------------------------------------------------------------------------
/**
* @return Scale of drawn image.
*/
public float scale()
{
return scale;
}
//-------------------------------------------------------------------------
/**
* @return Scale of drawn image along x-axis.
*/
public float scaleX()
{
return scaleX;
}
//-------------------------------------------------------------------------
/**
* @return Scale of drawn image along y-axis.
*/
public float scaleY()
{
return scaleY;
}
//-------------------------------------------------------------------------
/**
* @return Rotation of drawn image.
*/
public int rotation()
{
return rotation;
}
//-------------------------------------------------------------------------
/**
* @return Offset right for drawn image.
*/
public float offsetX()
{
return offsetX;
}
//-------------------------------------------------------------------------
/**
* @return Offset down for drawn image.
*/
public float offsetY()
{
return offsetY;
}
//-------------------------------------------------------------------------
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
return concepts;
}
@Override
public long gameFlags(final Game game)
{
final long gameFlags = 0l;
return gameFlags;
}
@Override
public boolean needRedraw()
{
return false;
}
}
| 4,787 | 23.304569 | 116 | java |
Ludii | Ludii-master/Core/src/metadata/graphics/board/ground/BoardForeground.java | package metadata.graphics.board.ground;
import java.util.BitSet;
import annotations.Hide;
import annotations.Name;
import annotations.Opt;
import game.Game;
import metadata.graphics.GraphicsItem;
import metadata.graphics.util.colour.Colour;
/**
* Draws a specified image in front of the game board.
*
* @author Matthew.Stephenson
*/
@Hide
public class BoardForeground implements GraphicsItem
{
/** Background image to draw. */
private final String image;
/** Fill colour of drawn image. */
private final Colour fillColour;
/** Edge colour of drawn image. */
private final Colour edgeColour;
/** Scale of drawn image. */
private final float scale;
/** Scale of drawn image along x-axis. */
private final float scaleX;
/** Scale of drawn image along y-axis. */
private final float scaleY;
/** Rotation of drawn image. */
private final int rotation;
/** Offset right for drawn image. */
private final float offsetX;
/** Offset down for drawn image. */
private final float offsetY;
//-------------------------------------------------------------------------
/**
* @param image Name of the foreground image to draw. Default value is an outline around the board.
* @param fillColour Colour for the inner sections of the image. Default value is the fill colour of the component.
* @param edgeColour Colour for the edges of the image. Default value is the edge colour of the component.
* @param scale Scale for the drawn image relative to the cell size of the container [1.0].
* @param rotation Rotation for the drawn image [0].
* @param scaleX Scale for the drawn image, relative to the cell size of the container, along x-axis [1.0].
* @param scaleY Scale for the drawn image, relative to the cell size of the container, along y-axis [1.0].
* @param offsetX Offset percentage distance to push the image to the right [0].
* @param offsetY Offset percentage distance to push the image down [0].
*/
public BoardForeground
(
@Opt @Name final String image,
@Opt @Name final Colour fillColour,
@Opt @Name final Colour edgeColour,
@Opt @Name final Float scale,
@Opt @Name final Float scaleX,
@Opt @Name final Float scaleY,
@Opt @Name final Integer rotation,
@Opt @Name final Float offsetX,
@Opt @Name final Float offsetY
)
{
this.image = image;
this.fillColour = fillColour;
this.edgeColour = edgeColour;
this.scale = (scale == null) ? (float)1.0 : scale.floatValue();
this.scaleX = (scaleX == null) ? (float)1.0 : scaleX.floatValue();
this.scaleY = (scaleY == null) ? (float)1.0 : scaleY.floatValue();
this.rotation = (rotation == null) ? 0 : rotation.intValue();
this.offsetX = (offsetX == null) ? 0 : offsetX.floatValue();
this.offsetY = (offsetY == null) ? 0 : offsetY.floatValue();
}
//-------------------------------------------------------------------------
/**
* @return Foreground image to draw.
*/
public String image()
{
return image;
}
//-------------------------------------------------------------------------
/**
* @return Fill colour of drawn image.
*/
public Colour fillColour()
{
return fillColour;
}
//-------------------------------------------------------------------------
/**
* @return Edge colour of drawn image.
*/
public Colour edgeColour()
{
return edgeColour;
}
//-------------------------------------------------------------------------
/**
* @return Scale of drawn image.
*/
public float scale()
{
return scale;
}
//-------------------------------------------------------------------------
/**
* @return Scale of drawn image along x-axis.
*/
public float scaleX()
{
return scaleX;
}
//-------------------------------------------------------------------------
/**
* @return Scale of drawn image along y-axis.
*/
public float scaleY()
{
return scaleY;
}
//-------------------------------------------------------------------------
/**
* @return Rotation of drawn image.
*/
public int rotation()
{
return rotation;
}
//-------------------------------------------------------------------------
/**
* @return Offset right for drawn image.
*/
public float offsetX()
{
return offsetX;
}
//-------------------------------------------------------------------------
/**
* @return Offset down for drawn image.
*/
public float offsetY()
{
return offsetY;
}
//-------------------------------------------------------------------------
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
return concepts;
}
@Override
public long gameFlags(final Game game)
{
final long gameFlags = 0l;
return gameFlags;
}
@Override
public boolean needRedraw()
{
return false;
}
}
| 4,789 | 23.438776 | 116 | java |
Ludii | Ludii-master/Core/src/metadata/graphics/board/placement/BoardPlacement.java | package metadata.graphics.board.placement;
import java.util.BitSet;
import annotations.Hide;
import annotations.Name;
import annotations.Opt;
import game.Game;
import metadata.graphics.GraphicsItem;
/**
* Modifies the central placement of the game board.
*
* @author Matthew.Stephenson
*/
@Hide
public class BoardPlacement implements GraphicsItem
{
/** Scale of board. */
private final float scale;
/** Offset right for board. */
private final float offsetX;
/** Offset down for board. */
private final float offsetY;
//-------------------------------------------------------------------------
/**
* @param scale Scale for the board [1.0].
* @param offsetX Offset distance percentage to push the board to the right [0].
* @param offsetY Offset distance percentage to push the board down [0].
*/
public BoardPlacement
(
@Opt @Name final Float scale,
@Opt @Name final Float offsetX,
@Opt @Name final Float offsetY
)
{
this.scale = (scale == null) ? (float)1.0 : scale.floatValue();
this.offsetX = (offsetX == null) ? 0 : offsetX.floatValue();
this.offsetY = (offsetY == null) ? 0 : offsetY.floatValue();
}
//-------------------------------------------------------------------------
/**
* @return Scale of board.
*/
public float scale()
{
return scale;
}
//-------------------------------------------------------------------------
/**
* @return Offset right for board.
*/
public float offsetX()
{
return offsetX;
}
//-------------------------------------------------------------------------
/**
* @return Offset down for board.
*/
public float offsetY()
{
return offsetY;
}
//-------------------------------------------------------------------------
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
return concepts;
}
@Override
public long gameFlags(final Game game)
{
final long gameFlags = 0l;
return gameFlags;
}
@Override
public boolean needRedraw()
{
return false;
}
}
| 2,048 | 19.49 | 87 | java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.