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/equipment/container/other/package-info.java | /**
* This section contains various types of containers (which can
* hold components) other than board types; these are often pieces,
* cards, etc. that are held by players in their hands. All of these
* types may be used for \texttt{<item>} parameters in
* \hyperref[Subsec:game.equipment.Equipment]{Equipment definitions}.
*/
package game.equipment.container.other;
| 375 | 40.777778 | 69 | java |
Ludii | Ludii-master/Core/src/game/equipment/other/Dominoes.java | package game.equipment.other;
import java.util.ArrayList;
import java.util.BitSet;
import annotations.Name;
import annotations.Opt;
import game.Game;
import game.equipment.Item;
import game.equipment.component.tile.Domino;
import game.types.play.RoleType;
import main.Constants;
import other.ItemType;
import other.concept.Concept;
/**
* Defines a dominoes set.
*
* @author Eric.Piette
*
*/
public class Dominoes extends Item
{
/** The number of dominoes. */
final int upTo;
/**
* Definition of a set of dominoes.
*
* @param upTo The number of dominoes [6].
* @example (dominoes)
*/
public Dominoes
(
@Opt @Name final Integer upTo
)
{
super(null, Constants.UNDEFINED, RoleType.Shared);
this.upTo = (upTo == null) ? 6 : upTo.intValue();
// Limit on the max dots on the dominoes.
if (this.upTo < 0 || this.upTo > Constants.MAX_PITS_DOMINOES)
throw new IllegalArgumentException(
"The limit of the dominoes pips can not be negative or to exceed " + Constants.MAX_PITS_DOMINOES
+ ".");
setType(ItemType.Dominoes);
}
/***
* @return A list of all the dominoes of this set.
*/
public ArrayList<Domino> generateDominoes()
{
final ArrayList<Domino> dominoes = new ArrayList<Domino>();
for (int i = 0; i <= upTo; i++)
for (int j = i; j <= upTo; j++)
{
final Domino domino = new Domino(
"Domino" + i + j, RoleType.Shared,
Integer.valueOf(i),
Integer.valueOf(j), null);
dominoes.add(domino);
}
return dominoes;
}
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
concepts.set(Concept.Domino.id(), true);
return concepts;
}
@Override
public BitSet writesEvalContextRecursive()
{
final BitSet writeEvalContext = new BitSet();
return writeEvalContext;
}
@Override
public BitSet readsEvalContextRecursive()
{
final BitSet readEvalContext = new BitSet();
return readEvalContext;
}
}
| 1,944 | 20.141304 | 101 | java |
Ludii | Ludii-master/Core/src/game/equipment/other/Hints.java | package game.equipment.other;
import java.util.BitSet;
import annotations.Opt;
import game.Game;
import game.equipment.Item;
import game.types.board.SiteType;
import game.types.play.RoleType;
import game.util.equipment.Hint;
import main.Constants;
import other.ItemType;
import other.concept.Concept;
/**
* Defines the hints of a deduction puzzle.
*
* @author Eric.Piette
*
* @remarks Used for any deduction puzzle with hints.
*/
public class Hints extends Item
{
/** Which vars. */
private final Integer[][] where;
/** Which values. */
private final Integer[] values;
/** On what kind of vars have hint. */
private final SiteType type;
//-------------------------------------------------------------------------
/**
* @param label The name of these hints.
* @param records The different hints.
* @param type The graph element type of the sites.
* @example (hints { (hint {0 5 10 15} 3 ) (hint {1 2 3 4} 4 ) (hint {6 11 16} 3
* ) (hint {7 8 9 12 13 14} 4 ) (hint {17 18 19} 3 ) (hint {20 21 22} 3
* ) (hint {23 24} 1 ) })*
*/
public Hints
(
@Opt final String label,
final Hint[] records,
@Opt final SiteType type
)
{
super(label, Constants.UNDEFINED, RoleType.Neutral);
if (records == null)
{
this.values = null;
this.where = null;
}
else
{
this.values = new Integer[records.length];
this.where = new Integer[records.length][];
for (int n = 0; n < records.length; n++)
{
this.where[n] = records[n].region();
this.values[n] = records[n].hint();
}
}
this.type = (type == null) ? SiteType.Cell : type;
setType(ItemType.Hints);
}
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
concepts.set(Concept.Hints.id(), true);
return concepts;
}
@Override
public BitSet writesEvalContextRecursive()
{
final BitSet writeEvalContext = new BitSet();
return writeEvalContext;
}
@Override
public BitSet readsEvalContextRecursive()
{
final BitSet readEvalContext = new BitSet();
return readEvalContext;
}
@Override
public boolean willCrash(final Game game)
{
boolean willCrash = false;
if (game.players().count() != 1)
{
game.addCrashToReport("The ludeme (hints ...) is used but the number of players is not 1.");
willCrash = true;
}
willCrash |= super.willCrash(game);
return willCrash;
}
//-------------------------------------------------------------------------
/**
* @return where
*/
public Integer[][] where()
{
return this.where;
}
/**
* @return values
*/
public Integer[] values()
{
return this.values;
}
/**
* @return type
*/
public SiteType getType()
{
return type;
}
}
| 2,720 | 19.458647 | 95 | java |
Ludii | Ludii-master/Core/src/game/equipment/other/Map.java | package game.equipment.other;
import java.util.BitSet;
import annotations.Opt;
import game.Game;
import game.equipment.Item;
import game.equipment.component.Component;
import game.equipment.container.board.Board;
import game.functions.ints.IntFunction;
import game.types.board.LandmarkType;
import game.types.board.SiteType;
import game.types.play.RoleType;
import game.util.math.Pair;
import gnu.trove.map.hash.TIntIntHashMap;
import main.Constants;
import main.StringRoutines;
import other.ItemType;
import other.context.Context;
import other.topology.SiteFinder;
import other.topology.TopologyElement;
import other.trial.Trial;
/**
* Defines a map between two locations or integers.
*
* @author Eric.Piette
* @remarks Used to map a site to another or to map an integer to another.
*/
public class Map extends Item
{
/** The map. */
private final TIntIntHashMap map = new TIntIntHashMap();
/** The pairs of the map. */
private final Pair[] mapPairs;
//------------------------------------------------------------------------------
/**
* For map of pairs.
*
* @param name The name of the map ["Map"].
* @param pairs The pairs of each map.
*
* @example (map "Entry" { (pair P1 "D1") (pair P2 "E8") (pair P3 "H4") (pair P4
* "A5")})
*
* @example (map { (pair 5 19) (pair 7 9) (pair 34 48) (pair 36 38) } )
*
* @example (map {(pair P1 P4) (pair P2 P5) (pair P3 P6) (pair P4 P1) (pair P5
* P2) (pair P6 P3)})
*/
public Map
(
@Opt final String name,
final Pair[] pairs
)
{
super(((name == null) ? "Map" : name), Constants.UNDEFINED, RoleType.Neutral);
this.mapPairs = pairs;
setType(ItemType.Map);
}
/**
* For map between integers.
*
* @param name The name of the map ["Map"].
* @param keys The keys of the map.
* @param values The values of the map.
*
* @example (map {1..9} {1 2 4 8 16 32 64 128 256})
*/
public Map
(
@Opt final String name,
final IntFunction[] keys,
final IntFunction[] values
)
{
super(((name == null) ? "Map" : name), Constants.UNDEFINED, RoleType.Neutral);
if (keys.length != values.length)
throw new IllegalArgumentException(
"A map has to be defined with exactly the same number of keys than values.");
final int minLength = Math.min(keys.length, values.length);
mapPairs = new Pair[minLength];
for (int i = 0; i < minLength; i++)
mapPairs[i] = new Pair(keys[i], values[i]);
setType(ItemType.Map);
}
//------------------------------------------------------------------------------
/**
* @return the map of Integer.
*/
public TIntIntHashMap map()
{
return this.map;
}
/**
* To get the value of the key in the map.
*
* @param key
* @return value corresponding to the key.
*/
public int to(final int key)
{
return map.get(key);
}
/**
* @return The value returned by map when values don't exist for any given key.
*/
public int noEntryValue()
{
return map.getNoEntryValue();
}
//-------------------------------------------------------------------------
/**
* We compute the maps.
*
* @param game The game.
*/
public void computeMap(final Game game)
{
for (final Pair pair : mapPairs)
{
int intKey = pair.intKey().eval(new Context(game, new Trial(game)));
if (intKey == Constants.OFF)
{
final TopologyElement element = SiteFinder.find(game.board(), pair.stringKey(),
game.board().defaultSite());
if (element != null)
intKey = element.index();
}
int intValue = pair.intValue().eval(new Context(game, new Trial(game)));
if (intValue == Constants.OFF)
{
if (pair.stringValue() != null)
{
if (StringRoutines.isCoordinate(pair.stringValue()))
{
final TopologyElement element = SiteFinder.find(game.board(), pair.stringValue(),
game.board().defaultSite());
if (element != null)
intValue = element.index();
}
else
{
for (int i = 1; i < game.equipment().components().length; i++)
{
final Component component = game.equipment().components()[i];
if (component.name().equals(pair.stringValue()))
{
intValue = i;
break;
}
}
}
}
else
{
final LandmarkType landmarkType = pair.landmarkType();
intValue = getSite(game.board(), landmarkType);
}
}
if (intValue != Constants.OFF && intKey != Constants.OFF)
map.put(intKey, intValue);
}
}
/**
* @param board The graph of the board.
* @param landmarkType The landmark site to get.
* @return The site corresponding to the landmark.
*/
private static int getSite(final Board board, final LandmarkType landmarkType)
{
switch (landmarkType)
{
case BottomSite:
return (board.defaultSite() == SiteType.Vertex
? board.topology().bottom(SiteType.Vertex)
: board.topology().bottom(SiteType.Cell)).get(0).index();
case CentreSite:
return (board.defaultSite() == SiteType.Vertex
? board.topology().centre(SiteType.Vertex)
: board.topology().centre(SiteType.Cell)).get(0).index();
case LeftSite:
return (board.defaultSite() == SiteType.Vertex
? board.topology().left(SiteType.Vertex)
: board.topology().left(SiteType.Cell))
.get(0).index();
case RightSite:
return (board.defaultSite() == SiteType.Vertex
? board.topology().right(SiteType.Vertex)
: board.topology().right(SiteType.Cell)).get(0).index();
case Topsite:
return (board.defaultSite() == SiteType.Vertex
? board.topology().top(SiteType.Vertex)
: board.topology().top(SiteType.Cell)).get(0).index();
case FirstSite:
return 0;
case LastSite:
return (board.defaultSite() == SiteType.Vertex
? board.topology().vertices().get(board.topology().vertices().size() - 1).index()
: board.topology().cells().get(board.topology().cells().size() - 1).index());
default:
return Constants.UNDEFINED;
}
}
@Override
public long gameFlags(final Game game)
{
long gameFlags = 0l;
for (final Pair pair : mapPairs)
gameFlags |= pair.gameFlags(game);
return gameFlags;
}
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
for (final Pair pair : mapPairs)
concepts.or(pair.concepts(game));
return concepts;
}
@Override
public BitSet writesEvalContextRecursive()
{
final BitSet writeEvalContext = new BitSet();
for (final Pair pair : mapPairs)
writeEvalContext.or(pair.writesEvalContextRecursive());
return writeEvalContext;
}
@Override
public BitSet readsEvalContextRecursive()
{
final BitSet readEvalContext = new BitSet();
for (final Pair pair : mapPairs)
readEvalContext.or(pair.readsEvalContextRecursive());
return readEvalContext;
}
@Override
public boolean missingRequirement(final Game game)
{
boolean missingRequirement = false;
if (role() != null)
{
final int indexOwnerPhase = role().owner();
if (
(
indexOwnerPhase < 1
&&
!role().equals(RoleType.Shared)
&&
!role().equals(RoleType.Neutral)
&&
!role().equals(RoleType.All)
)
||
indexOwnerPhase > game.players().count()
)
{
game.addRequirementToReport(
"A map is defined in the equipment with an incorrect owner: " + role() + ".");
missingRequirement = true;
}
}
for (final Pair pair : mapPairs)
missingRequirement |= pair.missingRequirement(game);
return missingRequirement;
}
@Override
public boolean willCrash(final Game game)
{
boolean willCrash = false;
for (final Pair pair : mapPairs)
willCrash |= pair.willCrash(game);
return willCrash;
}
}
| 7,691 | 23.893204 | 87 | java |
Ludii | Ludii-master/Core/src/game/equipment/other/Regions.java | package game.equipment.other;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.BitSet;
import java.util.List;
import annotations.Opt;
import annotations.Or;
import game.Game;
import game.equipment.Item;
import game.functions.region.RegionFunction;
import game.types.board.RegionTypeStatic;
import game.types.board.SiteType;
import game.types.play.RoleType;
import game.util.directions.AbsoluteDirection;
import game.util.directions.DirectionFacing;
import game.util.equipment.Region;
import game.util.graph.Radial;
import gnu.trove.list.array.TIntArrayList;
import main.Constants;
import other.ItemType;
import other.context.Context;
import other.topology.Cell;
import other.topology.Topology;
import other.topology.TopologyElement;
/**
* Defines a static region on the board.
*
* @author Eric.Piette and cambolbro
*/
public class Regions extends Item
{
/** If we can, we'll precompute once and cache. */
private int[] precomputedRegion = null;
//-------------------------------------------------------------------------
/** The sites implied. */
private final int[] sites;
/** The region function implied. */
private final RegionFunction[] region;
/** The type of pre-computed static region. */
private final RegionTypeStatic[] regionType;
/** The name of the hintRegion. */
private final String hintRegionName;
//-------------------------------------------------------------------------
/**
* @param name The name of the region ["Region" + owner index].
* @param role The owner of the region [P1].
* @param sites The sites included in the region.
* @param regionFn The region function corresponding to the region.
* @param regionsFn The region functions corresponding to the region.
* @param staticRegion Pre-computed static region corresponding to this region.
* @param staticRegions Pre-computed static regions corresponding to this region.
* @param hintRegionLabel Name of this hint region (for deduction puzzles).
*
* @example (regions P1 { (sites Side NE) (sites Side SW) } )
*
* @example (regions "Replay" {14 24 43 53})
*
* @example (regions "Traps" (sites {"C3" "C6" "F3" "F6"}))
*/
public Regions
(
@Opt final String name,
@Opt final RoleType role,
@Or final Integer[] sites,
@Or final RegionFunction regionFn,
@Or final RegionFunction[] regionsFn,
@Or final RegionTypeStatic staticRegion,
@Or final RegionTypeStatic[] staticRegions,
@Opt final String hintRegionLabel
)
{
super
(
(name == null) ? "Region" + ((role == null) ? RoleType.P1 : role) : name,
Constants.UNDEFINED,
RoleType.Neutral
);
int numNonNull = 0;
if (sites != null)
numNonNull++;
if (regionFn != null)
numNonNull++;
if (regionsFn != null)
numNonNull++;
if (staticRegion != null)
numNonNull++;
if (staticRegions != null)
numNonNull++;
if (numNonNull != 1)
throw new IllegalArgumentException("Exactly one Or parameter must be non-null.");
if (role != null)
{
setRole(role); //this.role = role;
}
else
{
setRole(RoleType.Neutral); // this.role = RoleType.None;
}
if (sites != null)
{
this.sites = new int[sites.length];
for (int i = 0; i < sites.length; i++)
this.sites[i] = sites[i].intValue();
}
else
{
this.sites = null;
}
region = (regionFn != null) ? new RegionFunction[] { regionFn } : regionsFn;
regionType = (staticRegion != null) ? new RegionTypeStatic[] { staticRegion } : staticRegions;
hintRegionName = hintRegionLabel;
setType(ItemType.Regions);
}
//-------------------------------------------------------------------------
@Override
public String toEnglish(final Game game)
{
String text = "";
if(region!=null)
{
int count=0;
for (final RegionFunction regionFunction : region())
{
text += this.name() + ": ";
text += regionFunction.toEnglish(game) + " for "+ RoleType.roleForPlayerId(owner()).name();
count++;
if(count == region().length-1)
text += " and ";
else if(count < region().length)
text += ", ";
}
}
else
{
text = this.name() + ": contains the sites " + Arrays.toString(sites);
}
return text;
}
//-------------------------------------------------------------------------
/**
* @param type
* @param context
* @return A list of locations corresponding to the area type.
*/
public Integer[][] convertStaticRegionOnLocs(final RegionTypeStatic type, final Context context)
{
Integer[][] regions = null;
final Topology graph = context.topology();
final SiteType defaultType = context.board().defaultSite();
switch (type)
{
case Corners:
regions = new Integer[graph.corners(defaultType).size()][1];
for (int c = 0; c < graph.corners(defaultType).size(); c++)
{
final TopologyElement corner = graph.corners(defaultType).get(c);
regions[c][0] = Integer.valueOf(corner.index());
}
break;
case Sides:
regions = new Integer[graph.sides(defaultType).size()][];
int indexSide = 0;
for (final java.util.Map.Entry<DirectionFacing, List<TopologyElement>> entry : graph.sides(defaultType).entrySet())
{
regions[indexSide] = new Integer[entry.getValue().size()];
for (int j = 0; j < entry.getValue().size(); j++)
{
final TopologyElement element = entry.getValue().get(j);
regions[indexSide][j] = Integer.valueOf(element.index());
}
indexSide++;
}
break;
case SidesNoCorners:
final TIntArrayList corners = new TIntArrayList();
for (int c = 0; c < graph.corners(defaultType).size(); c++)
{
final TopologyElement corner = graph.corners(defaultType).get(c);
corners.add(corner.index());
}
regions = new Integer[graph.sides(defaultType).size()][];
int indexSideNoCorners = 0;
for (final java.util.Map.Entry<DirectionFacing, List<TopologyElement>> entry : graph.sides(defaultType).entrySet())
{
final List<Integer> sideNoCorner = new ArrayList<Integer>();
regions[indexSideNoCorners] = new Integer[entry.getValue().size()];
for (int j = 0; j < entry.getValue().size(); j++)
{
final TopologyElement element = entry.getValue().get(j);
if (!corners.contains(element.index()))
sideNoCorner.add(Integer.valueOf(element.index()));
}
regions[indexSideNoCorners] = new Integer[sideNoCorner.size()];
for (int j = 0; j < sideNoCorner.size(); j++)
regions[indexSideNoCorners][j] = sideNoCorner.get(j);
indexSideNoCorners++;
}
break;
case AllSites:
regions = new Integer[1][graph.getGraphElements(defaultType).size()];
for (int i = 0; i < graph.getGraphElements(defaultType).size(); i++)
regions[0][i] = Integer.valueOf(i);
break;
case Columns:
regions = new Integer[graph.columns(defaultType).size()][];
for (int i = 0; i < graph.columns(defaultType).size(); i++)
{
final List<TopologyElement> col = graph.columns(defaultType).get(i);
regions[i] = new Integer[col.size()];
for (int j = 0; j < col.size(); j++)
regions[i][j] = Integer.valueOf(col.get(j).index());
}
break;
case Rows:
regions = new Integer[graph.rows(defaultType).size()][];
for (int i = 0; i < graph.rows(defaultType).size(); i++)
{
final List<TopologyElement> row = graph.rows(defaultType).get(i);
regions[i] = new Integer[row.size()];
for (int j = 0 ; j < row.size() ; j++)
regions[i][j]= Integer.valueOf(row.get(j).index());
}
break;
case Diagonals:
regions = new Integer[graph.diagonals(defaultType).size()][];
for (int i = 0; i < graph.diagonals(defaultType).size(); i++)
{
final List<TopologyElement> diag = graph.diagonals(defaultType).get(i);
regions[i] = new Integer[diag.size()];
for (int j = 0; j < diag.size(); j++)
regions[i][j] = Integer.valueOf(diag.get(j).index());
}
break;
case Layers:
regions = new Integer[graph.layers(defaultType).size()][];
for (int i = 0; i < graph.layers(defaultType).size(); i++)
{
final List<TopologyElement> diag = graph.layers(defaultType).get(i);
regions[i] = new Integer[diag.size()];
for (int j = 0 ; j < diag.size() ; j++)
regions[i][j] = Integer.valueOf(diag.get(j).index());
}
break;
case HintRegions:
if (hintRegionName != null)
{
if (context.game().equipment().verticesWithHints().length != 0)
return context.game().equipment().verticesWithHints();
else if (context.game().equipment().cellsWithHints().length != 0)
return context.game().equipment().cellsWithHints();
else if (context.game().equipment().edgesWithHints().length != 0)
return context.game().equipment().edgesWithHints();
}
else
{
return context.game().equipment().cellsWithHints();
}
break;
case AllDirections:
// list of cell indices in the chosen directions
regions = new Integer[graph.getGraphElements(defaultType).size()][];
for (final TopologyElement element : graph.getGraphElements(defaultType))
{
final List<Radial> radials = graph.trajectories().radials(defaultType, element.index(), AbsoluteDirection.All);
final TIntArrayList locs = new TIntArrayList();
locs.add(element.index());
for (final Radial radial : radials)
{
for (int toIdx = 1; toIdx < radial.steps().length; toIdx++)
{
final int to = radial.steps()[toIdx].id();
if (!locs.contains(to))
locs.add(to);
}
}
regions[element.index()] = new Integer[locs.size()];
for (int index = 0; index < locs.size(); index++)
regions[element.index()][index] = Integer.valueOf(locs.getQuick(index));
}
break;
case SubGrids:
final int sizeSubGrids = (int) Math.sqrt(Math.sqrt(graph.cells().size()));
regions = new Integer[sizeSubGrids*sizeSubGrids][sizeSubGrids*sizeSubGrids];
int indexRegion = 0;
for (int rowSubGrid = 0 ; rowSubGrid < sizeSubGrids ; rowSubGrid++)
for (int colSubGrid = 0 ; colSubGrid < sizeSubGrids ; colSubGrid++)
{
int indexOnTheRegion = 0 ;
for (final Cell vertex : context.board().topology().cells())
{
final int col = vertex.col();
final int row = vertex.row();
if (row >= rowSubGrid * sizeSubGrids && row < (rowSubGrid + 1) * sizeSubGrids)
if (col >= colSubGrid * sizeSubGrids && col < (colSubGrid + 1) * sizeSubGrids)
{
regions[indexRegion][indexOnTheRegion] = Integer.valueOf(vertex.index());
indexOnTheRegion++;
}
}
indexRegion++;
}
break;
case Regions:
case Vertices:
case Touching:
final ArrayList<ArrayList<TopologyElement>> touchingRegions = new ArrayList<ArrayList<TopologyElement>>();
for (final TopologyElement element : graph.getGraphElements(defaultType))
for (final TopologyElement vElement : element.adjacent())
{
final ArrayList<TopologyElement> touchingRegion = new ArrayList<TopologyElement>();
touchingRegion.add(element);
touchingRegion.add(vElement);
touchingRegions.add(touchingRegion);
}
regions = new Integer[touchingRegions.size()][2];
for (int i = 0; i < touchingRegions.size(); i++)
for (int j = 0; j < 2; j++)
regions[i][j] = Integer.valueOf(touchingRegions.get(i).get(j).index());
break;
default:
break;
}
return regions;
}
//-------------------------------------------------------------------------
/**
* @return The sites of that region.
*/
public int[] sites()
{
return sites;
}
/**
* @return The region functions of that region.
*/
public RegionFunction[] region()
{
return region;
}
/**
* @return The list of all the static regions.
*/
public RegionTypeStatic[] regionTypes()
{
return regionType;
}
/**
* @param context The context.
* @return Array of site indices for given context.
*/
public int[] eval(final Context context)
{
if (precomputedRegion != null)
return precomputedRegion;
if (region != null)
{
final List<TIntArrayList> siteLists = new ArrayList<TIntArrayList>();
int totalNumSites = 0;
for (final RegionFunction regionFn : region)
{
final TIntArrayList wrapped = TIntArrayList.wrap(regionFn.eval(context).sites());
siteLists.add(wrapped);
totalNumSites += wrapped.size();
}
final int[] toReturn = new int[totalNumSites];
int startIdx = 0;
for (final TIntArrayList wrapped : siteLists)
{
wrapped.toArray(toReturn, 0, startIdx, wrapped.size());
startIdx += wrapped.size();
}
if (siteLists.size() > 1)
{
// We might have duplicates, so just to be sure we'll wrap
// into Region and unwrap again to get rid of duplicates
return new Region(toReturn).sites();
}
return toReturn;
}
else
{
return sites;
}
}
/**
* @param context The context.
* @param location The location.
* @return True if the given location is in this Regions.
*/
public boolean contains(final Context context, final int location)
{
if (region != null)
{
for (final RegionFunction regionFn : region)
{
if (regionFn.contains(context, location))
return true;
}
return false;
}
else
{
for (final int site : sites)
{
if (site == location)
return true;
}
return false;
}
}
/**
* @return True if this Region is static (always evals to the same region
* regardless of context).
*/
@SuppressWarnings("static-method")
public boolean isStatic()
{
// if (region != null)
// {
// for (final RegionFunction regionFn : region)
// {
// if (!regionFn.isStatic())
// return false;
// }
// }
return true;
}
/**
* Does preprocessing for region functions in this region
* @param game
*/
public void preprocess(final Game game)
{
if (region() != null)
{
for (final RegionFunction regionFunction : region())
{
regionFunction.preprocess(game);
}
}
if (isStatic())
precomputedRegion = eval(new Context(game, null));
}
@Override
public boolean missingRequirement(final Game game)
{
boolean missingRequirement = false;
if (region != null)
for (final RegionFunction r : region)
missingRequirement |= r.missingRequirement(game);
return missingRequirement;
}
@Override
public String toString()
{
return "Regions in Equipment named = " + name();
}
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
if (region != null)
for (final RegionFunction reg : region)
concepts.or(reg.concepts(game));
return concepts;
}
//-------------------------------------------------------------------------
}
| 14,791 | 27.068311 | 118 | java |
Ludii | Ludii-master/Core/src/game/equipment/other/package-info.java | /**
* This section describes other types of {\tt Equipment} that the user can declare, apart from containers and components.
* These include {\t Dominoes} sets, {\tt Hint}s for puzzles, integer {\tt Map}s and {\tt Region}s, as follows.
*/
package game.equipment.other;
| 272 | 44.5 | 121 | java |
Ludii | Ludii-master/Core/src/game/functions/booleans/BaseBooleanFunction.java | package game.functions.booleans;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.List;
import game.functions.ints.IntFunction;
import game.functions.region.RegionFunction;
import game.types.board.RegionTypeStatic;
import other.BaseLudeme;
import other.context.Context;
import other.location.Location;
/**
* Is a common functionality for boolean functions to avoid lots of cookie-cutter
* code.
*
* @author mrraow and Eric.Piette
*/
public abstract class BaseBooleanFunction extends BaseLudeme implements BooleanFunction
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/** Only used for Puzzles to detect the region constraint*/
public RegionFunction regionConstraint;
/** Only used for Puzzles to detect the locs constraint*/
public IntFunction[] locsConstraint;
/** Only used for Puzzles to detect the area constraint*/
public RegionTypeStatic areaConstraint;
@Override
public boolean isStatic()
{
return false;
}
@Override
public boolean autoFails()
{
return false;
}
@Override
public boolean autoSucceeds()
{
return false;
}
@Override
public RegionFunction regionConstraint()
{
return regionConstraint;
}
@Override
public IntFunction[] locsConstraint()
{
return locsConstraint;
}
@Override
public RegionTypeStatic staticRegion()
{
return areaConstraint;
}
@Override
public List<Location> satisfyingSites(final Context context)
{
return new ArrayList<Location>();
}
@Override
public BitSet stateConcepts(final Context context)
{
if (eval(context))
return this.concepts(context.game());
return new BitSet();
}
}
| 1,709 | 18.655172 | 87 | java |
Ludii | Ludii-master/Core/src/game/functions/booleans/BooleanConstant.java | package game.functions.booleans;
import annotations.Hide;
import game.Game;
import other.context.Context;
/**
* Constant boolean value.
*
* @author cambolbro, Dennis Soemers
*/
@Hide
public final class BooleanConstant extends BaseBooleanFunction
{
private static final long serialVersionUID = 1L;
/** The boolean constant value. */
private final boolean a;
//-------------------------------------------------------------------------
// /** Singleton which returns True. */
// private static final TrueConstant TRUE_INSTANCE = new TrueConstant();
//
// /** Singleton which returns False. */
// private static final FalseConstant FALSE_INSTANCE = new FalseConstant();
//
// //-------------------------------------------------------------------------
//
// /**
// * Construct function
// *
// * @param a
// */
// @SuppressWarnings("javadoc")
// public static BaseBooleanFunction construct(final boolean a)
// {
// if (a)
// return TRUE_INSTANCE;
// else
// return FALSE_INSTANCE;
// }
//
// /**
// * Constructor. NOTE: should not be used anymore!
// *
// * @param a
// */
// private BooleanConstant(final boolean a)
// {
// this.a = a;
// }
/**
* @param a
*/
public BooleanConstant(final boolean a)
{
this.a = a;
}
//-------------------------------------------------------------------------
@Override
public boolean eval(final Context context)
{
return a;
}
//-------------------------------------------------------------------------
@Override
public String toString()
{
final String str = "" + a;
return str;
}
//-------------------------------------------------------------------------
@Override
public boolean isStatic()
{
return true;
}
@Override
public long gameFlags(final Game game)
{
return 0;
}
@Override
public void preprocess(final Game game)
{
// nothing to do
}
@Override
public String toEnglish(final Game game)
{
return toString();
}
/**
* Constant boolean function returning True
*
* @author Dennis Soemers
*/
public final static class TrueConstant extends BaseBooleanFunction
{
/** */
private static final long serialVersionUID = 1L;
//---------------------------------------------------------------------
/**
* Constructor.
*/
TrueConstant()
{
// Do nothing
}
//---------------------------------------------------------------------
@Override
public boolean eval(final Context context)
{
return true;
}
//---------------------------------------------------------------------
@Override
public String toString()
{
final String str = "True";
return str;
}
//---------------------------------------------------------------------
@Override
public boolean isStatic()
{
return true;
}
@Override
public long gameFlags(final Game game)
{
return 0;
}
@Override
public void preprocess(final Game game)
{
// nothing to do
}
@Override
public String toEnglish(final Game game)
{
return "true";
}
}
/**
* Constant boolean function returning False
*
* @author Dennis Soemers
*/
public final static class FalseConstant extends BaseBooleanFunction
{
/** */
private static final long serialVersionUID = 1L;
//---------------------------------------------------------------------
/**
* Constructor.
*/
FalseConstant()
{
// Do nothing
}
//---------------------------------------------------------------------
@Override
public boolean eval(final Context context)
{
return false;
}
//---------------------------------------------------------------------
@Override
public String toString()
{
final String str = "False";
return str;
}
//---------------------------------------------------------------------
@Override
public boolean isStatic()
{
return true;
}
@Override
public long gameFlags(final Game game)
{
return 0;
}
@Override
public void preprocess(final Game game)
{
// nothing to do
}
@Override
public String toEnglish(final Game game)
{
return "false";
}
}
}
| 4,133 | 16.591489 | 78 | java |
Ludii | Ludii-master/Core/src/game/functions/booleans/BooleanFunction.java | package game.functions.booleans;
import java.util.BitSet;
import java.util.List;
import game.Game;
import game.functions.ints.IntFunction;
import game.functions.region.RegionFunction;
import game.types.board.RegionTypeStatic;
import game.types.state.GameType;
import other.context.Context;
import other.location.Location;
/**
* Returns a boolean.
*
* @author cambolbro and Eric.Piette
*/
// **
// ** Do not @Hide, or loses mapping in grammar!
// **
public interface BooleanFunction extends GameType
{
/**
* @param context The context.
* @return The result of applying this function to this trial.
*/
boolean eval(final Context context);
/**
* @return True if the function is sure to return false if eval() were
* called now, regardless of context.
*/
boolean autoFails();
/**
* @return True if the function is sure to return true if eval() were
* called now, regardless of context.
*/
boolean autoSucceeds();
/**
* @return The regions constraints by this function.
*/
RegionFunction regionConstraint();
/**
* @return The locations constraints by this function.
*/
IntFunction[] locsConstraint();
/**
* @return The type of the static region.
*/
RegionTypeStatic staticRegion();
/**
* @param context The context.
* @return The sites satisfying the condition when sites are the cause.
*/
List<Location> satisfyingSites(final Context context);
/**
* @param game The game.
* @return Accumulated flags corresponding to the game concepts.
*/
BitSet concepts(final Game game);
/**
* @return Accumulated flags corresponding to read data in EvalContext.
*/
BitSet readsEvalContextRecursive();
/**
* @return Accumulated flags corresponding to write data in EvalContext.
*/
BitSet writesEvalContextRecursive();
/**
* @param game The game.
* @return True if a required ludeme is missing.
*/
boolean missingRequirement(final Game game);
/**
* @param game The game.
* @return True if the ludeme can crash the game during its play.
*/
boolean willCrash(final Game game);
/**
* @param context The context.
* @return The concepts returned only if the booleanFunction is true.
*/
BitSet stateConcepts(final Context context);
/**
* @param game
* @return This boolean Function in English.
*/
String toEnglish(Game game);
}
| 2,330 | 21.2 | 73 | java |
Ludii | Ludii-master/Core/src/game/functions/booleans/ToBool.java | package game.functions.booleans;
import java.util.BitSet;
import annotations.Or;
import game.Game;
import game.functions.floats.FloatFunction;
import game.functions.ints.IntFunction;
import other.context.Context;
/**
* Converts a IntFunction or a FloatFunction to a boolean (false if 0, else
* true).
*
* @author Eric.Piette
*/
public final class ToBool extends BaseBooleanFunction
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/** The int function. */
private final IntFunction intFn;
/** The float function. */
private final FloatFunction floatFn;
//-------------------------------------------------------------------------
/**
* @param intFn The int function.
* @param floatFn The float function.
*
* @example (toBool (count Moves))
* @example (toBool (sqrt 2))
*/
public ToBool
(
@Or final IntFunction intFn,
@Or final FloatFunction floatFn
)
{
int numNonNull = 0;
if (intFn != null)
numNonNull++;
if (floatFn != null)
numNonNull++;
if (numNonNull != 1)
throw new IllegalArgumentException("ToBool(): One intFn or floatFn parameter must be non-null.");
this.intFn = intFn;
this.floatFn = floatFn;
}
//-------------------------------------------------------------------------
@Override
public boolean eval(final Context context)
{
if (intFn != null)
return intFn.eval(context) != 0;
return floatFn.eval(context) != 0.0;
}
//-------------------------------------------------------------------------
@Override
public boolean isStatic()
{
if (intFn != null)
return intFn.isStatic();
if (floatFn != null)
return floatFn.isStatic();
return false;
}
@Override
public long gameFlags(final Game game)
{
long gameFlags = 0l;
if (intFn != null)
gameFlags |= intFn.gameFlags(game);
if (floatFn != null)
gameFlags |= floatFn.gameFlags(game);
return gameFlags;
}
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
if (intFn != null)
concepts.or(intFn.concepts(game));
if (floatFn != null)
concepts.or(floatFn.concepts(game));
return concepts;
}
@Override
public BitSet writesEvalContextRecursive()
{
final BitSet writeEvalContext = new BitSet();
if (intFn != null)
writeEvalContext.or(intFn.writesEvalContextRecursive());
return writeEvalContext;
}
@Override
public BitSet readsEvalContextRecursive()
{
final BitSet readEvalContext = new BitSet();
if (intFn != null)
readEvalContext.or(intFn.readsEvalContextRecursive());
return readEvalContext;
}
@Override
public void preprocess(final Game game)
{
if (intFn != null)
intFn.preprocess(game);
if (floatFn != null)
floatFn.preprocess(game);
}
@Override
public boolean missingRequirement(final Game game)
{
boolean missingRequirement = false;
if (intFn != null)
missingRequirement |= intFn.missingRequirement(game);
if (floatFn != null)
missingRequirement |= floatFn.missingRequirement(game);
return missingRequirement;
}
@Override
public boolean willCrash(final Game game)
{
boolean willCrash = false;
if (intFn != null)
willCrash |= intFn.willCrash(game);
if (floatFn != null)
willCrash |= floatFn.willCrash(game);
return willCrash;
}
}
| 3,324 | 20.451613 | 100 | java |
Ludii | Ludii-master/Core/src/game/functions/booleans/package-info.java | /**
* @chapter Boolean functions are ludemes that return a ``true'' or ``false'' result to some query
* about the current game state.
* They verify the {\it existence} of a given condition in the current game state.
*/
package game.functions.booleans;
| 276 | 38.571429 | 99 | java |
Ludii | Ludii-master/Core/src/game/functions/booleans/all/All.java | package game.functions.booleans.all;
import annotations.Name;
import annotations.Opt;
import game.Game;
import game.functions.booleans.BaseBooleanFunction;
import game.functions.booleans.BooleanFunction;
import game.functions.booleans.all.groups.AllGroups;
import game.functions.booleans.all.simple.AllDiceEqual;
import game.functions.booleans.all.simple.AllDiceUsed;
import game.functions.booleans.all.simple.AllPassed;
import game.functions.booleans.all.sites.AllDifferent;
import game.functions.booleans.all.sites.AllSites;
import game.functions.booleans.all.values.AllValues;
import game.functions.intArray.IntArrayFunction;
import game.functions.region.RegionFunction;
import game.types.board.SiteType;
import game.util.directions.Direction;
import other.context.Context;
/**
* Returns whether all aspects of the specified query are true.
*
* @author Eric.Piette
*/
@SuppressWarnings("javadoc")
public class All extends BaseBooleanFunction
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/**
* For checking a condition in each group of the board.
*
* @param allType The query type to perform.
* @param type The type of the graph elements of the group.
* @param directions The directions of the connection between elements in the
* group [Adjacent].
* @param of The condition on the pieces to include in the group [(= (to) (mover))].
* @param If The condition for each group to verify.
*
* @example (all Groups if:(= 3 (count Sites in:(sites))))
*/
public static BooleanFunction construct
(
final AllGroupsType allType,
@Opt final SiteType type,
@Opt final Direction directions,
@Opt @Name final BooleanFunction of,
@Name final BooleanFunction If
)
{
switch (allType)
{
case Groups:
return new AllGroups(type,directions, of, If);
default:
break;
}
// We should never reach that except if we forget some codes.
throw new IllegalArgumentException("All(): A AllGroupsType is not implemented.");
}
/**
* For checking a condition in each value of a integer array.
*
* @param allType The query type to perform.
* @param array The array to check.
* @param If The condition to check.
*
* @example (all Values (values Remembered) if:(> 2 (value)))
*/
public static BooleanFunction construct
(
final AllValuesType allType,
final IntArrayFunction array,
@Name final BooleanFunction If
)
{
switch (allType)
{
case Values:
return new AllValues(array, If);
default:
break;
}
// We should never reach that except if we forget some codes.
throw new IllegalArgumentException("All(): A AllValuesType is not implemented.");
}
/**
* For checking a condition in each site of a region.
*
* @param allType The query type to perform.
* @param region The region to check.
* @param If The condition to check.
*
* @example (all Sites (sites Occupied by:Mover) if:(= 2 (size Stack
* at:(site))))
*/
public static BooleanFunction construct
(
final AllSitesType allType,
final RegionFunction region,
@Name final BooleanFunction If
)
{
switch (allType)
{
case Sites:
return new AllSites(region, If);
case Different:
return new AllDifferent(region, If);
default:
break;
}
// We should never reach that except if we forget some codes.
throw new IllegalArgumentException("All(): A AllSitesType is not implemented.");
}
/**
* For a test with no parameter.
*
* @param allType The query type to perform.
*
* @example (all DiceUsed)
* @example (all Passed)
* @example (all DiceEqual)
*/
public static BooleanFunction construct
(
final AllSimpleType allType
)
{
switch (allType)
{
case DiceUsed:
return new AllDiceUsed();
case Passed:
return new AllPassed();
case DiceEqual:
return new AllDiceEqual();
default:
break;
}
// We should never reach that except if we forget some codes.
throw new IllegalArgumentException("All(): A AllSimpleType is not implemented.");
}
//-------------------------------------------------------------------------
private All()
{
// Ensure that compiler does pick up default constructor
}
@Override
public boolean isStatic()
{
// Should never be there
return false;
}
@Override
public long gameFlags(final Game game)
{
// Should never be there
return 0L;
}
@Override
public void preprocess(final Game game)
{
// Nothing to do.
}
@Override
public boolean eval(final Context context)
{
// Should not be called, should only be called on subclasses
throw new UnsupportedOperationException("All.eval(): Should never be called directly.");
// return false;
}
@Override
public String toEnglish(final Game game)
{
return "all of the following is true:";
}
}
| 4,949 | 24 | 94 | java |
Ludii | Ludii-master/Core/src/game/functions/booleans/all/AllGroupsType.java | package game.functions.booleans.all;
/**
* Defines the query types that can be used for an {\tt (all ...)} test for the groups.
*
* @author Eric.Piette
*/
public enum AllGroupsType
{
/** Returns whether all the groups verify a condition. */
Groups,
} | 258 | 20.583333 | 87 | java |
Ludii | Ludii-master/Core/src/game/functions/booleans/all/AllSimpleType.java | package game.functions.booleans.all;
/**
* Defines the query types that can be used for an {\tt (all ...)} test with no
* parameter.
*
* @author Eric.Piette
*/
public enum AllSimpleType
{
/** Returns whether all the dice have been used in the current turn. */
DiceUsed,
/** Returns whether all the dice are equal when they are rolled. */
DiceEqual,
/** Returns whether all players have passed in succession. */
Passed,
}
| 436 | 20.85 | 79 | java |
Ludii | Ludii-master/Core/src/game/functions/booleans/all/AllSitesType.java | package game.functions.booleans.all;
/**
* Defines the query types that can be used for an {\tt (all ...)} test related
* to sites.
*
* @author Eric.Piette
*/
public enum AllSitesType
{
/** Returns whether all the sites satisfy a condition. */
Sites,
/** Returns whether all the sites are different. */
Different,
}
| 328 | 18.352941 | 79 | java |
Ludii | Ludii-master/Core/src/game/functions/booleans/all/AllValuesType.java | package game.functions.booleans.all;
/**
* Defines the query types that can be used for an {\tt (all ...)} test related
* to integer arrays.
*
* @author Eric.Piette
*/
public enum AllValuesType
{
/** Returns whether all the values satisfy a condition. */
Values,
}
| 274 | 18.642857 | 79 | java |
Ludii | Ludii-master/Core/src/game/functions/booleans/all/package-info.java | /**
* All is a `super' ludeme that returns whether all aspects of a certain query
* about the game state are true, such as whether all players passed or all dice have been used.
*/
package game.functions.booleans.all;
| 224 | 36.5 | 98 | java |
Ludii | Ludii-master/Core/src/game/functions/booleans/all/groups/AllGroups.java | package game.functions.booleans.all.groups;
import java.util.BitSet;
import java.util.List;
import annotations.Hide;
import annotations.Name;
import annotations.Opt;
import game.Game;
import game.functions.booleans.BaseBooleanFunction;
import game.functions.booleans.BooleanFunction;
import game.functions.directions.Directions;
import game.functions.directions.DirectionsFunction;
import game.types.board.SiteType;
import game.util.directions.AbsoluteDirection;
import game.util.directions.Direction;
import game.util.equipment.Region;
import gnu.trove.list.array.TIntArrayList;
import other.concept.Concept;
import other.context.Context;
import other.context.EvalContextData;
import other.state.container.ContainerState;
import other.topology.Topology;
import other.topology.TopologyElement;
/**
* Returns true if all the groups of the board verify a condition.
*
* @author Eric.Piette
*/
@Hide
public final class AllGroups extends BaseBooleanFunction
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/** The condition for each element of the group. */
private final BooleanFunction groupElementConditionFn;
/** The condition for each group to check. */
private final BooleanFunction groupCondition;
/** Direction chosen. */
private final DirectionsFunction dirnChoice;
/** The graph element type. */
private SiteType type;
//-------------------------------------------------------------------------
/**
* @param type The type of the graph elements of the group.
* @param directions The directions of the connection between elements in the
* group [Adjacent].
* @param of The condition on the pieces to include in the group [(= (to) (mover))].
* @param If The condition for each group to verify.
*/
public AllGroups
(
@Opt final SiteType type,
@Opt final Direction directions,
@Opt @Name final BooleanFunction of,
@Name final BooleanFunction If
)
{
this.type = type;
groupCondition = If;
groupElementConditionFn = of;
dirnChoice = (directions != null) ? directions.directionsFunctions()
: new Directions(AbsoluteDirection.Adjacent, null);
}
//-------------------------------------------------------------------------
@Override
public boolean eval(final Context context)
{
final Topology topology = context.topology();
final int maxIndexElement = context.topology().getGraphElements(type).size();
final ContainerState cs = context.containerState(0);
final int origFrom = context.from();
final int origTo = context.to();
final Region origRegion = context.region();
final int who = context.state().mover();
// We get the minimum set of sites to look.
final TIntArrayList sitesToCheck = new TIntArrayList();
if (groupElementConditionFn != null)
{
for (int i = 0; i <= context.game().players().size(); i++)
{
final TIntArrayList allSites = context.state().owned().sites(i);
for (int j = 0; j < allSites.size(); j++)
{
final int site = allSites.get(j);
if (site < maxIndexElement)
sitesToCheck.add(site);
}
}
}
else
{
for (int j = 0; j < context.state().owned().sites(who).size(); j++)
{
final int site = context.state().owned().sites(who).get(j);
if (site < maxIndexElement)
sitesToCheck.add(site);
}
}
// We get each group.
final TIntArrayList sitesChecked = new TIntArrayList();
for (int k = 0; k < sitesToCheck.size(); k++)
{
final int from = sitesToCheck.get(k);
if (sitesChecked.contains(from))
continue;
final TIntArrayList groupSites = new TIntArrayList();
context.setFrom(from);
context.setTo(from);
if ((who == cs.who(from, type) && groupElementConditionFn == null) || (groupElementConditionFn != null && groupElementConditionFn.eval(context)))
groupSites.add(from);
if (groupSites.size() > 0)
{
context.setFrom(from);
final TIntArrayList sitesExplored = new TIntArrayList();
int i = 0;
while (sitesExplored.size() != groupSites.size())
{
final int site = groupSites.get(i);
final TopologyElement siteElement = topology.getGraphElements(type).get(site);
final List<AbsoluteDirection> directions = dirnChoice.convertToAbsolute(type, siteElement, null,
null, null, context);
for (final AbsoluteDirection direction : directions)
{
final List<game.util.graph.Step> steps = topology.trajectories().steps(type,
siteElement.index(), type, direction);
for (final game.util.graph.Step step : steps)
{
final int to = step.to().id();
// If we already have it we continue to look the others.
if (groupSites.contains(to))
continue;
context.setTo(to);
if ((groupElementConditionFn == null && who == cs.who(to, type)
|| (groupElementConditionFn != null && groupElementConditionFn.eval(context))))
groupSites.add(to);
}
}
sitesExplored.add(site);
i++;
}
context.setRegion(new Region(groupSites.toArray()));
if(!groupCondition.eval(context))
return false;
sitesChecked.addAll(groupSites);
}
}
context.setTo(origTo);
context.setFrom(origFrom);
context.setRegion(origRegion);
return true;
}
//-------------------------------------------------------------------------
@Override
public String toString()
{
return "AllGroups()";
}
//-------------------------------------------------------------------------
@Override
public boolean isStatic()
{
return false;
}
@Override
public long gameFlags(final Game game)
{
long gameFlags = 0L;
gameFlags |= SiteType.gameFlags(type);
if (groupElementConditionFn != null)
gameFlags |= groupElementConditionFn.gameFlags(game);
if (groupCondition != null)
gameFlags |= groupCondition.gameFlags(game);
return gameFlags;
}
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
concepts.or(SiteType.concepts(type));
concepts.set(Concept.Group.id(), true);
if (groupElementConditionFn != null)
concepts.or(groupElementConditionFn.concepts(game));
if (groupCondition != null)
concepts.or(groupCondition.concepts(game));
if (dirnChoice != null)
concepts.or(dirnChoice.concepts(game));
return concepts;
}
@Override
public BitSet writesEvalContextFlat()
{
final BitSet writeEvalContext = new BitSet();
writeEvalContext.set(EvalContextData.To.id(), true);
writeEvalContext.set(EvalContextData.From.id(), true);
writeEvalContext.set(EvalContextData.Region.id(), true);
return writeEvalContext;
}
@Override
public BitSet writesEvalContextRecursive()
{
final BitSet writeEvalContext = new BitSet();
if (groupElementConditionFn != null)
writeEvalContext.or(groupElementConditionFn.writesEvalContextRecursive());
if (groupCondition != null)
writeEvalContext.or(groupCondition.writesEvalContextRecursive());
if (dirnChoice != null)
writeEvalContext.or(dirnChoice.writesEvalContextRecursive());
return writeEvalContext;
}
@Override
public BitSet readsEvalContextRecursive()
{
final BitSet readEvalContext = new BitSet();
if (groupElementConditionFn != null)
readEvalContext.or(groupElementConditionFn.readsEvalContextRecursive());
if (groupCondition != null)
readEvalContext.or(groupCondition.readsEvalContextRecursive());
if (dirnChoice != null)
readEvalContext.or(dirnChoice.readsEvalContextRecursive());
return readEvalContext;
}
@Override
public void preprocess(final Game game)
{
type = SiteType.use(type, game);
if (groupElementConditionFn != null)
groupElementConditionFn.preprocess(game);
if (groupCondition != null)
groupCondition.preprocess(game);
}
@Override
public boolean missingRequirement(final Game game)
{
boolean missingRequirement = false;
if (groupElementConditionFn != null)
missingRequirement |= groupElementConditionFn.missingRequirement(game);
if (groupCondition != null)
missingRequirement |= groupCondition.missingRequirement(game);
return missingRequirement;
}
@Override
public boolean willCrash(final Game game)
{
boolean willCrash = false;
if (groupElementConditionFn != null)
willCrash |= groupElementConditionFn.willCrash(game);
if (groupCondition != null)
willCrash |= groupCondition.willCrash(game);
return willCrash;
}
@Override
public String toEnglish(final Game game)
{
return "all groups satisfy the condition " + groupCondition.toEnglish(game);
}
} | 8,623 | 26.205047 | 148 | java |
Ludii | Ludii-master/Core/src/game/functions/booleans/all/simple/AllDiceEqual.java | package game.functions.booleans.all.simple;
import java.util.BitSet;
import annotations.Hide;
import game.Game;
import game.functions.booleans.BaseBooleanFunction;
import game.types.state.GameType;
import other.concept.Concept;
import other.context.Context;
/**
* Returns true if all the dice are equal when they are rolled.
*
* @author Eric.Piette
*
* @remarks That data is modified only when the dice are rolled.
*/
@Hide
public final class AllDiceEqual extends BaseBooleanFunction
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/**
*
*/
public AllDiceEqual()
{
}
//-------------------------------------------------------------------------
@Override
public boolean eval(final Context context)
{
return context.state().isDiceAllEqual();
}
//-------------------------------------------------------------------------
@Override
public String toString()
{
return "AllDiceEqual()";
}
//-------------------------------------------------------------------------
@Override
public boolean isStatic()
{
return false;
}
@Override
public long gameFlags(final Game game)
{
return GameType.Stochastic;
}
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
concepts.set(Concept.Dice.id(), true);
return concepts;
}
@Override
public BitSet writesEvalContextRecursive()
{
final BitSet writeEvalContext = new BitSet();
return writeEvalContext;
}
@Override
public BitSet readsEvalContextRecursive()
{
final BitSet readEvalContext = new BitSet();
return readEvalContext;
}
@Override
public void preprocess(final Game game)
{
// nothing to do
}
@Override
public boolean missingRequirement(final Game game)
{
if (!game.hasHandDice())
{
game.addRequirementToReport("The ludeme (all DiceEqual) is used but the equipment has no dice.");
return true;
}
return false;
}
@Override
public String toEnglish(final Game game)
{
return "all dice show equal values";
}
} | 2,078 | 18.25 | 100 | java |
Ludii | Ludii-master/Core/src/game/functions/booleans/all/simple/AllDiceUsed.java | package game.functions.booleans.all.simple;
import java.util.BitSet;
import annotations.Hide;
import game.Game;
import game.functions.booleans.BaseBooleanFunction;
import game.types.state.GameType;
import other.concept.Concept;
import other.context.Context;
/**
* Returns true if all the dice are used during your turn.
*
* @author Eric.Piette
*
* @remarks In dice games when the dice can be used one by one. True if all the
* values of a dice container are equal to zero.
*/
@Hide
public final class AllDiceUsed extends BaseBooleanFunction
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/**
*
*/
public AllDiceUsed()
{
}
//-------------------------------------------------------------------------
@Override
public boolean eval(final Context context)
{
final int[][] diceValues = context.state().currentDice();
for (int indexHand = 0; indexHand < diceValues.length; indexHand++)
for (int indexDie = 0; indexDie < diceValues[indexHand].length; indexDie++)
if (diceValues[indexHand][indexDie] != 0)
return false;
return true;
}
//-------------------------------------------------------------------------
@Override
public String toString()
{
return "AllDiceUsed()";
}
//-------------------------------------------------------------------------
@Override
public boolean isStatic()
{
return false;
}
@Override
public long gameFlags(final Game game)
{
return GameType.Stochastic;
}
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
concepts.set(Concept.Dice.id(), true);
return concepts;
}
@Override
public BitSet writesEvalContextRecursive()
{
final BitSet writeEvalContext = new BitSet();
return writeEvalContext;
}
@Override
public BitSet readsEvalContextRecursive()
{
final BitSet readEvalContext = new BitSet();
return readEvalContext;
}
@Override
public void preprocess(final Game game)
{
// nothing to do
}
@Override
public boolean missingRequirement(final Game game)
{
if (!game.hasHandDice())
{
game.addRequirementToReport("The ludeme (all DiceUsed) is used but the equipment has no dice.");
return true;
}
return false;
}
@Override
public String toEnglish(final Game game)
{
return "all dice have been used";
}
}
| 2,388 | 19.418803 | 99 | java |
Ludii | Ludii-master/Core/src/game/functions/booleans/all/simple/AllPassed.java | package game.functions.booleans.all.simple;
import java.util.BitSet;
import annotations.Hide;
import game.Game;
import game.functions.booleans.BaseBooleanFunction;
import game.types.state.GameType;
import other.context.Context;
/**
* Returns whether all the players have passed in the previous turns.
*
* @author Eric.Piette
*
* @remarks For any game in which the game can end by all players passing.
*/
@Hide
public final class AllPassed extends BaseBooleanFunction
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/**
*
*/
public AllPassed()
{
// Nothing to do.
}
//-------------------------------------------------------------------------
@Override
public String toEnglish(final Game game)
{
return "all players have passed";
}
//-------------------------------------------------------------------------
@Override
public boolean eval(final Context context)
{
if (context.trial().moveNumber() < context.game().players().count())
return false;
return context.allPass();
}
//-------------------------------------------------------------------------
@Override
public String toString()
{
return "AllPass()";
}
//-------------------------------------------------------------------------
@Override
public boolean isStatic()
{
return false;
}
@Override
public long gameFlags(final Game game)
{
return GameType.NotAllPass;
}
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
return concepts;
}
@Override
public BitSet writesEvalContextRecursive()
{
final BitSet writeEvalContext = new BitSet();
return writeEvalContext;
}
@Override
public BitSet readsEvalContextRecursive()
{
final BitSet readEvalContext = new BitSet();
return readEvalContext;
}
@Override
public void preprocess(final Game game)
{
// nothing to do
}
}
| 1,947 | 18.098039 | 76 | java |
Ludii | Ludii-master/Core/src/game/functions/booleans/all/sites/AllDifferent.java | package game.functions.booleans.all.sites;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.List;
import annotations.Hide;
import annotations.Name;
import game.Game;
import game.functions.booleans.BaseBooleanFunction;
import game.functions.booleans.BooleanFunction;
import game.functions.region.RegionFunction;
import game.types.board.SiteType;
import gnu.trove.list.array.TIntArrayList;
import other.context.Context;
import other.context.EvalContextData;
import other.location.FullLocation;
import other.location.Location;
import other.state.container.ContainerState;
/**
* Returns true if all the sites are different.
*
* @author Eric.Piette
*/
@Hide
public final class AllDifferent extends BaseBooleanFunction
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/** Region to check. */
private final RegionFunction region;
/** Condition to check. */
private final BooleanFunction condition;
/**
* @param region The region.
* @param If The condition to satisfy.
*/
public AllDifferent
(
final RegionFunction region,
@Name final BooleanFunction If
)
{
this.region = region;
condition = If;
}
//-------------------------------------------------------------------------
@Override
public boolean eval(final Context context)
{
final int[] sites = region.eval(context).sites();
final int originSiteValue = context.site();
final SiteType type = context.board().defaultSite();
final ContainerState cs = context.containerState(0);
final TIntArrayList whats = new TIntArrayList();
for (final int site : sites)
{
context.setSite(site);
if (!condition.eval(context))
{
context.setSite(originSiteValue);
return false;
}
else
{
final int what = cs.what(site, type);
if (whats.contains(what))
{
context.setSite(originSiteValue);
return false;
}
else
{
whats.add(what);
}
}
}
context.setSite(originSiteValue);
return true;
}
//-------------------------------------------------------------------------
@Override
public boolean isStatic()
{
return condition.isStatic() && region.isStatic();
}
@Override
public long gameFlags(final Game game)
{
return condition.gameFlags(game) | region.gameFlags(game);
}
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
concepts.or(condition.concepts(game));
concepts.or(region.concepts(game));
return concepts;
}
@Override
public BitSet writesEvalContextRecursive()
{
final BitSet writeEvalContext = writesEvalContextFlat();
writeEvalContext.or(condition.writesEvalContextRecursive());
writeEvalContext.or(region.writesEvalContextRecursive());
return writeEvalContext;
}
@Override
public BitSet writesEvalContextFlat()
{
final BitSet writeEvalContext = new BitSet();
writeEvalContext.set(EvalContextData.Site.id(), true);
return writeEvalContext;
}
@Override
public BitSet readsEvalContextRecursive()
{
final BitSet readEvalContext = new BitSet();
readEvalContext.or(condition.readsEvalContextRecursive());
readEvalContext.or(region.readsEvalContextRecursive());
return readEvalContext;
}
@Override
public void preprocess(final Game game)
{
condition.preprocess(game);
region.preprocess(game);
}
@Override
public boolean missingRequirement(final Game game)
{
boolean missingRequirement = false;
missingRequirement |= region.missingRequirement(game);
missingRequirement |= condition.missingRequirement(game);
return missingRequirement;
}
@Override
public boolean willCrash(final Game game)
{
boolean willCrash = false;
willCrash |= region.willCrash(game);
willCrash |= condition.willCrash(game);
return willCrash;
}
//-------------------------------------------------------------------------
@Override
public List<Location> satisfyingSites(final Context context)
{
if (!eval(context))
return new ArrayList<Location>();
final List<Location> winningSites = new ArrayList<Location>();
final int[] sites = region.eval(context).sites();
final SiteType type = context.board().defaultSite();
for (final int site : sites)
winningSites.add(new FullLocation(site, 0, type));
return winningSites;
}
@Override
public String toEnglish(final Game game)
{
return "all sites in " + region.toEnglish(game) + " have different results for the condition " + condition.toEnglish(game);
}
} | 4,508 | 22.984043 | 125 | java |
Ludii | Ludii-master/Core/src/game/functions/booleans/all/sites/AllSites.java | package game.functions.booleans.all.sites;
import java.util.BitSet;
import annotations.Hide;
import annotations.Name;
import game.Game;
import game.functions.booleans.BaseBooleanFunction;
import game.functions.booleans.BooleanFunction;
import game.functions.region.RegionFunction;
import other.concept.Concept;
import other.context.Context;
import other.context.EvalContextData;
/**
* Returns true if all the sites of a region satisfy a condition.
*
* @author Eric.Piette
*/
@Hide
public final class AllSites extends BaseBooleanFunction
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/** Region to check. */
private final RegionFunction region;
/** Condition to check. */
private final BooleanFunction condition;
/**
* @param region The region.
* @param If The condition to satisfy.
*/
public AllSites
(
final RegionFunction region,
@Name final BooleanFunction If
)
{
this.region = region;
condition = If;
}
//-------------------------------------------------------------------------
@Override
public boolean eval(final Context context)
{
final int[] sites = region.eval(context).sites();
final int originSiteValue = context.site();
for (final int site : sites)
{
context.setSite(site);
if (!condition.eval(context))
{
context.setSite(originSiteValue);
return false;
}
}
context.setSite(originSiteValue);
return true;
}
//-------------------------------------------------------------------------
@Override
public boolean isStatic()
{
return condition.isStatic() && region.isStatic();
}
@Override
public long gameFlags(final Game game)
{
return condition.gameFlags(game) | region.gameFlags(game);
}
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
concepts.or(condition.concepts(game));
concepts.or(region.concepts(game));
if(region.getClass().toString().contains("Board") && condition.concepts(game).get(Concept.PieceCount.id()))
concepts.set(Concept.NoPiece.id(), true);
return concepts;
}
@Override
public BitSet writesEvalContextRecursive()
{
final BitSet writeEvalContext = writesEvalContextFlat();
writeEvalContext.or(condition.writesEvalContextRecursive());
writeEvalContext.or(region.writesEvalContextRecursive());
return writeEvalContext;
}
@Override
public BitSet writesEvalContextFlat()
{
final BitSet writeEvalContext = new BitSet();
writeEvalContext.set(EvalContextData.Site.id(), true);
return writeEvalContext;
}
@Override
public BitSet readsEvalContextRecursive()
{
final BitSet readEvalContext = new BitSet();
readEvalContext.or(condition.readsEvalContextRecursive());
readEvalContext.or(region.readsEvalContextRecursive());
return readEvalContext;
}
@Override
public void preprocess(final Game game)
{
condition.preprocess(game);
region.preprocess(game);
}
@Override
public boolean missingRequirement(final Game game)
{
boolean missingRequirement = false;
missingRequirement |= region.missingRequirement(game);
missingRequirement |= condition.missingRequirement(game);
return missingRequirement;
}
@Override
public boolean willCrash(final Game game)
{
boolean willCrash = false;
willCrash |= region.willCrash(game);
willCrash |= condition.willCrash(game);
return willCrash;
}
@Override
public String toEnglish(final Game game)
{
return "all sites in " + region.toEnglish(game) + " satisfy the condition " + condition.toEnglish(game);
}
} | 3,584 | 22.741722 | 109 | java |
Ludii | Ludii-master/Core/src/game/functions/booleans/all/values/AllValues.java | package game.functions.booleans.all.values;
import java.util.BitSet;
import annotations.Hide;
import annotations.Name;
import game.Game;
import game.functions.booleans.BaseBooleanFunction;
import game.functions.booleans.BooleanFunction;
import game.functions.intArray.IntArrayFunction;
import other.context.Context;
import other.context.EvalContextData;
/**
* Returns true if all the values of an integer array satisfy a condition.
*
* @author Eric.Piette
*/
@Hide
public final class AllValues extends BaseBooleanFunction
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/** Integer array to check. */
private final IntArrayFunction array;
/** Condition to check. */
private final BooleanFunction condition;
/**
* @param array The array.
* @param If The condition to satisfy.
*/
public AllValues
(
final IntArrayFunction array,
@Name final BooleanFunction If
)
{
this.array = array;
condition = If;
}
//-------------------------------------------------------------------------
@Override
public boolean eval(final Context context)
{
final int[] values = array.eval(context);
final int originValue = context.value();
for (final int site : values)
{
context.setValue(site);
if (!condition.eval(context))
{
context.setValue(originValue);
return false;
}
}
context.setValue(originValue);
return true;
}
//-------------------------------------------------------------------------
@Override
public boolean isStatic()
{
return condition.isStatic() && array.isStatic();
}
@Override
public long gameFlags(final Game game)
{
return condition.gameFlags(game) | array.gameFlags(game);
}
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
concepts.or(condition.concepts(game));
concepts.or(array.concepts(game));
return concepts;
}
@Override
public BitSet writesEvalContextRecursive()
{
final BitSet writeEvalContext = writesEvalContextFlat();
writeEvalContext.or(condition.writesEvalContextRecursive());
writeEvalContext.or(array.writesEvalContextRecursive());
return writeEvalContext;
}
@Override
public BitSet writesEvalContextFlat()
{
final BitSet writeEvalContext = new BitSet();
writeEvalContext.set(EvalContextData.Value.id(), true);
return writeEvalContext;
}
@Override
public BitSet readsEvalContextRecursive()
{
final BitSet readEvalContext = new BitSet();
readEvalContext.or(condition.readsEvalContextRecursive());
readEvalContext.or(array.readsEvalContextRecursive());
return readEvalContext;
}
@Override
public void preprocess(final Game game)
{
condition.preprocess(game);
array.preprocess(game);
}
@Override
public boolean missingRequirement(final Game game)
{
boolean missingRequirement = false;
missingRequirement |= array.missingRequirement(game);
missingRequirement |= condition.missingRequirement(game);
return missingRequirement;
}
@Override
public boolean willCrash(final Game game)
{
boolean willCrash = false;
willCrash |= array.willCrash(game);
willCrash |= condition.willCrash(game);
return willCrash;
}
@Override
public String toEnglish(final Game game)
{
return "all values in " + array.toEnglish(game) + " satisfy the condition " + condition.toEnglish(game);
}
} | 3,393 | 22.088435 | 106 | java |
Ludii | Ludii-master/Core/src/game/functions/booleans/can/Can.java | package game.functions.booleans.can;
import game.Game;
import game.functions.booleans.BaseBooleanFunction;
import game.functions.booleans.BooleanFunction;
import game.rules.play.moves.Moves;
import other.context.Context;
/**
* Returns whether a given property can be achieved in the current game state.
*
* @author Eric.Piette
*/
@SuppressWarnings("javadoc")
public class Can extends BaseBooleanFunction
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/**
* @param canType Type of query.
* @param moves List of moves.
*
* @example (can Move (forEach Piece))
*/
public static BooleanFunction construct
(
final CanType canType,
final Moves moves
)
{
switch (canType)
{
case Move:
return new CanMove(moves);
default:
break;
}
// We should never reach that except if we forget some codes.
throw new IllegalArgumentException("Can(): A CanType is not implemented.");
}
//-------------------------------------------------------------------------
private Can()
{
// Ensure that compiler does pick up default constructor
}
@Override
public boolean isStatic()
{
// Should never be there
return false;
}
@Override
public long gameFlags(final Game game)
{
// Should never be there
return 0L;
}
@Override
public void preprocess(final Game game)
{
// Nothing to do.
}
@Override
public boolean eval(Context context)
{
// Should not be called, should only be called on subclasses
throw new UnsupportedOperationException("Can.eval(): Should never be called directly.");
}
}
| 1,636 | 19.721519 | 90 | java |
Ludii | Ludii-master/Core/src/game/functions/booleans/can/CanMove.java | package game.functions.booleans.can;
import java.util.BitSet;
import annotations.Hide;
import game.Game;
import game.functions.booleans.BaseBooleanFunction;
import game.rules.play.moves.Moves;
import other.concept.Concept;
import other.context.Context;
import other.move.Move;
import other.state.State;
/**
* Checks if a list of moves is not empty.
*
* @author Eric.Piette
*/
@Hide
public class CanMove extends BaseBooleanFunction
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/** The moves to check. */
private final Moves moves;
//-------------------------------------------------------------------------
/**
* @param moves The list of moves.
*/
public CanMove
(
final Moves moves
)
{
this.moves = moves;
}
//-------------------------------------------------------------------------
@Override
public String toEnglish(final Game game)
{
if(moves != null)
return "can move " + moves.toEnglish(game);
else
return "can move";
}
//-------------------------------------------------------------------------
@Override
public boolean eval(final Context context)
{
if (context.game().requiresVisited())
{
final Move lastMove = context.trial().lastMove();
final State state = context.state();
final int from = lastMove.fromNonDecision();
final int to = lastMove.toNonDecision();
state.visit(from);
state.visit(to);
boolean canMove = moves.canMove(context);
state.unvisit(from);
state.unvisit(to);
return canMove;
}
return moves.canMove(context);
}
//-------------------------------------------------------------------------
@Override
public long gameFlags(final Game game)
{
return moves.gameFlags(game);
}
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
concepts.or(moves.concepts(game));
concepts.set(Concept.CanMove.id(), true);
return concepts;
}
@Override
public BitSet writesEvalContextRecursive()
{
final BitSet writeEvalContext = new BitSet();
writeEvalContext.or(moves.writesEvalContextRecursive());
return writeEvalContext;
}
@Override
public BitSet readsEvalContextRecursive()
{
final BitSet readEvalContext = new BitSet();
readEvalContext.or(moves.readsEvalContextRecursive());
return readEvalContext;
}
@Override
public boolean isStatic()
{
return moves.isStatic();
}
@Override
public void preprocess(final Game game)
{
moves.preprocess(game);
}
@Override
public boolean missingRequirement(final Game game)
{
boolean missingRequirement = false;
missingRequirement |= moves.missingRequirement(game);
return missingRequirement;
}
@Override
public boolean willCrash(final Game game)
{
boolean willCrash = false;
willCrash |= moves.willCrash(game);
return willCrash;
}
}
| 2,872 | 20.281481 | 76 | java |
Ludii | Ludii-master/Core/src/game/functions/booleans/can/CanType.java | package game.functions.booleans.can;
/**
* Defines the types properties that 'can' be tested.
*/
public enum CanType
{
/** Checks if a list of moves is not empty. */
Move,
}
| 179 | 15.363636 | 53 | java |
Ludii | Ludii-master/Core/src/game/functions/booleans/can/package-info.java | /**
* Can is a `super' ludeme that returns whether a given property can be achieved in the current game state,
* such as whether the player can make at least one move.
*/
package game.functions.booleans.can;
| 213 | 34.666667 | 108 | java |
Ludii | Ludii-master/Core/src/game/functions/booleans/deductionPuzzle/ForAll.java | package game.functions.booleans.deductionPuzzle;
import java.util.BitSet;
import java.util.List;
import game.Game;
import game.functions.booleans.BaseBooleanFunction;
import game.functions.booleans.BooleanFunction;
import game.functions.ints.IntConstant;
import game.functions.ints.IntFunction;
import game.functions.region.sites.custom.SitesCustom;
import game.types.board.PuzzleElementType;
import game.types.state.GameType;
import main.StringRoutines;
import other.concept.Concept;
import other.context.Context;
import other.context.EvalContextData;
import other.state.container.ContainerState;
import other.topology.Edge;
import other.topology.TopologyElement;
/**
* Returns true if the constraint is satisfied for each element.
*
* @author Eric.Piette
*
* @remarks This is used to test a constraint on each vertex, edge, face or site
* with a hint. This works only for deduction puzzles.
*/
public class ForAll extends BaseBooleanFunction
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/** Which type. */
private final PuzzleElementType type;
/** Constraint to satisfy. */
private final BooleanFunction constraint;
//-------------------------------------------------------------------------
/**
* @param type The type of the graph element.
* @param constraint The constraint to check.
* @example (forAll Hint (is Count (sites Around (from) includeSelf:True) of:1
* (hint) ) )
*/
public ForAll
(
final PuzzleElementType type,
final BooleanFunction constraint
)
{
this.type = type;
this.constraint = constraint;
}
//--------------------------------------------------------------------------
@Override
public boolean eval(Context context)
{
final int saveTo = context.to();
final int saveFrom = context.to();
final int saveHint = context.hint();
final int saveEdge = context.edge();
if (!type.equals(PuzzleElementType.Hint))
{
final List<? extends TopologyElement> elements = context.topology()
.getGraphElements(PuzzleElementType.convert(type));
for (int i = 0; i < elements.size(); i++)
{
final TopologyElement element = elements.get(i);
context.setFrom(element.index());
if (!constraint.eval(context))
{
context.setHint(saveHint);
context.setEdge(saveEdge);
context.setTo(saveTo);
context.setFrom(saveFrom);
return false;
}
}
}
else
{
final Integer[][] regions = context.game().equipment().withHints(context.board().defaultSite());
final Integer[] hints = context.game().equipment().hints(context.board().defaultSite());
final int size = Math.min(regions.length, hints.length);
for (int i = 0; i < size; i++)
{
// We compute the number of edges with hints
int nbEdges = 0;
boolean allEdgesSet = true;
for (int j = 0; j < regions[i].length; j++)
{
nbEdges = 0;
final int indexVertex = regions[i][j].intValue();
final ContainerState ps = context.state().containerStates()[0];
final List<Edge> edges = context.game().board().topology().edges();
for (int indexEdge = 0; indexEdge < edges.size(); indexEdge++)
{
final Edge edge = edges.get(indexEdge);
if (edge.containsVertex(indexVertex))
{
if (ps.isResolvedEdges(indexEdge))
nbEdges += ps.whatEdge(indexEdge);
else
allEdgesSet = false;
}
}
}
// System.out.println(
// "number of edges solved for the vertex " + regions[i][j].intValue() + " is " + nbEdges);
// if all the edges are assigned or the number of edges is greater than the
// hints we set the nbEdge to satisfy the constraint.
if (!allEdgesSet && hints[i] != null && nbEdges < hints[i].intValue())
context.setEdge(hints[i].intValue());
else
context.setEdge(nbEdges);
if (regions[i].length > 0)
context.setFrom(regions[i][0].intValue());
if (regions[i].length > 1)
context.setTo(regions[i][1].intValue());
if (hints[i] != null)
context.setHint(hints[i].intValue());
// System.out.println("Edge: " + context.edge());
// System.out.println("From: " + context.from());
// System.out.println("To: " + context.to());
// System.out.println("Hint: " + context.hint());
// System.out.println();
final IntFunction[] setFn = new IntFunction[regions.length];
for (int h = 0; h < regions[i].length; h++)
setFn[h] = new IntConstant(regions[i][h].intValue());
context.setHintRegion(
new SitesCustom(setFn));
if (!constraint.eval(context))
{
context.setHint(saveHint);
context.setEdge(saveEdge);
context.setTo(saveTo);
context.setFrom(saveFrom);
return false;
}
}
}
// else if (type.equals(PuzzleElementType.Cell))
// {
// final Integer[][] regions = context.game().equipment().cellsWithHints();
// final Integer[] hints = context.game().equipment().cellHints();
//
// final int size = Math.min(regions.length, hints.length);
// for (int i = 0; i < size; i++)
// {
// if (regions[i].length > 0)
// context.setFrom(regions[i][0].intValue());
// if (regions[i].length > 1)
// context.setTo(regions[i][1].intValue());
// if (hints[i] != null)
// context.setHint(hints[i].intValue());
// if (!constraint.eval(context))
// {
// context.setHint(saveHint);
// context.setEdge(saveEdge);
// context.setTo(saveTo);
// context.setFrom(saveFrom);
// return false;
// }
// }
// }
context.setHint(saveHint);
context.setEdge(saveEdge);
context.setTo(saveTo);
context.setFrom(saveFrom);
return true;
}
//-------------------------------------------------------------------------
@Override
public boolean isStatic()
{
return constraint.isStatic();
}
@Override
public void preprocess(final Game game)
{
if (constraint != null)
constraint.preprocess(game);
}
@Override
public long gameFlags(final Game game)
{
long gameFlags = GameType.DeductionPuzzle;
if (constraint != null)
gameFlags |= constraint.gameFlags(game);
return gameFlags;
}
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
concepts.or(super.concepts(game));
concepts.set(Concept.DeductionPuzzle.id(), true);
if (constraint != null)
concepts.or(constraint.concepts(game));
return concepts;
}
@Override
public BitSet writesEvalContextRecursive()
{
final BitSet writeEvalContext = writesEvalContextFlat();
if (constraint != null)
writeEvalContext.or(constraint.writesEvalContextRecursive());
return writeEvalContext;
}
@Override
public BitSet writesEvalContextFlat()
{
final BitSet writeEvalContext = new BitSet();
writeEvalContext.set(EvalContextData.Hint.id(), true);
writeEvalContext.set(EvalContextData.HintRegion.id(), true);
writeEvalContext.set(EvalContextData.Edge.id(), true);
writeEvalContext.set(EvalContextData.To.id(), true);
writeEvalContext.set(EvalContextData.From.id(), true);
return writeEvalContext;
}
@Override
public BitSet readsEvalContextRecursive()
{
final BitSet readEvalContext = new BitSet();
readEvalContext.or(super.readsEvalContextRecursive());
if (constraint != null)
readEvalContext.or(constraint.readsEvalContextRecursive());
return readEvalContext;
}
@Override
public boolean missingRequirement(final Game game)
{
boolean missingRequirement = false;
missingRequirement |= super.missingRequirement(game);
if (constraint != null)
missingRequirement |= constraint.missingRequirement(game);
return missingRequirement;
}
@Override
public boolean willCrash(final Game game)
{
boolean willCrash = false;
if (game.players().count() != 1)
{
game.addCrashToReport("The ludeme (forAll ...) is used but the number of players is not 1.");
willCrash = true;
}
willCrash |= super.willCrash(game);
if (constraint != null)
willCrash |= constraint.willCrash(game);
return willCrash;
}
/**
* @return The graph element.
*/
public PuzzleElementType type()
{
return type;
}
/**
* @return The constraint.
*/
public BooleanFunction constraint() {
return constraint;
}
//-------------------------------------------------------------------------
@Override
public String toString()
{
String str = "";
str += "AllTrue " + type + ": " + constraint;
return str;
}
//-------------------------------------------------------------------------
@Override
public String toEnglish(final Game game)
{
return constraint.toEnglish(game) + " is true for all " + type.name().toLowerCase() + StringRoutines.getPlural(type.name());
}
//-------------------------------------------------------------------------
} | 8,795 | 26.148148 | 126 | java |
Ludii | Ludii-master/Core/src/game/functions/booleans/deductionPuzzle/package-info.java | /**
* Deduction puzzle queries return a boolean result based on whether
* certain constraints are respected in the current state of a puzzle challenge
* solution.
*/
package game.functions.booleans.deductionPuzzle;
| 219 | 30.428571 | 79 | java |
Ludii | Ludii-master/Core/src/game/functions/booleans/deductionPuzzle/all/All.java | package game.functions.booleans.deductionPuzzle.all;
import annotations.Name;
import annotations.Opt;
import annotations.Or;
import game.Game;
import game.functions.booleans.BaseBooleanFunction;
import game.functions.booleans.BooleanFunction;
import game.functions.ints.IntFunction;
import game.functions.region.RegionFunction;
import game.types.board.SiteType;
import other.context.Context;
/**
* Whether the specified query is all true for a deduction puzzle.
*
* @author Eric.Piette
*/
@SuppressWarnings("javadoc")
public class All extends BaseBooleanFunction
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/**
* @param allType The query type to perform.
* @param elementType Type of graph elements to return [Cell].
* @param region The region to check [Regions].
* @param except The exception on the test.
* @param excepts The exceptions on the test.
*
* @example (all Different)
*
* @example (all Different except:0)
*/
public static BooleanFunction construct
(
final AllPuzzleType allType,
@Opt final SiteType elementType,
@Opt final RegionFunction region,
@Opt @Or @Name final IntFunction except,
@Opt @Or @Name final IntFunction[] excepts
)
{
int numNonNull = 0;
if (except != null)
numNonNull++;
if (excepts != null)
numNonNull++;
if (numNonNull > 1)
throw new IllegalArgumentException(
"All(): With AllPuzzleType zero or one except or excepts parameter must be non-null.");
switch (allType)
{
case Different:
return new AllDifferent(elementType, region, except, excepts);
default:
break;
}
// We should never reach that except if we forget some codes.
throw new IllegalArgumentException("All(): A AllPuzzleType is not implemented.");
}
//-------------------------------------------------------------------------
private All()
{
// Ensure that compiler does pick up default constructor
}
@Override
public boolean isStatic()
{
// Should never be there
return false;
}
@Override
public long gameFlags(final Game game)
{
// Should never be there
return 0L;
}
@Override
public void preprocess(final Game game)
{
// Nothing to do.
}
@Override
public boolean eval(final Context context)
{
// Should not be called, should only be called on subclasses
throw new UnsupportedOperationException("All.eval(): Should never be called directly.");
// return false;
}
@Override
public String toEnglish(final Game game)
{
return "all of the following is true:";
}
}
| 2,649 | 23.090909 | 92 | java |
Ludii | Ludii-master/Core/src/game/functions/booleans/deductionPuzzle/all/AllDifferent.java | package game.functions.booleans.deductionPuzzle.all;
import java.util.BitSet;
import annotations.Hide;
import annotations.Name;
import annotations.Opt;
import annotations.Or;
import game.Game;
import game.equipment.other.Regions;
import game.functions.booleans.BaseBooleanFunction;
import game.functions.ints.IntFunction;
import game.functions.region.RegionFunction;
import game.types.board.RegionTypeStatic;
import game.types.board.SiteType;
import game.types.state.GameType;
import gnu.trove.list.array.TIntArrayList;
import other.concept.Concept;
import other.context.Context;
import other.state.container.ContainerState;
/**
* Returns true if every item is different in the specific region.
*
* @author Eric.Piette
*
* @remarks This is used for the constraints of a deduction puzzle. This works
* only for deduction puzzles.
*/
@Hide
public class AllDifferent extends BaseBooleanFunction
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/** Which region. */
private final RegionFunction region;
/** Which type of area. */
private final RegionTypeStatic typeRegion;
/** Values to ignore. */
private final IntFunction[] exceptions;
/** Graph element type. */
private final SiteType type;
//-------------------------------------------------------------------------
/**
* @param elementType Type of graph elements to return.
* @param region The region to check [Regions].
* @param except The exception on the test.
* @param excepts The exceptions on the test.
*/
public AllDifferent
(
@Opt final SiteType elementType,
@Opt final RegionFunction region,
@Opt @Name @Or final IntFunction except,
@Opt @Name @Or final IntFunction[] excepts
)
{
this.region = region;
typeRegion = (region == null) ? RegionTypeStatic.Regions : null;
if(region != null)
regionConstraint = region;
else
areaConstraint = typeRegion;
if (excepts != null)
exceptions = excepts;
else if (except != null)
{
exceptions = new IntFunction[1];
exceptions[0] = except;
}
else
exceptions = new IntFunction[0];
type = elementType;
}
//---------------------------------------------------------------------------
@Override
public String toEnglish(final Game game)
{
return "Every item within a region is different";
}
//---------------------------------------------------------------------------
@Override
public boolean eval(final Context context)
{
final SiteType realType = (type == null) ? context.board().defaultSite() : type;
final ContainerState cs = context.state().containerStates()[0];
final TIntArrayList excepts = new TIntArrayList();
for (final IntFunction exception : exceptions)
excepts.add(exception.eval(context));
if (typeRegion == null)
{
final TIntArrayList history = new TIntArrayList();
final int[] sites = region.eval(context).sites();
if (sites.length == 0)
return true;
for (final int site : sites)
{
if (!cs.isResolved(site, realType))
continue;
final int what = cs.what(site, realType);
if (what == 0 && !excepts.contains(what))
return false;
if (!excepts.contains(what))
{
if(history.contains(what))
return false;
history.add(what);
}
}
}
else if (typeRegion.equals(RegionTypeStatic.Regions))
{
final Regions[] regions = context.game().equipment().regions();
for (final Regions rgn : regions)
{
if (rgn.regionTypes() != null)
{
final RegionTypeStatic[] areas = rgn.regionTypes();
for (final RegionTypeStatic area : areas)
{
final Integer[][] regionsList = rgn.convertStaticRegionOnLocs(area, context);
for (final Integer[] locs : regionsList)
{
final TIntArrayList history = new TIntArrayList();
if (area.equals(RegionTypeStatic.AllDirections))
if (cs.what(locs[0].intValue(), realType) == 0)
continue;
for (final Integer loc : locs)
{
if (loc != null)
{
if (!cs.isResolved(loc.intValue(), realType))
continue;
final int what = cs.what(loc.intValue(), realType);
if (what == 0 && !excepts.contains(what))
return false;
if (!excepts.contains(what))
{
if (history.contains(what))
return false;
history.add(what);
}
}
}
}
}
}
else if (rgn.region() != null)
{
final RegionFunction[] regionsFunctions = rgn.region();
for (final RegionFunction regionFunction : regionsFunctions)
{
final int[] locs = regionFunction.eval(context).sites();
final TIntArrayList history = new TIntArrayList();
for (final int loc : locs)
{
if (!cs.isResolved(loc, realType))
continue;
final int what = cs.what(loc, realType);
if (what == 0 && !excepts.contains(what))
return false;
if (!excepts.contains(what))
{
if (history.contains(what))
return false;
history.add(what);
}
}
}
}
else if (rgn.sites() != null)
{
final TIntArrayList history = new TIntArrayList();
for (final int loc : rgn.sites())
{
if (!cs.isResolved(loc, realType))
continue;
final int what = cs.what(loc, realType);
if (what == 0 && !excepts.contains(what))
return false;
if (!excepts.contains(what))
{
if (history.contains(what))
return false;
history.add(what);
}
}
}
}
}
return true;
}
//-------------------------------------------------------------------------
@Override
public String toString()
{
String str = "";
if(region != null)
str += "AllDifferent(" + region + ")";
else
str += "AllDifferent(" + typeRegion.toString() + ")";
return str;
}
@Override
public boolean isStatic()
{
return false;
}
@Override
public long gameFlags(final Game game)
{
long gameFlags = GameType.DeductionPuzzle;
if (region != null)
gameFlags |= region.gameFlags(game);
for (final IntFunction fn : exceptions)
gameFlags |= fn.gameFlags(game);
return gameFlags;
}
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
concepts.or(super.concepts(game));
concepts.set(Concept.DeductionPuzzle.id(), true);
if (region != null)
concepts.or(region.concepts(game));
for (final IntFunction fn : exceptions)
concepts.or(fn.concepts(game));
return concepts;
}
@Override
public BitSet writesEvalContextRecursive()
{
final BitSet writeEvalContext = new BitSet();
writeEvalContext.or(super.writesEvalContextRecursive());
if (region != null)
writeEvalContext.or(region.writesEvalContextRecursive());
for (final IntFunction fn : exceptions)
writeEvalContext.or(fn.writesEvalContextRecursive());
return writeEvalContext;
}
@Override
public BitSet readsEvalContextRecursive()
{
final BitSet readEvalContext = new BitSet();
readEvalContext.or(super.readsEvalContextRecursive());
if (region != null)
readEvalContext.or(region.readsEvalContextRecursive());
for (final IntFunction fn : exceptions)
readEvalContext.or(fn.readsEvalContextRecursive());
return readEvalContext;
}
@Override
public void preprocess(final Game game)
{
if (region != null)
region.preprocess(game);
for(final IntFunction fn : exceptions)
fn.preprocess(game);
}
@Override
public boolean missingRequirement(final Game game)
{
boolean missingRequirement = false;
missingRequirement |= super.missingRequirement(game);
if (region != null)
missingRequirement |= region.missingRequirement(game);
for (final IntFunction fn : exceptions)
missingRequirement |= fn.missingRequirement(game);
return missingRequirement;
}
@Override
public boolean willCrash(final Game game)
{
boolean willCrash = false;
if (game.players().count() != 1)
{
game.addCrashToReport("The ludeme (all Different ...) is used but the number of players is not 1.");
willCrash = true;
}
willCrash |= super.willCrash(game);
if (region != null)
willCrash |= region.willCrash(game);
for (final IntFunction fn : exceptions)
willCrash |= fn.willCrash(game);
return willCrash;
}
//--------------------------------------------------------------------
/**
* @return The region to check.
*/
public RegionFunction region()
{
return region;
}
/**
* @return The static region.
*/
public RegionTypeStatic area()
{
return typeRegion;
}
/**
* The exceptions of the test.
*
* @return The indices of all the exceptions sites.
*/
public IntFunction[] exceptions()
{
return exceptions;
}
}
| 8,849 | 23.515235 | 103 | java |
Ludii | Ludii-master/Core/src/game/functions/booleans/deductionPuzzle/all/AllPuzzleType.java | package game.functions.booleans.deductionPuzzle.all;
/**
* Defines the types of Is test for puzzle according to region.
*/
public enum AllPuzzleType
{
/** To check if every item is different in the specific region. */
Different,
}
| 236 | 20.545455 | 67 | java |
Ludii | Ludii-master/Core/src/game/functions/booleans/deductionPuzzle/all/package-info.java | /**
* All is a `super' puzzle ludeme that returns whether all aspects of a certain query
* about the puzzle state are true, such as whether all values in a region are different.
*/
package game.functions.booleans.deductionPuzzle.all;
| 240 | 39.166667 | 91 | java |
Ludii | Ludii-master/Core/src/game/functions/booleans/deductionPuzzle/is/Is.java | package game.functions.booleans.deductionPuzzle.is;
import annotations.Name;
import annotations.Opt;
import game.Game;
import game.functions.booleans.BaseBooleanFunction;
import game.functions.booleans.BooleanFunction;
import game.functions.booleans.deductionPuzzle.is.graph.IsUnique;
import game.functions.booleans.deductionPuzzle.is.regionResult.IsCount;
import game.functions.booleans.deductionPuzzle.is.regionResult.IsSum;
import game.functions.booleans.deductionPuzzle.is.simple.IsSolved;
import game.functions.ints.IntFunction;
import game.functions.region.RegionFunction;
import game.types.board.SiteType;
import other.context.Context;
/**
* Whether the specified query is true for a deduction puzzle.
*
* @author Eric.Piette and cambolbro
*
*/
@SuppressWarnings("javadoc")
public class Is extends BaseBooleanFunction
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/**
* For solving a puzzle.
*
* @param isType The query type to perform.
*
* @example (is Solved)
*/
public static BooleanFunction construct
(
final IsPuzzleSimpleType isType
)
{
switch (isType)
{
case Solved:
return new IsSolved();
default:
break;
}
// We should never reach that except if we forget some codes.
throw new IllegalArgumentException("Is(): A IsPuzzleSimpleType is not implemented.");
}
//-------------------------------------------------------------------------
/**
* For the unique constraint.
*
* @param isType The query type to perform.
* @param elementType The graph element type [Cell].
*
* @example (is Unique)
*/
public static BooleanFunction construct
(
final IsPuzzleGraphType isType,
@Opt final SiteType elementType
)
{
switch (isType)
{
case Unique:
return new IsUnique(elementType);
default:
break;
}
// We should never reach that except if we forget some codes.
throw new IllegalArgumentException("Is(): A IsPuzzleGraphType is not implemented.");
}
//-------------------------------------------------------------------------
/**
* For a constraint related to count or sum.
*
* @param isType The query type to perform.
* @param type The graph element of the region [Default SiteType of the board].
* @param region The region [Regions].
* @param of The index of the piece [1].
* @param nameRegion The name of the region to check.
* @param result The result to check.
*
* @example (is Count (sites All) of:1 8)
* @example (is Sum 5)
*/
public static BooleanFunction construct
(
final IsPuzzleRegionResultType isType,
@Opt final SiteType type,
@Opt final RegionFunction region,
@Opt @Name final IntFunction of,
@Opt final String nameRegion,
final IntFunction result
)
{
switch (isType)
{
case Count:
return new IsCount(type, region, of, result);
case Sum:
return new IsSum(type, region, nameRegion, result);
default:
break;
}
// We should never reach that except if we forget some codes.
throw new IllegalArgumentException("Is(): A IsPuzzleRegionResultType is not implemented.");
}
//-------------------------------------------------------------------------
private Is()
{
// Ensure that compiler does pick up default constructor
}
@Override
public boolean isStatic()
{
// Should never be there
return false;
}
@Override
public long gameFlags(final Game game)
{
// Should never be there
return 0L;
}
@Override
public void preprocess(final Game game)
{
// Nothing to do.
}
@Override
public boolean eval(Context context)
{
// Should not be called, should only be called on subclasses
throw new UnsupportedOperationException("Is.eval(): Should never be called directly.");
// return false;
}
}
| 3,945 | 24.133758 | 93 | java |
Ludii | Ludii-master/Core/src/game/functions/booleans/deductionPuzzle/is/IsPuzzleGraphType.java | package game.functions.booleans.deductionPuzzle.is;
/**
* Defines the types of Is test for puzzle according to a graph element.
*/
public enum IsPuzzleGraphType
{
/**
* To check if each sub region of a static region is different.
*/
Unique,
}
| 252 | 18.461538 | 72 | java |
Ludii | Ludii-master/Core/src/game/functions/booleans/deductionPuzzle/is/IsPuzzleRegionResultType.java | package game.functions.booleans.deductionPuzzle.is;
/**
* Defines the types of Is test for puzzle according to region and a specific
* result to check.
*/
public enum IsPuzzleRegionResultType
{
/** To check if the count of a region is equal to the result. */
Count,
/** To check if the sum of a region is equal to the result. */
Sum,
}
| 345 | 22.066667 | 77 | java |
Ludii | Ludii-master/Core/src/game/functions/booleans/deductionPuzzle/is/IsPuzzleSimpleType.java | package game.functions.booleans.deductionPuzzle.is;
/**
* Defines the types of Is test for puzzle with no parameter.
*/
public enum IsPuzzleSimpleType
{
/**
* To check if all the variables of a deduction puzzle are set to values
* satisfying all the constraints.
*/
Solved,
}
| 288 | 18.266667 | 73 | java |
Ludii | Ludii-master/Core/src/game/functions/booleans/deductionPuzzle/is/package-info.java | /**
* The {\tt (is ...)} puzzle `super' ludeme returns a true/false result to a given query about
* the puzzle state. The type of query is defined by a parameter specified by the user,
* and typically refer to constraints that the puzzle must satisfy, for example
* whether all values in a region are different, or sum to a certain hint value, etc.
*/
package game.functions.booleans.deductionPuzzle.is;
| 415 | 51 | 95 | java |
Ludii | Ludii-master/Core/src/game/functions/booleans/deductionPuzzle/is/graph/IsUnique.java | package game.functions.booleans.deductionPuzzle.is.graph;
import java.util.BitSet;
import annotations.Hide;
import annotations.Opt;
import game.Game;
import game.equipment.other.Regions;
import game.functions.booleans.BaseBooleanFunction;
import game.types.board.RegionTypeStatic;
import game.types.board.SiteType;
import game.types.state.GameType;
import other.concept.Concept;
import other.context.Context;
import other.state.container.ContainerState;
/**
* Returns true if each sub region of a static region is different.
*
* @author Eric.Piette
*
* @remarks This works only for deduction puzzles.
*/
@Hide
public class IsUnique extends BaseBooleanFunction
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/** Graph element type. */
private final SiteType type;
/**
* @param elementType The graph element type [Cell].
*/
public IsUnique
(
@Opt final SiteType elementType
)
{
areaConstraint = RegionTypeStatic.Regions;
type = (elementType == null) ? SiteType.Cell : elementType;
}
//--------------------------------------------------------------------------
@Override
public boolean eval(Context context)
{
final ContainerState ps = context.state().containerStates()[0];
final Regions[] regions = context.game().equipment().regions();
for (final Regions region : regions)
{
if (region.regionTypes() != null)
{
final RegionTypeStatic[] regionTypes = region.regionTypes();
for (final RegionTypeStatic regionType : regionTypes)
{
final Integer[][] regionsList = region.convertStaticRegionOnLocs(regionType, context);
for (int i = 0; i < regionsList.length; i++)
for (int j = i + 1; j < regionsList.length; j++)
{
final Integer[] set1 = regionsList[i];
final Integer[] set2 = regionsList[j];
if (regionAllAssigned(set1, ps) && regionAllAssigned(set2, ps))
{
boolean identical = true;
for (int index = 0; index < set1.length; index++)
if (ps.what(set1[index].intValue(), type) != ps.what(set2[index].intValue(), type))
{
identical = false;
break;
}
if (identical)
return false;
}
}
}
}
}
return true;
}
/**
* @param region
* @param ps
* @return True if all the vars corresponding to the locs are assigned
*/
public boolean regionAllAssigned(final Integer[] region, final ContainerState ps)
{
for (final Integer loc : region)
if (!ps.isResolved(loc.intValue(), type))
return false;
return true;
}
//-------------------------------------------------------------------------
@Override
public boolean isStatic()
{
return false;
}
@Override
public void preprocess(final Game game)
{
// Do nothing.
}
@Override
public long gameFlags(final Game game)
{
final long gameFlags = GameType.DeductionPuzzle;
return gameFlags;
}
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
concepts.set(Concept.DeductionPuzzle.id(), true);
return concepts;
}
@Override
public BitSet writesEvalContextRecursive()
{
final BitSet writeEvalContext = new BitSet();
return writeEvalContext;
}
@Override
public BitSet readsEvalContextRecursive()
{
final BitSet readEvalContext = new BitSet();
return readEvalContext;
}
@Override
public boolean willCrash(final Game game)
{
boolean willCrash = false;
if (game.players().count() != 1)
{
game.addCrashToReport("The ludeme (is Unique ...) is used but the number of players is not 1.");
willCrash = true;
}
return willCrash;
}
//-------------------------------------------------------------------------
@Override
public String toString()
{
String str = "";
str += "Unique()";
return str;
}
//-------------------------------------------------------------------------
@Override
public String toEnglish(final Game game)
{
return "each sub-region of the board is different";
}
//-------------------------------------------------------------------------
}
| 4,154 | 22.474576 | 99 | java |
Ludii | Ludii-master/Core/src/game/functions/booleans/deductionPuzzle/is/regionResult/IsCount.java | package game.functions.booleans.deductionPuzzle.is.regionResult;
import java.util.BitSet;
import annotations.Hide;
import annotations.Opt;
import game.Game;
import game.functions.booleans.BaseBooleanFunction;
import game.functions.ints.IntConstant;
import game.functions.ints.IntFunction;
import game.functions.region.RegionFunction;
import game.types.board.SiteType;
import game.types.state.GameType;
import main.StringRoutines;
import other.concept.Concept;
import other.context.Context;
import other.state.container.ContainerState;
/**
* Returns true if the count of a region is equal to the result.
*
* @author Eric.Piette
*
* @remarks This works only for deduction puzzles.
*/
@Hide
public class IsCount extends BaseBooleanFunction
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/** Which region. */
private final RegionFunction region;
/** What. */
private final IntFunction whatFn;
/** Which result. */
private final IntFunction resultFn;
/** Which type. */
private final SiteType type;
//-------------------------------------------------------------------------
/**
* @param type The graph element of the region [Default SiteType of the board].
* @param region The region to count.
* @param what The index of the piece to count [1].
* @param result The result to check.
*/
public IsCount
(
@Opt final SiteType type,
@Opt final RegionFunction region,
@Opt final IntFunction what,
final IntFunction result
)
{
this.region = region;
whatFn = (what == null) ? new IntConstant(1) : what;
resultFn = result;
this.type = type;
}
//--------------------------------------------------------------------------
@Override
public boolean eval(Context context)
{
if (region == null)
return false;
final SiteType realType = (type == null) ? context.board().defaultSite() : type;
final ContainerState ps = context.state().containerStates()[0];
final int what = whatFn.eval(context);
final int result = resultFn.eval(context);
final int[] sites = region.eval(context).sites();
boolean assigned = true;
int currentCount = 0;
for (final int site : sites)
{
if (ps.isResolved(site, realType))
{
final int whatSite = ps.what(site, realType);
if (whatSite == what)
currentCount++;
}
else
assigned = false;
}
if ((assigned && currentCount != result) || (currentCount > result))
return false;
return true;
}
//-------------------------------------------------------------------------
@Override
public boolean isStatic()
{
return false;
}
@Override
public void preprocess(final Game game)
{
region.preprocess(game);
whatFn.preprocess(game);
resultFn.preprocess(game);
}
@Override
public long gameFlags(final Game game)
{
long gameFlags = GameType.DeductionPuzzle;
gameFlags |= region.gameFlags(game);
gameFlags |= whatFn.gameFlags(game);
gameFlags |= resultFn.gameFlags(game);
return gameFlags;
}
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
concepts.or(super.concepts(game));
concepts.set(Concept.DeductionPuzzle.id(), true);
concepts.or(region.concepts(game));
concepts.or(whatFn.concepts(game));
concepts.or(resultFn.concepts(game));
return concepts;
}
@Override
public BitSet writesEvalContextRecursive()
{
final BitSet writeEvalContext = new BitSet();
writeEvalContext.or(super.writesEvalContextRecursive());
writeEvalContext.or(region.writesEvalContextRecursive());
writeEvalContext.or(whatFn.writesEvalContextRecursive());
writeEvalContext.or(resultFn.writesEvalContextRecursive());
return writeEvalContext;
}
@Override
public BitSet readsEvalContextRecursive()
{
final BitSet readEvalContext = new BitSet();
readEvalContext.or(super.readsEvalContextRecursive());
readEvalContext.or(region.readsEvalContextRecursive());
readEvalContext.or(whatFn.readsEvalContextRecursive());
readEvalContext.or(resultFn.readsEvalContextRecursive());
return readEvalContext;
}
@Override
public boolean missingRequirement(final Game game)
{
boolean missingRequirement = false;
missingRequirement |= super.missingRequirement(game);
missingRequirement |= region.missingRequirement(game);
missingRequirement |= whatFn.missingRequirement(game);
missingRequirement |= resultFn.missingRequirement(game);
return missingRequirement;
}
@Override
public boolean willCrash(final Game game)
{
boolean willCrash = false;
if (game.players().count() != 1)
{
game.addCrashToReport("The ludeme (is Count ...) is used but the number of players is not 1.");
willCrash = true;
}
willCrash |= super.willCrash(game);
willCrash |= region.willCrash(game);
willCrash |= whatFn.willCrash(game);
willCrash |= resultFn.willCrash(game);
return willCrash;
}
//-------------------------------------------------------------------------
/**
* @return The region to count.
*/
public RegionFunction region()
{
return region;
}
/**
* @return The result to check.
*/
public IntFunction result()
{
return resultFn;
}
/**
* @return The piece to count.
*/
public IntFunction what()
{
return whatFn;
}
//-------------------------------------------------------------------------
@Override
public String toString()
{
String str = "";
str += "Count(" + region + ") = " + resultFn;
return str;
}
//-------------------------------------------------------------------------
@Override
public String toEnglish(final Game game)
{
return "the number of " + whatFn.toEnglish(game) + StringRoutines.getPlural(whatFn.toEnglish(game)) + " in " + region.toEnglish(game) + " equals " + resultFn.toEnglish(game);
}
//-------------------------------------------------------------------------
}
| 5,902 | 23.595833 | 176 | java |
Ludii | Ludii-master/Core/src/game/functions/booleans/deductionPuzzle/is/regionResult/IsSum.java | package game.functions.booleans.deductionPuzzle.is.regionResult;
import java.util.BitSet;
import annotations.Hide;
import annotations.Opt;
import game.Game;
import game.equipment.other.Regions;
import game.functions.booleans.BaseBooleanFunction;
import game.functions.ints.IntFunction;
import game.functions.region.RegionFunction;
import game.types.board.RegionTypeStatic;
import game.types.board.SiteType;
import game.types.state.GameType;
import other.concept.Concept;
import other.context.Context;
import other.context.EvalContextData;
import other.state.container.ContainerState;
/**
* Returns true if the sum of a region is equal to the result.
*
* @author Lianne.Hufkens and Eric.Piette
*
* @remarks This works only for deduction puzzles.
*/
@Hide
public class IsSum extends BaseBooleanFunction
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/** Which region. */
private final RegionFunction region;
/** Which result. */
private final IntFunction resultFn;
/** Graph element type. */
private final SiteType type;
/** The name of the region to check.. */
private final String name;
//-------------------------------------------------------------------------
/**
* @param elementType Type of graph elements to return [Default SiteType of the board].
* @param region The region to sum [Regions].
* @param nameRegion The name of the region to check.
* @param result The result to check.
*/
public IsSum
(
@Opt final SiteType elementType,
@Opt final RegionFunction region,
@Opt final String nameRegion,
final IntFunction result
)
{
this.region = region;
resultFn = result;
if(region != null)
regionConstraint = region;
else
areaConstraint = RegionTypeStatic.Regions;
type = (elementType == null) ? SiteType.Cell : elementType;
name = (nameRegion == null) ? "" : nameRegion;
}
//--------------------------------------------------------------------------
@Override
public boolean eval(final Context context)
{
final ContainerState ps = context.state().containerStates()[0];
if (region != null)
{
final int result = resultFn.eval(context);
final int[] sites = region.eval(context).sites();
boolean allAssigned = true;
int currentSum = 0;
for (final int site : sites)
if (ps.isResolved(site, type))
currentSum += ps.what(site, type);
else
allAssigned = false;
if ((allAssigned && currentSum != result) || (currentSum > result))
return false;
}
else
{
int result = resultFn.eval(context);
final Regions[] regions = context.game().equipment().regions();
Integer[] regionHint;
if (type == SiteType.Cell)
regionHint = context.game().equipment().cellHints();
else if (type == SiteType.Vertex)
regionHint = context.game().equipment().vertexHints();
else
regionHint = context.game().equipment().edgeHints();
for (final Regions reg : regions)
{
if (reg.name().contains(name))
if (reg.regionTypes() != null)
{
final RegionTypeStatic[] areas = reg.regionTypes();
for (final RegionTypeStatic area : areas)
{
final Integer[][] regionsList = reg.convertStaticRegionOnLocs(area, context);
int indexRegion = 0;
for (final Integer[] locs : regionsList)
{
if (resultFn.isHint())
{
context.setHint(regionHint[indexRegion].intValue());
result = resultFn.eval(context);
}
boolean allAssigned = true;
int currentSum = 0;
for (final Integer loc : locs)
{
if (ps.isResolved(loc.intValue(), type))
currentSum += ps.what(loc.intValue(), type);
else
allAssigned = false;
}
if ((allAssigned && currentSum != result) || (currentSum > result))
return false;
indexRegion++;
}
}
}
}
}
return true;
}
//-------------------------------------------------------------------------
@Override
public String toString()
{
String str = "";
str += "Sum(" + region + ") = " + resultFn;
return str;
}
@Override
public boolean isStatic()
{
return false;
}
@Override
public void preprocess(final Game game)
{
resultFn.preprocess(game);
if (region != null)
region.preprocess(game);
}
@Override
public long gameFlags(final Game game)
{
long gameFlags = GameType.DeductionPuzzle;
gameFlags |= resultFn.gameFlags(game);
if (region != null)
gameFlags |= region.gameFlags(game);
return gameFlags;
}
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
concepts.set(Concept.DeductionPuzzle.id(), true);
concepts.or(resultFn.concepts(game));
if (region != null)
concepts.or(region.concepts(game));
return concepts;
}
@Override
public BitSet writesEvalContextRecursive()
{
final BitSet writeEvalContext = writesEvalContextFlat();
writeEvalContext.or(resultFn.writesEvalContextRecursive());
if (region != null)
writeEvalContext.or(region.writesEvalContextRecursive());
return writeEvalContext;
}
@Override
public BitSet writesEvalContextFlat()
{
final BitSet writeEvalContext = new BitSet();
writeEvalContext.set(EvalContextData.Hint.id(), true);
return writeEvalContext;
}
@Override
public BitSet readsEvalContextRecursive()
{
final BitSet readEvalContext = new BitSet();
readEvalContext.or(resultFn.readsEvalContextRecursive());
if (region != null)
readEvalContext.or(region.readsEvalContextRecursive());
return readEvalContext;
}
@Override
public boolean missingRequirement(final Game game)
{
boolean missingRequirement = false;
missingRequirement |= super.missingRequirement(game);
missingRequirement |= resultFn.missingRequirement(game);
if (region != null)
missingRequirement |= region.missingRequirement(game);
return missingRequirement;
}
@Override
public boolean willCrash(final Game game)
{
boolean willCrash = false;
if (game.players().count() != 1)
{
game.addCrashToReport("The ludeme (is Sum ...) is used but the number of players is not 1.");
willCrash = true;
}
willCrash |= super.willCrash(game);
willCrash |= resultFn.willCrash(game);
if (region != null)
willCrash |= region.willCrash(game);
return willCrash;
}
//-------------------------------------------------------------------------
/**
* @return The region to sum.
*/
public RegionFunction region()
{
return region;
}
/**
* @return The result to check.
*/
public IntFunction result()
{
return resultFn;
}
//-------------------------------------------------------------------------
@Override
public String toEnglish(final Game game)
{
String regionName = "the board";
if (name.length() > 0)
regionName = name;
else if (region != null)
regionName = region.toEnglish(game);
return "the sum of " + type.name().toLowerCase() + " in " + regionName + " is equal to " + resultFn.toEnglish(game);
}
//-------------------------------------------------------------------------
}
| 7,181 | 23.680412 | 118 | java |
Ludii | Ludii-master/Core/src/game/functions/booleans/deductionPuzzle/is/simple/IsSolved.java | package game.functions.booleans.deductionPuzzle.is.simple;
import java.util.BitSet;
import annotations.Hide;
import game.Game;
import game.functions.booleans.BaseBooleanFunction;
import game.functions.booleans.BooleanFunction;
import game.rules.play.moves.nonDecision.effect.Satisfy;
import game.types.board.SiteType;
import game.types.state.GameType;
import gnu.trove.list.array.TIntArrayList;
import other.concept.Concept;
import other.context.Context;
import other.context.TempContext;
import other.state.container.ContainerState;
import other.state.puzzle.ContainerDeductionPuzzleState;
/**
* Returns true if all the variables of a deduction puzzle are set to value
* satisfying all the constraints.
*
* @author Eric.Piette
*
* @remarks Works only for the ending condition of a deduction puzzle.
*/
@Hide
public final class IsSolved extends BaseBooleanFunction
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/**
*
*/
public IsSolved()
{
// Nothing to do.
}
@Override
public boolean eval(final Context context)
{
final ContainerState ps = context.state().containerStates()[0];
final TIntArrayList varsConstraints = context.game().constraintVariables();
final BooleanFunction[] constraints = ((Satisfy) context.game().rules().phases()[0].play().moves()).constraints();
final TIntArrayList notAssignedVars = new TIntArrayList();
final SiteType type = context.board().defaultSite();
for (int i = 0; i < varsConstraints.size(); i++)
{
final int var = varsConstraints.getQuick(i);
if (!ps.isResolved(var, type))
notAssignedVars.add(var);
}
// Check constraint
final Context newContext = new TempContext(context);
for (int i = 0; i < notAssignedVars.size(); i++)
((ContainerDeductionPuzzleState) newContext.state().containerStates()[0]).set(notAssignedVars.getQuick(i), 0, type);
boolean constraintOK = true;
if (constraints != null)
for (final BooleanFunction constraint : constraints)
if (!constraint.eval(newContext))
{
constraintOK = false;
break;
}
if (constraintOK)
return true;
else
return false;
}
//-------------------------------------------------------------------------
@Override
public boolean isStatic()
{
return false;
}
@Override
public long gameFlags(final Game game)
{
return GameType.DeductionPuzzle;
}
@Override
public boolean willCrash(final Game game)
{
boolean willCrash = false;
if (game.players().count() != 1)
{
game.addCrashToReport("The ludeme (is Solved) is used but the number of players is not 1.");
willCrash = true;
}
return willCrash;
}
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
concepts.set(Concept.DeductionPuzzle.id(), true);
concepts.set(Concept.CopyContext.id(), true);
concepts.set(Concept.SolvedEnd.id(), true);
return concepts;
}
@Override
public BitSet writesEvalContextRecursive()
{
final BitSet writeEvalContext = new BitSet();
return writeEvalContext;
}
@Override
public BitSet readsEvalContextRecursive()
{
final BitSet readEvalContext = new BitSet();
return readEvalContext;
}
@Override
public void preprocess(final Game game)
{
// Do nothing
}
@Override
public String toEnglish(final Game game)
{
return "the puzzle is solved";
}
}
| 3,408 | 23.35 | 119 | java |
Ludii | Ludii-master/Core/src/game/functions/booleans/is/Is.java | package game.functions.booleans.is;
import annotations.Name;
import annotations.Opt;
import annotations.Or;
import annotations.Or2;
import game.Game;
import game.functions.booleans.BaseBooleanFunction;
import game.functions.booleans.BooleanFunction;
import game.functions.booleans.is.Hidden.IsHidden;
import game.functions.booleans.is.Hidden.IsHiddenCount;
import game.functions.booleans.is.Hidden.IsHiddenRotation;
import game.functions.booleans.is.Hidden.IsHiddenState;
import game.functions.booleans.is.Hidden.IsHiddenValue;
import game.functions.booleans.is.Hidden.IsHiddenWhat;
import game.functions.booleans.is.Hidden.IsHiddenWho;
import game.functions.booleans.is.angle.IsAcute;
import game.functions.booleans.is.angle.IsObtuse;
import game.functions.booleans.is.angle.IsReflex;
import game.functions.booleans.is.angle.IsRight;
import game.functions.booleans.is.component.IsThreatened;
import game.functions.booleans.is.component.IsWithin;
import game.functions.booleans.is.connect.IsBlocked;
import game.functions.booleans.is.connect.IsConnected;
import game.functions.booleans.is.edge.IsCrossing;
import game.functions.booleans.is.graph.IsLastFrom;
import game.functions.booleans.is.graph.IsLastTo;
import game.functions.booleans.is.in.IsIn;
import game.functions.booleans.is.integer.IsAnyDie;
import game.functions.booleans.is.integer.IsEven;
import game.functions.booleans.is.integer.IsFlat;
import game.functions.booleans.is.integer.IsOdd;
import game.functions.booleans.is.integer.IsPipsMatch;
import game.functions.booleans.is.integer.IsSidesMatch;
import game.functions.booleans.is.integer.IsVisited;
import game.functions.booleans.is.line.IsLine;
import game.functions.booleans.is.loop.IsLoop;
import game.functions.booleans.is.path.IsPath;
import game.functions.booleans.is.pattern.IsPattern;
import game.functions.booleans.is.player.IsActive;
import game.functions.booleans.is.player.IsEnemy;
import game.functions.booleans.is.player.IsFriend;
import game.functions.booleans.is.player.IsMover;
import game.functions.booleans.is.player.IsNext;
import game.functions.booleans.is.player.IsPrev;
import game.functions.booleans.is.regularGraph.IsRegularGraph;
import game.functions.booleans.is.related.IsRelated;
import game.functions.booleans.is.repeat.IsRepeat;
import game.functions.booleans.is.simple.IsCycle;
import game.functions.booleans.is.simple.IsFull;
import game.functions.booleans.is.simple.IsPending;
import game.functions.booleans.is.site.IsEmpty;
import game.functions.booleans.is.site.IsOccupied;
import game.functions.booleans.is.string.IsDecided;
import game.functions.booleans.is.string.IsProposed;
import game.functions.booleans.is.target.IsTarget;
import game.functions.booleans.is.tree.IsCaterpillarTree;
import game.functions.booleans.is.tree.IsSpanningTree;
import game.functions.booleans.is.tree.IsTree;
import game.functions.booleans.is.tree.IsTreeCentre;
import game.functions.booleans.is.triggered.IsTriggered;
import game.functions.intArray.IntArrayFunction;
import game.functions.ints.IntFunction;
import game.functions.range.RangeFunction;
import game.functions.region.RegionFunction;
import game.rules.play.moves.Moves;
import game.types.board.HiddenData;
import game.types.board.RegionTypeStatic;
import game.types.board.RelationType;
import game.types.board.SiteType;
import game.types.board.StepType;
import game.types.play.RepetitionType;
import game.types.play.RoleType;
import game.util.directions.AbsoluteDirection;
import game.util.directions.Direction;
import game.util.moves.Player;
import other.IntArrayFromRegion;
import other.context.Context;
/**
* Returns whether the specified query about the game state is true or not.
*
* @author Eric.Piette and cambolbro
*/
@SuppressWarnings("javadoc")
public class Is extends BaseBooleanFunction
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/**
* For checking angles between sites.
*
* @param isType The type of query to perform.
* @param type The graph element type [default of the board].
* @param at The site to look the angle.
* @param conditionSite The condition on the left site.
* @param conditionSite2 The condition on the right site.
*
* @example (is Acute at:(last To) (is Enemy (who at:(site))) (is Enemy (who at:(site))))
*/
public static BooleanFunction construct
(
final IsAngleType isType,
@Opt final SiteType type,
@Name final IntFunction at,
final BooleanFunction conditionSite,
final BooleanFunction conditionSite2
)
{
switch (isType)
{
case Acute:
return new IsAcute(type, at, conditionSite, conditionSite2);
case Obtuse:
return new IsObtuse(type, at, conditionSite, conditionSite2);
case Reflex:
return new IsReflex(type, at, conditionSite, conditionSite2);
case Right:
return new IsRight(type, at, conditionSite, conditionSite2);
default:
break;
}
// We should never reach that except if we forget some codes.
throw new IllegalArgumentException("Is(): An IsAngleType is not implemented.");
}
//-------------------------------------------------------------------------
/**
* For checking hidden information at a location for a specific player.
*
* @param isType The type of query to perform.
* @param dataType The type of hidden data [Invisible].
* @param type The graph element type [default of the board].
* @param at The site to set the hidden information.
* @param level The level to set the hidden information [0].
* @param to The player with these hidden information.
* @param To The roleType with these hidden information.
*
* @example (is Hidden at:(to) to:Mover)
*/
public static BooleanFunction construct
(
final IsHiddenType isType,
@Opt final HiddenData dataType,
@Opt final SiteType type,
@Name final IntFunction at,
@Name @Opt final IntFunction level,
@Name @Or final Player to,
@Name @Or final RoleType To
)
{
int numNonNull = 0;
if (to != null)
numNonNull++;
if (To != null)
numNonNull++;
if (numNonNull != 1)
throw new IllegalArgumentException("Set(): With IsHiddenType one to or To parameter must be non-null.");
switch (isType)
{
case Hidden:
if (dataType == null)
return new IsHidden(type, at, level, to, To);
else
{
switch (dataType)
{
case What:
return new IsHiddenWhat(type, at, level, to, To);
case Who:
return new IsHiddenWho(type, at, level, to, To);
case Count:
return new IsHiddenCount(type, at, level, to, To);
case State:
return new IsHiddenState(type, at, level, to, To);
case Rotation:
return new IsHiddenRotation(type, at, level, to, To);
case Value:
return new IsHiddenValue(type, at, level, to, To);
}
}
}
// We should never reach that except if we forget some codes.
throw new IllegalArgumentException("Is(): An IsHiddenType is not implemented.");
}
//-------------------------------------------------------------------------
/**
* For detecting a specific pattern from a site.
*
* @param isType The type of query to perform.
* @param repetitionType The type of repetition [Positional].
*
* @example (is Repeat Positional)
*/
public static BooleanFunction construct
(
final IsRepeatType isType,
@Opt final RepetitionType repetitionType
)
{
switch (isType)
{
case Repeat:
return new IsRepeat(repetitionType);
default:
break;
}
// We should never reach that except if we forget some codes.
throw new IllegalArgumentException("Is(): An IsRepeatType is not implemented.");
}
//-------------------------------------------------------------------------
/**
* For detecting a specific pattern from a site.
*
* @param isType The type of query to perform.
* @param walk The walk describing the pattern.
* @param type The type of the site from to detect the pattern.
* @param from The site from to detect the pattern [(last To)].
* @param what The piece to check in the pattern [piece in from].
* @param whats The sequence of pieces to check in the pattern [piece in from].
*
* @example (is Pattern {F R F R F})
*/
public static BooleanFunction construct
(
final IsPatternType isType,
final StepType[] walk,
@Opt final SiteType type,
@Opt @Name final IntFunction from,
@Or @Opt @Name final IntFunction what,
@Or @Opt @Name final IntFunction[] whats
)
{
int numNonNull = 0;
if (what != null)
numNonNull++;
if (whats != null)
numNonNull++;
if (numNonNull > 1)
throw new IllegalArgumentException("Only one parameter between what and whats can be non-null.");
switch (isType)
{
case Pattern:
return new IsPattern(walk, type, from, what, whats);
default:
break;
}
// We should never reach that except if we forget some codes.
throw new IllegalArgumentException("Is(): An IsPatternType is not implemented.");
}
//-------------------------------------------------------------------------
/**
* For testing a tree.
*
* @param isType The type of query to perform.
* @param who Data about the owner of the tree.
* @param role RoleType of the owner of the tree.
*
* @example (is Tree Mover)
* @example (is SpanningTree Mover)
* @example (is CaterpillarTree Mover)
* @example (is TreeCentre Mover)
*/
public static BooleanFunction construct
(
final IsTreeType isType,
@Or final Player who,
@Or final RoleType role
)
{
switch (isType)
{
case Tree:
return new IsTree(who, role);
case SpanningTree:
return new IsSpanningTree(who, role);
case CaterpillarTree:
return new IsCaterpillarTree(who, role);
case TreeCentre:
return new IsTreeCentre(who, role);
default:
break;
}
// We should never reach that except if we forget some codes.
throw new IllegalArgumentException("Is(): A IsTreeType is not implemented.");
}
//-------------------------------------------------------------------------
/**
* For testing if a graph is regular.
*
* @param isType The type of query to perform.
* @param who The owner of the tree.
* @param role RoleType of the owner of the tree.
* @param k The parameter of k-regular graph.
* @param odd Flag to recognise the k (in k-regular graph) is odd or not.
* @param even Flag to recognise the k (in k-regular graph) is even or not.
*
* @example (is RegularGraph Mover)
*/
public static BooleanFunction construct
(
final IsRegularGraphType isType,
@Or final Player who,
@Or final RoleType role,
@Opt @Or2 @Name final IntFunction k,
@Opt @Or2 @Name final BooleanFunction odd,
@Opt @Or2 @Name final BooleanFunction even
)
{
int numNonNull1 = 0;
if (who != null)
numNonNull1++;
if (role != null)
numNonNull1++;
if (numNonNull1 != 1)
throw new IllegalArgumentException(
"Is(): with IsRegularGraphType one of who or role has to be non-null.");
numNonNull1 = 0;
if (k != null)
numNonNull1++;
if (odd != null)
numNonNull1++;
if (even != null)
numNonNull1++;
if (numNonNull1 > 1)
throw new IllegalArgumentException(
"Is(): with IsRegularGraphType only one of k, odd, even has to be non-null.");
switch (isType)
{
case RegularGraph:
return new IsRegularGraph(who, role, k, odd, even);
default:
break;
}
// We should never reach that except if we forget some codes.
throw new IllegalArgumentException("Is(): A IsRegularGraphType is not implemented.");
}
//-------------------------------------------------------------------------
/**
* For test relative to player.
*
* @param isType The type of query to perform.
* @param index Index of the player or the component.
* @param role The Role type corresponding to the index.
*
* @example (is Enemy (who at:(last To)))
* @example (is Prev Mover)
*/
public static BooleanFunction construct
(
final IsPlayerType isType,
@Or final IntFunction index,
@Or final RoleType role
)
{
int numNonNull = 0;
if (index != null)
numNonNull++;
if (role != null)
numNonNull++;
if (numNonNull != 1)
throw new IllegalArgumentException(
"Is(): with IsPlayerType only one of index, role has to be non-null.");
switch (isType)
{
case Enemy:
return new IsEnemy(index, role);
case Friend:
return new IsFriend(index, role);
case Mover:
return new IsMover(index, role);
case Next:
return new IsNext(index, role);
case Prev:
return new IsPrev(index, role);
case Active:
return new IsActive(index, role);
default:
break;
}
// We should never reach that except if we forget some codes.
throw new IllegalArgumentException("Is(): A IsPlayerType is not implemented.");
}
//-------------------------------------------------------------------------
/**
* For a triggered test.
*
* @param isType The type of query to perform.
* @param event The event triggered.
* @param index Index of the player or the component.
* @param role The Role type corresponding to the index.
*
* @example (is Triggered "Lost" Next)
*/
public static BooleanFunction construct
(
final IsTriggeredType isType,
final String event,
@Or final IntFunction index,
@Or final RoleType role
)
{
int numNonNull = 0;
if (index != null)
numNonNull++;
if (role != null)
numNonNull++;
if (numNonNull != 1)
throw new IllegalArgumentException(
"Is(): with IsTriggeredType only one of index, role has to be non-null.");
switch (isType)
{
case Triggered:
return new IsTriggered(event,index, role);
default:
break;
}
// We should never reach that except if we forget some codes.
throw new IllegalArgumentException("Is(): A IsTriggeredType is not implemented.");
}
//-------------------------------------------------------------------------
/**
* For a test with no parameter.
*
* @param isType The type of query to perform.
*
* @example (is Cycle)
* @example (is Full)
*/
public static BooleanFunction construct
(
final IsSimpleType isType
)
{
switch (isType)
{
case Cycle:
return new IsCycle();
case Pending:
return new IsPending();
case Full:
return new IsFull();
default:
break;
}
// We should never reach that except if we forget some codes.
throw new IllegalArgumentException("Is(): A IsSimpleType is not implemented.");
}
//-------------------------------------------------------------------------
/**
* For testing two edges crossing each other.
*
* @param isType The type of query to perform.
* @param edge1 The index of the first edge.
* @param edge2 The index of the second edge.
*
* @example (is Crossing (last To) (to))
*/
public static BooleanFunction construct
(
final IsEdgeType isType,
final IntFunction edge1,
final IntFunction edge2
)
{
switch (isType)
{
case Crossing:
return new IsCrossing(edge1,edge2);
default:
break;
}
// We should never reach that except if we forget some codes.
throw new IllegalArgumentException("Is(): A IsEdgeType is not implemented.");
}
//-------------------------------------------------------------------------
/**
* For test relative to a string.
*
* @param isType The type of query to perform.
* @param string The string to check.
*
* @example (is Decided "End")
* @example (is Proposed "End")
*/
public static BooleanFunction construct
(
final IsStringType isType,
final String string
)
{
switch (isType)
{
case Decided:
return new IsDecided(string);
case Proposed:
return new IsProposed(string);
default:
break;
}
// We should never reach that except if we forget some codes.
throw new IllegalArgumentException("Is(): A IsStringType is not implemented.");
}
//-------------------------------------------------------------------------
/**
* For test relative to a graph element type.
*
* @param isType The type of query to perform.
* @param type The graph element type [default SiteType of the board].
*
* @example (is LastFrom Vertex)
*/
public static BooleanFunction construct
(
final IsGraphType isType,
final SiteType type
)
{
switch (isType)
{
case LastFrom:
return new IsLastFrom(type);
case LastTo:
return new IsLastTo(type);
default:
break;
}
// We should never reach that except if we forget some codes.
throw new IllegalArgumentException("Is(): A IsGraphType is not implemented.");
}
//-------------------------------------------------------------------------
/**
* For test about a single integer.
*
* @param isType The type of query to perform.
* @param value The value.
*
* @example (is Even (last To))
* @example (is Visited (last To))
*/
public static BooleanFunction construct
(
final IsIntegerType isType,
@Opt final IntFunction value
)
{
switch (isType)
{
case Even:
return new IsEven(value);
case Odd:
return new IsOdd(value);
case Flat:
return new IsFlat(value);
case PipsMatch:
return new IsPipsMatch(value);
case SidesMatch:
return new IsSidesMatch(value);
case Visited:
return new IsVisited(value);
case AnyDie:
return new IsAnyDie(value);
default:
break;
}
// We should never reach that except if we forget some codes.
throw new IllegalArgumentException("Is(): A IsValueType is not implemented.");
}
//-------------------------------------------------------------------------
/**
* For tests relative to a component.
*
* @param isType The type of query to perform.
* @param what The piece possibly under threat.
* @param type The graph element type [default SiteType of the board].
* @param at The location of the piece to check.
* @param in The locations of the piece to check.
* @param specificMoves The specific moves used to threat.
*
*
* @example (is Threatened (id "King" Mover) at:(to))
*/
public static BooleanFunction construct
(
final IsComponentType isType,
@Opt final IntFunction what,
@Opt final SiteType type,
@Opt @Or @Name final IntFunction at,
@Opt @Or @Name final RegionFunction in,
@Opt final Moves specificMoves
)
{
int numNonNull = 0;
if (at != null)
numNonNull++;
if (in != null)
numNonNull++;
if (numNonNull > 1)
throw new IllegalArgumentException(
"Is(): With IsComponentType only one 'site' or 'sites' parameter must be non-null.");
switch (isType)
{
case Threatened:
return new IsThreatened(what, type, at, in, specificMoves);
case Within:
return new IsWithin(what, type, at, in);
default:
break;
}
// We should never reach that except if we forget some codes.
throw new IllegalArgumentException("Is(): A IsComponentType is not implemented.");
}
//-------------------------------------------------------------------------
/**
* For testing the relation between two sites.
*
* @param isType The type of query to perform.
* @param relationType The type of relation to check between the graph elements.
* @param type The graph element type [default SiteType of the board].
* @param siteA The first site.
* @param siteB The second site.
* @param region The region of the second site.
*
* @example (is Related Adjacent (from) (sites Occupied by:Next))
*/
public static BooleanFunction construct
(
final IsRelationType isType,
final RelationType relationType,
@Opt final SiteType type,
final IntFunction siteA,
@Or final IntFunction siteB,
@Or final RegionFunction region
)
{
int numNonNull = 0;
if (siteB != null)
numNonNull++;
if (region != null)
numNonNull++;
if (numNonNull != 1)
throw new IllegalArgumentException(
"Is(): With IsRelationType only one siteB or region parameter can be non-null.");
switch (isType)
{
case Related:
return new IsRelated(relationType, type, siteA, new IntArrayFromRegion(siteB, region));
default:
break;
}
// We should never reach that except if we forget some codes.
throw new IllegalArgumentException("Is(): A IsRelationType is not implemented.");
}
//-------------------------------------------------------------------------
/**
* For testing a region.
*
* @param isType The type of query to perform.
* @param containerIdFn The index of the container [0].
* @param containerName The name of the container ["Board"].
* @param configuration The configuration defined by the indices of each piece.
* @param specificSite The specific site of the configuration.
* @param specificSites The specific sites of the configuration.
*
* @example (is Target {2 2 2 2 0 0 1 1 1 1})
*/
public static BooleanFunction construct
(
final IsTargetType isType,
@Opt @Or final IntFunction containerIdFn,
@Opt @Or final String containerName,
final Integer[] configuration,
@Opt @Or final Integer specificSite,
@Opt @Or final Integer[] specificSites
)
{
int numNonNull = 0;
if (containerIdFn != null)
numNonNull++;
if (containerName != null)
numNonNull++;
if (numNonNull > 1)
throw new IllegalArgumentException(
"Is(): with IsTargetType zero or one containerId or containerName parameter must be non-null.");
int numNonNullA = 0;
if (specificSite != null)
numNonNullA++;
if (specificSites != null)
numNonNullA++;
if (numNonNullA > 1)
throw new IllegalArgumentException(
"Is(): with IsTargetType zero or one specificSite or specificSites parameter must be non-null.");
switch (isType)
{
case Target:
return new IsTarget(containerIdFn, containerName, configuration, specificSite, specificSites);
default:
break;
}
// We should never reach that except if we forget some codes.
throw new IllegalArgumentException("Is(): A IsTargetType is not implemented.");
}
//-------------------------------------------------------------------------
/**
* For test relative to a connection.
*
* @param isType The type of query to perform.
* @param number The minimum number of regions to connect [All of them].
* @param type The graph element type [default SiteType of the board].
* @param at The specific starting position need to connect.
* @param directions The directions of the connected pieces used to connect the
* region [Adjacent].
* @param regions The disjointed regions set, which need to use for
* connection.
* @param role The role of the player.
* @param regionType Type of the regions to connect.
*
* @example (is Blocked Mover)
* @example (is Connected Mover)
* @example (is Connected { (sites Side S) (sites Side NW) (sites Side NE)})
*/
public static BooleanFunction construct
(
final IsConnectType isType,
@Opt final IntFunction number,
@Opt final SiteType type,
@Opt @Name final IntFunction at,
@Opt final Direction directions,
@Or final RegionFunction[] regions,
@Or final RoleType role,
@Or final RegionTypeStatic regionType
)
{
int numNonNull = 0;
if (regions != null)
numNonNull++;
if (role != null)
numNonNull++;
if (regionType != null)
numNonNull++;
if (numNonNull != 1)
throw new IllegalArgumentException(
"Is(): wtih IsConnectType Exactly one regions, role or regionType parameter must be non-null.");
switch (isType)
{
case Blocked:
return new IsBlocked(type, number, directions, regions, role, regionType);
case Connected:
return new IsConnected(number, type, at, directions, regions, role, regionType);
default:
break;
}
// We should never reach that except if we forget some codes.
throw new IllegalArgumentException("Is(): A IsConnectType is not implemented.");
}
//-------------------------------------------------------------------------
/**
* For test relative to a line.
*
* @param isType The type of query to perform.
* @param type The graph element type [default SiteType of the board].
* @param length Minimum length of lines.
* @param dirn Direction category to which potential lines must belong
* [Adjacent].
* @param through Location through which the line must pass.
* @param throughAny The line must pass through at least one of these sites.
* @param who The owner of the pieces making a line [Mover].
* @param what The index of the component composing the line [(mover)].
* @param whats The indices of the components composing the line.
* @param exact If true, then lines cannot exceed minimum length [False].
* @param contiguous If true, the line has to be contiguous [True].
* @param If The condition on each site on the line [True].
* @param byLevel If true, then lines are detected in using the level in a
* stack [False].
* @param top If true, then lines are detected in using only the top level
* in a stack [False].
*
* @example (is Line 3)
* @example (is Line 5 Orthogonal if:(not (is In (to) (sites Mover))))
*/
public static BooleanFunction construct
(
final IsLineType isType,
@Opt final SiteType type,
final IntFunction length,
@Opt final AbsoluteDirection dirn,
@Or2 @Opt @Name final IntFunction through,
@Or2 @Opt @Name final RegionFunction throughAny,
@Or @Opt final RoleType who,
@Or @Opt @Name final IntFunction what,
@Or @Opt @Name final IntFunction[] whats,
@Opt @Name final BooleanFunction exact,
@Opt @Name final BooleanFunction contiguous,
@Opt @Name final BooleanFunction If,
@Opt @Name final BooleanFunction byLevel,
@Opt @Name final BooleanFunction top
)
{
int numNonNull = 0;
if (what != null)
numNonNull++;
if (whats != null)
numNonNull++;
if (who != null)
numNonNull++;
if (numNonNull > 1)
throw new IllegalArgumentException(
"Is(): With IsLineType zero or one what, whats or who parameter can be non-null.");
int numNonNull2 = 0;
if (through != null)
numNonNull2++;
if (throughAny != null)
numNonNull2++;
if (numNonNull2 > 1)
throw new IllegalArgumentException(
"Is(): With IsLineType zero or one through or throughAny parameter can be non-null.");
switch (isType)
{
case Line:
return new IsLine(type, length, dirn, through, throughAny, who, what, whats, exact, contiguous, If, byLevel, top);
default:
break;
}
// We should never reach that except if we forget some codes.
throw new IllegalArgumentException("Is(): A IsLineType is not implemented.");
}
//-------------------------------------------------------------------------
/**
* For test relative to a loop.
*
* @param isType The type of query to perform.
* @param type The graph element type [default SiteType of the board].
* @param surround Used to define the inside condition of the loop.
* @param surroundList The list of items inside the loop.
* @param directions The direction of the connection [Adjacent].
* @param colour The owner of the looping pieces [Mover].
* @param start The starting point of the loop [(last To)].
* @param regionStart The region to start to detect the loop.
* @param path Whether to detect loops in the paths of pieces (e.g.
* Trax).
*
* @example (is Loop)
* @example (is Loop (mover) path:True)
*/
public static BooleanFunction construct
(
final IsLoopType isType,
@Opt final SiteType type,
@Or @Opt @Name final RoleType surround,
@Or @Opt final RoleType[] surroundList,
@Opt final Direction directions,
@Opt final IntFunction colour,
@Or2 @Opt final IntFunction start,
@Or2 @Opt final RegionFunction regionStart,
@Opt @Name final Boolean path
)
{
int numNonNull = 0;
if (surround != null)
numNonNull++;
if (surroundList != null)
numNonNull++;
if (numNonNull > 1)
throw new IllegalArgumentException(
"Is(): With IsLoopType zero or one surround or surroundList parameter can be non-null.");
int numNonNull2 = 0;
if (start != null)
numNonNull2++;
if (regionStart != null)
numNonNull2++;
if (numNonNull2 > 1)
throw new IllegalArgumentException(
"Is(): With IsLoopType zero or one start or regionStart parameter can be non-null.");
switch (isType)
{
case Loop:
return new IsLoop(type, surround, surroundList, directions, colour, start, regionStart, path);
default:
break;
}
// We should never reach that except if we forget some codes.
throw new IllegalArgumentException("Is(): A IsLoopType is not implemented.");
}
//-------------------------------------------------------------------------
/**
* For test relative a path.
*
* @param isType The type of query to perform.
* @param type The graph element type [default SiteType of the board].
* @param from The site to look the path [(last To)].
* @param who The owner of the pieces on the path.
* @param role The role of the player owning the pieces on the path.
* @param length The range size of the path.
* @param closed Is used to detect closed components [False].
*
* @example (is Path Edge Mover length:(exact 4))
*/
public static BooleanFunction construct
(
final IsPathType isType,
final SiteType type,
@Opt @Name final IntFunction from,
@Or final game.util.moves.Player who,
@Or final RoleType role,
@Name final RangeFunction length,
@Opt @Name final BooleanFunction closed
)
{
int numNonNull = 0;
if (who != null)
numNonNull++;
if (role != null)
numNonNull++;
if (numNonNull != 1)
throw new IllegalArgumentException(
"Is(): With IsPathType Only one who or role parameter must be non-null.");
switch (isType)
{
case Path:
return new IsPath(type, from, who, role, length, closed);
default:
break;
}
// We should never reach that except if we forget some codes.
throw new IllegalArgumentException("Is(): A IsPathType is not implemented.");
}
//-------------------------------------------------------------------------
/**
* For test relative to an empty or occupied site.
*
* @param isType The type of query to perform.
* @param type Graph element type [default SiteType of the board].
* @param at The index of the site.
*
* @example (is Empty (to))
* @example (is Occupied Vertex (to))
*/
public static BooleanFunction construct
(
final IsSiteType isType,
@Opt final SiteType type,
final IntFunction at
)
{
switch (isType)
{
case Empty:
return new IsEmpty(type, at);
case Occupied:
return new IsOccupied(type, at);
default:
break;
}
// We should never reach that except if we forget some codes.
throw new IllegalArgumentException("Is(): A IsSiteType is not implemented.");
}
//-------------------------------------------------------------------------
/**
* For testing if a site is in a region or if an integer is in an array of
* integers.
*
* @param isType The type of query to perform.
* @param site The site [(to)].
* @param sites The sites.
* @param region The region.
* @param array The array of integers.
*
* @example (is In {(last To) (last From)} (sites Mover))
* @example (is In (last To) (sites Mover))
*/
public static BooleanFunction construct
(
final IsInType isType,
@Opt @Or final IntFunction site,
@Opt @Or final IntFunction[] sites,
@Or2 final RegionFunction region,
@Or2 final IntArrayFunction array
)
{
int numNonNull = 0;
if (site != null)
numNonNull++;
if (sites != null)
numNonNull++;
if (numNonNull > 1)
throw new IllegalArgumentException(
"Is(): With IsInType Only one site or sites parameter can be non-null.");
int numNonNull2 = 0;
if (region != null)
numNonNull2++;
if (array != null)
numNonNull2++;
if (numNonNull2 != 1)
throw new IllegalArgumentException(
"Is(): With IsInType one region or array parameter must be non-null.");
switch (isType)
{
case In:
return IsIn.construct(site, sites, region, array);
default:
break;
}
// We should never reach that except if we forget some codes.
throw new IllegalArgumentException("Is(): A IsInType is not implemented.");
}
//-------------------------------------------------------------------------
private Is()
{
// Ensure that compiler does not pick up default constructor
}
//-------------------------------------------------------------------------
@Override
public boolean isStatic()
{
// Should never be there
return false;
}
@Override
public long gameFlags(final Game game)
{
// Should never be there
return 0L;
}
@Override
public void preprocess(final Game game)
{
// Nothing to do.
}
@Override
public boolean eval(Context context)
{
// Should not be called, should only be called on subclasses
throw new UnsupportedOperationException("Is.eval(): Should never be called directly.");
// return false;
}
}
| 34,098 | 28.702962 | 117 | java |
Ludii | Ludii-master/Core/src/game/functions/booleans/is/IsAngleType.java | package game.functions.booleans.is;
/**
* Defines the types of Is for a connected or blocked test.
*
* @author Eric.Piette
*/
public enum IsAngleType
{
/** To check if a site and two other sites checking conditions form an acute angle (< 90 degrees). */
Acute,
/** To check if a site and two other sites checking conditions form a right angle (= 90 degrees). */
Right,
/** To check if a site and two other sites checking conditions form an obtuse angle (> 90 degrees). */
Obtuse,
/** To check if a site and two other sites checking conditions form a reflex angle (> 180 degrees). */
Reflex
}
| 609 | 26.727273 | 103 | java |
Ludii | Ludii-master/Core/src/game/functions/booleans/is/IsComponentType.java | package game.functions.booleans.is;
/**
* Defines the types of Is test according to a component and a site/region.
*
* @author Eric.Piette
*/
public enum IsComponentType
{
/** To check if a location is under threat. */
Threatened,
/** To check if a specific piece is on the designed region. */
Within,
}
| 315 | 18.75 | 75 | java |
Ludii | Ludii-master/Core/src/game/functions/booleans/is/IsConnectType.java | package game.functions.booleans.is;
/**
* Defines the types of Is for a connected or blocked test.
*
* @author Eric.Piette
*/
public enum IsConnectType
{
/** To check if regions are connected by pieces owned by a player. */
Connected,
/** To check if a player can not connect regions with his pieces. */
Blocked,
}
| 326 | 19.4375 | 70 | java |
Ludii | Ludii-master/Core/src/game/functions/booleans/is/IsEdgeType.java | package game.functions.booleans.is;
/**
* Defines the types of Is for two edges.
*
* @author Eric.Piette
*/
public enum IsEdgeType
{
/** To check if two edges are crossing each other. */
Crossing,
}
| 207 | 15 | 54 | java |
Ludii | Ludii-master/Core/src/game/functions/booleans/is/IsGraphType.java | package game.functions.booleans.is;
/**
* Defines the types of Is test according to a graph element.
*
* @author Eric.Piette
*/
public enum IsGraphType
{
/** Check the graph element type of the ``from'' location of the last move. */
LastFrom,
/** Check the graph element type of the ``to'' location of the last move. */
LastTo,
}
| 341 | 20.375 | 79 | java |
Ludii | Ludii-master/Core/src/game/functions/booleans/is/IsHiddenType.java | package game.functions.booleans.is;
/**
* Defines the types of Is test according to hidden information.
*
* @author Eric.Piette
*/
public enum IsHiddenType
{
/** To check if a specific site is hidden to a specific player. */
Hidden,
}
| 243 | 17.769231 | 67 | java |
Ludii | Ludii-master/Core/src/game/functions/booleans/is/IsInType.java | package game.functions.booleans.is;
/**
* Defines the types of Is test according for the In test.
*
* @author Eric.Piette
*/
public enum IsInType
{
/** To check if a specific location is in a region. */
In,
}
| 217 | 15.769231 | 58 | java |
Ludii | Ludii-master/Core/src/game/functions/booleans/is/IsIntegerType.java | package game.functions.booleans.is;
/**
* Defines the types of Is test according to an integer.
*
* @author Eric.Piette
*/
public enum IsIntegerType
{
/** To check if a value is odd. */
Odd,
/** To check if a value is even. */
Even,
/** To check if a site was already visited by a piece in the same turn. */
Visited,
/** To detect whether the terminus of a tile matches with its neighbors. */
SidesMatch,
/** To detect whether the pips of a domino match its neighbours. */
PipsMatch,
/**
* To Ensures that in a 3D board, all the pieces in the bottom layer must be
* placed so that they do not fall.
*/
Flat,
/**
* To check if any current die is equal to a specific value.
*/
AnyDie,
}
| 721 | 19.055556 | 77 | java |
Ludii | Ludii-master/Core/src/game/functions/booleans/is/IsLineType.java | package game.functions.booleans.is;
/**
* Defines the types of Is for the detection of a line.
*
* @author Eric.Piette
*/
public enum IsLineType
{
/** To check whether a succession of sites are occupied by a specified piece. */
Line,
}
| 244 | 17.846154 | 81 | java |
Ludii | Ludii-master/Core/src/game/functions/booleans/is/IsLoopType.java | package game.functions.booleans.is;
/**
* Defines the types of Is for the detection of a loop.
*
* @author Eric.Piette
*/
public enum IsLoopType
{
/** To detect a loop. */
Loop,
}
| 188 | 13.538462 | 55 | java |
Ludii | Ludii-master/Core/src/game/functions/booleans/is/IsPathType.java | package game.functions.booleans.is;
/**
* Defines the types of Is for the detection of a path.
*
* @author Eric.Piette
*/
public enum IsPathType
{
/** To detect a cycle or path with specific size. */
Path,
}
| 216 | 15.692308 | 55 | java |
Ludii | Ludii-master/Core/src/game/functions/booleans/is/IsPatternType.java | package game.functions.booleans.is;
/**
* Defines the types of Is for the detection of a pattern.
*
* @author Eric.Piette
*/
public enum IsPatternType
{
/** To detect a pattern from a site. */
Pattern,
}
| 212 | 15.384615 | 58 | java |
Ludii | Ludii-master/Core/src/game/functions/booleans/is/IsPlayerType.java | package game.functions.booleans.is;
/**
* Defines the types of Is test for a player.
*
* @author Eric.Piette
*/
public enum IsPlayerType
{
/** To check if a player is the mover. */
Mover,
/** To check if a player is the next mover. */
Next,
/** To check if a player is the previous mover. */
Prev,
/** To check if a player is the friend of the mover. */
Friend,
/** To check if a player is the enemy of the mover. */
Enemy,
/** To check if a player is active. */
Active
}
| 495 | 16.714286 | 56 | java |
Ludii | Ludii-master/Core/src/game/functions/booleans/is/IsRegularGraphType.java | package game.functions.booleans.is;
/**
* Defines the types of Is test for a regular graph.
*
* @author Eric.Piette
*/
public enum IsRegularGraphType
{
/** To check the graph is regular. */
RegularGraph,
}
| 214 | 15.538462 | 52 | java |
Ludii | Ludii-master/Core/src/game/functions/booleans/is/IsRelationType.java | package game.functions.booleans.is;
/**
* Defines the types of Is test according to a relation.
*
* @author Eric.Piette
*/
public enum IsRelationType
{
/**
* To check if two sites are related by a specific relation. Can also check if a
* site is related by a specific relation with at least one site of a region.
*/
Related,
}
| 341 | 20.375 | 81 | java |
Ludii | Ludii-master/Core/src/game/functions/booleans/is/IsRepeatType.java | package game.functions.booleans.is;
/**
* Defines the types of Is test according to a repetition.
*
* @author Eric.Piette
*/
public enum IsRepeatType
{
/**
* To check if a site was already encounter previously.
*/
Repeat,
}
| 236 | 14.8 | 58 | java |
Ludii | Ludii-master/Core/src/game/functions/booleans/is/IsSimpleType.java | package game.functions.booleans.is;
/**
* Defines the types of Is test for a player with no parameter.
*/
public enum IsSimpleType
{
/**
* To check if the game is repeating the same set of states three times with
* exactly the same moves during these states.
*/
Cycle,
/** To check if the state is in pending. */
Pending,
/** To check if the board is full. */
Full,
}
| 386 | 17.428571 | 77 | java |
Ludii | Ludii-master/Core/src/game/functions/booleans/is/IsSiteType.java | package game.functions.booleans.is;
/**
* Defines the types of Is test for a site.
*
* @author Eric.Piette
*/
public enum IsSiteType
{
/** To check if a site is empty. */
Empty,
/** To check if a site is occupied. */
Occupied,
}
| 241 | 13.235294 | 43 | java |
Ludii | Ludii-master/Core/src/game/functions/booleans/is/IsStringType.java | package game.functions.booleans.is;
/**
* Defines the types of Is test according to a String parameter.
*
* @author Eric.Piette
*/
public enum IsStringType
{
/** To check if a specific proposition was made. */
Proposed,
/** To check if a specific proposition was decided. */
Decided,
}
| 297 | 17.625 | 64 | java |
Ludii | Ludii-master/Core/src/game/functions/booleans/is/IsTargetType.java | package game.functions.booleans.is;
/**
* Defines the types of Is test according to a target.
*
* @author Eric.Piette
*/
public enum IsTargetType
{
/**
* To check when a specific configuration is on the board
*/
Target,
}
| 234 | 14.666667 | 58 | java |
Ludii | Ludii-master/Core/src/game/functions/booleans/is/IsTreeType.java | package game.functions.booleans.is;
/**
* Defines the types of Is test for a regular graph.
*
* @author Eric.Piette
*/
public enum IsTreeType
{
/** To check if the induced graph (by adding or deleting edges) is a tree or not. */
Tree,
/**
* To check if the induced graph (by adding or deleting edges) is a spanning
* tree or not.
*/
SpanningTree,
/**
* To check if the induced graph (by adding or deleting edges) is the largest
* caterpillar Tree or not.
*/
CaterpillarTree,
/** To check whether the last vertex is the centre of the tree (or sub tree). */
TreeCentre,
}
| 600 | 20.464286 | 85 | java |
Ludii | Ludii-master/Core/src/game/functions/booleans/is/IsTriggeredType.java | package game.functions.booleans.is;
/**
* Defines the types of Is test to trigger an event.
*
* @author Eric.Piette
*/
public enum IsTriggeredType
{
/** To check if a player is triggered. */
Triggered,
}
| 212 | 15.384615 | 52 | java |
Ludii | Ludii-master/Core/src/game/functions/booleans/is/package-info.java | /**
* The {\tt (is ...)} `super' ludeme returns whether a given query about the game state is true or not.
* Such queries might include whether a given piece belongs to a certain player, or is visible,
* whether certain regions are connected, etc.
*/
package game.functions.booleans.is;
| 294 | 41.142857 | 104 | java |
Ludii | Ludii-master/Core/src/game/functions/booleans/is/Hidden/IsHidden.java | package game.functions.booleans.is.Hidden;
import java.util.BitSet;
import annotations.Hide;
import game.Game;
import game.functions.booleans.BaseBooleanFunction;
import game.functions.ints.IntConstant;
import game.functions.ints.IntFunction;
import game.types.board.SiteType;
import game.types.play.RoleType;
import game.types.state.GameType;
import game.util.moves.Player;
import other.concept.Concept;
import other.context.Context;
import other.state.container.ContainerState;
/**
* Checks if a site is hidden (invisible) to a player.
*
* @author Eric.Piette
*/
@Hide
public final class IsHidden extends BaseBooleanFunction
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/** Which site. */
private final IntFunction siteFn;
/** Level. */
private final IntFunction levelFn;
/** The player to get the hidden information. */
private final IntFunction whoFn;
/** Cell/Edge/Vertex. */
private final SiteType type;
/** Precomputed boolean. */
private Boolean precomputedBoolean;
//-------------------------------------------------------------------------
/**
* For checking hidden information (invisible) at a location for a specific
* player.
*
* @param type The graph element type [default of the board].
* @param at The site to set the hidden information.
* @param level The level to set the hidden information [0].
* @param to The player with these hidden information.
* @param To The roleType with these hidden information.
*/
public IsHidden
(
final SiteType type,
final IntFunction at,
final IntFunction level,
final Player to,
final RoleType To
)
{
this.type = type;
this.siteFn = at;
this.levelFn = (level == null) ? new IntConstant(0) : level;
this.whoFn = (to == null && To == null) ? null : To != null ? RoleType.toIntFunction(To) : to.originalIndex();
}
//-------------------------------------------------------------------------
@Override
public boolean eval(final Context context)
{
if (precomputedBoolean != null)
return precomputedBoolean.booleanValue();
final int site = siteFn.eval(context);
if (site < 0)
return false;
final int containerId = context.containerId()[site];
final ContainerState cs = context.state().containerStates()[containerId];
final int level = levelFn.eval(context);
final SiteType realType = (type != null) ? type : context.game().board().defaultSite();
final int who = whoFn.eval(context);
return cs.isHidden(who, site, level, realType);
}
//-------------------------------------------------------------------------
@Override
public boolean isStatic()
{
return this.siteFn.isStatic() && this.levelFn.isStatic() && whoFn.isStatic();
}
@Override
public long gameFlags(final Game game)
{
long gameFlags = siteFn.gameFlags(game) | levelFn.gameFlags(game) | whoFn.gameFlags(game) | GameType.HiddenInfo;
gameFlags |= SiteType.gameFlags(type);
return gameFlags;
}
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
concepts.or(siteFn.concepts(game));
concepts.or(levelFn.concepts(game));
concepts.or(whoFn.concepts(game));
concepts.set(Concept.HiddenInformation.id(), true);
concepts.set(Concept.InvisiblePiece.id(), true);
return concepts;
}
@Override
public BitSet writesEvalContextRecursive()
{
final BitSet writeEvalContext = new BitSet();
writeEvalContext.or(siteFn.writesEvalContextRecursive());
writeEvalContext.or(levelFn.writesEvalContextRecursive());
writeEvalContext.or(whoFn.writesEvalContextRecursive());
return writeEvalContext;
}
@Override
public BitSet readsEvalContextRecursive()
{
final BitSet readEvalContext = new BitSet();
readEvalContext.or(siteFn.readsEvalContextRecursive());
readEvalContext.or(levelFn.readsEvalContextRecursive());
readEvalContext.or(whoFn.readsEvalContextRecursive());
return readEvalContext;
}
@Override
public void preprocess(final Game game)
{
levelFn.preprocess(game);
siteFn.preprocess(game);
whoFn.preprocess(game);
if (isStatic())
precomputedBoolean = Boolean.valueOf(eval(new Context(game, null)));
}
@Override
public boolean missingRequirement(final Game game)
{
boolean missingRequirement = false;
missingRequirement |= levelFn.missingRequirement(game);
missingRequirement |= siteFn.missingRequirement(game);
missingRequirement |= whoFn.missingRequirement(game);
return missingRequirement;
}
@Override
public boolean willCrash(final Game game)
{
boolean willCrash = false;
willCrash |= levelFn.willCrash(game);
willCrash |= siteFn.willCrash(game);
willCrash |= whoFn.willCrash(game);
return willCrash;
}
}
| 4,765 | 26.234286 | 114 | java |
Ludii | Ludii-master/Core/src/game/functions/booleans/is/Hidden/IsHiddenCount.java | package game.functions.booleans.is.Hidden;
import java.util.BitSet;
import annotations.Hide;
import game.Game;
import game.functions.booleans.BaseBooleanFunction;
import game.functions.ints.IntConstant;
import game.functions.ints.IntFunction;
import game.types.board.SiteType;
import game.types.play.RoleType;
import game.types.state.GameType;
import game.util.moves.Player;
import other.concept.Concept;
import other.context.Context;
import other.state.container.ContainerState;
/**
* Checks if the count on a site is hidden to a player.
*
* @author Eric.Piette
*/
@Hide
public final class IsHiddenCount extends BaseBooleanFunction
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/** Which site. */
private final IntFunction siteFn;
/** Level. */
private final IntFunction levelFn;
/** The player to get the hidden information. */
private final IntFunction whoFn;
/** Cell/Edge/Vertex. */
private final SiteType type;
/** Precomputed boolean. */
private Boolean precomputedBoolean;
//-------------------------------------------------------------------------
/**
* For checking the hidden information about the count at a location for a specific
* player.
*
* @param type The graph element type [default of the board].
* @param at The site to set the hidden information.
* @param level The level to set the hidden information [0].
* @param to The player with these hidden information.
* @param To The roleType with these hidden information.
*/
public IsHiddenCount
(
final SiteType type,
final IntFunction at,
final IntFunction level,
final Player to,
final RoleType To
)
{
this.type = type;
this.siteFn = at;
this.levelFn = (level == null) ? new IntConstant(0) : level;
this.whoFn = (to == null && To == null) ? null : To != null ? RoleType.toIntFunction(To) : to.originalIndex();
}
//-------------------------------------------------------------------------
@Override
public boolean eval(final Context context)
{
if (precomputedBoolean != null)
return precomputedBoolean.booleanValue();
final int site = siteFn.eval(context);
if (site < 0)
return false;
final int containerId = context.containerId()[site];
final ContainerState cs = context.state().containerStates()[containerId];
final int level = levelFn.eval(context);
final SiteType realType = (type != null) ? type : context.game().board().defaultSite();
final int who = whoFn.eval(context);
return cs.isHiddenCount(who, site, level, realType);
}
//-------------------------------------------------------------------------
@Override
public boolean isStatic()
{
return this.siteFn.isStatic() && this.levelFn.isStatic() && whoFn.isStatic();
}
@Override
public long gameFlags(final Game game)
{
long gameFlags = siteFn.gameFlags(game) | levelFn.gameFlags(game) | whoFn.gameFlags(game) | GameType.HiddenInfo;
gameFlags |= SiteType.gameFlags(type);
return gameFlags;
}
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
concepts.or(siteFn.concepts(game));
concepts.or(levelFn.concepts(game));
concepts.or(whoFn.concepts(game));
concepts.set(Concept.HiddenInformation.id(), true);
concepts.set(Concept.HidePieceCount.id(), true);
return concepts;
}
@Override
public BitSet writesEvalContextRecursive()
{
final BitSet writeEvalContext = new BitSet();
writeEvalContext.or(siteFn.writesEvalContextRecursive());
writeEvalContext.or(levelFn.writesEvalContextRecursive());
writeEvalContext.or(whoFn.writesEvalContextRecursive());
return writeEvalContext;
}
@Override
public BitSet readsEvalContextRecursive()
{
final BitSet readEvalContext = new BitSet();
readEvalContext.or(siteFn.readsEvalContextRecursive());
readEvalContext.or(levelFn.readsEvalContextRecursive());
readEvalContext.or(whoFn.readsEvalContextRecursive());
return readEvalContext;
}
@Override
public void preprocess(final Game game)
{
levelFn.preprocess(game);
siteFn.preprocess(game);
whoFn.preprocess(game);
if (isStatic())
precomputedBoolean = Boolean.valueOf(eval(new Context(game, null)));
}
@Override
public boolean missingRequirement(final Game game)
{
boolean missingRequirement = false;
missingRequirement |= levelFn.missingRequirement(game);
missingRequirement |= siteFn.missingRequirement(game);
missingRequirement |= whoFn.missingRequirement(game);
return missingRequirement;
}
@Override
public boolean willCrash(final Game game)
{
boolean willCrash = false;
willCrash |= levelFn.willCrash(game);
willCrash |= siteFn.willCrash(game);
willCrash |= whoFn.willCrash(game);
return willCrash;
}
}
| 4,789 | 26.371429 | 114 | java |
Ludii | Ludii-master/Core/src/game/functions/booleans/is/Hidden/IsHiddenRotation.java | package game.functions.booleans.is.Hidden;
import java.util.BitSet;
import annotations.Hide;
import game.Game;
import game.functions.booleans.BaseBooleanFunction;
import game.functions.ints.IntConstant;
import game.functions.ints.IntFunction;
import game.types.board.SiteType;
import game.types.play.RoleType;
import game.types.state.GameType;
import game.util.moves.Player;
import other.concept.Concept;
import other.context.Context;
import other.state.container.ContainerState;
/**
* Checks if the rotation on a site is hidden to a player.
*
* @author Eric.Piette
*/
@Hide
public final class IsHiddenRotation extends BaseBooleanFunction
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/** Which site. */
private final IntFunction siteFn;
/** Level. */
private final IntFunction levelFn;
/** The player to get the hidden information. */
private final IntFunction whoFn;
/** Cell/Edge/Vertex. */
private final SiteType type;
/** Precomputed boolean. */
private Boolean precomputedBoolean;
//-------------------------------------------------------------------------
/**
* For checking the hidden information about the rotation at a location for a specific
* player.
*
* @param type The graph element type [default of the board].
* @param at The site to set the hidden information.
* @param level The level to set the hidden information [0].
* @param to The player with these hidden information.
* @param To The roleType with these hidden information.
*/
public IsHiddenRotation
(
final SiteType type,
final IntFunction at,
final IntFunction level,
final Player to,
final RoleType To
)
{
this.type = type;
this.siteFn = at;
this.levelFn = (level == null) ? new IntConstant(0) : level;
this.whoFn = (to == null && To == null) ? null : To != null ? RoleType.toIntFunction(To) : to.originalIndex();
}
//-------------------------------------------------------------------------
@Override
public boolean eval(final Context context)
{
if (precomputedBoolean != null)
return precomputedBoolean.booleanValue();
final int site = siteFn.eval(context);
if (site < 0)
return false;
final int containerId = context.containerId()[site];
final ContainerState cs = context.state().containerStates()[containerId];
final int level = levelFn.eval(context);
final SiteType realType = (type != null) ? type : context.game().board().defaultSite();
final int who = whoFn.eval(context);
return cs.isHiddenRotation(who, site, level, realType);
}
//-------------------------------------------------------------------------
@Override
public boolean isStatic()
{
return this.siteFn.isStatic() && this.levelFn.isStatic() && whoFn.isStatic();
}
@Override
public long gameFlags(final Game game)
{
long gameFlags = siteFn.gameFlags(game) | levelFn.gameFlags(game) | whoFn.gameFlags(game) | GameType.HiddenInfo;
gameFlags |= SiteType.gameFlags(type);
return gameFlags;
}
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
concepts.or(siteFn.concepts(game));
concepts.or(levelFn.concepts(game));
concepts.or(whoFn.concepts(game));
concepts.set(Concept.HiddenInformation.id(), true);
concepts.set(Concept.HidePieceRotation.id(), true);
return concepts;
}
@Override
public BitSet writesEvalContextRecursive()
{
final BitSet writeEvalContext = new BitSet();
writeEvalContext.or(siteFn.writesEvalContextRecursive());
writeEvalContext.or(levelFn.writesEvalContextRecursive());
writeEvalContext.or(whoFn.writesEvalContextRecursive());
return writeEvalContext;
}
@Override
public BitSet readsEvalContextRecursive()
{
final BitSet readEvalContext = new BitSet();
readEvalContext.or(siteFn.readsEvalContextRecursive());
readEvalContext.or(levelFn.readsEvalContextRecursive());
readEvalContext.or(whoFn.readsEvalContextRecursive());
return readEvalContext;
}
@Override
public void preprocess(final Game game)
{
levelFn.preprocess(game);
siteFn.preprocess(game);
whoFn.preprocess(game);
if (isStatic())
precomputedBoolean = Boolean.valueOf(eval(new Context(game, null)));
}
@Override
public boolean missingRequirement(final Game game)
{
boolean missingRequirement = false;
missingRequirement |= levelFn.missingRequirement(game);
missingRequirement |= siteFn.missingRequirement(game);
missingRequirement |= whoFn.missingRequirement(game);
return missingRequirement;
}
@Override
public boolean willCrash(final Game game)
{
boolean willCrash = false;
willCrash |= levelFn.willCrash(game);
willCrash |= siteFn.willCrash(game);
willCrash |= whoFn.willCrash(game);
return willCrash;
}
}
| 4,807 | 26.474286 | 114 | java |
Ludii | Ludii-master/Core/src/game/functions/booleans/is/Hidden/IsHiddenState.java | package game.functions.booleans.is.Hidden;
import java.util.BitSet;
import annotations.Hide;
import game.Game;
import game.functions.booleans.BaseBooleanFunction;
import game.functions.ints.IntConstant;
import game.functions.ints.IntFunction;
import game.types.board.SiteType;
import game.types.play.RoleType;
import game.types.state.GameType;
import game.util.moves.Player;
import other.concept.Concept;
import other.context.Context;
import other.state.container.ContainerState;
/**
* Checks if the site state is hidden to a player.
*
* @author Eric.Piette
*/
@Hide
public final class IsHiddenState extends BaseBooleanFunction
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/** Which site. */
private final IntFunction siteFn;
/** Level. */
private final IntFunction levelFn;
/** The player to get the hidden information. */
private final IntFunction whoFn;
/** Cell/Edge/Vertex. */
private final SiteType type;
/** Precomputed boolean. */
private Boolean precomputedBoolean;
//-------------------------------------------------------------------------
/**
* For checking the hidden information about the state at a location for a specific
* player.
*
* @param type The graph element type [default of the board].
* @param at The site to set the hidden information.
* @param level The level to set the hidden information [0].
* @param to The player with these hidden information.
* @param To The roleType with these hidden information.
*/
public IsHiddenState
(
final SiteType type,
final IntFunction at,
final IntFunction level,
final Player to,
final RoleType To
)
{
this.type = type;
this.siteFn = at;
this.levelFn = (level == null) ? new IntConstant(0) : level;
this.whoFn = (to == null && To == null) ? null : To != null ? RoleType.toIntFunction(To) : to.originalIndex();
}
//-------------------------------------------------------------------------
@Override
public boolean eval(final Context context)
{
if (precomputedBoolean != null)
return precomputedBoolean.booleanValue();
final int site = siteFn.eval(context);
if (site < 0)
return false;
final int containerId = context.containerId()[site];
final ContainerState cs = context.state().containerStates()[containerId];
final int level = levelFn.eval(context);
final SiteType realType = (type != null) ? type : context.game().board().defaultSite();
final int who = whoFn.eval(context);
return cs.isHiddenState(who, site, level, realType);
}
//-------------------------------------------------------------------------
@Override
public boolean isStatic()
{
return this.siteFn.isStatic() && this.levelFn.isStatic() && whoFn.isStatic();
}
@Override
public long gameFlags(final Game game)
{
long gameFlags = siteFn.gameFlags(game) | levelFn.gameFlags(game) | whoFn.gameFlags(game) | GameType.HiddenInfo;
gameFlags |= SiteType.gameFlags(type);
return gameFlags;
}
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
concepts.or(siteFn.concepts(game));
concepts.or(levelFn.concepts(game));
concepts.or(whoFn.concepts(game));
concepts.set(Concept.HiddenInformation.id(), true);
concepts.set(Concept.HidePieceState.id(), true);
return concepts;
}
@Override
public BitSet writesEvalContextRecursive()
{
final BitSet writeEvalContext = new BitSet();
writeEvalContext.or(siteFn.writesEvalContextRecursive());
writeEvalContext.or(levelFn.writesEvalContextRecursive());
writeEvalContext.or(whoFn.writesEvalContextRecursive());
return writeEvalContext;
}
@Override
public BitSet readsEvalContextRecursive()
{
final BitSet readEvalContext = new BitSet();
readEvalContext.or(siteFn.readsEvalContextRecursive());
readEvalContext.or(levelFn.readsEvalContextRecursive());
readEvalContext.or(whoFn.readsEvalContextRecursive());
return readEvalContext;
}
@Override
public void preprocess(final Game game)
{
levelFn.preprocess(game);
siteFn.preprocess(game);
whoFn.preprocess(game);
if (isStatic())
precomputedBoolean = Boolean.valueOf(eval(new Context(game, null)));
}
@Override
public boolean missingRequirement(final Game game)
{
boolean missingRequirement = false;
missingRequirement |= levelFn.missingRequirement(game);
missingRequirement |= siteFn.missingRequirement(game);
missingRequirement |= whoFn.missingRequirement(game);
return missingRequirement;
}
@Override
public boolean willCrash(final Game game)
{
boolean willCrash = false;
willCrash |= levelFn.willCrash(game);
willCrash |= siteFn.willCrash(game);
willCrash |= whoFn.willCrash(game);
return willCrash;
}
}
| 4,784 | 26.342857 | 114 | java |
Ludii | Ludii-master/Core/src/game/functions/booleans/is/Hidden/IsHiddenValue.java | package game.functions.booleans.is.Hidden;
import java.util.BitSet;
import annotations.Hide;
import game.Game;
import game.functions.booleans.BaseBooleanFunction;
import game.functions.ints.IntConstant;
import game.functions.ints.IntFunction;
import game.types.board.SiteType;
import game.types.play.RoleType;
import game.types.state.GameType;
import game.util.moves.Player;
import other.concept.Concept;
import other.context.Context;
import other.state.container.ContainerState;
/**
* Checks if the piece value on a site is hidden to a player.
*
* @author Eric.Piette
*/
@Hide
public final class IsHiddenValue extends BaseBooleanFunction
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/** Which site. */
private final IntFunction siteFn;
/** Level. */
private final IntFunction levelFn;
/** The player to get the hidden information. */
private final IntFunction whoFn;
/** Cell/Edge/Vertex. */
private final SiteType type;
/** Precomputed boolean. */
private Boolean precomputedBoolean;
//-------------------------------------------------------------------------
/**
* For checking the hidden information about the piece value at a location for a specific
* player.
*
* @param type The graph element type [default of the board].
* @param at The site to set the hidden information.
* @param level The level to set the hidden information [0].
* @param to The player with these hidden information.
* @param To The roleType with these hidden information.
*/
public IsHiddenValue
(
final SiteType type,
final IntFunction at,
final IntFunction level,
final Player to,
final RoleType To
)
{
this.type = type;
this.siteFn = at;
this.levelFn = (level == null) ? new IntConstant(0) : level;
this.whoFn = (to == null && To == null) ? null : To != null ? RoleType.toIntFunction(To) : to.originalIndex();
}
//-------------------------------------------------------------------------
@Override
public boolean eval(final Context context)
{
if (precomputedBoolean != null)
return precomputedBoolean.booleanValue();
final int site = siteFn.eval(context);
if (site < 0)
return false;
final int containerId = context.containerId()[site];
final ContainerState cs = context.state().containerStates()[containerId];
final int level = levelFn.eval(context);
final SiteType realType = (type != null) ? type : context.game().board().defaultSite();
final int who = whoFn.eval(context);
return cs.isHiddenValue(who, site, level, realType);
}
//-------------------------------------------------------------------------
@Override
public boolean isStatic()
{
return this.siteFn.isStatic() && this.levelFn.isStatic() && whoFn.isStatic();
}
@Override
public long gameFlags(final Game game)
{
long gameFlags = siteFn.gameFlags(game) | levelFn.gameFlags(game) | whoFn.gameFlags(game) | GameType.HiddenInfo;
gameFlags |= SiteType.gameFlags(type);
return gameFlags;
}
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
concepts.or(siteFn.concepts(game));
concepts.or(levelFn.concepts(game));
concepts.or(whoFn.concepts(game));
concepts.set(Concept.HiddenInformation.id(), true);
concepts.set(Concept.HidePieceValue.id(), true);
return concepts;
}
@Override
public BitSet writesEvalContextRecursive()
{
final BitSet writeEvalContext = new BitSet();
writeEvalContext.or(siteFn.writesEvalContextRecursive());
writeEvalContext.or(levelFn.writesEvalContextRecursive());
writeEvalContext.or(whoFn.writesEvalContextRecursive());
return writeEvalContext;
}
@Override
public BitSet readsEvalContextRecursive()
{
final BitSet readEvalContext = new BitSet();
readEvalContext.or(siteFn.readsEvalContextRecursive());
readEvalContext.or(levelFn.readsEvalContextRecursive());
readEvalContext.or(whoFn.readsEvalContextRecursive());
return readEvalContext;
}
@Override
public void preprocess(final Game game)
{
levelFn.preprocess(game);
siteFn.preprocess(game);
whoFn.preprocess(game);
if (isStatic())
precomputedBoolean = Boolean.valueOf(eval(new Context(game, null)));
}
@Override
public boolean missingRequirement(final Game game)
{
boolean missingRequirement = false;
missingRequirement |= levelFn.missingRequirement(game);
missingRequirement |= siteFn.missingRequirement(game);
missingRequirement |= whoFn.missingRequirement(game);
return missingRequirement;
}
@Override
public boolean willCrash(final Game game)
{
boolean willCrash = false;
willCrash |= levelFn.willCrash(game);
willCrash |= siteFn.willCrash(game);
willCrash |= whoFn.willCrash(game);
return willCrash;
}
}
| 4,801 | 26.44 | 114 | java |
Ludii | Ludii-master/Core/src/game/functions/booleans/is/Hidden/IsHiddenWhat.java | package game.functions.booleans.is.Hidden;
import java.util.BitSet;
import annotations.Hide;
import game.Game;
import game.functions.booleans.BaseBooleanFunction;
import game.functions.ints.IntConstant;
import game.functions.ints.IntFunction;
import game.functions.ints.board.Id;
import game.types.board.SiteType;
import game.types.play.RoleType;
import game.types.state.GameType;
import game.util.moves.Player;
import other.concept.Concept;
import other.context.Context;
import other.state.container.ContainerState;
/**
* Checks if the piece index is hidden to a player.
*
* @author Eric.Piette
*/
@Hide
public final class IsHiddenWhat extends BaseBooleanFunction
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/** Which site. */
private final IntFunction siteFn;
/** Level. */
private final IntFunction levelFn;
/** The player to get the hidden information. */
private final IntFunction whoFn;
/** Cell/Edge/Vertex. */
private final SiteType type;
/** Precomputed boolean. */
private Boolean precomputedBoolean;
//-------------------------------------------------------------------------
/**
* For checking the hidden information about the piece index at a location for a
* specific player.
*
* @param type The graph element type [default of the board].
* @param at The site to set the hidden information.
* @param level The level to set the hidden information [0].
* @param to The player with these hidden information.
* @param To The roleType with these hidden information.
*/
public IsHiddenWhat
(
final SiteType type,
final IntFunction at,
final IntFunction level,
final Player to,
final RoleType To
)
{
this.type = type;
this.siteFn = at;
this.levelFn = (level == null) ? new IntConstant(0) : level;
this.whoFn = (to == null && To == null) ? null : To != null ? new Id(null, To) : to.originalIndex();
}
//-------------------------------------------------------------------------
@Override
public boolean eval(final Context context)
{
if (precomputedBoolean != null)
return precomputedBoolean.booleanValue();
final int site = siteFn.eval(context);
if (site < 0)
return false;
final int containerId = context.containerId()[site];
final ContainerState cs = context.state().containerStates()[containerId];
final int level = levelFn.eval(context);
final SiteType realType = (type != null) ? type : context.game().board().defaultSite();
final int who = whoFn.eval(context);
return cs.isHiddenWhat(who, site, level, realType);
}
//-------------------------------------------------------------------------
@Override
public boolean isStatic()
{
return this.siteFn.isStatic() && this.levelFn.isStatic() && whoFn.isStatic();
}
@Override
public long gameFlags(final Game game)
{
long gameFlags = siteFn.gameFlags(game) | levelFn.gameFlags(game) | whoFn.gameFlags(game) | GameType.HiddenInfo;
gameFlags |= SiteType.gameFlags(type);
return gameFlags;
}
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
concepts.or(siteFn.concepts(game));
concepts.or(levelFn.concepts(game));
concepts.or(whoFn.concepts(game));
concepts.set(Concept.HiddenInformation.id(), true);
concepts.set(Concept.HidePieceType.id(), true);
return concepts;
}
@Override
public BitSet writesEvalContextRecursive()
{
final BitSet writeEvalContext = new BitSet();
writeEvalContext.or(siteFn.writesEvalContextRecursive());
writeEvalContext.or(levelFn.writesEvalContextRecursive());
writeEvalContext.or(whoFn.writesEvalContextRecursive());
return writeEvalContext;
}
@Override
public BitSet readsEvalContextRecursive()
{
final BitSet readEvalContext = new BitSet();
readEvalContext.or(siteFn.readsEvalContextRecursive());
readEvalContext.or(levelFn.readsEvalContextRecursive());
readEvalContext.or(whoFn.readsEvalContextRecursive());
return readEvalContext;
}
@Override
public void preprocess(final Game game)
{
levelFn.preprocess(game);
siteFn.preprocess(game);
whoFn.preprocess(game);
if (isStatic())
precomputedBoolean = Boolean.valueOf(eval(new Context(game, null)));
}
@Override
public boolean missingRequirement(final Game game)
{
boolean missingRequirement = false;
missingRequirement |= levelFn.missingRequirement(game);
missingRequirement |= siteFn.missingRequirement(game);
missingRequirement |= whoFn.missingRequirement(game);
return missingRequirement;
}
@Override
public boolean willCrash(final Game game)
{
boolean willCrash = false;
willCrash |= levelFn.willCrash(game);
willCrash |= siteFn.willCrash(game);
willCrash |= whoFn.willCrash(game);
return willCrash;
}
}
| 4,810 | 26.335227 | 114 | java |
Ludii | Ludii-master/Core/src/game/functions/booleans/is/Hidden/IsHiddenWho.java | package game.functions.booleans.is.Hidden;
import java.util.BitSet;
import annotations.Hide;
import game.Game;
import game.functions.booleans.BaseBooleanFunction;
import game.functions.ints.IntConstant;
import game.functions.ints.IntFunction;
import game.types.board.SiteType;
import game.types.play.RoleType;
import game.types.state.GameType;
import game.util.moves.Player;
import other.concept.Concept;
import other.context.Context;
import other.state.container.ContainerState;
/**
* Checks if the piece owner is hidden to a player.
*
* @author Eric.Piette
*/
@Hide
public final class IsHiddenWho extends BaseBooleanFunction
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/** Which site. */
private final IntFunction siteFn;
/** Level. */
private final IntFunction levelFn;
/** The player to get the hidden information. */
private final IntFunction whoFn;
/** Cell/Edge/Vertex. */
private final SiteType type;
/** Precomputed boolean. */
private Boolean precomputedBoolean;
//-------------------------------------------------------------------------
/**
* For checking the hidden information about the piece owner at a location for a
* specific player.
*
* @param type The graph element type [default of the board].
* @param at The site to set the hidden information.
* @param level The level to set the hidden information [0].
* @param to The player with these hidden information.
* @param To The roleType with these hidden information.
*/
public IsHiddenWho
(
final SiteType type,
final IntFunction at,
final IntFunction level,
final Player to,
final RoleType To
)
{
this.type = type;
this.siteFn = at;
this.levelFn = (level == null) ? new IntConstant(0) : level;
this.whoFn = (to == null && To == null) ? null : To != null ? RoleType.toIntFunction(To) : to.originalIndex();
}
//-------------------------------------------------------------------------
@Override
public boolean eval(final Context context)
{
if (precomputedBoolean != null)
return precomputedBoolean.booleanValue();
final int site = siteFn.eval(context);
if (site < 0)
return false;
final int containerId = context.containerId()[site];
final ContainerState cs = context.state().containerStates()[containerId];
final int level = levelFn.eval(context);
final SiteType realType = (type != null) ? type : context.game().board().defaultSite();
final int who = whoFn.eval(context);
return cs.isHiddenWho(who, site, level, realType);
}
//-------------------------------------------------------------------------
@Override
public boolean isStatic()
{
return this.siteFn.isStatic() && this.levelFn.isStatic() && whoFn.isStatic();
}
@Override
public long gameFlags(final Game game)
{
long gameFlags = siteFn.gameFlags(game) | levelFn.gameFlags(game) | whoFn.gameFlags(game) | GameType.HiddenInfo;
gameFlags |= SiteType.gameFlags(type);
return gameFlags;
}
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
concepts.or(siteFn.concepts(game));
concepts.or(levelFn.concepts(game));
concepts.or(whoFn.concepts(game));
concepts.set(Concept.HiddenInformation.id(), true);
concepts.set(Concept.HidePieceOwner.id(), true);
return concepts;
}
@Override
public BitSet writesEvalContextRecursive()
{
final BitSet writeEvalContext = new BitSet();
writeEvalContext.or(siteFn.writesEvalContextRecursive());
writeEvalContext.or(levelFn.writesEvalContextRecursive());
writeEvalContext.or(whoFn.writesEvalContextRecursive());
return writeEvalContext;
}
@Override
public BitSet readsEvalContextRecursive()
{
final BitSet readEvalContext = new BitSet();
readEvalContext.or(siteFn.readsEvalContextRecursive());
readEvalContext.or(levelFn.readsEvalContextRecursive());
readEvalContext.or(whoFn.readsEvalContextRecursive());
return readEvalContext;
}
@Override
public void preprocess(final Game game)
{
levelFn.preprocess(game);
siteFn.preprocess(game);
whoFn.preprocess(game);
if (isStatic())
precomputedBoolean = Boolean.valueOf(eval(new Context(game, null)));
}
@Override
public boolean missingRequirement(final Game game)
{
boolean missingRequirement = false;
missingRequirement |= levelFn.missingRequirement(game);
missingRequirement |= siteFn.missingRequirement(game);
missingRequirement |= whoFn.missingRequirement(game);
return missingRequirement;
}
@Override
public boolean willCrash(final Game game)
{
boolean willCrash = false;
willCrash |= levelFn.willCrash(game);
willCrash |= siteFn.willCrash(game);
willCrash |= whoFn.willCrash(game);
return willCrash;
}
}
| 4,781 | 26.325714 | 114 | java |
Ludii | Ludii-master/Core/src/game/functions/booleans/is/angle/IsAcute.java | package game.functions.booleans.is.angle;
import java.awt.geom.Point2D;
import java.util.BitSet;
import annotations.Hide;
import annotations.Name;
import annotations.Opt;
import game.Game;
import game.functions.booleans.BaseBooleanFunction;
import game.functions.booleans.BooleanFunction;
import game.functions.ints.IntFunction;
import game.types.board.SiteType;
import other.context.Context;
/**
* Returns true if a site and two other sites checking conditions form an acute angle (< 90 degrees).
*
* @author Eric.Piette
*/
@Hide
public final class IsAcute extends BaseBooleanFunction
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/** Cell/Edge/Vertex. */
private SiteType type;
/** The site. */
private IntFunction atFn;
/** The condition on the first site. */
private BooleanFunction cond1;
/** The condition on the second site. */
private BooleanFunction cond2;
//-------------------------------------------------------------------------
/**
* @param type The graph element type [default of the board].
* @param at The site
* @param conditionSite The condition on the first site.
* @param conditionSite2 The condition on the second site.
*/
public IsAcute
(
@Opt final SiteType type,
@Name final IntFunction at,
final BooleanFunction conditionSite,
final BooleanFunction conditionSite2
)
{
this.atFn = at;
this.cond1 = conditionSite;
this.cond2 = conditionSite2;
this.type = type;
}
//-------------------------------------------------------------------------
@Override
public boolean eval(final Context context)
{
final SiteType realSiteType = type == null ? context.board().defaultSite() : type;
final int site = atFn.eval(context);
final int originSite = context.site();
if (site < 0)
return false;
// Always 0 for the container because we look for angle only on the main board.
final int numSites = context.topology().getGraphElements(realSiteType).size();
if (site >= numSites)
return false;
for(int site1 = 0; site1 < numSites; site1++)
for(int site2 = site1 + 1; site2 < numSites; site2++)
if(site1 != site && site2 != site)
{
context.setSite(site1);
final boolean condition1 = cond1.eval(context);
context.setSite(site2);
final boolean condition2 = cond2.eval(context);
if(condition1 && condition2)
{
final Point2D p1 = context.topology().getGraphElements(realSiteType).get(site1).centroid();
final Point2D p2 = context.topology().getGraphElements(realSiteType).get(site2).centroid();
double difX = p2.getX() - p1.getX(); double difY = p2.getY() - p1.getY();
double angle = Math.abs(Math.toDegrees(Math.atan2(difX,-difY)));
if(angle < 90)
{
context.setSite(originSite);
return true;
}
}
}
context.setSite(originSite);
return false;
}
//-------------------------------------------------------------------------
@Override
public String toString()
{
return "IsAcute(" + atFn + "," + cond1 + "," + cond2+ ")";
}
@Override
public boolean isStatic()
{
return false;
}
@Override
public long gameFlags(final Game game)
{
long gameFlags = 0l;
gameFlags |= SiteType.gameFlags(type);
gameFlags |= atFn.gameFlags(game);
gameFlags |= cond1.gameFlags(game);
gameFlags |= cond2.gameFlags(game);
return gameFlags;
}
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
concepts.or(super.concepts(game));
concepts.or(SiteType.concepts(type));
concepts.or(atFn.concepts(game));
concepts.or(cond1.concepts(game));
concepts.or(cond2.concepts(game));
return concepts;
}
@Override
public BitSet writesEvalContextRecursive()
{
final BitSet writeEvalContext = new BitSet();
writeEvalContext.or(super.writesEvalContextRecursive());
writeEvalContext.or(atFn.writesEvalContextRecursive());
writeEvalContext.or(cond1.writesEvalContextRecursive());
writeEvalContext.or(cond2.writesEvalContextRecursive());
return writeEvalContext;
}
@Override
public BitSet readsEvalContextRecursive()
{
final BitSet readEvalContext = new BitSet();
readEvalContext.or(super.readsEvalContextRecursive());
readEvalContext.or(atFn.readsEvalContextRecursive());
readEvalContext.or(cond1.readsEvalContextRecursive());
readEvalContext.or(cond2.readsEvalContextRecursive());
return readEvalContext;
}
@Override
public void preprocess(final Game game)
{
type = SiteType.use(type, game);
atFn.preprocess(game);
cond1.preprocess(game);
cond2.preprocess(game);
}
@Override
public boolean missingRequirement(final Game game)
{
boolean missingRequirement = false;
missingRequirement |= super.missingRequirement(game);
missingRequirement |= atFn.missingRequirement(game);
missingRequirement |= cond1.missingRequirement(game);
missingRequirement |= cond2.missingRequirement(game);
return missingRequirement;
}
@Override
public boolean willCrash(final Game game)
{
boolean willCrash = false;
willCrash |= super.willCrash(game);
willCrash |= atFn.willCrash(game);
willCrash |= cond1.willCrash(game);
willCrash |= cond2.willCrash(game);
return willCrash;
}
@Override
public String toEnglish(final Game game)
{
return "is Acute at " + atFn.toEnglish(game) + " with condition 1 = " + cond1.toEnglish(game) + " and condition 2 = " + cond2.toEnglish(game);
}
}
| 5,544 | 26.181373 | 145 | java |
Ludii | Ludii-master/Core/src/game/functions/booleans/is/angle/IsObtuse.java | package game.functions.booleans.is.angle;
import java.awt.geom.Point2D;
import java.util.BitSet;
import annotations.Hide;
import annotations.Name;
import annotations.Opt;
import game.Game;
import game.functions.booleans.BaseBooleanFunction;
import game.functions.booleans.BooleanFunction;
import game.functions.ints.IntFunction;
import game.types.board.SiteType;
import other.context.Context;
/**
* Returns true if a site and two other sites checking conditions form an obtuse angle (> 90 degrees).
*
* @author Eric.Piette
*/
@Hide
public final class IsObtuse extends BaseBooleanFunction
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/** Cell/Edge/Vertex. */
private SiteType type;
/** The site. */
private IntFunction atFn;
/** The condition on the first site. */
private BooleanFunction cond1;
/** The condition on the second site. */
private BooleanFunction cond2;
//-------------------------------------------------------------------------
/**
* @param type The graph element type [default of the board].
* @param at The site
* @param conditionSite The condition on the first site.
* @param conditionSite2 The condition on the second site.
*/
public IsObtuse
(
@Opt final SiteType type,
@Name final IntFunction at,
final BooleanFunction conditionSite,
final BooleanFunction conditionSite2
)
{
this.atFn = at;
this.cond1 = conditionSite;
this.cond2 = conditionSite2;
this.type = type;
}
//-------------------------------------------------------------------------
@Override
public boolean eval(final Context context)
{
final SiteType realSiteType = type == null ? context.board().defaultSite() : type;
final int site = atFn.eval(context);
final int originSite = context.site();
if (site < 0)
return false;
// Always 0 for the container because we look for angle only on the main board.
final int numSites = context.topology().getGraphElements(realSiteType).size();
if (site >= numSites)
return false;
for(int site1 = 0; site1 < numSites; site1++)
for(int site2 = site1 + 1; site2 < numSites; site2++)
if(site1 != site && site2 != site)
{
context.setSite(site1);
final boolean condition1 = cond1.eval(context);
context.setSite(site2);
final boolean condition2 = cond2.eval(context);
if(condition1 && condition2)
{
final Point2D p1 = context.topology().getGraphElements(realSiteType).get(site1).centroid();
final Point2D p2 = context.topology().getGraphElements(realSiteType).get(site2).centroid();
double difX = p2.getX() - p1.getX(); double difY = p2.getY() - p1.getY();
double angle = Math.abs(Math.toDegrees(Math.atan2(difX,-difY)));
if(angle > 90)
{
context.setSite(originSite);
return true;
}
}
}
context.setSite(originSite);
return false;
}
//-------------------------------------------------------------------------
@Override
public String toString()
{
return "IsObtuse(" + atFn + "," + cond1 + "," + cond2+ ")";
}
@Override
public boolean isStatic()
{
return false;
}
@Override
public long gameFlags(final Game game)
{
long gameFlags = 0l;
gameFlags |= SiteType.gameFlags(type);
gameFlags |= atFn.gameFlags(game);
gameFlags |= cond1.gameFlags(game);
gameFlags |= cond2.gameFlags(game);
return gameFlags;
}
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
concepts.or(super.concepts(game));
concepts.or(SiteType.concepts(type));
concepts.or(atFn.concepts(game));
concepts.or(cond1.concepts(game));
concepts.or(cond2.concepts(game));
return concepts;
}
@Override
public BitSet writesEvalContextRecursive()
{
final BitSet writeEvalContext = new BitSet();
writeEvalContext.or(super.writesEvalContextRecursive());
writeEvalContext.or(atFn.writesEvalContextRecursive());
writeEvalContext.or(cond1.writesEvalContextRecursive());
writeEvalContext.or(cond2.writesEvalContextRecursive());
return writeEvalContext;
}
@Override
public BitSet readsEvalContextRecursive()
{
final BitSet readEvalContext = new BitSet();
readEvalContext.or(super.readsEvalContextRecursive());
readEvalContext.or(atFn.readsEvalContextRecursive());
readEvalContext.or(cond1.readsEvalContextRecursive());
readEvalContext.or(cond2.readsEvalContextRecursive());
return readEvalContext;
}
@Override
public void preprocess(final Game game)
{
type = SiteType.use(type, game);
atFn.preprocess(game);
cond1.preprocess(game);
cond2.preprocess(game);
}
@Override
public boolean missingRequirement(final Game game)
{
boolean missingRequirement = false;
missingRequirement |= super.missingRequirement(game);
missingRequirement |= atFn.missingRequirement(game);
missingRequirement |= cond1.missingRequirement(game);
missingRequirement |= cond2.missingRequirement(game);
return missingRequirement;
}
@Override
public boolean willCrash(final Game game)
{
boolean willCrash = false;
willCrash |= super.willCrash(game);
willCrash |= atFn.willCrash(game);
willCrash |= cond1.willCrash(game);
willCrash |= cond2.willCrash(game);
return willCrash;
}
@Override
public String toEnglish(final Game game)
{
return "is Obtuse at " + atFn.toEnglish(game) + " with condition 1 = " + cond1.toEnglish(game) + " and condition 2 = " + cond2.toEnglish(game);
}
}
| 5,549 | 26.205882 | 146 | java |
Ludii | Ludii-master/Core/src/game/functions/booleans/is/angle/IsReflex.java | package game.functions.booleans.is.angle;
import java.awt.geom.Point2D;
import java.util.BitSet;
import annotations.Hide;
import annotations.Name;
import annotations.Opt;
import game.Game;
import game.functions.booleans.BaseBooleanFunction;
import game.functions.booleans.BooleanFunction;
import game.functions.ints.IntFunction;
import game.types.board.SiteType;
import other.context.Context;
/**
* Returns true if a site and two other sites checking conditions form a reflex angle (> 180 degrees).
*
* @author Eric.Piette
*/
@Hide
public final class IsReflex extends BaseBooleanFunction
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/** Cell/Edge/Vertex. */
private SiteType type;
/** The site. */
private IntFunction atFn;
/** The condition on the first site. */
private BooleanFunction cond1;
/** The condition on the second site. */
private BooleanFunction cond2;
//-------------------------------------------------------------------------
/**
* @param type The graph element type [default of the board].
* @param at The site
* @param conditionSite The condition on the first site.
* @param conditionSite2 The condition on the second site.
*/
public IsReflex
(
@Opt final SiteType type,
@Name final IntFunction at,
final BooleanFunction conditionSite,
final BooleanFunction conditionSite2
)
{
this.atFn = at;
this.cond1 = conditionSite;
this.cond2 = conditionSite2;
this.type = type;
}
//-------------------------------------------------------------------------
@Override
public boolean eval(final Context context)
{
final SiteType realSiteType = type == null ? context.board().defaultSite() : type;
final int site = atFn.eval(context);
final int originSite = context.site();
if (site < 0)
return false;
// Always 0 for the container because we look for angle only on the main board.
final int numSites = context.topology().getGraphElements(realSiteType).size();
if (site >= numSites)
return false;
for(int site1 = 0; site1 < numSites; site1++)
for(int site2 = site1 + 1; site2 < numSites; site2++)
if(site1 != site && site2 != site)
{
context.setSite(site1);
final boolean condition1 = cond1.eval(context);
context.setSite(site2);
final boolean condition2 = cond2.eval(context);
if(condition1 && condition2)
{
final Point2D p1 = context.topology().getGraphElements(realSiteType).get(site1).centroid();
final Point2D p2 = context.topology().getGraphElements(realSiteType).get(site2).centroid();
double difX = p2.getX() - p1.getX(); double difY = p2.getY() - p1.getY();
double angle = Math.abs(Math.toDegrees(Math.atan2(difX,-difY)));
if(angle > 180)
{
context.setSite(originSite);
return true;
}
}
}
context.setSite(originSite);
return false;
}
//-------------------------------------------------------------------------
@Override
public String toString()
{
return "IsReflex(" + atFn + "," + cond1 + "," + cond2+ ")";
}
@Override
public boolean isStatic()
{
return false;
}
@Override
public long gameFlags(final Game game)
{
long gameFlags = 0l;
gameFlags |= SiteType.gameFlags(type);
gameFlags |= atFn.gameFlags(game);
gameFlags |= cond1.gameFlags(game);
gameFlags |= cond2.gameFlags(game);
return gameFlags;
}
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
concepts.or(super.concepts(game));
concepts.or(SiteType.concepts(type));
concepts.or(atFn.concepts(game));
concepts.or(cond1.concepts(game));
concepts.or(cond2.concepts(game));
return concepts;
}
@Override
public BitSet writesEvalContextRecursive()
{
final BitSet writeEvalContext = new BitSet();
writeEvalContext.or(super.writesEvalContextRecursive());
writeEvalContext.or(atFn.writesEvalContextRecursive());
writeEvalContext.or(cond1.writesEvalContextRecursive());
writeEvalContext.or(cond2.writesEvalContextRecursive());
return writeEvalContext;
}
@Override
public BitSet readsEvalContextRecursive()
{
final BitSet readEvalContext = new BitSet();
readEvalContext.or(super.readsEvalContextRecursive());
readEvalContext.or(atFn.readsEvalContextRecursive());
readEvalContext.or(cond1.readsEvalContextRecursive());
readEvalContext.or(cond2.readsEvalContextRecursive());
return readEvalContext;
}
@Override
public void preprocess(final Game game)
{
type = SiteType.use(type, game);
atFn.preprocess(game);
cond1.preprocess(game);
cond2.preprocess(game);
}
@Override
public boolean missingRequirement(final Game game)
{
boolean missingRequirement = false;
missingRequirement |= super.missingRequirement(game);
missingRequirement |= atFn.missingRequirement(game);
missingRequirement |= cond1.missingRequirement(game);
missingRequirement |= cond2.missingRequirement(game);
return missingRequirement;
}
@Override
public boolean willCrash(final Game game)
{
boolean willCrash = false;
willCrash |= super.willCrash(game);
willCrash |= atFn.willCrash(game);
willCrash |= cond1.willCrash(game);
willCrash |= cond2.willCrash(game);
return willCrash;
}
@Override
public String toEnglish(final Game game)
{
return "is Reflex at " + atFn.toEnglish(game) + " with condition 1 = " + cond1.toEnglish(game) + " and condition 2 = " + cond2.toEnglish(game);
}
}
| 5,550 | 26.210784 | 146 | java |
Ludii | Ludii-master/Core/src/game/functions/booleans/is/angle/IsRight.java | package game.functions.booleans.is.angle;
import java.awt.geom.Point2D;
import java.util.BitSet;
import annotations.Hide;
import annotations.Name;
import annotations.Opt;
import game.Game;
import game.functions.booleans.BaseBooleanFunction;
import game.functions.booleans.BooleanFunction;
import game.functions.ints.IntFunction;
import game.types.board.SiteType;
import other.context.Context;
/**
* Returns true if a site and two other sites checking conditions form a right angle (= 90 degrees).
*
* @author Eric.Piette
*/
@Hide
public final class IsRight extends BaseBooleanFunction
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/** Cell/Edge/Vertex. */
private SiteType type;
/** The site. */
private IntFunction atFn;
/** The condition on the first site. */
private BooleanFunction cond1;
/** The condition on the second site. */
private BooleanFunction cond2;
//-------------------------------------------------------------------------
/**
* @param type The graph element type [default of the board].
* @param at The site
* @param conditionSite The condition on the first site.
* @param conditionSite2 The condition on the second site.
*/
public IsRight
(
@Opt final SiteType type,
@Name final IntFunction at,
final BooleanFunction conditionSite,
final BooleanFunction conditionSite2
)
{
this.atFn = at;
this.cond1 = conditionSite;
this.cond2 = conditionSite2;
this.type = type;
}
//-------------------------------------------------------------------------
@Override
public boolean eval(final Context context)
{
final SiteType realSiteType = type == null ? context.board().defaultSite() : type;
final int site = atFn.eval(context);
final int originSite = context.site();
if (site < 0)
return false;
// Always 0 for the container because we look for angle only on the main board.
final int numSites = context.topology().getGraphElements(realSiteType).size();
if (site >= numSites)
return false;
for(int site1 = 0; site1 < numSites; site1++)
for(int site2 = site1 + 1; site2 < numSites; site2++)
if(site1 != site && site2 != site)
{
context.setSite(site1);
final boolean condition1 = cond1.eval(context);
context.setSite(site2);
final boolean condition2 = cond2.eval(context);
if(condition1 && condition2)
{
final Point2D p1 = context.topology().getGraphElements(realSiteType).get(site1).centroid();
final Point2D p2 = context.topology().getGraphElements(realSiteType).get(site2).centroid();
double difX = p2.getX() - p1.getX(); double difY = p2.getY() - p1.getY();
double angle = Math.abs(Math.toDegrees(Math.atan2(difX,-difY)));
if(angle == 90)
{
context.setSite(originSite);
return true;
}
}
}
context.setSite(originSite);
return false;
}
//-------------------------------------------------------------------------
@Override
public String toString()
{
return "IsRight(" + atFn + "," + cond1 + "," + cond2+ ")";
}
@Override
public boolean isStatic()
{
return false;
}
@Override
public long gameFlags(final Game game)
{
long gameFlags = 0l;
gameFlags |= SiteType.gameFlags(type);
gameFlags |= atFn.gameFlags(game);
gameFlags |= cond1.gameFlags(game);
gameFlags |= cond2.gameFlags(game);
return gameFlags;
}
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
concepts.or(super.concepts(game));
concepts.or(SiteType.concepts(type));
concepts.or(atFn.concepts(game));
concepts.or(cond1.concepts(game));
concepts.or(cond2.concepts(game));
return concepts;
}
@Override
public BitSet writesEvalContextRecursive()
{
final BitSet writeEvalContext = new BitSet();
writeEvalContext.or(super.writesEvalContextRecursive());
writeEvalContext.or(atFn.writesEvalContextRecursive());
writeEvalContext.or(cond1.writesEvalContextRecursive());
writeEvalContext.or(cond2.writesEvalContextRecursive());
return writeEvalContext;
}
@Override
public BitSet readsEvalContextRecursive()
{
final BitSet readEvalContext = new BitSet();
readEvalContext.or(super.readsEvalContextRecursive());
readEvalContext.or(atFn.readsEvalContextRecursive());
readEvalContext.or(cond1.readsEvalContextRecursive());
readEvalContext.or(cond2.readsEvalContextRecursive());
return readEvalContext;
}
@Override
public void preprocess(final Game game)
{
type = SiteType.use(type, game);
atFn.preprocess(game);
cond1.preprocess(game);
cond2.preprocess(game);
}
@Override
public boolean missingRequirement(final Game game)
{
boolean missingRequirement = false;
missingRequirement |= super.missingRequirement(game);
missingRequirement |= atFn.missingRequirement(game);
missingRequirement |= cond1.missingRequirement(game);
missingRequirement |= cond2.missingRequirement(game);
return missingRequirement;
}
@Override
public boolean willCrash(final Game game)
{
boolean willCrash = false;
willCrash |= super.willCrash(game);
willCrash |= atFn.willCrash(game);
willCrash |= cond1.willCrash(game);
willCrash |= cond2.willCrash(game);
return willCrash;
}
@Override
public String toEnglish(final Game game)
{
return "is Right at " + atFn.toEnglish(game) + " with condition 1 = " + cond1.toEnglish(game) + " and condition 2 = " + cond2.toEnglish(game);
}
}
| 5,544 | 26.181373 | 145 | java |
Ludii | Ludii-master/Core/src/game/functions/booleans/is/component/IsThreatened.java | package game.functions.booleans.is.component;
import java.util.BitSet;
import java.util.function.Supplier;
import annotations.Hide;
import annotations.Opt;
import annotations.Or;
import game.Game;
import game.functions.booleans.BaseBooleanFunction;
import game.functions.ints.IntFunction;
import game.functions.ints.board.where.WhereSite;
import game.functions.region.RegionFunction;
import game.functions.region.sites.occupied.SitesOccupied;
import game.rules.play.moves.Moves;
import game.types.board.SiteType;
import game.types.play.RoleType;
import gnu.trove.list.array.TIntArrayList;
import main.Constants;
import other.IntArrayFromRegion;
import other.concept.Concept;
import other.context.Context;
import other.context.TempContext;
import other.state.container.ContainerState;
/**
* Returns true if a location is under threat for one specific player.
*
* @author Eric.Piette
* @remarks Used to avoid being under threat, for example to know if the king is
* check.
*/
@Hide
public final class IsThreatened extends BaseBooleanFunction
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/** What is under threat. */
private final IntFunction what;
/** Which sites. */
protected final IntArrayFromRegion region;
/** Cell/Edge/Vertex. */
private SiteType type;
/** The specific moves used to threat. */
private final Moves specificMoves;
/** For every thread, store if we'll auto-fail for nested calls in the same thread */
private static ThreadLocal<Boolean> autoFail =
ThreadLocal.withInitial(new Supplier<Boolean>()
{
@Override
public Boolean get()
{
return Boolean.FALSE;
}
});
//-------------------------------------------------------------------------
/**
* @param what The component.
* @param type The graph element type [default SiteType of the board].
* @param site The location to check.
* @param sites The locations to check.
* @param specificMoves The specific moves used to threat.
*/
public IsThreatened
(
@Opt final IntFunction what,
@Opt final SiteType type,
@Opt @Or final IntFunction site,
@Opt @Or final RegionFunction sites,
@Opt final Moves specificMoves
)
{
RegionFunction regionFn = null;
if (site == null && sites == null && what == null)
regionFn = new SitesOccupied(null, RoleType.All, null, null, null, null, null, null, null);
else if (sites != null)
regionFn = sites;
IntFunction intFn = null;
if (site != null)
intFn = site;
else if (sites == null && what != null)
intFn = new WhereSite(what, null);
region = new IntArrayFromRegion(intFn, regionFn);
this.what = what;
this.type = type;
this.specificMoves = specificMoves;
}
//-------------------------------------------------------------------------
@Override
public boolean eval(final Context context)
{
if (autoFails())
return false;
final SiteType realSiteType = (
(
(type != null && type.equals(SiteType.Cell))
||
(type == null && context.game().board().defaultSite() != SiteType.Vertex)
)
? SiteType.Vertex : SiteType.Cell);
if (what != null)
{
if (what.eval(context) < 1)
return false;
// To avoid the infinite call of this ludeme.
if (context.recursiveCalled())
return false;
final int ownerWhat = context.components()[what.eval(context)].owner();
final int[] sites = region.eval(context);
for (final int site : sites)
{
if (site == Constants.OFF)
continue;
final Context newContext = new TempContext(context);
newContext.state().setPrev(ownerWhat);
newContext.containerState(newContext.containerId()[site]).setSite
(
newContext.state(),
site,
ownerWhat,
what.eval(newContext),
Constants.UNDEFINED,
Constants.UNDEFINED,
Constants.UNDEFINED,
Constants.UNDEFINED,
realSiteType
);
autoFail.set(Boolean.TRUE);
final TIntArrayList enemies = context.game().players().players().get(ownerWhat).enemies();
for (int i = 0; i < enemies.size(); i++)
{
final int enemyId = enemies.getQuick(i);
newContext.state().setMover(enemyId);
newContext.setRecursiveCalled(true);
final int enemyPhase = newContext.state().currentPhase(enemyId);
final Moves moves = (specificMoves == null)
? newContext.game().rules().phases()[enemyPhase].play().moves()
: specificMoves;
if (moves.canMoveTo(newContext, site))
{
autoFail.set(Boolean.FALSE);
return true;
}
}
autoFail.set(Boolean.FALSE);
}
return false;
}
else // We check if any piece is under threat.
{
final int[] sites = region.eval(context);
if (sites.length == 0)
return false;
final ContainerState cs = context.containerState(context.containerId()[sites[0]]);
for (final int site : sites)
{
final int idPiece = cs.what(site, type);
if (idPiece <= 0 || site == Constants.OFF)
continue;
final int ownerWhat = context.components()[idPiece].owner();
// To avoid the infinite call of this ludeme.
final int nextPlayer = context.state().next();
if (0 == nextPlayer || nextPlayer > context.game().players().count())
return false;
final Context newContext = new TempContext(context);
newContext.state().setPrev(ownerWhat);
newContext.containerState(newContext.containerId()[site]).setSite
(
newContext.state(),
site,
ownerWhat,
idPiece,
Constants.UNDEFINED,
Constants.UNDEFINED,
Constants.UNDEFINED,
Constants.UNDEFINED,
realSiteType
);
autoFail.set(Boolean.TRUE);
final TIntArrayList enemies = newContext.game().players().players().get(ownerWhat).enemies();
for (int i = 0; i < enemies.size(); i++)
{
newContext.state().setMover(enemies.getQuick(i));
newContext.state().setNext(ownerWhat);
final int enemyPhase = newContext.state().currentPhase(enemies.getQuick(i));
final Moves moves = (specificMoves == null)
? newContext.game().rules().phases()[enemyPhase].play().moves()
: specificMoves;
if (moves.canMoveTo(newContext, site))
{
autoFail.set(Boolean.FALSE);
return true;
}
}
autoFail.set(Boolean.FALSE);
}
return false;
}
}
//-------------------------------------------------------------------------
@Override
public String toString()
{
return "Threatened(" + what + "," + region + ")";
}
@Override
public boolean isStatic()
{
return false;
}
@Override
public long gameFlags(final Game game)
{
long gameFlags = 0l;
gameFlags |= SiteType.gameFlags(type);
if (what != null)
gameFlags |= what.gameFlags(game);
if (specificMoves != null)
gameFlags |= specificMoves.gameFlags(game);
gameFlags |= region.gameFlags(game);
return gameFlags;
}
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
concepts.or(super.concepts(game));
concepts.set(Concept.Threat.id(), true);
concepts.or(SiteType.concepts(type));
concepts.set(Concept.CopyContext.id(), true);
if (what != null)
concepts.or(what.concepts(game));
if (specificMoves != null)
concepts.or(specificMoves.concepts(game));
concepts.or(region.concepts(game));
return concepts;
}
@Override
public BitSet writesEvalContextRecursive()
{
final BitSet writeEvalContext = new BitSet();
writeEvalContext.or(super.writesEvalContextRecursive());
if (what != null)
writeEvalContext.or(what.writesEvalContextRecursive());
if (specificMoves != null)
writeEvalContext.or(specificMoves.writesEvalContextRecursive());
writeEvalContext.or(region.writesEvalContextRecursive());
return writeEvalContext;
}
@Override
public BitSet readsEvalContextRecursive()
{
final BitSet readEvalContext = new BitSet();
readEvalContext.or(super.readsEvalContextRecursive());
if (what != null)
readEvalContext.or(what.readsEvalContextRecursive());
if (specificMoves != null)
readEvalContext.or(specificMoves.readsEvalContextRecursive());
readEvalContext.or(region.readsEvalContextRecursive());
return readEvalContext;
}
@Override
public void preprocess(final Game game)
{
type = SiteType.use(type, game);
if (what != null)
what.preprocess(game);
region.preprocess(game);
if (specificMoves != null)
specificMoves.preprocess(game);
}
@Override
public boolean missingRequirement(final Game game)
{
boolean missingRequirement = false;
missingRequirement |= super.missingRequirement(game);
if (what != null)
missingRequirement |= what.missingRequirement(game);
if (specificMoves != null)
missingRequirement |= specificMoves.missingRequirement(game);
missingRequirement |= region.missingRequirement(game);
return missingRequirement;
}
@Override
public boolean willCrash(final Game game)
{
boolean willCrash = false;
willCrash |= super.willCrash(game);
if (what != null)
willCrash |= what.willCrash(game);
if (specificMoves != null)
willCrash |= specificMoves.willCrash(game);
willCrash |= region.willCrash(game);
return willCrash;
}
@Override
public boolean autoFails()
{
return autoFail.get().booleanValue();
}
@Override
public String toEnglish(final Game game)
{
String whatEnglish = "a piece";
if (what != null)
whatEnglish = what.toEnglish(game);
return whatEnglish + " is threatened";
}
}
| 9,587 | 24.568 | 97 | java |
Ludii | Ludii-master/Core/src/game/functions/booleans/is/component/IsWithin.java | package game.functions.booleans.is.component;
import java.util.BitSet;
import annotations.Hide;
import annotations.Opt;
import annotations.Or;
import game.Game;
import game.functions.booleans.BaseBooleanFunction;
import game.functions.ints.IntFunction;
import game.functions.ints.last.LastTo;
import game.functions.region.RegionFunction;
import game.types.board.SiteType;
import gnu.trove.list.array.TIntArrayList;
import other.IntArrayFromRegion;
import other.context.Context;
/**
* Tests if a specific piece is on the designed region.
*
* @author Eric.Piette
*/
@Hide
public final class IsWithin extends BaseBooleanFunction
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/** The item identity. */
private final IntFunction pieceId;
/** Which region. */
protected final IntArrayFromRegion region;
/** Cell/Edge/Vertex. */
private SiteType type;
//-------------------------------------------------------------------------
/**
* @param pieceId The index of the item.
* @param type The graph element type.
* @param locn The location to check [(lastTo)].
* @param region The region to check.
*/
public IsWithin
(
final IntFunction pieceId,
@Opt final SiteType type,
@Or final IntFunction locn,
@Or final RegionFunction region
)
{
this.pieceId = pieceId;
this.region = new IntArrayFromRegion
(
(region == null && locn != null ? locn : region == null ? new LastTo(null) : null),
(region != null) ? region : null
);
this.type = type;
}
@Override
public final boolean eval(final Context context)
{
final int pid = pieceId.eval(context);
final int owner = context.components()[pid].owner();
final TIntArrayList sites = new TIntArrayList(region.eval(context));
final TIntArrayList owned = context.state().owned().sites(owner, pid);
for (int i = 0; i < owned.size(); i++)
{
final int location = owned.getQuick(i);
if (sites.contains(location))
return true;
}
return false;
}
//-------------------------------------------------------------------------
@Override
public String toString()
{
return "IsWithin(" + pieceId + "," + region + ")";
}
//-------------------------------------------------------------------------
@Override
public boolean isStatic()
{
return false;
}
@Override
public long gameFlags(final Game game)
{
long gameFlags = pieceId.gameFlags(game) | region.gameFlags(game);
gameFlags |= SiteType.gameFlags(type);
return gameFlags;
}
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
concepts.or(pieceId.concepts(game));
concepts.or(region.concepts(game));
concepts.or(SiteType.concepts(type));
return concepts;
}
@Override
public BitSet writesEvalContextRecursive()
{
final BitSet writeEvalContext = new BitSet();
writeEvalContext.or(pieceId.writesEvalContextRecursive());
writeEvalContext.or(region.writesEvalContextRecursive());
return writeEvalContext;
}
@Override
public BitSet readsEvalContextRecursive()
{
final BitSet readEvalContext = new BitSet();
readEvalContext.or(pieceId.readsEvalContextRecursive());
readEvalContext.or(region.readsEvalContextRecursive());
return readEvalContext;
}
@Override
public void preprocess(final Game game)
{
type = SiteType.use(type, game);
pieceId.preprocess(game);
region.preprocess(game);
}
@Override
public boolean missingRequirement(final Game game)
{
boolean missingRequirement = false;
missingRequirement |= pieceId.missingRequirement(game);
missingRequirement |= region.missingRequirement(game);
return missingRequirement;
}
@Override
public boolean willCrash(final Game game)
{
boolean willCrash = false;
willCrash |= pieceId.willCrash(game);
willCrash |= region.willCrash(game);
return willCrash;
}
@Override
public String toEnglish(final Game game)
{
return pieceId.toEnglish(game)+ " is in "+ region.toEnglish(game);
}
}
| 4,069 | 22.80117 | 87 | java |
Ludii | Ludii-master/Core/src/game/functions/booleans/is/connect/IsBlocked.java | package game.functions.booleans.is.connect;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.List;
import annotations.Hide;
import annotations.Opt;
import annotations.Or;
import game.Game;
import game.equipment.other.Regions;
import game.functions.booleans.BaseBooleanFunction;
import game.functions.directions.Directions;
import game.functions.directions.DirectionsFunction;
import game.functions.ints.IntFunction;
import game.functions.region.RegionFunction;
import game.types.board.RegionTypeStatic;
import game.types.board.SiteType;
import game.types.play.RoleType;
import game.util.directions.AbsoluteDirection;
import game.util.directions.Direction;
import gnu.trove.list.array.TIntArrayList;
import main.Constants;
import other.context.Context;
import other.state.container.ContainerState;
import other.topology.Topology;
import other.topology.TopologyElement;
import other.trial.Trial;
/**
* Detects whether regions cannot possibly be connected by a player.
*
* @author Eric.Piette and Dennis Soemers and cambolbro
*/
@Hide
public final class IsBlocked extends BaseBooleanFunction
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/** the regions to connect */
private final RegionFunction[] regionsToConnectFn;
/** The owner of the regions */
private final IntFunction roleFunc;
/** The different regions of the regionType. */
private final Regions staticRegions;
/** The minimum number of set need to connect */
private final IntFunction number;
/** Cell/Edge/Vertex. */
private SiteType type;
/** Direction chosen. */
private final DirectionsFunction dirnChoice;
// -------------------------Pre-computation------------------------------------------
/** The pre-computed regions to connect. */
private List<TIntArrayList> precomputedSitesRegions;
/** The pre-computed owned regions. */
private List<List<TIntArrayList>> precomputedOwnedRegions;
/**
* Precomputed lists of BitSets (only used in case where role != null currently)
* One list of BitSets per player index
*/
// private List<List<BitSet>> precomputedRegionsBitSets = null;
//-------------------------------------------------------------------------
/**
* @param type The graph element type [default SiteType of the board].
* @param number The minimum number of set need to connect [number of owned
* regions if not specified].
* @param directions The directions of the connected pieces used to connect the
* region [Adjacent].
* @param regions The disjointed regions set, which need to use for
* connection.
* @param role The role of the player.
* @param regionType Type of the regions.
*/
public IsBlocked
(
@Opt final SiteType type,
@Opt final IntFunction number,
@Opt final Direction directions,
@Or final RegionFunction[] regions,
@Or final RoleType role,
@Or final RegionTypeStatic regionType
)
{
this.number = number;
this.regionsToConnectFn = regions;
roleFunc = (role == null) ? null : RoleType.toIntFunction(role);
this.staticRegions = (regionType == null)
? null
: new game.equipment.other.Regions(null, null, null, null, null, regionType, null, null);
this.type = type;
this.dirnChoice = (directions != null) ? directions.directionsFunctions()
: new Directions(AbsoluteDirection.Adjacent, null);
}
//-------------------------------------------------------------------------
@Override
public boolean eval(final Context context)
{
final Game game = context.game();
final Topology topology = context.topology();
final SiteType realType = (type != null) ? type : context.game().board().defaultSite();
// Check if the site is in the board.
final ContainerState cs = context.containerState(0);
final int who = (roleFunc != null) ? roleFunc.eval(context) : context.state().mover();
// We get the regions to connect.
final int playerRegion = (roleFunc == null) ? Constants.UNDEFINED : roleFunc.eval(context);
List<TIntArrayList> sitesRegions;
if (precomputedSitesRegions == null)
{
final RegionFunction[] regionsToConnect = regionsToConnectFn;
sitesRegions = new ArrayList<TIntArrayList>();
if (regionsToConnect != null)
{
for (final RegionFunction regionToConnect : regionsToConnect)
sitesRegions.add(new TIntArrayList(regionToConnect.eval(context).sites()));
}
else
{
if (staticRegions != null)
{
// Conversion of the static region.
final Integer[][] regionSets = staticRegions.convertStaticRegionOnLocs(staticRegions.regionTypes()[0], context);
for (final Integer[] region : regionSets)
{
final TIntArrayList regionToAdd = new TIntArrayList();
for (final Integer site : region)
regionToAdd.add(site.intValue());
if (regionToAdd.size() > 0)
sitesRegions.add(regionToAdd);
}
}
else
{
if (precomputedOwnedRegions != null)
{
for (final TIntArrayList preComputedRegions : precomputedOwnedRegions.get(playerRegion))
sitesRegions.add(preComputedRegions);
}
else
{
// Get the regions to connect.
for (final Regions region : game.equipment().regions())
{
if (region.owner() == playerRegion)
{
if (region.region() != null)
{
for (final RegionFunction r : region.region())
sitesRegions.add(new TIntArrayList(r.eval(context).sites()));
}
else
{
final TIntArrayList bitSet = new TIntArrayList();
for (final int site : region.sites())
bitSet.add(site);
sitesRegions.add(bitSet);
}
}
}
}
}
}
}
else // Already precomputed.
{
sitesRegions = new ArrayList<TIntArrayList>(precomputedSitesRegions);
}
final int numRegionToConnect = (number != null) ? number.eval(context) : sitesRegions.size();
final TIntArrayList originalRegion = sitesRegions.get(0);
for (int i = 0; i < originalRegion.size(); i++)
{
final ArrayList<TIntArrayList> othersRegionToConnect = new ArrayList<TIntArrayList>(sitesRegions);
// We remove the region from when we start to look
othersRegionToConnect.remove(0);
final int from = originalRegion.get(i);
// We get the group of sites connected from the location owned by the owner or
// empty.
final TIntArrayList groupSites = new TIntArrayList();
if (cs.who(from, realType) == who || cs.what(from, realType) == 0)
groupSites.add(from);
// Counter of connected regions.
int numRegionConnected = 0;
// Already one region connected.
numRegionConnected++;
if (numRegionConnected == numRegionToConnect)
return false;
if (groupSites.size() > 0)
{
final TIntArrayList sitesExplored = new TIntArrayList();
int j = 0;
while (sitesExplored.size() != groupSites.size())
{
final int site = groupSites.get(j);
final TopologyElement siteElement = topology.getGraphElements(realType).get(site);
final List<AbsoluteDirection> directions = dirnChoice.convertToAbsolute(realType, siteElement, null,
null, null, context);
for (final AbsoluteDirection direction : directions)
{
final List<game.util.graph.Step> steps = topology.trajectories().steps(realType,
siteElement.index(), realType, direction);
for (final game.util.graph.Step step : steps)
{
final int to = step.to().id();
// If we already have it we continue to look the others.
if (groupSites.contains(to))
continue;
// New element in the group.
if (who == cs.who(to, realType) || cs.what(to, realType) == 0)
{
groupSites.add(to);
// Check if that element is in one of the regions to connect.
for (int k = othersRegionToConnect.size() - 1; k >= 0; k--)
{
final TIntArrayList regionToConnect = othersRegionToConnect.get(k);
if (regionToConnect.contains(to))
{
numRegionConnected++;
// Region is connected we remove it.
othersRegionToConnect.remove(k);
}
// If enough regions connected we return false.
if (numRegionConnected == numRegionToConnect)
return false;
}
}
}
}
sitesExplored.add(site);
j++;
}
}
}
return true;
}
//-------------------------------------------------------------------------
@Override
public String toString()
{
String str = "";
str += "IsBlocked";
return str;
}
//-------------------------------------------------------------------------
@Override
public boolean isStatic()
{
return false;
}
@Override
public long gameFlags(final Game game)
{
long flags = 0l;
if (regionsToConnectFn != null)
{
for (final RegionFunction regionFunc : regionsToConnectFn)
{
if (regionFunc != null)
flags |= regionFunc.gameFlags(game);
}
}
flags |= SiteType.gameFlags(type);
if (number != null)
flags |= number.gameFlags(game);
return flags;
}
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
concepts.or(SiteType.concepts(type));
if (dirnChoice != null)
concepts.or(dirnChoice.concepts(game));
if (regionsToConnectFn != null)
{
for (final RegionFunction regionFunc : regionsToConnectFn)
{
if (regionFunc != null)
concepts.or(regionFunc.concepts(game));
}
}
if (number != null)
concepts.or(number.concepts(game));
return concepts;
}
@Override
public BitSet writesEvalContextRecursive()
{
final BitSet writeEvalContext = new BitSet();
if (dirnChoice != null)
writeEvalContext.or(dirnChoice.writesEvalContextRecursive());
if (regionsToConnectFn != null)
{
for (final RegionFunction regionFunc : regionsToConnectFn)
{
if (regionFunc != null)
writeEvalContext.or(regionFunc.writesEvalContextRecursive());
}
}
if (number != null)
writeEvalContext.or(number.writesEvalContextRecursive());
return writeEvalContext;
}
@Override
public BitSet readsEvalContextRecursive()
{
final BitSet readEvalContext = new BitSet();
if (dirnChoice != null)
readEvalContext.or(dirnChoice.readsEvalContextRecursive());
if (regionsToConnectFn != null)
{
for (final RegionFunction regionFunc : regionsToConnectFn)
{
if (regionFunc != null)
readEvalContext.or(regionFunc.readsEvalContextRecursive());
}
}
if (number != null)
readEvalContext.or(number.readsEvalContextRecursive());
return readEvalContext;
}
@Override
public boolean missingRequirement(final Game game)
{
boolean missingRequirement = false;
if (regionsToConnectFn != null)
{
for (final RegionFunction regionFunc : regionsToConnectFn)
{
if (regionFunc != null)
missingRequirement |= regionFunc.missingRequirement(game);
}
}
if (number != null)
missingRequirement |= number.missingRequirement(game);
return missingRequirement;
}
@Override
public boolean willCrash(final Game game)
{
boolean willCrash = false;
if (regionsToConnectFn != null)
{
for (final RegionFunction regionFunc : regionsToConnectFn)
{
if (regionFunc != null)
willCrash |= regionFunc.willCrash(game);
}
}
if (number != null)
willCrash |= number.willCrash(game);
return willCrash;
}
@Override
public void preprocess(final Game game)
{
type = SiteType.use(type, game);
if (number != null)
number.preprocess(game);
// Precomputation of the regions to connect if they are static.
// Look the array of regions to connect.
if (regionsToConnectFn != null)
{
boolean allStatic = true;
for (final RegionFunction regionFunc : regionsToConnectFn)
{
if (regionFunc != null && !regionFunc.isStatic())
{
allStatic = false;
break;
}
}
if (allStatic)
{
precomputedSitesRegions = new ArrayList<TIntArrayList>();
for (final RegionFunction regionToConnect : regionsToConnectFn)
if (regionToConnect != null)
{
precomputedSitesRegions.add(
new TIntArrayList(regionToConnect.eval(new Context(game, new Trial(game))).sites()));
}
}
}
else
{
// Look the static regions used in entry.
if (staticRegions != null)
{
precomputedSitesRegions = new ArrayList<TIntArrayList>();
final Integer[][] regionSets = staticRegions.convertStaticRegionOnLocs(staticRegions.regionTypes()[0],
new Context(game, new Trial(game)));
for (final Integer[] region : regionSets)
{
final TIntArrayList regionToAdd = new TIntArrayList();
for (final Integer site : region)
regionToAdd.add(site.intValue());
if (regionToAdd.size() > 0)
precomputedSitesRegions.add(regionToAdd);
}
}
// Look the regions owned.
else
{
if (roleFunc != null)
{
boolean allStatic = true;
for (final Regions region : game.equipment().regions())
{
if (!region.isStatic())
{
allStatic = false;
break;
}
}
if (allStatic)
{
precomputedOwnedRegions = new ArrayList<List<TIntArrayList>>();
for (int i = 0; i < game.players().size(); i++)
precomputedOwnedRegions.add(new ArrayList<TIntArrayList>());
for (final Regions region : game.equipment().regions())
{
if (region.region() != null)
{
for (final RegionFunction r : region.region())
{
final TIntArrayList sitesToConnect = new TIntArrayList(
r.eval(new Context(game, new Trial(game))).sites());
precomputedOwnedRegions.get(region.owner()).add(sitesToConnect);
}
}
else
{
final TIntArrayList sitesToConnect = new TIntArrayList();
for (final int site : region.sites())
sitesToConnect.add(site);
precomputedOwnedRegions.get(region.owner()).add(sitesToConnect);
}
}
}
}
}
}
}
} | 14,117 | 26.574219 | 117 | java |
Ludii | Ludii-master/Core/src/game/functions/booleans/is/connect/IsConnected.java | package game.functions.booleans.is.connect;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.List;
import annotations.Hide;
import annotations.Name;
import annotations.Opt;
import annotations.Or;
import game.Game;
import game.equipment.other.Regions;
import game.functions.booleans.BaseBooleanFunction;
import game.functions.directions.Directions;
import game.functions.directions.DirectionsFunction;
import game.functions.ints.IntFunction;
import game.functions.ints.last.LastTo;
import game.functions.region.RegionFunction;
import game.types.board.RegionTypeStatic;
import game.types.board.SiteType;
import game.types.play.RoleType;
import game.util.directions.AbsoluteDirection;
import game.util.directions.Direction;
import gnu.trove.list.array.TIntArrayList;
import main.Constants;
import main.collections.ChunkSet;
import other.concept.Concept;
import other.context.Context;
import other.location.FullLocation;
import other.location.Location;
import other.state.container.ContainerState;
import other.topology.Topology;
import other.topology.TopologyElement;
import other.trial.Trial;
/**
* Is used to detect if regions are connected by a group of pieces.
*
* @author Eric.Piette and tahmina (for UF version)
*/
@Hide
public final class IsConnected extends BaseBooleanFunction
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/** The regions to connect. */
private final RegionFunction[] regionsToConnectFn;
/** The owner of the regions. */
private final IntFunction roleFunc;
/** The different regions of the regionType. */
private final Regions staticRegions;
/** The minimum number of regions to connect */
private final IntFunction number;
/** The SiteType of the sites to look. */
private SiteType type;
/** The starting location of the group of pieces. */
private final IntFunction startLocationFn;
/** Direction chosen. */
private final DirectionsFunction dirnChoice;
//-------------------------Pre-computation------------------------------------------
/** The pre-computed regions to connect. */
private List<ChunkSet> precomputedSitesRegions;
/** The pre-computed owned regions. */
private List<List<ChunkSet>> precomputedOwnedRegions;
//-------------------------------------------------------------------------
/**
* @param number The minimum number of regions to connect [0].
* @param type The graph element type [default SiteType of the board].
* @param at The specific starting position need to connect.
* @param directions The directions of the connected pieces used to connect the
* region [Adjacent].
* @param regions The disjoint regions set, which need to use for connection.
* @param role Role of the player.
* @param regionType Type of the regions.
*/
public IsConnected
(
@Opt final IntFunction number,
@Opt final SiteType type,
@Opt @Name final IntFunction at,
@Opt final Direction directions,
@Or final RegionFunction[] regions,
@Or final RoleType role,
@Or final RegionTypeStatic regionType
)
{
int numNonNull = 0;
if (regions != null) numNonNull++;
if (role != null) numNonNull++;
if (regionType != null) numNonNull++;
if (numNonNull != 1) throw new IllegalArgumentException("Exactly one Or parameter must be non-null.");
startLocationFn = at == null ? new LastTo(null) : at;
regionsToConnectFn = regions;
roleFunc = (role == null) ? null : RoleType.toIntFunction(role);
staticRegions = (regionType == null) ? null : new game.equipment.other.Regions(null, null, null, null, null, regionType, null, null);
this.type = type;
this.number = number;
dirnChoice = (directions != null) ? directions.directionsFunctions()
: new Directions(AbsoluteDirection.Adjacent, null);
}
//-------------------------------------------------------------------------
@Override
public boolean eval(final Context context)
{
final Game game = context.game();
final int from = startLocationFn.eval(context);
// Check if this is a site.
if (from < 0)
return false;
final Topology topology = context.topology();
final SiteType realType = (type != null) ? type : context.game().board().defaultSite();
// Check if the site is in the board.
final List<? extends TopologyElement> realTypeElements = topology.getGraphElements(realType);
if (from >= realTypeElements.size())
return false;
final ContainerState cs = context.containerState(0);
final int who = cs.who(from, realType);
// Check if the site is not empty.
if (who <= 0)
return false;
// We get the regions to connect.
final int playerRegion = (roleFunc == null) ? Constants.UNDEFINED : roleFunc.eval(context);
List<ChunkSet> sitesRegions;
if (precomputedSitesRegions == null)
{
final RegionFunction[] regionsToConnect = regionsToConnectFn;
sitesRegions = new ArrayList<ChunkSet>();
if (regionsToConnect != null)
{
for (final RegionFunction regionToConnect : regionsToConnect)
sitesRegions.add(regionToConnect.eval(context).bitSet());
}
else
{
if (staticRegions != null)
{
// Conversion of the static region.
final Integer[][] regionSets = staticRegions
.convertStaticRegionOnLocs(staticRegions.regionTypes()[0], context);
for (final Integer[] region : regionSets)
{
final ChunkSet regionToAdd = new ChunkSet();
for (final Integer site : region)
regionToAdd.set(site.intValue());
if (regionToAdd.size() > 0)
sitesRegions.add(regionToAdd);
}
}
else
{
if (precomputedOwnedRegions != null)
{
for (final ChunkSet preComputedRegions : precomputedOwnedRegions.get(playerRegion))
sitesRegions.add(preComputedRegions);
}
else
{
// Get the regions to connect.
for (final Regions region : game.equipment().regions())
{
if (region.owner() == playerRegion)
{
if (region.region() != null)
{
for (final RegionFunction r : region.region())
sitesRegions.add(r.eval(context).bitSet());
}
else
{
final ChunkSet bitSet = new ChunkSet();
for (final int site : region.sites())
bitSet.set(site);
sitesRegions.add(bitSet);
}
}
}
}
}
}
}
else // Already precomputed.
{
sitesRegions = new ArrayList<ChunkSet>(precomputedSitesRegions);
}
final int numRegionToConnect = (number != null) ? number.eval(context) : sitesRegions.size();
// We get the group of sites connected from the location.
final TIntArrayList groupSites = new TIntArrayList();
if (cs.who(from, realType) == playerRegion || playerRegion == Constants.UNDEFINED)
groupSites.add(from);
// Counter of connected regions.
int numRegionConnected = 0;
// Check if the origin of the connected group is in one of the regions to
// connect.
for (int j = sitesRegions.size() - 1; j >= 0; j--)
{
final ChunkSet regionToConnect = sitesRegions.get(j);
if (regionToConnect.get(from))
{
numRegionConnected++;
// Region is connected we remove it.
sitesRegions.remove(j);
}
if (numRegionConnected == numRegionToConnect)
return true;
}
if (groupSites.size() > 0)
{
final boolean[] visited = new boolean[realTypeElements.size()];
visited[from] = true;
int i = 0;
while (i < groupSites.size())
{
final int site = groupSites.getQuick(i);
final TopologyElement siteElement = realTypeElements.get(site);
final List<AbsoluteDirection> directions = dirnChoice.convertToAbsolute(realType, siteElement, null,
null,
null, context);
for (final AbsoluteDirection direction : directions)
{
final List<game.util.graph.Step> steps = topology.trajectories().steps(realType,
site, realType, direction);
for (final game.util.graph.Step step : steps)
{
final int to = step.to().id();
// If we already have it we continue to look the others.
if (visited[to])
continue;
visited[to] = true;
// New element in the group.
if (who == cs.who(to, realType))
{
// Check if that element is in one of the regions to connect.
for (int j = sitesRegions.size() - 1; j >= 0; j--)
{
final ChunkSet regionToConnect = sitesRegions.get(j);
if (regionToConnect.get(to))
{
numRegionConnected++;
// If enough regions connected we return true.
// Do this inside loop because we almost always expect
// to enter this if-block only once per loop anyway
if (numRegionConnected == numRegionToConnect)
return true;
// Region is connected we remove it.
sitesRegions.remove(j);
}
}
groupSites.add(to);
}
}
}
i++;
}
}
return false;
}
//------------------------------------------------------------------------
@Override
public String toString()
{
String str = "";
str += "IsConnected (" + regionsToConnectFn + ")";
return str;
}
//-------------------------------------------------------------------------
@Override
public boolean isStatic()
{
return false;
}
@Override
public long gameFlags(final Game game)
{
long flags = 0L;
if (regionsToConnectFn != null)
{
for (final RegionFunction regionFunc : regionsToConnectFn)
{
if (regionFunc != null)
flags |= regionFunc.gameFlags(game);
}
}
flags |= SiteType.gameFlags(type);
if (number != null)
flags |= number.gameFlags(game);
return flags;
}
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
concepts.or(super.concepts(game));
concepts.or(SiteType.concepts(type));
concepts.set(Concept.Connection.id(), true);
if (dirnChoice != null)
concepts.or(dirnChoice.concepts(game));
if (regionsToConnectFn != null)
{
for (final RegionFunction regionFunc : regionsToConnectFn)
{
if (regionFunc != null)
concepts.or(regionFunc.concepts(game));
}
}
if (number != null)
concepts.or(number.concepts(game));
return concepts;
}
@Override
public BitSet writesEvalContextRecursive()
{
final BitSet writeEvalContext = new BitSet();
if (dirnChoice != null)
writeEvalContext.or(dirnChoice.writesEvalContextRecursive());
if (regionsToConnectFn != null)
{
for (final RegionFunction regionFunc : regionsToConnectFn)
{
if (regionFunc != null)
writeEvalContext.or(regionFunc.writesEvalContextRecursive());
}
}
if (number != null)
writeEvalContext.or(number.writesEvalContextRecursive());
return writeEvalContext;
}
@Override
public BitSet readsEvalContextRecursive()
{
final BitSet readEvalContext = new BitSet();
if (dirnChoice != null)
readEvalContext.or(dirnChoice.readsEvalContextRecursive());
if (regionsToConnectFn != null)
{
for (final RegionFunction regionFunc : regionsToConnectFn)
{
if (regionFunc != null)
readEvalContext.or(regionFunc.readsEvalContextRecursive());
}
}
if (number != null)
readEvalContext.or(number.readsEvalContextRecursive());
return readEvalContext;
}
@Override
public boolean missingRequirement(final Game game)
{
boolean missingRequirement = false;
if (regionsToConnectFn != null)
{
for (final RegionFunction regionFunc : regionsToConnectFn)
{
if (regionFunc != null)
missingRequirement |= regionFunc.missingRequirement(game);
}
}
if (number != null)
missingRequirement |= number.missingRequirement(game);
return missingRequirement;
}
@Override
public boolean willCrash(final Game game)
{
boolean willCrash = false;
if (regionsToConnectFn != null)
{
for (final RegionFunction regionFunc : regionsToConnectFn)
{
if (regionFunc != null)
willCrash |= regionFunc.willCrash(game);
}
}
if (number != null)
willCrash |= number.willCrash(game);
return willCrash;
}
@Override
public void preprocess(final Game game)
{
type = SiteType.use(type, game);
if (regionsToConnectFn != null)
{
for (final RegionFunction regionFunc : regionsToConnectFn)
{
if (regionFunc != null)
regionFunc.preprocess(game);
}
}
if (number != null)
number.preprocess(game);
// Precomputation of the regions to connect if they are static.
// Look the array of regions to connect.
if (regionsToConnectFn != null)
{
boolean allStatic = true;
for (final RegionFunction regionFunc : regionsToConnectFn)
{
if (regionFunc != null && !regionFunc.isStatic())
{
allStatic = false;
break;
}
}
if (allStatic)
{
precomputedSitesRegions = new ArrayList<ChunkSet>();
for (final RegionFunction regionToConnect : regionsToConnectFn)
if (regionToConnect != null)
{
precomputedSitesRegions.add(
regionToConnect.eval(new Context(game, new Trial(game))).bitSet());
}
}
}
else
{
// Look the static regions used in entry.
if (staticRegions != null)
{
precomputedSitesRegions = new ArrayList<ChunkSet>();
final Integer[][] regionSets = staticRegions.convertStaticRegionOnLocs(staticRegions.regionTypes()[0],
new Context(game, new Trial(game)));
for (final Integer[] region : regionSets)
{
final ChunkSet regionToAdd = new ChunkSet();
for (final Integer site : region)
regionToAdd.set(site.intValue());
if (regionToAdd.size() > 0)
precomputedSitesRegions.add(regionToAdd);
}
}
// Look the regions owned.
else
{
if (roleFunc != null)
{
boolean allStatic = true;
for (final Regions region : game.equipment().regions())
{
if (!region.isStatic())
{
allStatic = false;
break;
}
}
if (allStatic)
{
precomputedOwnedRegions = new ArrayList<List<ChunkSet>>();
for (int i = 0; i < game.players().size(); i++)
precomputedOwnedRegions.add(new ArrayList<ChunkSet>());
for (final Regions region : game.equipment().regions())
{
if (region.region() != null)
{
for (final RegionFunction r : region.region())
{
final ChunkSet sitesToConnect =
r.eval(new Context(game, new Trial(game))).bitSet();
precomputedOwnedRegions.get(region.owner()).add(sitesToConnect);
}
}
else
{
final ChunkSet sitesToConnect = new ChunkSet();
for (final int site : region.sites())
sitesToConnect.set(site);
precomputedOwnedRegions.get(region.owner()).add(sitesToConnect);
}
}
}
}
}
}
}
// ----------------------Visualisation for the GUI---------------------------------------
@Override
public List<Location> satisfyingSites(final Context context)
{
if (!eval(context))
return new ArrayList<Location>();
final List<Location> winningSites = new ArrayList<Location>();
final Game game = context.game();
final int from = (startLocationFn == null) ? context.trial().lastMove().toNonDecision()
: startLocationFn.eval(context);
// Check if this is a site.
if (from < 0)
return new ArrayList<Location>();
final Topology topology = context.topology();
final SiteType realType = (type != null) ? type : context.game().board().defaultSite();
// Check if the site is in the board.
if (from >= topology.getGraphElements(realType).size())
return new ArrayList<Location>();
final ContainerState cs = context.containerState(0);
final int who = cs.who(from, type);
// Check if the site is not empty.
if (who <= 0)
return new ArrayList<Location>();
// We get the regions to connect.
final int playerRegion = (roleFunc == null) ? Constants.UNDEFINED : roleFunc.eval(context);
List<ChunkSet> sitesRegions;
if (precomputedSitesRegions == null)
{
final RegionFunction[] regionsToConnect = regionsToConnectFn;
sitesRegions = new ArrayList<ChunkSet>();
if (regionsToConnect != null)
{
for (final RegionFunction regionToConnect : regionsToConnect)
sitesRegions.add(regionToConnect.eval(context).bitSet());
}
else
{
if (staticRegions != null)
{
// Conversion of the static region.
final Integer[][] regionSets = staticRegions
.convertStaticRegionOnLocs(staticRegions.regionTypes()[0], context);
for (final Integer[] region : regionSets)
{
final ChunkSet regionToAdd = new ChunkSet();
for (final Integer site : region)
regionToAdd.set(site.intValue());
if (regionToAdd.size() > 0)
sitesRegions.add(regionToAdd);
}
}
else
{
if (precomputedOwnedRegions != null)
{
for (final ChunkSet preComputedRegions : precomputedOwnedRegions.get(playerRegion))
sitesRegions.add(preComputedRegions);
}
else
{
// Get the regions to connect.
for (final Regions region : game.equipment().regions())
{
if (region.owner() == playerRegion)
{
if (region.region() != null)
{
for (final RegionFunction r : region.region())
sitesRegions.add(r.eval(context).bitSet());
}
else
{
final ChunkSet bitSet = new ChunkSet();
for (final int site : region.sites())
bitSet.set(site);
sitesRegions.add(bitSet);
}
}
}
}
}
}
}
else // Already precomputed.
{
sitesRegions = new ArrayList<ChunkSet>(precomputedSitesRegions);
}
final int numRegionToConnect = (number != null) ? number.eval(context) : sitesRegions.size();
// We get the group of sites connected from the location.
final TIntArrayList groupSites = new TIntArrayList();
if (cs.who(from, realType) == playerRegion || playerRegion == Constants.UNDEFINED)
groupSites.add(from);
winningSites.add(new FullLocation(from, 0, realType));
// Counter of connected regions.
int numRegionConnected = 0;
// Check if the origin of the connected group is in one of the regions to
// connect.
for (int j = sitesRegions.size() - 1; j >= 0; j--)
{
final ChunkSet regionToConnect = sitesRegions.get(j);
if (regionToConnect.get(from))
{
numRegionConnected++;
// Region is connected we remove it.
sitesRegions.remove(j);
}
if (numRegionConnected == numRegionToConnect)
return filterWinningSites(context, winningSites);
}
if (groupSites.size() > 0)
{
final TIntArrayList sitesExplored = new TIntArrayList();
int i = 0;
while (sitesExplored.size() != groupSites.size())
{
final int site = groupSites.get(i);
final TopologyElement siteElement = topology.getGraphElements(realType).get(site);
final List<AbsoluteDirection> directions = dirnChoice.convertToAbsolute(realType, siteElement, null,
null,
null, context);
for (final AbsoluteDirection direction : directions)
{
final List<game.util.graph.Step> steps = topology.trajectories().steps(realType,
siteElement.index(), realType, direction);
for (final game.util.graph.Step step : steps)
{
final int to = step.to().id();
// If we already have it we continue to look the others.
if (groupSites.contains(to))
continue;
// New element in the group.
if (who == cs.who(to, realType))
{
groupSites.add(to);
winningSites.add(new FullLocation(to, 0, realType));
// Check if that element is in one of the regions to connect.
for (int j = sitesRegions.size() - 1; j >= 0; j--)
{
final ChunkSet regionToConnect = sitesRegions.get(j);
if (regionToConnect.get(to))
{
numRegionConnected++;
// Region is connected we remove it.
sitesRegions.remove(j);
}
// If enough regions connected we return true.
if (numRegionConnected == numRegionToConnect)
return filterWinningSites(context, winningSites);
}
}
}
}
sitesExplored.add(site);
i++;
}
}
return new ArrayList<Location>();
}
/**
* @param context the context.
* @param winningGroup The winning group detected in satisfyingSites.
* @return The minimum group of sites to connect the regions.
*/
public List<Location> filterWinningSites(final Context context, final List<Location> winningGroup)
{
final Game game = context.game();
final Topology topology = context.topology();
final SiteType realType = (type != null) ? type : context.game().board().defaultSite();
// We get the regions to connect.
final int playerRegion = (roleFunc == null) ? Constants.UNDEFINED : roleFunc.eval(context);
List<ChunkSet> sitesRegions;
if (precomputedSitesRegions == null)
{
final RegionFunction[] regionsToConnect = regionsToConnectFn;
sitesRegions = new ArrayList<ChunkSet>();
if (regionsToConnect != null)
{
for (final RegionFunction regionToConnect : regionsToConnect)
sitesRegions.add(regionToConnect.eval(context).bitSet());
}
else
{
if (staticRegions != null)
{
// Conversion of the static region.
final Integer[][] regionSets = staticRegions
.convertStaticRegionOnLocs(staticRegions.regionTypes()[0], context);
for (final Integer[] region : regionSets)
{
final ChunkSet regionToAdd = new ChunkSet();
for (final Integer site : region)
regionToAdd.set(site.intValue());
if (regionToAdd.size() > 0)
sitesRegions.add(regionToAdd);
}
}
else
{
if (precomputedOwnedRegions != null)
{
for (final ChunkSet preComputedRegions : precomputedOwnedRegions.get(playerRegion))
sitesRegions.add(preComputedRegions);
}
else
{
// Get the regions to connect.
for (final Regions region : game.equipment().regions())
{
if (region.owner() == playerRegion)
{
if (region.region() != null)
{
for (final RegionFunction r : region.region())
sitesRegions.add(r.eval(context).bitSet());
}
else
{
final ChunkSet bitSet = new ChunkSet();
for (final int site : region.sites())
bitSet.set(site);
sitesRegions.add(bitSet);
}
}
}
}
}
}
}
else // Already precomputed.
{
sitesRegions = new ArrayList<ChunkSet>(precomputedSitesRegions);
}
final int numRegionToConnect = (number != null) ? number.eval(context) : sitesRegions.size();
// Minimum group to connect the regions.
final List<Location> minimumGroup = new ArrayList<Location>(winningGroup);
for (int i = minimumGroup.size() - 1; i >= 0; i--)
{
final TIntArrayList groupMinusI = new TIntArrayList();
for (int j = 0; j < minimumGroup.size(); j++)
if(j != i)
groupMinusI.add(minimumGroup.get(j).site());
// System.out.println("groupMinusI is" + groupMinusI);
// Check if all the pieces are in one group.
if (groupMinusI.isEmpty())
continue;
final int startGroup = groupMinusI.get(0);
final TIntArrayList groupSites = new TIntArrayList();
groupSites.add(startGroup);
if (groupSites.size() > 0)
{
final TIntArrayList sitesExplored = new TIntArrayList();
int k = 0;
while (sitesExplored.size() != groupSites.size())
{
final int site = groupSites.get(k);
final TopologyElement siteElement = topology.getGraphElements(realType).get(site);
final List<AbsoluteDirection> directions = dirnChoice.convertToAbsolute(realType, siteElement, null,
null, null, context);
for (final AbsoluteDirection direction : directions)
{
final List<game.util.graph.Step> steps = topology.trajectories().steps(realType,
siteElement.index(), realType, direction);
for (final game.util.graph.Step step : steps)
{
final int to = step.to().id();
// If we already have it we continue to look the others.
if (groupSites.contains(to))
continue;
// New element in the group.
if (groupMinusI.contains(to))
groupSites.add(to);
}
}
sitesExplored.add(site);
k++;
}
}
final boolean oneSingleGroup = (groupSites.size() == groupMinusI.size());
// Check if the connected regions are still connected.
// Counter of connected regions.
int numRegionConnected = 0;
// Check if that element is in one of the regions to connect.
for (int j = sitesRegions.size() - 1; j >= 0; j--)
{
final ChunkSet regionToConnect = sitesRegions.get(j);
for (int siteToCheck = regionToConnect.nextSetBit(0); siteToCheck >= 0; siteToCheck = regionToConnect.nextSetBit(siteToCheck + 1))
{
if (groupMinusI.contains(siteToCheck))
{
numRegionConnected++;
break;
}
}
// If enough regions connected we return true.
if (numRegionConnected == numRegionToConnect)
{
break;
}
}
if (oneSingleGroup && numRegionConnected == numRegionToConnect)
minimumGroup.remove(i);
}
return minimumGroup;
}
//-------------------------------------------------------------------------
@Override
public String toEnglish(final Game game)
{
String regionsString = "regions";
String numberString = "";
if (regionsToConnectFn != null)
{
for (RegionFunction region : regionsToConnectFn)
regionsString += region.toEnglish(game) + ", ";
regionsString = regionsString.substring(0, regionsString.length()-2);
}
else if (this.roleFunc != null)
regionsString = "region(s) of " + roleFunc.toEnglish(game);
else
regionsString = "region(s) of the mover";
if (number != null)
numberString = " by "+ number.toEnglish(game);
return "the " + regionsString + " are connected" + numberString;
}
//-------------------------------------------------------------------------
}
| 26,119 | 27.055854 | 135 | java |
Ludii | Ludii-master/Core/src/game/functions/booleans/is/edge/IsCrossing.java | package game.functions.booleans.is.edge;
import java.util.BitSet;
import annotations.Hide;
import game.Game;
import game.functions.booleans.BaseBooleanFunction;
import game.functions.ints.IntFunction;
import game.types.state.GameType;
import other.context.Context;
/**
* Checks if two edges are crossing.
*
* @author Eric.Piette
*/
@Hide
public final class IsCrossing extends BaseBooleanFunction
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/** First edge. */
private final IntFunction edge1Fn;
/** Second edge. */
private final IntFunction edge2Fn;
/** Precomputed boolean. */
private Boolean precomputedBoolean;
//-------------------------------------------------------------------------
/**
* @param edge1 The index of the first edge.
* @param edge2 The index of the second edge.
*/
public IsCrossing
(
final IntFunction edge1,
final IntFunction edge2
)
{
this.edge1Fn = edge1;
this.edge2Fn = edge2;
}
//-------------------------------------------------------------------------
@Override
public boolean eval(final Context context)
{
if (precomputedBoolean != null)
return precomputedBoolean.booleanValue();
final int edge1 = edge1Fn.eval(context);
final int edge2 = edge2Fn.eval(context);
if (
edge1 < 0
||
edge2 < 0
||
edge1 >= context.topology().edges().size()
||
edge2 >= context.topology().edges().size()
)
return false;
return context.topology().edges().get(edge1).doesCross(edge2);
}
//-------------------------------------------------------------------------
@Override
public boolean isStatic()
{
return this.edge1Fn.isStatic() && this.edge2Fn.isStatic();
}
@Override
public long gameFlags(final Game game)
{
return edge1Fn.gameFlags(game) | edge2Fn.gameFlags(game) | GameType.Edge | GameType.Graph;
}
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
concepts.or(edge1Fn.concepts(game));
concepts.or(edge2Fn.concepts(game));
return concepts;
}
@Override
public BitSet writesEvalContextRecursive()
{
final BitSet writeEvalContext = new BitSet();
writeEvalContext.or(edge1Fn.writesEvalContextRecursive());
writeEvalContext.or(edge2Fn.writesEvalContextRecursive());
return writeEvalContext;
}
@Override
public BitSet readsEvalContextRecursive()
{
final BitSet readEvalContext = new BitSet();
readEvalContext.or(edge1Fn.readsEvalContextRecursive());
readEvalContext.or(edge2Fn.readsEvalContextRecursive());
return readEvalContext;
}
@Override
public void preprocess(final Game game)
{
edge1Fn.preprocess(game);
edge2Fn.preprocess(game);
if (isStatic())
precomputedBoolean = Boolean.valueOf(eval(new Context(game, null)));
}
@Override
public boolean missingRequirement(final Game game)
{
boolean missingRequirement = false;
missingRequirement |= edge1Fn.missingRequirement(game);
missingRequirement |= edge2Fn.missingRequirement(game);
return missingRequirement;
}
@Override
public boolean willCrash(final Game game)
{
boolean willCrash = false;
willCrash |= edge1Fn.willCrash(game);
willCrash |= edge2Fn.willCrash(game);
return willCrash;
}
} | 3,271 | 22.042254 | 92 | java |
Ludii | Ludii-master/Core/src/game/functions/booleans/is/graph/IsLastFrom.java | package game.functions.booleans.is.graph;
import java.util.BitSet;
import annotations.Hide;
import game.Game;
import game.functions.booleans.BaseBooleanFunction;
import game.types.board.SiteType;
import other.context.Context;
/**
* Checks if the from location of the last move is a specific graph element
* type.
*
* @author Eric.Piette
*/
@Hide
public final class IsLastFrom extends BaseBooleanFunction
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/** The graph Element Type to check. */
private final SiteType type;
//-------------------------------------------------------------------------
/**
* @param type The graph element type to check.
*/
public IsLastFrom
(
final SiteType type
)
{
this.type = type;
}
//-------------------------------------------------------------------------
@Override
public boolean eval(final Context context)
{
return context.trial().lastMove().fromType() == type;
}
//-------------------------------------------------------------------------
@Override
public boolean isStatic()
{
return false;
}
@Override
public long gameFlags(final Game game)
{
return SiteType.gameFlags(type);
}
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
concepts.or(SiteType.concepts(type));
return concepts;
}
@Override
public BitSet writesEvalContextRecursive()
{
final BitSet writeEvalContext = new BitSet();
return writeEvalContext;
}
@Override
public BitSet readsEvalContextRecursive()
{
final BitSet readEvalContext = new BitSet();
return readEvalContext;
}
@Override
public void preprocess(final Game game)
{
// Nothing to do.
}
}
| 1,767 | 18.644444 | 76 | java |
Ludii | Ludii-master/Core/src/game/functions/booleans/is/graph/IsLastTo.java | package game.functions.booleans.is.graph;
import java.util.BitSet;
import annotations.Hide;
import game.Game;
import game.functions.booleans.BaseBooleanFunction;
import game.types.board.SiteType;
import other.context.Context;
/**
* Checks if the to location of the last move is a specific graph element type.
*
* @author Eric.Piette
*/
@Hide
public final class IsLastTo extends BaseBooleanFunction
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/** The graph Element Type to check. */
private final SiteType type;
//-------------------------------------------------------------------------
/**
* @param type The graph element type to check.
*/
public IsLastTo
(
final SiteType type
)
{
this.type = type;
}
//-------------------------------------------------------------------------
@Override
public boolean eval(final Context context)
{
return context.trial().lastMove().toType() == type;
}
//-------------------------------------------------------------------------
@Override
public boolean isStatic()
{
return false;
}
@Override
public long gameFlags(final Game game)
{
return SiteType.gameFlags(type);
}
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
concepts.or(SiteType.concepts(type));
return concepts;
}
@Override
public BitSet writesEvalContextRecursive()
{
final BitSet writeEvalContext = new BitSet();
return writeEvalContext;
}
@Override
public BitSet readsEvalContextRecursive()
{
final BitSet readEvalContext = new BitSet();
return readEvalContext;
}
@Override
public void preprocess(final Game game)
{
// Nothing to do.
}
//-------------------------------------------------------------------------
@Override
public String toEnglish(final Game game)
{
return "the last to locations is on a " + type.name().toLowerCase();
}
//-------------------------------------------------------------------------
}
| 2,046 | 19.676768 | 79 | java |
Ludii | Ludii-master/Core/src/game/functions/booleans/is/in/IsIn.java | package game.functions.booleans.is.in;
import java.util.BitSet;
import annotations.Hide;
import annotations.Opt;
import annotations.Or;
import annotations.Or2;
import game.Game;
import game.functions.booleans.BaseBooleanFunction;
import game.functions.booleans.BooleanFunction;
import game.functions.intArray.IntArrayFunction;
import game.functions.ints.IntFunction;
import game.functions.ints.iterator.To;
import game.functions.region.RegionFunction;
import main.Constants;
import other.concept.Concept;
import other.context.Context;
/**
* Tests if a specific location is in a region.
*
* @author mrraow and cambolbro
*/
@Hide
public final class IsIn extends BaseBooleanFunction
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/** Which site. */
private final IntFunction[] sites;
/** Which region. */
private final RegionFunction region;
/** Which array. */
private final IntArrayFunction array;
//-------------------------------------------------------------------------
/**
* @param site The site to check if they are in the region [(to)].
* @param sites The sites to check if they are in the region.
* @param containsRegion The region possibly containing the site(s).
*/
@SuppressWarnings("javadoc")
public static BooleanFunction construct
(
@Opt @Or final IntFunction site,
@Opt @Or final IntFunction[] sites,
@Opt @Or2 final RegionFunction containsRegion,
@Opt @Or2 final IntArrayFunction array
)
{
if(array != null)
{
if (sites != null)
return new IsIn(sites, array);
else
return new IsIn(site == null ? new IntFunction[]
{ To.instance() } : new IntFunction[]
{ site }, array);
}
else
{
if (sites != null)
return new IsIn(sites, containsRegion);
else
return new InSingleSite(site == null ? To.instance() : site, containsRegion);
}
}
/**
* @param sites The sites.
* @param region The region.
*/
private IsIn
(
final IntFunction[] sites,
final IntArrayFunction array
)
{
this.sites = sites;
region = null;
this.array = array;
}
/**
* @param sites The sites.
* @param region The region.
*/
private IsIn
(
final IntFunction[] sites,
final RegionFunction region
)
{
// TODO should probably make this a construct() method such that we can
// also jump to the single-site case if we're given an array of length 1?
this.sites = sites;
this.region = region;
array = null;
}
//-------------------------------------------------------------------------
@Override
public String toEnglish(final Game game)
{
String sitesString = "[";
for (final IntFunction i : sites)
sitesString += i.toEnglish(game) + ",";
sitesString = sitesString.substring(0,sitesString.length()-1);
sitesString += "]";
String regionText = "";
if (region != null)
regionText = region.toEnglish(game);
else
regionText = array.toEnglish(game);
return sitesString + " is in " + regionText;
}
//-------------------------------------------------------------------------
@Override
public boolean eval(final Context context)
{
if (sites != null)
{
if (region != null)
{
for (final IntFunction site : sites)
{
final int location = site.eval(context);
if (location == Constants.OFF || !region.eval(context).bitSet().get(location))
return false;
}
}
else
{
final int[] values = array.eval(context);
for (final IntFunction site : sites)
{
final int value = site.eval(context);
boolean found = false;
for (int i = 0; i < values.length; i++)
{
if (value == values[i])
{
found = true;
break;
}
}
if (!found)
return false;
}
}
}
return true;
}
//-------------------------------------------------------------------------
@Override
public String toString()
{
if (sites.length == 1)
{
return "In(" + sites[0] + "," + region + ")";
}
else
{
String str = "In({";
for (final IntFunction site : sites)
{
str += site + " ";
}
if (region != null)
str += "}," + region + ")";
else
str += "}," + array + ")";
return str;
}
}
@Override
public boolean isStatic()
{
if (sites != null)
for (final IntFunction site : sites)
if (!site.isStatic())
return false;
if (region != null)
return region.isStatic();
else
return array.isStatic();
}
@Override
public long gameFlags(final Game game)
{
long gameFlags = 0l;
if (region != null)
gameFlags |= region.gameFlags(game);
if (array != null)
gameFlags |= array.gameFlags(game);
if (sites != null)
{
for (final IntFunction site : sites)
gameFlags |= site.gameFlags(game);
}
return gameFlags;
}
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
if (region != null)
concepts.or(region.concepts(game));
if (array != null)
concepts.or(array.concepts(game));
concepts.set(Concept.Contains.id(), true);
if (sites != null)
for (final IntFunction site : sites)
concepts.or(site.concepts(game));
return concepts;
}
@Override
public BitSet writesEvalContextRecursive()
{
final BitSet writeEvalContext = new BitSet();
if (region != null)
writeEvalContext.or(region.writesEvalContextRecursive());
if (array != null)
writeEvalContext.or(array.writesEvalContextRecursive());
if (sites != null)
for (final IntFunction site : sites)
writeEvalContext.or(site.writesEvalContextRecursive());
return writeEvalContext;
}
@Override
public BitSet readsEvalContextRecursive()
{
final BitSet readEvalContext = new BitSet();
if (region != null)
readEvalContext.or(region.readsEvalContextRecursive());
if (array != null)
readEvalContext.or(array.readsEvalContextRecursive());
if (sites != null)
for (final IntFunction site : sites)
readEvalContext.or(site.readsEvalContextRecursive());
return readEvalContext;
}
@Override
public boolean missingRequirement(final Game game)
{
boolean missingRequirement = false;
if (region != null)
missingRequirement |= region.missingRequirement(game);
if (array != null)
missingRequirement |= array.missingRequirement(game);
if (sites != null)
for (final IntFunction site : sites)
missingRequirement |= site.missingRequirement(game);
return missingRequirement;
}
@Override
public boolean willCrash(final Game game)
{
boolean willCrash = false;
if (region != null)
willCrash |= region.willCrash(game);
if (array != null)
willCrash |= array.willCrash(game);
if (sites != null)
for (final IntFunction site : sites)
willCrash |= site.willCrash(game);
return willCrash;
}
@Override
public void preprocess(final Game game)
{
if (region != null)
region.preprocess(game);
if (array != null)
array.preprocess(game);
if (sites != null)
{
for (final IntFunction site : sites)
site.preprocess(game);
}
}
//-------------------------------------------------------------------------
/**
* @return RegionFunction of this In test
*/
public RegionFunction region()
{
return region;
}
/**
* @return Sites
*/
public IntFunction[] site()
{
return sites;
}
//-------------------------------------------------------------------------
/**
* Optimised version of In ludeme for single-site arg
*
* @author Dennis Soemers
*/
private static class InSingleSite extends BaseBooleanFunction
{
private static final long serialVersionUID = 1L;
//---------------------------------------------------------------------
/** Which site. */
protected final IntFunction siteFunc;
/** Which region. */
protected final RegionFunction region;
//---------------------------------------------------------------------
/**
* @param site The site.
* @param region The region.
*
* @example (in (lastTo) (region Mover))
*/
public InSingleSite
(
final IntFunction site,
final RegionFunction region
)
{
siteFunc = site;
this.region = region;
}
//---------------------------------------------------------------------
@Override
public boolean eval(final Context context)
{
final int location = siteFunc.eval(context);
return (location >= 0 && region.contains(context, location));
}
//---------------------------------------------------------------------
@Override
public String toEnglish(final Game game)
{
return siteFunc.toEnglish(game) + " is in " + region.toEnglish(game);
}
@Override
public String toString()
{
return "In(" + siteFunc + "," + region + ")";
}
@Override
public boolean isStatic()
{
return (region.isStatic() && siteFunc.isStatic());
}
@Override
public long gameFlags(final Game game)
{
long gameFlags = region.gameFlags(game);
gameFlags |= siteFunc.gameFlags(game);
return gameFlags;
}
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
concepts.set(Concept.Contains.id(), true);
concepts.or(region.concepts(game));
concepts.or(siteFunc.concepts(game));
return concepts;
}
@Override
public BitSet writesEvalContextRecursive()
{
final BitSet writeEvalContext = new BitSet();
writeEvalContext.or(region.writesEvalContextRecursive());
writeEvalContext.or(siteFunc.writesEvalContextRecursive());
return writeEvalContext;
}
@Override
public BitSet readsEvalContextRecursive()
{
final BitSet readEvalContext = new BitSet();
readEvalContext.or(region.readsEvalContextRecursive());
readEvalContext.or(siteFunc.readsEvalContextRecursive());
return readEvalContext;
}
@Override
public void preprocess(final Game game)
{
region.preprocess(game);
siteFunc.preprocess(game);
}
@Override
public boolean missingRequirement(final Game game)
{
boolean missingRequirement = false;
missingRequirement |= region.missingRequirement(game);
missingRequirement |= siteFunc.missingRequirement(game);
return missingRequirement;
}
@Override
public boolean willCrash(final Game game)
{
boolean willCrash = false;
willCrash |= region.willCrash(game);
willCrash |= siteFunc.willCrash(game);
return willCrash;
}
}
} | 10,376 | 21.412527 | 83 | java |
Ludii | Ludii-master/Core/src/game/functions/booleans/is/integer/IsAnyDie.java | package game.functions.booleans.is.integer;
import java.util.BitSet;
import annotations.Hide;
import game.Game;
import game.functions.booleans.BaseBooleanFunction;
import game.functions.ints.IntFunction;
import game.types.state.GameType;
import other.concept.Concept;
import other.context.Context;
/**
* Returns true if any die is equal to the value.
*
* @author Eric.Piette
*/
@Hide
public final class IsAnyDie extends BaseBooleanFunction
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/** The site to check. */
private final IntFunction valueFn;
//-------------------------------------------------------------------------
/**
* @param value The value to check.
*/
public IsAnyDie(final IntFunction value)
{
valueFn = value;
}
//-------------------------------------------------------------------------
@Override
public boolean eval(final Context context)
{
if (valueFn == null)
return false;
final int value = valueFn.eval(context);
final int[] dieValues = context.state().currentDice(0);
for (final int dieValue : dieValues)
if (value == dieValue)
return true;
return false;
}
//-------------------------------------------------------------------------
@Override
public String toString()
{
return "IsDie";
}
//-------------------------------------------------------------------------
@Override
public boolean isStatic()
{
return false;
}
@Override
public long gameFlags(final Game game)
{
return GameType.Stochastic | valueFn.gameFlags(game);
}
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
concepts.or(valueFn.concepts(game));
concepts.set(Concept.Dice.id(), true);
return concepts;
}
@Override
public BitSet writesEvalContextRecursive()
{
final BitSet writeEvalContext = new BitSet();
writeEvalContext.or(valueFn.writesEvalContextRecursive());
return writeEvalContext;
}
@Override
public BitSet readsEvalContextRecursive()
{
final BitSet readEvalContext = new BitSet();
readEvalContext.or(valueFn.readsEvalContextRecursive());
return readEvalContext;
}
@Override
public void preprocess(final Game game)
{
valueFn.preprocess(game);
}
@Override
public boolean missingRequirement(final Game game)
{
boolean missingRequirement = false;
if (!game.hasHandDice())
{
game.addRequirementToReport("The ludeme (is AnyDie ...) is used but the equipment has no dice.");
missingRequirement = true;
}
missingRequirement |= valueFn.missingRequirement(game);
return missingRequirement;
}
//-------------------------------------------------------------------------
@Override
public String toEnglish(final Game game)
{
return "any die is showing " + valueFn.toEnglish(game);
}
//-------------------------------------------------------------------------
}
| 2,925 | 21.335878 | 100 | java |
Ludii | Ludii-master/Core/src/game/functions/booleans/is/integer/IsEven.java | package game.functions.booleans.is.integer;
import java.util.BitSet;
import annotations.Hide;
import game.Game;
import game.functions.booleans.BaseBooleanFunction;
import game.functions.ints.IntFunction;
import other.concept.Concept;
import other.context.Context;
/**
* Tests if an integer is even.
*
* @author mrraow and cambolbro
*
*/
@Hide
public final class IsEven extends BaseBooleanFunction
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/** Boolean condition. */
private final IntFunction value;
/** Precomputed boolean. */
private Boolean precomputedBoolean;
//-------------------------------------------------------------------------
/**
* @param value The value to test.
* @example (isEven (mover))
*/
public IsEven(final IntFunction value)
{
this.value = value;
}
//-------------------------------------------------------------------------
@Override
public boolean eval(final Context context)
{
if (precomputedBoolean != null)
return precomputedBoolean.booleanValue();
final int resolvedValue = value.eval(context);
return (resolvedValue & 1) == 0;
}
//-------------------------------------------------------------------------
@Override
public boolean isStatic()
{
return value.isStatic();
}
@Override
public long gameFlags(final Game game)
{
return value.gameFlags(game);
}
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
concepts.or(value.concepts(game));
concepts.set(Concept.Even.id(), true);
return concepts;
}
@Override
public BitSet writesEvalContextRecursive()
{
final BitSet writeEvalContext = new BitSet();
writeEvalContext.or(value.writesEvalContextRecursive());
return writeEvalContext;
}
@Override
public BitSet readsEvalContextRecursive()
{
final BitSet readEvalContext = new BitSet();
readEvalContext.or(value.readsEvalContextRecursive());
return readEvalContext;
}
@Override
public void preprocess(final Game game)
{
value.preprocess(game);
if (isStatic())
precomputedBoolean = Boolean.valueOf(eval(new Context(game, null)));
}
@Override
public boolean missingRequirement(final Game game)
{
boolean missingRequirement = false;
missingRequirement |= value.missingRequirement(game);
return missingRequirement;
}
@Override
public boolean willCrash(final Game game)
{
boolean willCrash = false;
willCrash |= value.willCrash(game);
return willCrash;
}
//-------------------------------------------------------------------------
@Override
public String toEnglish(final Game game)
{
return value.toEnglish(game) + " is even";
}
//-------------------------------------------------------------------------
}
| 2,804 | 20.744186 | 76 | java |
Ludii | Ludii-master/Core/src/game/functions/booleans/is/integer/IsFlat.java | package game.functions.booleans.is.integer;
import java.util.BitSet;
import java.util.List;
import annotations.Hide;
import annotations.Opt;
import game.Game;
import game.functions.booleans.BaseBooleanFunction;
import game.functions.ints.IntFunction;
import game.functions.ints.iterator.To;
import game.types.board.SiteType;
import game.util.directions.AbsoluteDirection;
import game.util.graph.Step;
import main.Constants;
import other.context.Context;
import other.state.container.ContainerState;
import other.topology.Topology;
/**
* Ensures that in a 3D board, all the pieces in the bottom layer have to be
* placed so that they do not fall.
*
* @author Eric.Piette
* @remarks This is used, for example, in almost all Shibumi games.
*/
@Hide
public final class IsFlat extends BaseBooleanFunction
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/** The site to test. */
private final IntFunction siteFn;
//-------------------------------------------------------------------------
/**
* @param site The site to check [(to)].
*/
public IsFlat(@Opt final IntFunction site)
{
siteFn = (site == null) ? To.instance() : site;
}
//-------------------------------------------------------------------------
@Override
public boolean eval(final Context context)
{
final int site = siteFn.eval(context);
if (site == Constants.OFF && site >= context.topology().vertices().size())
return false;
final other.topology.Vertex v = context.topology().vertices().get(site);
final Topology topology = context.topology();
if (v.layer() == 0)
return true;
final ContainerState cs = context.containerState(context.containerId()[site]);
final List<game.util.graph.Step> steps = topology.trajectories().steps(SiteType.Vertex, site, SiteType.Vertex,
AbsoluteDirection.Downward);
for (final Step step : steps)
if (cs.what(step.to().id(), SiteType.Vertex) == 0)
return false;
return true;
}
//-------------------------------------------------------------------------
@Override
public String toString()
{
return "IsFlat()";
}
//-------------------------------------------------------------------------
@Override
public boolean isStatic()
{
return false;
}
@Override
public long gameFlags(final Game game)
{
return siteFn.gameFlags(game);
}
@Override
public BitSet concepts(final Game game)
{
return siteFn.concepts(game);
}
@Override
public BitSet writesEvalContextRecursive()
{
final BitSet writeEvalContext = new BitSet();
writeEvalContext.or(siteFn.writesEvalContextRecursive());
return writeEvalContext;
}
@Override
public BitSet readsEvalContextRecursive()
{
final BitSet readEvalContext = new BitSet();
readEvalContext.or(siteFn.readsEvalContextRecursive());
return readEvalContext;
}
@Override
public void preprocess(final Game game)
{
siteFn.preprocess(game);
}
@Override
public boolean missingRequirement(final Game game)
{
boolean missingRequirement = false;
missingRequirement |= siteFn.missingRequirement(game);
return missingRequirement;
}
@Override
public boolean willCrash(final Game game)
{
boolean willCrash = false;
willCrash |= siteFn.willCrash(game);
return willCrash;
}
//-------------------------------------------------------------------------
@Override
public String toEnglish(final Game game)
{
return "site " + siteFn.toEnglish(game) + " is flat";
}
//-------------------------------------------------------------------------
}
| 3,588 | 22.611842 | 112 | java |
Ludii | Ludii-master/Core/src/game/functions/booleans/is/integer/IsOdd.java | package game.functions.booleans.is.integer;
import java.util.BitSet;
import annotations.Hide;
import game.Game;
import game.functions.booleans.BaseBooleanFunction;
import game.functions.ints.IntFunction;
import other.concept.Concept;
import other.context.Context;
/**
* Tests if an integer is odd.
*
* @author mrraow and cambolbro
*
*/
@Hide
public final class IsOdd extends BaseBooleanFunction
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/** Boolean condition. */
private final IntFunction value;
/** Precomputed boolean. */
private Boolean precomputedBoolean;
//-------------------------------------------------------------------------
/**
* @param value The value to test.
* @example (isOdd (mover))
*/
public IsOdd(final IntFunction value)
{
this.value = value;
}
//-------------------------------------------------------------------------
@Override
public boolean eval(final Context context)
{
if (precomputedBoolean != null)
return precomputedBoolean.booleanValue();
return (value.eval(context) & 1) == 1;
}
//-------------------------------------------------------------------------
@Override
public boolean isStatic()
{
return value.isStatic();
}
@Override
public long gameFlags(final Game game)
{
return value.gameFlags(game);
}
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
concepts.or(value.concepts(game));
concepts.set(Concept.Odd.id(), true);
return concepts;
}
@Override
public BitSet writesEvalContextRecursive()
{
final BitSet writeEvalContext = new BitSet();
writeEvalContext.or(value.writesEvalContextRecursive());
return writeEvalContext;
}
@Override
public BitSet readsEvalContextRecursive()
{
final BitSet readEvalContext = new BitSet();
readEvalContext.or(value.readsEvalContextRecursive());
return readEvalContext;
}
@Override
public void preprocess(final Game game)
{
value.preprocess(game);
if (isStatic())
precomputedBoolean = Boolean.valueOf(eval(new Context(game, null)));
}
@Override
public boolean missingRequirement(final Game game)
{
boolean missingRequirement = false;
missingRequirement |= value.missingRequirement(game);
return missingRequirement;
}
@Override
public boolean willCrash(final Game game)
{
boolean willCrash = false;
willCrash |= value.willCrash(game);
return willCrash;
}
//-------------------------------------------------------------------------
@Override
public String toEnglish(final Game game)
{
return value.toEnglish(game) + " is odd";
}
//-------------------------------------------------------------------------
}
| 2,752 | 20.677165 | 76 | java |
Ludii | Ludii-master/Core/src/game/functions/booleans/is/integer/IsPipsMatch.java | package game.functions.booleans.is.integer;
import java.util.BitSet;
import java.util.List;
import annotations.Hide;
import annotations.Opt;
import game.Game;
import game.equipment.component.Component;
import game.functions.booleans.BaseBooleanFunction;
import game.functions.ints.IntFunction;
import game.functions.ints.last.LastTo;
import game.types.board.SiteType;
import game.types.state.GameType;
import game.util.directions.AbsoluteDirection;
import game.util.graph.Radial;
import gnu.trove.list.array.TIntArrayList;
import other.concept.Concept;
import other.context.Context;
import other.state.container.ContainerState;
import other.topology.Topology;
/**
* Detects whether the pips of a domino match its neighbours.
*
* @author Eric.Piette and cambolbro
*
* @remarks Used for domino games to detect if the pips of the dominoes
* match on a specific site with its neighbours.
*/
@Hide
public final class IsPipsMatch extends BaseBooleanFunction
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/** Site to check. */
private final IntFunction siteFn;
//-------------------------------------------------------------------------
/**
* To detect if the pips of the dominoes match with his neighbors.
*
* @param site The site to check [(lastTo)].
*/
public IsPipsMatch
(
@Opt final IntFunction site
)
{
this.siteFn = (site == null) ? new LastTo(null) : site;
}
//-------------------------------------------------------------------------
@Override
public boolean eval(final Context context)
{
final int site = siteFn.eval(context);
final ContainerState cs = context.containerState(context.containerId()[site]);
final int what = cs.what(site, SiteType.Cell);
if(what == 0)
return true;
final Component component = context.components()[what];
final Topology topology = context.topology();
if (!component.isDomino())
return true;
final int state = cs.state(site, SiteType.Cell);
final TIntArrayList locs = component.locs(context, site, state, context.topology());
final TIntArrayList locsAroundOccupied = new TIntArrayList();
for (int i = 0; i < locs.size(); i++)
{
final int loc = locs.getQuick(i);
final int value = cs.valueCell(loc);
final other.topology.Cell cell = context.topology().cells().get(loc);
final List<game.util.graph.Step> steps = topology.trajectories().steps(SiteType.Cell, cell.index(),
SiteType.Cell, AbsoluteDirection.Orthogonal);
for (final game.util.graph.Step step : steps)
{
final int to = step.to().id();
if (!locs.contains(to)) // We do not check in the domino itself
{
final int valueTo = cs.valueCell(to);
final boolean empty = cs.isEmpty(to, SiteType.Cell);
if (!empty && valueTo != value)
return false;
if (cs.isOccupied(to))
locsAroundOccupied.add(to);
}
}
}
if (context.trial().moveNumber() > 1) // Not for the first domino
{
boolean okMatch = false;
for (int i = 0; i < locsAroundOccupied.size(); i++)
{
final other.topology.Cell cellI = context.topology().cells().get(locsAroundOccupied.getQuick(i));
final List<Radial> radials = topology.trajectories().radials(SiteType.Cell, cellI.index(), AbsoluteDirection.Orthogonal);
final TIntArrayList nbors = new TIntArrayList();
nbors.add(cellI.index());
for(final Radial radial : radials)
{
for (int j = 1; j < radial.steps().length; j++)
{
final int to = radial.steps()[j].id();
if (locsAroundOccupied.contains(to))
{
nbors.add(to);
}
}
if (nbors.size() > 2)
return false;
if (nbors.size() == 2)
okMatch = (cs.countCell(nbors.getQuick(0)) == cs.countCell(nbors.getQuick(1)));
}
}
return okMatch;
}
else
return true;
}
//-------------------------------------------------------------------------
@Override
public boolean isStatic()
{
final boolean isStatic = siteFn.isStatic();
return isStatic;
}
@Override
public long gameFlags(final Game game)
{
final long stateFlag = siteFn.gameFlags(game) | GameType.Dominoes | GameType.LargePiece;
return stateFlag;
}
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
concepts.or(siteFn.concepts(game));
concepts.set(Concept.Domino.id(), true);
return concepts;
}
@Override
public BitSet writesEvalContextRecursive()
{
final BitSet writeEvalContext = new BitSet();
writeEvalContext.or(siteFn.writesEvalContextRecursive());
return writeEvalContext;
}
@Override
public BitSet readsEvalContextRecursive()
{
final BitSet readEvalContext = new BitSet();
readEvalContext.or(siteFn.readsEvalContextRecursive());
return readEvalContext;
}
@Override
public void preprocess(final Game game)
{
siteFn.preprocess(game);
}
@Override
public boolean missingRequirement(final Game game)
{
boolean missingRequirement = false;
if (!game.hasDominoes())
{
game.addRequirementToReport(
"The ludeme (is PipsMatch ...) is used but the equipment has no dominoes.");
missingRequirement = true;
}
missingRequirement |= siteFn.missingRequirement(game);
return missingRequirement;
}
@Override
public boolean willCrash(final Game game)
{
boolean willCrash = false;
willCrash |= siteFn.willCrash(game);
return willCrash;
}
//-------------------------------------------------------------------------
@Override
public String toString()
{
final StringBuilder sb = new StringBuilder();
sb.append("[MatchPips ");
sb.append("]");
return sb.toString();
}
}
| 5,682 | 24.714932 | 125 | java |
Ludii | Ludii-master/Core/src/game/functions/booleans/is/integer/IsSidesMatch.java | package game.functions.booleans.is.integer;
import java.util.BitSet;
import java.util.List;
import annotations.Hide;
import annotations.Opt;
import game.Game;
import game.equipment.component.Component;
import game.equipment.component.tile.Path;
import game.functions.booleans.BaseBooleanFunction;
import game.functions.ints.IntFunction;
import game.functions.ints.last.LastTo;
import game.types.board.SiteType;
import game.util.directions.AbsoluteDirection;
import game.util.directions.DirectionFacing;
import game.util.graph.Step;
import main.Constants;
import other.context.Context;
import other.state.container.ContainerState;
import other.topology.Cell;
/**
* Is used to detect whether the terminus of a tile matches with its neighbours.
*
* @author Eric.Piette
* @remarks Used to detect whether a specific player is the mover. If no tile is
* on the location the function returns true.
*/
@Hide
public final class IsSidesMatch extends BaseBooleanFunction
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/** The position of the tile to check. */
private final IntFunction toFn;
//-------------------------------------------------------------------------
/**
* @param to The location of the tile [(lastTo)].
*/
public IsSidesMatch
(
@Opt final IntFunction to
)
{
this.toFn = (to == null) ? new LastTo(null) : to;
}
//-------------------------------------------------------------------------
@Override
public boolean eval(final Context context)
{
final int to = toFn.eval(context);
if (to == Constants.UNDEFINED)
return false;
final int cid = context.containerId()[to];
final other.topology.Topology graph = context.containers()[cid].topology();
final int ratioAdjOrtho = graph.supportedAdjacentDirections(SiteType.Cell).size()
/ graph.supportedOrthogonalDirections(SiteType.Cell).size();
final ContainerState cs = context.containerState(cid);
final int what = cs.whatCell(to);
if (what == 0)
return false;
final Component component = context.components()[what];
if (!component.isTile())
return true;
final int numberEdges = graph.numEdges();
int rotation = cs.rotation(to, SiteType.Cell) / ratioAdjOrtho;
int[] terminus = component.terminus();
final Integer numTerminus = component.numTerminus();
final Path[] paths = component.paths();
if (numTerminus != null)
{
terminus = new int[numberEdges];
for (int i = 0; i < numberEdges; i++)
terminus[i] = numTerminus.intValue();
}
final int[][] coloredTerminus = new int[numberEdges][];
for (int i = 0; i < numberEdges; i++)
coloredTerminus[i] = new int[terminus[i]];
for (final Path path : paths)
{
final int side1 = path.side1().intValue();
final int terminus1 = path.terminus1().intValue();
final int side2 = path.side2().intValue();
final int terminus2 = path.terminus2().intValue();
final int colour = path.colour().intValue();
coloredTerminus[side1][terminus1] = colour;
coloredTerminus[side2][terminus2] = colour;
}
while (rotation != 0)
{
for (int i = 0; i < numberEdges - 1; i++)
{
final int[] temp = coloredTerminus[i + 1];
coloredTerminus[i + 1] = coloredTerminus[0];
coloredTerminus[0] = temp;
}
rotation--;
}
final Cell toCell = graph.cells().get(to);
// System.out.println("toV is " + toCell.index());
// System.out.print("{");
// for (int i = 0; i < coloredTerminus.length; i++)
// {
// System.out.print(coloredTerminus[i][0] + " ");
// }
// System.out.println("}");
for (final Cell vOrtho : toCell.orthogonal())
{
final int whatOrtho = cs.what(vOrtho.index(), SiteType.Cell);
if (whatOrtho == 0)
continue;
final Component compOrtho = context.components()[whatOrtho];
if (!compOrtho.isTile())
continue;
int rotationOrtho = cs.rotation(vOrtho.index(), SiteType.Cell) / ratioAdjOrtho;
int[] terminusOrtho = compOrtho.terminus();
final Integer numTerminusOrtho = compOrtho.numTerminus();
final Path[] pathsOrtho = compOrtho.paths();
if (numTerminusOrtho != null)
{
terminusOrtho = new int[numberEdges];
for (int i = 0; i < numberEdges; i++)
terminusOrtho[i] = numTerminusOrtho.intValue();
}
final int[][] coloredTerminusOrtho = new int[numberEdges][];
for (int i = 0; i < numberEdges; i++)
coloredTerminusOrtho[i] = new int[terminusOrtho[i]];
for (final Path path : pathsOrtho)
{
final int side1 = path.side1().intValue();
final int terminus1 = path.terminus1().intValue();
final int side2 = path.side2().intValue();
final int terminus2 = path.terminus2().intValue();
final int colour = path.colour().intValue();
coloredTerminusOrtho[side1][terminus1] = colour;
coloredTerminusOrtho[side2][terminus2] = colour;
}
while (rotationOrtho != 0)
{
for (int i = 0; i < numberEdges - 1; i++)
{
final int[] temp = coloredTerminusOrtho[i + 1];
coloredTerminusOrtho[i + 1] = coloredTerminusOrtho[0];
coloredTerminusOrtho[0] = temp;
}
rotationOrtho--;
}
// System.out.println("vOrtho is " + vOrtho.index());
// System.out.print("{");
// for (int i = 0; i < coloredTerminusOrtho.length; i++)
// {
// System.out.print(coloredTerminusOrtho[i][0] + " ");
// }
// System.out.println("}");
final List<DirectionFacing> directions = graph.supportedOrthogonalDirections(SiteType.Cell);
int indexSideTile = 0;
for (; indexSideTile < directions.size(); indexSideTile++)
{
final DirectionFacing direction = directions.get(indexSideTile);
final AbsoluteDirection absDirection = direction.toAbsolute();
final List<game.util.graph.Step> steps = graph.trajectories().steps(SiteType.Cell, toCell.index(),
SiteType.Cell, absDirection);
boolean found = false;
for (final Step step : steps)
if (step.to().id() == vOrtho.index())
{
// System.out.println("Direction form = " + vOrtho.index() + " and the step.to() = " + to
// + " is " + direction);
// System.out.println("SO INDEX SIDE IS " + indexSideTile);
found = true;
break;
}
if (found)
break;
}
final int[] toColor = coloredTerminus[indexSideTile];
final int indexSideOrthoTile = (indexSideTile
+ (graph.numEdges() / 2))
% graph.numEdges();
final int[] orthoColor = coloredTerminusOrtho[indexSideOrthoTile];
for (int i = 0; i < toColor.length; i++)
if (toColor[i] != orthoColor[orthoColor.length - (1 + i)])
{
// System.out.println("not match");
return false;
}
}
// System.out.println("match");
return true;
}
//-------------------------------------------------------------------------
@Override
public boolean isStatic()
{
return false;
}
@Override
public long gameFlags(final Game game)
{
return toFn.gameFlags(game);
}
@Override
public BitSet concepts(final Game game)
{
return toFn.concepts(game);
}
@Override
public BitSet writesEvalContextRecursive()
{
final BitSet writeEvalContext = new BitSet();
writeEvalContext.or(toFn.writesEvalContextRecursive());
return writeEvalContext;
}
@Override
public BitSet readsEvalContextRecursive()
{
final BitSet readEvalContext = new BitSet();
readEvalContext.or(toFn.readsEvalContextRecursive());
return readEvalContext;
}
@Override
public void preprocess(final Game game)
{
toFn.preprocess(game);
}
@Override
public boolean missingRequirement(final Game game)
{
boolean missingRequirement = false;
boolean gameHasTile = false;
for (int i = 1; i < game.equipment().components().length; i++)
if (game.equipment().components()[i].isTile())
{
gameHasTile = true;
break;
}
if (!gameHasTile)
{
game.addRequirementToReport(
"The ludeme (is SidesMatch ...) is used but the equipment has no tiles.");
missingRequirement = true;
}
missingRequirement |= toFn.missingRequirement(game);
return missingRequirement;
}
@Override
public boolean willCrash(final Game game)
{
boolean willCrash = false;
willCrash |= toFn.willCrash(game);
return willCrash;
}
}
| 8,201 | 25.980263 | 102 | java |
Ludii | Ludii-master/Core/src/game/functions/booleans/is/integer/IsVisited.java | package game.functions.booleans.is.integer;
import java.util.BitSet;
import annotations.Hide;
import game.Game;
import game.functions.booleans.BaseBooleanFunction;
import game.functions.ints.IntFunction;
import game.types.state.GameType;
import other.concept.Concept;
import other.context.Context;
/**
* Returns true if a site was already visited by a player in the same sequence
* of their turn.
*
* @author Eric.Piette
* @remarks This is used to avoid visiting a site more than once during a
* sequence of moves.
*/
@Hide
public final class IsVisited extends BaseBooleanFunction
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/** The site to check. */
private final IntFunction siteId;
//-------------------------------------------------------------------------
/**
* @param site The site to check.
*/
public IsVisited(final IntFunction site)
{
siteId = site;
}
//-------------------------------------------------------------------------
@Override
public boolean eval(final Context context)
{
return context.state().isVisited(siteId.eval(context));
}
//-------------------------------------------------------------------------
@Override
public String toString()
{
return "Visited(" + siteId + ")";
}
//-------------------------------------------------------------------------
@Override
public boolean isStatic()
{
return siteId.isStatic();
}
@Override
public long gameFlags(final Game game)
{
long gameFlags = GameType.Visited;
if (siteId != null)
gameFlags |= siteId.gameFlags(game);
return gameFlags;
}
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
concepts.or(super.concepts(game));
concepts.set(Concept.VisitedSites.id(), true);
if (siteId != null)
concepts.or(siteId.concepts(game));
return concepts;
}
@Override
public BitSet writesEvalContextRecursive()
{
final BitSet writeEvalContext = new BitSet();
writeEvalContext.or(super.writesEvalContextRecursive());
if (siteId != null)
writeEvalContext.or(siteId.writesEvalContextRecursive());
return writeEvalContext;
}
@Override
public BitSet readsEvalContextRecursive()
{
final BitSet readEvalContext = new BitSet();
readEvalContext.or(super.readsEvalContextRecursive());
if (siteId != null)
readEvalContext.or(siteId.readsEvalContextRecursive());
return readEvalContext;
}
@Override
public void preprocess(final Game game)
{
siteId.preprocess(game);
}
@Override
public boolean missingRequirement(final Game game)
{
boolean missingRequirement = false;
missingRequirement |= siteId.missingRequirement(game);
return missingRequirement;
}
@Override
public boolean willCrash(final Game game)
{
boolean willCrash = false;
willCrash |= siteId.willCrash(game);
return willCrash;
}
//-------------------------------------------------------------------------
@Override
public String toEnglish(final Game game)
{
return "site " + siteId.toEnglish(game) + " has already been visited";
}
//-------------------------------------------------------------------------
}
| 3,210 | 21.77305 | 78 | java |
Ludii | Ludii-master/Core/src/game/functions/booleans/is/line/IsLine.java | package game.functions.booleans.is.line;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.List;
import annotations.Hide;
import annotations.Name;
import annotations.Opt;
import annotations.Or;
import annotations.Or2;
import game.Game;
import game.equipment.component.Component;
import game.functions.booleans.BaseBooleanFunction;
import game.functions.booleans.BooleanConstant;
import game.functions.booleans.BooleanFunction;
import game.functions.directions.Directions;
import game.functions.ints.IntFunction;
import game.functions.ints.last.LastTo;
import game.functions.region.RegionFunction;
import game.types.board.SiteType;
import game.types.play.RoleType;
import game.types.state.GameType;
import game.util.directions.AbsoluteDirection;
import game.util.graph.Radial;
import gnu.trove.list.array.TIntArrayList;
import main.Constants;
import other.concept.Concept;
import other.context.Context;
import other.location.FullLocation;
import other.location.Location;
import other.state.container.ContainerState;
import other.state.puzzle.ContainerDeductionPuzzleState;
import other.state.stacking.BaseContainerStateStacking;
import other.topology.TopologyElement;
/**
* Tests whether a succession of sites are occupied by a specified piece.
*
* @author Eric.Piette
*
* @remarks Used for any line games.
*/
@Hide
public class IsLine extends BaseBooleanFunction
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/** Minimum length of the line. */
private final IntFunction length;
/** The direction category of potential lines. */
private final Directions dirn;
/** The location to look for a line. */
private final IntFunction through;
/** The locations to look for a line. */
private final RegionFunction throughAny;
/** To simulate this kind of piece is on the pivot. (e.g. Dara) */
private final IntFunction[] whatFn;
/** The owner of the pieces to make a line */
private final IntFunction whoFn;
/** To detect exactly the size or not. */
private final BooleanFunction exactly;
/** To detect The line only by level in a stack. */
private final BooleanFunction byLevelFn;
/** To detect The line only in using the top level in a stack. */
private final BooleanFunction topFn;
/** Condition for every piece in the line. */
private final BooleanFunction condition;
/** True if we look for contiguous lines. */
private final BooleanFunction contiguousFn;
/** Add on Cell/Edge/Vertex. */
private SiteType type;
//-------------------------------------------------------------------------
/**
* @param type The graph element type [default SiteType of the board].
* @param length Minimum length of lines.
* @param dirn Direction category to which potential lines must belong
* [Adjacent].
* @param through Location through which the line must pass. [(last To)]
* @param throughAny The line must pass through at least one of these sites.
* @param who The owner of the pieces making a line.
* @param what The index of the component composing the line.
* @param whats The indices of the components composing the line.
* @param exact If true, then lines cannot exceed minimum length [False].
* @param contiguous If true, the line has to be contiguous [True].
* @param If The condition on each site on the line [True].
* @param byLevel If true, then lines are detected in using the level in a
* stack [False].
* @param top If true, then lines are detected in using only the top level
* in a stack [False].
*/
public IsLine
(
@Opt final SiteType type,
final IntFunction length,
@Opt final AbsoluteDirection dirn,
@Opt @Or @Name final IntFunction through,
@Opt @Or @Name final RegionFunction throughAny,
@Opt @Or2 final RoleType who,
@Opt @Or2 @Name final IntFunction what,
@Opt @Or2 @Name final IntFunction[] whats,
@Opt @Name final BooleanFunction exact,
@Opt @Name final BooleanFunction contiguous,
@Opt @Name final BooleanFunction If,
@Opt @Name final BooleanFunction byLevel,
@Opt @Name final BooleanFunction top
)
{
this.length = length;
this.dirn = (dirn == null) ? new Directions(AbsoluteDirection.Adjacent, null) : new Directions(dirn, null);
this.through = (through == null) ? new LastTo(null) : through;
this.throughAny = throughAny;
exactly = (exact == null) ? new BooleanConstant(false) : exact;
condition = (If == null) ? new BooleanConstant(true) : If;
if (whats != null)
{
whatFn = whats;
}
else if (what != null)
{
whatFn = new IntFunction[1];
whatFn[0] = what;
}
else
{
whatFn = null;
}
whoFn = (who != null) ? RoleType.toIntFunction(who) : null;
this.type = type;
byLevelFn = (byLevel == null) ? new BooleanConstant(false) : byLevel;
topFn = (top == null) ? new BooleanConstant(false) : top;
contiguousFn = (contiguous == null) ? new BooleanConstant(true) : contiguous;
}
//-------------------------------------------------------------------------
@Override
public boolean eval(final Context context)
{
if (context.game().isStacking())
return evalStack(context);
if (context.game().isDeductionPuzzle())
return evalDeductionPuzzle(context);
final boolean contiguous = contiguousFn.eval(context);
final int[] pivots;
if (throughAny != null)
{
final TIntArrayList listPivots = new TIntArrayList(throughAny.eval(context).sites());
if (whatFn != null)
{
final TIntArrayList whats = new TIntArrayList();
for (final IntFunction what : whatFn)
whats.add(what.eval(context));
for (int i = listPivots.size() - 1; i >= 0; i--)
{
final int loc = listPivots.getQuick(i);
final int contId = context.containerId()[loc];
final ContainerState state = context.state().containerStates()[contId];
final int what = state.what(loc, type);
if (!whats.contains(what))
listPivots.removeAt(i);
}
}
pivots = listPivots.toArray();
}
else
{
pivots = new int[1];
pivots[0] = through.eval(context);
}
final other.topology.Topology graph = context.topology();
final boolean playOnCell = (type != null && type.equals(SiteType.Cell)
|| (type == null && (context.game().board().defaultSite() != SiteType.Vertex)));
for (int p = 0; p < pivots.length; p++)
{
final int locn = pivots[p];
if (locn < 0)
return false;
final int origTo = context.to();
context.setTo(locn);
if (!condition.eval(context))
{
context.setTo(origTo);
return false;
}
if (playOnCell && locn >= graph.cells().size())
return false;
if (!playOnCell && locn >= graph.vertices().size())
return false;
final TopologyElement vertexLoc = playOnCell ? graph.cells().get(locn) : graph.vertices().get(locn);
final ContainerState state = context.state().containerStates()[context.containerId()[vertexLoc.index()]];
final TIntArrayList whats = new TIntArrayList();
final int whatLocn = state.what(locn, type);
if (whatFn == null)
{
if (whoFn == null)
{
whats.add(whatLocn);
}
else
{
if (whoFn != null)
{
final int who = whoFn.eval(context);
for (int i = 1; i < context.components().length; i++)
{
final Component component = context.components()[i];
if (component.owner() == who)
whats.add(component.index());
}
}
}
}
else
{
for (final IntFunction what : whatFn)
whats.add(what.eval(context));
}
if (!whats.contains(whatLocn))
continue;
final int len = length.eval(context);
final boolean exact = exactly.eval(context);
final List<Radial> radials = graph.trajectories().radials(type, locn)
.distinctInDirection(dirn.absoluteDirection());
for (final Radial radial : radials)
{
int count = 1;
for (int indexPath = 1; indexPath < radial.steps().length; indexPath++)
{
final int index = radial.steps()[indexPath].id();
context.setTo(index);
if (whats.contains(state.what(index, type)) && condition.eval(context))
{
count++;
if (!exact)
{
if (count == len)
{
context.setTo(origTo);
return true;
}
}
}
else if (contiguous)
{
break;
}
}
final List<Radial> oppositeRadials = radial.opposites();
if (oppositeRadials != null)
{
for (final Radial oppositeRadial : oppositeRadials)
{
int oppositeCount = count;
for (int indexPath = 1; indexPath < oppositeRadial.steps().length; indexPath++)
{
final int index = oppositeRadial.steps()[indexPath].id();
context.setTo(index);
if (whats.contains(state.what(index, type)) && condition.eval(context))
{
oppositeCount++;
if (!exact)
{
if (oppositeCount == len)
{
context.setTo(origTo);
return true;
}
}
}
else if (contiguous)
{
break;
}
}
if (oppositeCount == len)
{
context.setTo(origTo);
return true;
}
}
}
else if (count == len)
{
context.setTo(origTo);
return true;
}
}
context.setTo(origTo);
}
return false;
}
//-------------------------------------------------------------------------
/**
*
* Method for isLine but with a slightly modification for deduction puzzle
*
* @param context
* @return True if a line exists.
*/
public boolean evalDeductionPuzzle(final Context context)
{
final boolean contiguous = contiguousFn.eval(context);
final int[] pivots;
if (throughAny != null)
{
final TIntArrayList listPivots = new TIntArrayList(throughAny.eval(context).sites());
if (whatFn != null)
{
final TIntArrayList whats = new TIntArrayList();
for (final IntFunction what : whatFn)
whats.add(what.eval(context));
for (int i = 0; i < listPivots.size(); i++)
{
final int loc = listPivots.getQuick(i);
final int contId = context.containerId()[loc];
final ContainerState state = context.state().containerStates()[contId];
final int what = state.what(loc, type);
if (!whats.contains(what))
{
listPivots.remove(loc);
i--;
}
}
}
pivots = listPivots.toArray();
}
else
{
pivots = new int[1];
pivots[0] = through.eval(context);
}
for (int p = 0; p < pivots.length; p++)
{
final int locn = pivots[p];
if (locn == -1)
return false;
final int origTo = context.to();
context.setTo(locn);
if (!condition.eval(context))
{
context.setTo(origTo);
return false;
}
final int contId = 0;
final other.topology.Topology graph = context.containers()[contId].topology();
final boolean playOnCell = (type != null && type.equals(SiteType.Cell)
|| (type == null && context.game().board().defaultSite() != SiteType.Vertex));
if (playOnCell && locn >= graph.cells().size())
return false;
if (!playOnCell && locn >= graph.vertices().size())
return false;
final ContainerDeductionPuzzleState state = (ContainerDeductionPuzzleState) context.state().containerStates()[contId];
if (!state.isResolved(locn, type))
return false;
final TIntArrayList whats = new TIntArrayList();
final int whatLocn = state.what(locn, type);
if (whatFn == null)
whats.add(whatLocn);
else
for (final IntFunction what : whatFn)
whats.add(what.eval(context));
if (!whats.contains(whatLocn))
return false;
final int from = context.from();
final int len = length.eval(context);
final boolean exact = exactly.eval(context);
final List<Radial> radials = graph.trajectories().radials(type, locn)
.distinctInDirection(dirn.absoluteDirection());
for (final Radial radial : radials)
{
int count = whats.contains(state.what(locn, type)) ? 1 : 0;
for (int indexPath = 1; indexPath < radial.steps().length; indexPath++)
{
final int index = radial.steps()[indexPath].id();
if (!state.isResolved(index, type))
break;
context.setTo(index);
if (whats.contains(state.what(index, type)) && (whatFn == null || index != from)
&& condition.eval(context))
{
count++;
if (!exact)
if (count == len)
{
context.setTo(origTo);
return true;
}
}
else if (contiguous)
{
break;
}
}
final List<Radial> oppositeRadials = radial.opposites();
if (oppositeRadials != null)
{
for (final Radial oppositeRadial : oppositeRadials)
{
int oppositeCount = count;
for (int indexPath = 1; indexPath < oppositeRadial.steps().length; indexPath++)
{
final int index = oppositeRadial.steps()[indexPath].id();
if (!state.isResolved(index, type))
break;
context.setTo(index);
if (whats.contains(state.what(index, type)) && (whatFn == null || index != from)
&& condition.eval(context))
{
oppositeCount++;
if (!exact)
if (oppositeCount == len)
{
context.setTo(origTo);
return true;
}
}
else if (contiguous)
{
break;
}
}
if (oppositeCount == len)
{
context.setTo(origTo);
return true;
}
}
}
else if (count == len)
{
context.setTo(origTo);
return true;
}
}
context.setTo(origTo);
}
return false;
}
//-------------------------------------------------------------------------
/**
* Line for stacking game.
*
* @param context The context.
* @return True if a line is detected.
*/
private boolean evalStack(final Context context)
{
final int locn = through.eval(context);
final boolean top = topFn.eval(context);
if (locn == Constants.UNDEFINED)
return false;
SiteType realType = type;
if (realType == null)
realType = context.board().defaultSite();
final int contId = context.containerId()[locn];
final other.topology.Topology graph = context.containers()[contId].topology();
final BaseContainerStateStacking state = (BaseContainerStateStacking) context.state().containerStates()[contId];
final TIntArrayList whats = new TIntArrayList();
if (whatFn == null)
{
if (whoFn == null)
{
whats.add(state.what(locn, realType));
}
else
{
if (whoFn != null)
{
final int who = whoFn.eval(context);
for (int i = 1; i < context.components().length; i++)
{
final Component component = context.components()[i];
if (component.owner() == who)
whats.add(component.index());
}
}
}
}
else
{
for (final IntFunction what : whatFn)
whats.add(what.eval(context));
}
final int len = length.eval(context);
if (len == 1)
return true;
final boolean exact = exactly.eval(context);
final boolean byLevel = byLevelFn.eval(context);
if (byLevel)
{
// check a line directly on the stack (hypothesis we add a piece only on the
// top, e.g. connect-4)
final int sizeStack = state.sizeStack(locn, realType);
if (sizeStack >= len)
{
final int level = sizeStack - 2;
int count = 1;
for (int i = 0; i < len - 1; i++)
{
if (!whats.contains(state.what(locn, level - i, realType)))
{
break;
}
else
{
count++;
if (!exact)
if (count == len)
return true;
}
}
if (count == len)
return true;
}
final List<Radial> radials = graph.trajectories().radials(realType, locn)
.distinctInDirection(dirn.absoluteDirection());
final int levelOrigin = sizeStack - 1;
if(levelOrigin < 0)
return false;
for (final Radial radial : radials)
{
final List<Radial> oppositeRadials = radial.opposites();
// Same Level
int count = 0;
for (int indexPath = 0; indexPath < radial.steps().length; indexPath++)
{
final int index = radial.steps()[indexPath].id();
if (state.sizeStack(index, realType) <= levelOrigin)
break;
if (whats.contains(state.what(index, levelOrigin, realType)))
{
count++;
if (!exact)
if (count == len)
return true;
}
else
break;
}
if (oppositeRadials != null)
{
for (final Radial oppositeRadial : oppositeRadials)
{
int oppositeCount = count;
for (int indexPath = 1; indexPath < oppositeRadial.steps().length; indexPath++)
{
final int index = oppositeRadial.steps()[indexPath].id();
if (state.sizeStack(index, realType) <= levelOrigin)
break;
if (whats.contains(state.what(index, levelOrigin, realType)))
{
oppositeCount++;
if (!exact)
if (oppositeCount == len)
return true;
}
else
{
break;
}
}
if (oppositeCount == len)
return true;
}
}
else if (count == len)
return true;
// level -1 / level +1
count = 0;
int diffLevel = 0;
for (int indexPath = 0; indexPath < radial.steps().length; indexPath++)
{
if ((levelOrigin - diffLevel) == -1)
continue;
final int index = radial.steps()[indexPath].id();
if (state.sizeStack(index, realType) <= (levelOrigin - diffLevel))
break;
if (whats.contains(state.what(index, levelOrigin - diffLevel, realType)))
{
count++;
diffLevel++;
if (!exact)
if (count == len)
return true;
}
else
{
break;
}
}
if (oppositeRadials != null)
{
diffLevel = 1;
for (final Radial oppositeRadial : oppositeRadials)
{
int oppositeCount = count;
for (int indexPath = 1; indexPath < oppositeRadial.steps().length; indexPath++)
{
final int index = oppositeRadial.steps()[indexPath].id();
if (state.sizeStack(index, realType) <= (levelOrigin + diffLevel))
break;
if (whats.contains(state.what(index, levelOrigin + diffLevel, realType)))
{
oppositeCount++;
diffLevel++;
if (!exact)
if (oppositeCount == len)
return true;
}
else
{
break;
}
}
if (count == len)
return true;
}
}
else if (count == len)
return true;
// level +1 / level -1
count = 0;
diffLevel = 0;
for (int indexPath = 0; indexPath < radial.steps().length; indexPath++)
{
final int index = radial.steps()[indexPath].id();
if (state.sizeStack(index, realType) <= (levelOrigin + diffLevel))
break;
if (whats.contains(state.what(index, levelOrigin + diffLevel, realType)))
{
count++;
diffLevel++;
if (!exact)
if (count == len)
return true;
}
else
{
break;
}
}
if (oppositeRadials != null)
{
diffLevel = 1;
for (final Radial oppositeRadial : oppositeRadials)
{
int oppositeCount = count;
for (int indexPath = 1; indexPath < oppositeRadial.steps().length; indexPath++)
{
if ((levelOrigin - diffLevel) == -1)
continue;
final int index = oppositeRadial.steps()[indexPath].id();
if (state.sizeStack(index, realType) <= (levelOrigin - diffLevel))
break;
if (whats.contains(state.what(index, levelOrigin - diffLevel, realType)))
{
oppositeCount++;
diffLevel++;
if (!exact)
if (oppositeCount == len)
return true;
}
else
{
break;
}
}
if (oppositeCount == len)
return true;
}
}
else if (count == len)
return true;
}
return false;
}
else
{
int count = 0;
if (top)
{
if (whats.contains(state.what(locn, realType)))
count++;
}
else
{
final int sizeStack = state.sizeStack(locn, realType);
for (int level = 0; level < sizeStack; level++)
{
final int whatLevel = state.what(locn, level, realType);
if (whats.contains(whatLevel))
{
count++;
break;
}
}
}
if (count == 0)
return false;
final List<Radial> radials = graph.trajectories().radials(realType, locn)
.distinctInDirection(dirn.absoluteDirection());
for (final Radial radial : radials)
{
count = 1;
for (int indexPath = 1; indexPath < radial.steps().length; indexPath++)
{
final int index = radial.steps()[indexPath].id();
context.setTo(index);
boolean whatFound = false;
if (top)
{
if (whats.contains(state.what(index, realType)))
whatFound = true;
}
else
{
final int sizeStackTo = state.sizeStack(index, realType);
for (int level = 0; level < sizeStackTo; level++)
{
final int whatLevel = state.what(index, level, realType);
if (whats.contains(whatLevel))
{
whatFound = true;
break;
}
}
}
if (whatFound && condition.eval(context))
{
count++;
if (!exact)
if (count == len)
return true;
}
else
{
break;
}
}
final List<Radial> oppositeRadials = radial.opposites();
if (oppositeRadials != null)
{
for (final Radial oppositeRadial : oppositeRadials)
{
int oppositeCount = count;
for (int indexPath = 1; indexPath < oppositeRadial.steps().length; indexPath++)
{
final int index = oppositeRadial.steps()[indexPath].id();
boolean whatFound = false;
if (top)
{
if (whats.contains(state.what(index, realType)))
whatFound = true;
}
else
{
final int sizeStackTo = state.sizeStack(index, realType);
for (int level = 0; level < sizeStackTo; level++)
{
final int whatLevel = state.what(index, level, realType);
if (whats.contains(whatLevel))
{
whatFound = true;
break;
}
}
}
context.setTo(index);
if (whatFound && condition.eval(context))
{
oppositeCount++;
if (!exact)
if (oppositeCount == len)
return true;
}
else
{
break;
}
}
if (oppositeCount == len)
return true;
}
}
else if (count == len)
return true;
}
}
return false;
}
//-------------------------------------------------------------------------
@Override
public String toString()
{
String str = "";
str += "Line(" + length + ", " + dirn + ", " + through + ", " + exactly + ")";
return str;
}
@Override
public boolean isStatic()
{
// we're always inspecting the "what" ChunkSet of our context, so we're
// never static
return false;
}
@Override
public long gameFlags(final Game game)
{
long flags = length.gameFlags(game);
if (type != null && (type.equals(SiteType.Edge) || type.equals(SiteType.Vertex)))
flags |= GameType.Graph;
if (exactly != null)
flags |= exactly.gameFlags(game);
if (through != null)
flags |= through.gameFlags(game);
if (whatFn != null)
{
for (final IntFunction what : whatFn)
flags |= what.gameFlags(game);
}
if (whoFn != null)
flags |= whoFn.gameFlags(game);
flags |= condition.gameFlags(game);
flags |= byLevelFn.gameFlags(game);
flags |= topFn.gameFlags(game);
if (throughAny != null)
flags |= throughAny.gameFlags(game);
return flags;
}
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
concepts.set(Concept.Line.id(), true);
concepts.or(length.concepts(game));
if (exactly != null)
concepts.or(exactly.concepts(game));
if (through != null)
concepts.or(through.concepts(game));
if (whatFn != null)
for (final IntFunction what : whatFn)
concepts.or(what.concepts(game));
if (whoFn != null)
concepts.or(whoFn.concepts(game));
concepts.or(condition.concepts(game));
concepts.or(byLevelFn.concepts(game));
concepts.or(topFn.concepts(game));
if (throughAny != null)
concepts.or(throughAny.concepts(game));
if (dirn != null)
concepts.or(dirn.concepts(game));
return concepts;
}
@Override
public BitSet writesEvalContextRecursive()
{
final BitSet writeEvalContext = new BitSet();
writeEvalContext.or(length.writesEvalContextRecursive());
if (exactly != null)
writeEvalContext.or(exactly.writesEvalContextRecursive());
if (through != null)
writeEvalContext.or(through.writesEvalContextRecursive());
if (whatFn != null)
for (final IntFunction what : whatFn)
writeEvalContext.or(what.writesEvalContextRecursive());
if (whoFn != null)
writeEvalContext.or(whoFn.writesEvalContextRecursive());
writeEvalContext.or(condition.writesEvalContextRecursive());
writeEvalContext.or(byLevelFn.writesEvalContextRecursive());
writeEvalContext.or(topFn.writesEvalContextRecursive());
if (throughAny != null)
writeEvalContext.or(throughAny.writesEvalContextRecursive());
if (dirn != null)
writeEvalContext.or(dirn.writesEvalContextRecursive());
return writeEvalContext;
}
@Override
public BitSet readsEvalContextRecursive()
{
final BitSet readEvalContext = new BitSet();
readEvalContext.or(length.readsEvalContextRecursive());
if (exactly != null)
readEvalContext.or(exactly.readsEvalContextRecursive());
if (through != null)
readEvalContext.or(through.readsEvalContextRecursive());
if (whatFn != null)
for (final IntFunction what : whatFn)
readEvalContext.or(what.readsEvalContextRecursive());
if (whoFn != null)
readEvalContext.or(whoFn.readsEvalContextRecursive());
readEvalContext.or(condition.readsEvalContextRecursive());
readEvalContext.or(byLevelFn.readsEvalContextRecursive());
readEvalContext.or(topFn.readsEvalContextRecursive());
if (throughAny != null)
readEvalContext.or(throughAny.readsEvalContextRecursive());
if (dirn != null)
readEvalContext.or(dirn.readsEvalContextRecursive());
return readEvalContext;
}
@Override
public void preprocess(final Game game)
{
type = SiteType.use(type, game);
length.preprocess(game);
if (exactly != null)
exactly.preprocess(game);
if (through != null)
through.preprocess(game);
if (whatFn != null)
{
for (final IntFunction what : whatFn)
what.preprocess(game);
}
if (whoFn != null)
whoFn.preprocess(game);
byLevelFn.preprocess(game);
topFn.preprocess(game);
condition.preprocess(game);
if (throughAny != null)
throughAny.preprocess(game);
}
@Override
public boolean missingRequirement(final Game game)
{
boolean missingRequirement = false;
missingRequirement |= length.missingRequirement(game);
if (exactly != null)
missingRequirement |= exactly.missingRequirement(game);
if (through != null)
missingRequirement |= through.missingRequirement(game);
if (whatFn != null)
for (final IntFunction what : whatFn)
missingRequirement |= what.missingRequirement(game);
if (whoFn != null)
missingRequirement |= whoFn.missingRequirement(game);
missingRequirement |= condition.missingRequirement(game);
missingRequirement |= byLevelFn.missingRequirement(game);
if (throughAny != null)
missingRequirement |= throughAny.missingRequirement(game);
if (byLevelFn != null)
missingRequirement |= byLevelFn.missingRequirement(game);
if (topFn != null)
missingRequirement |= topFn.missingRequirement(game);
return missingRequirement;
}
@Override
public boolean willCrash(final Game game)
{
boolean willCrash = false;
willCrash |= length.willCrash(game);
if (exactly != null)
willCrash |= exactly.willCrash(game);
if (through != null)
willCrash |= through.willCrash(game);
if (whatFn != null)
for (final IntFunction what : whatFn)
willCrash |= what.willCrash(game);
if (whoFn != null)
willCrash |= whoFn.willCrash(game);
willCrash |= condition.willCrash(game);
willCrash |= byLevelFn.willCrash(game);
if (throughAny != null)
willCrash |= throughAny.willCrash(game);
if (byLevelFn != null)
willCrash |= byLevelFn.willCrash(game);
if (topFn != null)
willCrash |= topFn.willCrash(game);
return willCrash;
}
//-------------------------------------------------------------------------
/**
* @return Our target length IntFunction
*/
public IntFunction length()
{
return length;
}
//-------------------------------------------------------------------------
@Override
public List<Location> satisfyingSites(final Context context)
{
if (!eval(context))
return new ArrayList<Location>();
final List<Location> winningSites = new ArrayList<Location>();
final SiteType realType = type != null ? type : context.board().defaultSite();
final int[] pivots;
if (throughAny != null)
{
final TIntArrayList listPivots = new TIntArrayList(throughAny.eval(context).sites());
if (whatFn != null)
{
final TIntArrayList whats = new TIntArrayList();
for (final IntFunction what : whatFn)
whats.add(what.eval(context));
for (int i = listPivots.size() - 1; i >= 0; i--)
{
final int loc = listPivots.getQuick(i);
final int contId = context.containerId()[loc];
final ContainerState state = context.state().containerStates()[contId];
final int what = state.what(loc, type);
if (!whats.contains(what))
listPivots.removeAt(i);
}
}
pivots = listPivots.toArray();
}
else
{
pivots = new int[1];
pivots[0] = through.eval(context);
}
final other.topology.Topology graph = context.topology();
final boolean playOnCell = (type != null && type.equals(SiteType.Cell)
|| (type == null && context.game().board().defaultSite() != SiteType.Vertex));
for (int p = 0; p < pivots.length; p++)
{
final int locn = pivots[p];
if (locn == -1)
return new ArrayList<Location>();
final int origTo = context.to();
context.setTo(locn);
if (!condition.eval(context))
{
context.setTo(origTo);
return new ArrayList<Location>();
}
if (playOnCell && locn >= graph.cells().size())
return new ArrayList<Location>();
if (!playOnCell && locn >= graph.vertices().size())
return new ArrayList<Location>();
final TopologyElement vertexLoc = playOnCell ? graph.cells().get(locn) : graph.vertices().get(locn);
final ContainerState state = context.state().containerStates()[context.containerId()[vertexLoc.index()]];
final TIntArrayList whats = new TIntArrayList();
final int whatLocn = state.what(locn, type);
if (whatFn == null)
{
if (whoFn == null)
{
whats.add(whatLocn);
}
else
{
if (whoFn != null)
{
final int who = whoFn.eval(context);
for (int i = 1; i < context.components().length; i++)
{
final Component component = context.components()[i];
if (component.owner() == who)
whats.add(component.index());
}
}
}
}
else
{
for (final IntFunction what : whatFn)
whats.add(what.eval(context));
}
if (!whats.contains(whatLocn))
continue;
final int len = length.eval(context);
final boolean exact = exactly.eval(context);
final List<Radial> radials = graph.trajectories().radials(type, locn)
.distinctInDirection(dirn.absoluteDirection());
for (final Radial radial : radials)
{
winningSites.clear();
winningSites.add(new FullLocation(locn, 0, realType));
int count = whats.contains(whatLocn) ? 1 : 0;
for (int indexPath = 1; indexPath < radial.steps().length; indexPath++)
{
final int index = radial.steps()[indexPath].id();
context.setTo(index);
if (whats.contains(state.what(index, type)) && condition.eval(context))
{
count++;
winningSites.add(new FullLocation(index, 0, realType));
if (!exact)
if (count == len)
{
context.setTo(origTo);
return winningSites;
}
}
else
{
break;
}
}
final List<Radial> oppositeRadials = radial.opposites();
if (oppositeRadials != null)
{
for (final Radial oppositeRadial : oppositeRadials)
{
int oppositeCount = count;
for (int indexPath = 1; indexPath < oppositeRadial.steps().length; indexPath++)
{
final int index = oppositeRadial.steps()[indexPath].id();
context.setTo(index);
if (whats.contains(state.what(index, type)) && condition.eval(context))
{
winningSites.add(new FullLocation(index, 0, realType));
oppositeCount++;
if (!exact)
if (oppositeCount == len)
{
context.setTo(origTo);
return winningSites;
}
}
else
{
break;
}
}
if (oppositeCount == len)
{
context.setTo(origTo);
return winningSites;
}
}
}
else if (count == len)
{
context.setTo(origTo);
return winningSites;
}
}
context.setTo(origTo);
}
return new ArrayList<Location>();
}
@Override
public String toEnglish(final Game game)
{
String whoString = "of their";
if (whatFn != null)
whoString = whatFn.toString();
String directionString = dirn.toEnglish(game) + " direction";
return "a player places " + length.toString() + " " + whoString + " pieces in an " + directionString + " line";
}
} | 33,783 | 24.382419 | 121 | java |
Ludii | Ludii-master/Core/src/game/functions/booleans/is/loop/IsLoop.java | package game.functions.booleans.is.loop;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.BitSet;
import java.util.List;
import annotations.Hide;
import annotations.Name;
import annotations.Opt;
import annotations.Or;
import annotations.Or2;
import game.Game;
import game.equipment.component.Component;
import game.equipment.component.tile.Path;
import game.functions.booleans.BaseBooleanFunction;
import game.functions.directions.Directions;
import game.functions.directions.DirectionsFunction;
import game.functions.ints.IntFunction;
import game.functions.ints.last.LastTo;
import game.functions.ints.state.Mover;
import game.functions.region.RegionFunction;
import game.functions.region.sites.simple.SitesLastTo;
import game.types.board.RelationType;
import game.types.board.SiteType;
import game.types.play.RoleType;
import game.util.directions.AbsoluteDirection;
import game.util.directions.Direction;
import game.util.directions.RelativeDirection;
import game.util.equipment.Region;
import game.util.graph.Radial;
import gnu.trove.list.array.TIntArrayList;
import main.Constants;
import other.concept.Concept;
import other.context.Context;
import other.location.FullLocation;
import other.location.Location;
import other.state.container.ContainerState;
import other.topology.Cell;
import other.topology.Topology;
import other.topology.TopologyElement;
/**
* Detects a loop.
*
* @author Eric.Piette & cambolbro & tahmina
*
* @remarks This is used for tile games or connection games.
*/
@Hide
public final class IsLoop extends BaseBooleanFunction
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/** List of all the possible owners inside the loop. */
private final IntFunction[] rolesArray;
/** The starting point of the loop. */
private final IntFunction startFn;
/** The starting points of the loop. */
private final RegionFunction regionStartFn;
/** The SiteType of the site. */
private SiteType type;
/** Direction chosen. */
private final DirectionsFunction dirnChoice;
//---------------------------Data for Path Tile ------------------------------
/** True if we check a loop path. */
private final boolean tilePath;
/** The colour of the path. */
private final IntFunction colourFn;
// ----------------------pre-computed-----------------------------------------
// Indices of the outer sites of the board.
TIntArrayList outerIndices;
//-------------------------------------------------------------------------
/**
* @param type The graph element type [default SiteType of the board].
* @param surround Used to define the inside condition of the loop.
* @param surroundList The list of items inside the loop.
* @param directions The directions of the connected pieces used to connect
* the region [Adjacent].
* @param colour The owner of the looping pieces [Mover].
* @param start The starting point of the loop [(last To)].
* @param regionStart The region to start to detect the loop.
* @param path True if attempting to detect a loop in the path of the
* pieces (e.g. Trax).
*/
public IsLoop
(
@Opt final SiteType type,
@Or @Opt @Name final RoleType surround,
@Or @Opt final RoleType[] surroundList,
@Opt final Direction directions,
@Opt final IntFunction colour,
@Or2 @Opt final IntFunction start,
@Or2 @Opt final RegionFunction regionStart,
@Opt @Name final Boolean path
)
{
int numNonNull = 0;
if (surround != null)
numNonNull++;
if (surroundList != null)
numNonNull++;
if (numNonNull > 1)
throw new IllegalArgumentException("Zero or one Or parameter can be non-null.");
int numNonNull2 = 0;
if (start != null)
numNonNull2++;
if (regionStart != null)
numNonNull2++;
if (numNonNull2 > 1)
throw new IllegalArgumentException("Zero or one Or2 parameter can be non-null.");
colourFn = (colour == null) ? new Mover() : colour;
startFn = (start == null) ? new LastTo(null) : start;
regionStartFn = (regionStart == null)? ((start == null) ? new SitesLastTo() : null) : regionStart;
tilePath = (path == null) ? false : path.booleanValue();
if (surround != null)
{
rolesArray = new IntFunction[]
{ RoleType.toIntFunction(surround) };
}
else
{
if (surroundList != null)
{
rolesArray = new IntFunction[surroundList.length];
for (int i = 0; i < surroundList.length; i++)
rolesArray[i] = RoleType.toIntFunction(surroundList[i]);
}
else
rolesArray = null;
}
this.type = type;
dirnChoice = (directions != null) ? directions.directionsFunctions()
: new Directions(AbsoluteDirection.Adjacent, null);
}
//------------------------------------------------------------------------------------------
/**
* @param context The current Context of the game board.
* @return Is the last move create a ring or not?
*/
@Override
public boolean eval(final Context context)
{
final int from = startFn.eval(context);
// Check if this is a site.
if (from < 0)
return false;
final Topology topology = context.topology();
final SiteType realType = (type != null) ? type : context.game().board().defaultSite();
// Check if the site is in the board.
if (from >= topology.getGraphElements(realType).size())
return false;
final ContainerState cs = context.containerState(0);
final int what = cs.what(from, realType);
final int colourLoop = colourFn.eval(context);
// Check if the site is not empty.
if (what <= 0)
return false;
// If the piece is a tile we run the corresponding code.
if (context.components()[what].isTile() && tilePath)
return evalTilePath(context);
final TIntArrayList ownersOfEnclosedSite = (rolesArray == null) ? null : new TIntArrayList();
if (rolesArray != null)
for (int i = 0; i < rolesArray.length; i++)
ownersOfEnclosedSite.add(rolesArray[i].eval(context));
// We get all the sites around the starting position with not the same piece on
// them.
final TIntArrayList aroundSites = new TIntArrayList();
final TopologyElement startElement = topology.getGraphElements(realType).get(from);
final List<AbsoluteDirection> directionsFromStart = new Directions(AbsoluteDirection.Adjacent, null)
.convertToAbsolute(realType, startElement, null,
null, null,
context);
for (final AbsoluteDirection direction : directionsFromStart)
{
final List<game.util.graph.Step> steps = topology.trajectories().steps(realType, startElement.index(),
realType, direction);
for (final game.util.graph.Step step : steps)
{
final int to = step.to().id();
if (ownersOfEnclosedSite != null)
{
final int whoTo = cs.who(to, realType);
if (ownersOfEnclosedSite.contains(whoTo) && !outerIndices.contains(to))
aroundSites.add(to);
}
else if (!outerIndices.contains(to))
aroundSites.add(to);
}
}
// We look for a group starting from each site around which not touch the outer
// sites.
for (int indexSite = aroundSites.size() - 1; indexSite >= 0; indexSite--)
{
final int origin = aroundSites.get(indexSite);
// If site already checked we do not look at it again.
// if (sitesToCheckInPreviousGroup.contains(origin))
// continue;
final TIntArrayList groupSites = new TIntArrayList();
groupSites.add(origin);
boolean continueSearch = true;
final TIntArrayList sitesExplored = new TIntArrayList();
int i = 0;
while (sitesExplored.size() != groupSites.size())
{
final int site = groupSites.get(i);
final TopologyElement siteElement = topology.getGraphElements(realType).get(site);
final List<AbsoluteDirection> directions = new Directions(AbsoluteDirection.Orthogonal, null)
.convertToAbsolute(realType, siteElement, null,
null, null, context);
for (final AbsoluteDirection direction : directions)
{
final List<Radial> radials = topology.trajectories().radials(type, siteElement.index(), direction);
for (final Radial radial : radials)
{
for (int toIdx = 1; toIdx < radial.steps().length; toIdx++)
{
final int to = radial.steps()[toIdx].id();
// If we already have it we continue to look the others.
if (groupSites.contains(to))
continue;
// Not the border of the loop.
if (what != cs.what(to, realType))
{
if (ownersOfEnclosedSite != null)
{
final int whoTo = cs.who(to, realType);
if (ownersOfEnclosedSite.contains(whoTo) && !outerIndices.contains(to))
{
groupSites.add(to);
}
}
else
{
groupSites.add(to);
}
// If outer site, no loop.
if (outerIndices.contains(to))
{
continueSearch = false;
break;
}
}
else // We stop this radial because this is the loop.
break;
}
if (!continueSearch)
break;
}
if (!continueSearch)
break;
}
if (!continueSearch)
break;
sitesExplored.add(site);
i++;
}
// If a potential loop is detected we need to check if a path using the
// direction selected exist in it and if all the pieces looping are owned by the
// correct player.
if (continueSearch)
{
// Get the loop
final TIntArrayList loop = new TIntArrayList();
for (int indexGroup = 0; indexGroup < groupSites.size(); indexGroup++)
{
final int siteGroup = groupSites.get(indexGroup);
final TopologyElement element = topology.getGraphElements(realType).get(siteGroup);
final List<AbsoluteDirection> directionsElement = new Directions(AbsoluteDirection.Orthogonal, null)
.convertToAbsolute(realType, element,
null, null, null, context);
for (final AbsoluteDirection direction : directionsElement)
{
final List<game.util.graph.Step> steps = topology.trajectories().steps(realType,
element.index(), realType, direction);
for (final game.util.graph.Step step : steps)
{
final int to = step.to().id();
if (!groupSites.contains(to) && !loop.contains(to))
loop.add(to);
}
}
}
// If all the pieces looping are owned by the correct player.
boolean ownedPiecesLooping = true;
for (int indexLoop = 0; indexLoop < loop.size(); indexLoop++)
{
final int siteLoop = loop.get(indexLoop);
if (cs.who(siteLoop, realType) != colourLoop)
{
ownedPiecesLooping = false;
break;
}
}
if (!ownedPiecesLooping)
continue;
boolean loopFound = false;
int previousIndice = 0;
int indexSiteLoop = 0;
final TIntArrayList exploredLoop = new TIntArrayList();
while (!loopFound)
{
if (loop.size() == 0)
break;
final int siteLoop = loop.get(indexSiteLoop);
final int whatElement = cs.what(siteLoop, realType);
if (whatElement != what)
{
loop.remove(siteLoop);
indexSiteLoop = previousIndice;
continue;
}
final TopologyElement element = topology.getGraphElements(realType).get(siteLoop);
final List<AbsoluteDirection> directionsElement = dirnChoice.convertToAbsolute(realType, element,
null, null, null, context);
int newSite = Constants.UNDEFINED;
for (final AbsoluteDirection direction : directionsElement)
{
final List<game.util.graph.Step> steps = topology.trajectories().steps(realType,
element.index(), realType, direction);
for (final game.util.graph.Step step : steps)
{
final int to = step.to().id();
final int whatTo = cs.what(to, realType);
if (loop.contains(to) && whatTo == what)
{
newSite = to;
break;
}
}
if (newSite != Constants.UNDEFINED)
break;
}
if (newSite == Constants.UNDEFINED)
{
loop.remove(siteLoop);
exploredLoop.remove(siteLoop);
indexSiteLoop = previousIndice;
continue;
}
else
{
exploredLoop.add(siteLoop);
if (exploredLoop.size() == loop.size())
{
loopFound = true;
break;
}
previousIndice = indexSiteLoop;
indexSiteLoop = loop.indexOf(newSite);
}
}
if (loopFound)
return true;
}
}
return false;
}
//----------------------------------------------------------------------------------
/**
* @param context
* @return if a loop is realised with paths on pieces.
*/
public boolean evalTilePath(final Context context)
{
final int[] regionToCheck;
if (regionStartFn != null)
{
final Region region = regionStartFn.eval(context);
regionToCheck = region.sites();
}
else
{
regionToCheck = new int[1];
regionToCheck[0] = startFn.eval(context);
}
final DirectionsFunction directionFunction = new Directions(RelativeDirection.Forward, null,
RelationType.Orthogonal, null);
for (int p = 0; p < regionToCheck.length; p++)
{
final int from = regionToCheck[p];
final int colourLoop = colourFn.eval(context);
final int cid = context.containerId()[from];
final Topology graph = context.topology();
final ContainerState cs = context.containerState(cid);
final int ratioAdjOrtho = context.topology().numEdges();
final TIntArrayList tileConnected = new TIntArrayList();
final TIntArrayList originTileConnected = new TIntArrayList();
tileConnected.add(from);
originTileConnected.add(from);
for (int index = 0; index < tileConnected.size(); index++)
{
final int site = tileConnected.getQuick(index);
final Cell cell = graph.cells().get(site);
final int what = cs.what(site, SiteType.Cell);
final Component component = context.components()[what];
final int rotation = (cs.rotation(site, SiteType.Cell) * 2) / ratioAdjOrtho;
final Path[] paths = Arrays.copyOf(component.paths(), component.paths().length);
for (int i = 0; i < paths.length; i++)
{
final Path path = paths[i];
if (path.colour().intValue() == colourLoop)
{
// Side1
final List<AbsoluteDirection> directionsStep1 = directionFunction.convertToAbsolute(SiteType.Cell,
cell, null, null, Integer.valueOf(path.side1(rotation,
graph.numEdges())),
context);
final AbsoluteDirection directionSide1 = directionsStep1.get(0);
final List<game.util.graph.Step> stepsSide1 = graph.trajectories().steps(SiteType.Cell, cell.index(),
SiteType.Cell, directionSide1);
if (stepsSide1.size() != 0)
{
final int site1Connected = stepsSide1.get(0).to().id();
if (originTileConnected.getQuick(index) != site1Connected && site1Connected == from)
return true;
final int whatSide1 = cs.whatCell(site1Connected);
if (originTileConnected.getQuick(index) != site1Connected && whatSide1 != 0
&& context.components()[whatSide1].isTile())
{
tileConnected.add(site1Connected);
originTileConnected.add(site);
}
}
// Side 2
final List<AbsoluteDirection> directionsSide2 = directionFunction.convertToAbsolute(
SiteType.Cell, cell, null, null,
Integer.valueOf(path.side2(rotation, graph.numEdges())), context);
final AbsoluteDirection directionSide2 = directionsSide2.get(0);
final List<game.util.graph.Step> stepsSide2 = graph.trajectories().steps(SiteType.Cell,
cell.index(), SiteType.Cell, directionSide2);
if (stepsSide2.size() != 0)
{
final int site2Connected = stepsSide2.get(0).to().id();
if (originTileConnected.getQuick(index) != site2Connected && site2Connected == from)
return true;
final int whatSide2 = cs.whatCell(site2Connected);
if (originTileConnected.getQuick(index) != site2Connected && whatSide2 != 0
&& context.components()[whatSide2].isTile())
{
tileConnected.add(site2Connected);
originTileConnected.add(site);
}
}
}
}
}
}
return false;
}
//------------------------------------------------------------------------------
@Override
public String toString()
{
String str = "";
str += "IsLoop()";
return str;
}
//-------------------------------------------------------------------------
@Override
public boolean isStatic()
{
return false;
}
@Override
public long gameFlags(final Game game)
{
long gameFlags = 0L;
gameFlags |= SiteType.gameFlags(type);
if (colourFn != null)
gameFlags |= colourFn.gameFlags(game);
if (regionStartFn != null)
gameFlags |= regionStartFn.gameFlags(game);
if (startFn != null)
gameFlags |= startFn.gameFlags(game);
return gameFlags;
}
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
concepts.or(super.concepts(game));
concepts.set(Concept.Loop.id(), true);
if (colourFn != null)
concepts.or(colourFn.concepts(game));
if (regionStartFn != null)
concepts.or(regionStartFn.concepts(game));
if (startFn != null)
concepts.or(startFn.concepts(game));
concepts.or(SiteType.concepts(type));
if (dirnChoice != null)
concepts.or(dirnChoice.concepts(game));
return concepts;
}
@Override
public boolean missingRequirement(final Game game)
{
boolean missingRequirement = false;
missingRequirement |= super.missingRequirement(game);
if (colourFn != null)
missingRequirement |= colourFn.missingRequirement(game);
if (regionStartFn != null)
missingRequirement |= regionStartFn.missingRequirement(game);
if (startFn != null)
missingRequirement |= startFn.missingRequirement(game);
return missingRequirement;
}
@Override
public boolean willCrash(final Game game)
{
boolean willCrash = false;
willCrash |= super.willCrash(game);
if (colourFn != null)
willCrash |= colourFn.willCrash(game);
if (regionStartFn != null)
willCrash |= regionStartFn.willCrash(game);
if (startFn != null)
willCrash |= startFn.willCrash(game);
return willCrash;
}
@Override
public void preprocess(final Game game)
{
type = SiteType.use(type, game);
// We get the outer sites.
final List<TopologyElement> outerElements = game.board().topology().outer(type);
outerIndices = new TIntArrayList();
for (final TopologyElement element : outerElements)
outerIndices.add(element.index());
if (colourFn != null)
colourFn.preprocess(game);
if (rolesArray != null)
for (final IntFunction role : rolesArray)
role.preprocess(game);
if (startFn != null)
startFn.preprocess(game);
if (regionStartFn != null)
regionStartFn.preprocess(game);
}
// ------------------------------for GUI-------------------------------------
@Override
public List<Location> satisfyingSites(final Context context)
{
if (!eval(context))
return new ArrayList<Location>();
final List<Location> winningSites = new ArrayList<Location>();
final int from = startFn.eval(context);
// Check if this is a site.
if (from < 0)
return new ArrayList<Location>();
final Topology topology = context.topology();
final SiteType realType = (type != null) ? type : context.game().board().defaultSite();
// Check if the site is in the board.
if (from >= topology.getGraphElements(realType).size())
return new ArrayList<Location>();
final ContainerState cs = context.containerState(0);
final int what = cs.what(from, realType);
// Check if the site is not empty.
if (what <= 0)
return new ArrayList<Location>();
// If the piece is a tile we run the corresponding code.
if (context.components()[what].isTile() && tilePath)
return new ArrayList<Location>();
final TIntArrayList ownersOfEnclosedSite = (rolesArray == null) ? null : new TIntArrayList();
if (rolesArray != null)
for (int i = 0; i < rolesArray.length; i++)
ownersOfEnclosedSite.add(rolesArray[i].eval(context));
// We get all the sites around the starting position with not the same piece on
// them.
final TIntArrayList aroundSites = new TIntArrayList();
final TopologyElement startElement = topology.getGraphElements(realType).get(from);
final List<AbsoluteDirection> directionsFromStart = new Directions(AbsoluteDirection.Adjacent, null)
.convertToAbsolute(realType, startElement, null, null, null, context);
for (final AbsoluteDirection direction : directionsFromStart)
{
final List<game.util.graph.Step> steps = topology.trajectories().steps(realType, startElement.index(),
realType, direction);
for (final game.util.graph.Step step : steps)
{
final int to = step.to().id();
if (ownersOfEnclosedSite != null)
{
final int whoTo = cs.who(to, realType);
if (ownersOfEnclosedSite.contains(whoTo) && !outerIndices.contains(to))
aroundSites.add(to);
}
else if (!outerIndices.contains(to))
aroundSites.add(to);
}
}
// We look for a group starting from each site around which not touch the outer
// sites.
for (int indexSite = aroundSites.size() - 1; indexSite >= 0; indexSite--)
{
final int origin = aroundSites.get(indexSite);
final TIntArrayList groupSites = new TIntArrayList();
groupSites.add(origin);
boolean continueSearch = true;
final TIntArrayList sitesExplored = new TIntArrayList();
int i = 0;
while (sitesExplored.size() != groupSites.size())
{
final int site = groupSites.get(i);
final TopologyElement siteElement = topology.getGraphElements(realType).get(site);
final List<AbsoluteDirection> directions = new Directions(AbsoluteDirection.Orthogonal, null)
.convertToAbsolute(realType, siteElement, null, null, null, context);
for (final AbsoluteDirection direction : directions)
{
final List<Radial> radials = topology.trajectories().radials(type, siteElement.index(), direction);
for (final Radial radial : radials)
{
for (int toIdx = 1; toIdx < radial.steps().length; toIdx++)
{
final int to = radial.steps()[toIdx].id();
// If we already have it we continue to look the others.
if (groupSites.contains(to))
continue;
// Not the border of the loop.
if (what != cs.what(to, realType))
{
if (ownersOfEnclosedSite != null)
{
final int whoTo = cs.who(to, realType);
if (ownersOfEnclosedSite.contains(whoTo) && !outerIndices.contains(to))
{
groupSites.add(to);
}
}
else
{
groupSites.add(to);
}
// If outer site, no loop.
if (outerIndices.contains(to))
{
continueSearch = false;
break;
}
}
else // We stop this radial because this is the loop.
break;
}
if (!continueSearch)
break;
}
if (!continueSearch)
break;
}
if (!continueSearch)
break;
sitesExplored.add(site);
i++;
}
// If a group is found without to touch the outer sites, a loop is detecting.
if (continueSearch)
{
final TIntArrayList loop = new TIntArrayList();
for (int indexGroup = 0; indexGroup < groupSites.size(); indexGroup++)
{
final int siteGroup = groupSites.get(indexGroup);
final TopologyElement element = topology.getGraphElements(realType).get(siteGroup);
final List<AbsoluteDirection> directionsElement = new Directions(AbsoluteDirection.Orthogonal, null)
.convertToAbsolute(realType, element, null, null, null, context);
for (final AbsoluteDirection direction : directionsElement)
{
final List<game.util.graph.Step> steps = topology.trajectories().steps(realType,
element.index(), realType, direction);
for (final game.util.graph.Step step : steps)
{
final int to = step.to().id();
if (!groupSites.contains(to) && !loop.contains(to))
loop.add(to);
}
}
}
for (int indexWin = 0; indexWin < loop.size(); indexWin++)
winningSites.add(new FullLocation(loop.get(indexWin), 0, realType));
return filterWinningSites(context, winningSites);
}
}
return new ArrayList<Location>();
}
/**
* @param context the context.
* @param winningGroup The winning group detected in satisfyingSites.
* @return The minimum group of sites making the loop.
*/
public List<Location> filterWinningSites(final Context context, final List<Location> winningGroup)
{
final Topology topology = context.topology();
final SiteType realType = (type != null) ? type : context.game().board().defaultSite();
// Minimum group to connect the regions.
final List<Location> minimumGroup = new ArrayList<Location>(winningGroup);
for (int i = minimumGroup.size() - 1; i >= 0; i--)
{
final TIntArrayList groupMinusI = new TIntArrayList();
for (int j = 0; j < minimumGroup.size(); j++)
if (j != i)
groupMinusI.add(minimumGroup.get(j).site());
// System.out.println("groupMinusI is" + groupMinusI);
// Check if all the pieces are in one group.
final int startGroup = groupMinusI.get(0);
int lastExploredSite = startGroup;
final TIntArrayList groupSites = new TIntArrayList();
groupSites.add(startGroup);
if (groupSites.size() > 0)
{
final TIntArrayList sitesExplored = new TIntArrayList();
int k = 0;
while (sitesExplored.size() != groupSites.size())
{
final int site = groupSites.get(k);
final TopologyElement siteElement = topology.getGraphElements(realType).get(site);
final List<AbsoluteDirection> directions = dirnChoice.convertToAbsolute(realType, siteElement, null,
null, null, context);
for (final AbsoluteDirection direction : directions)
{
final List<game.util.graph.Step> steps = topology.trajectories().steps(realType,
siteElement.index(), realType, direction);
boolean foundNextElement = false;
for (final game.util.graph.Step step : steps)
{
final int to = step.to().id();
// If we already have it we continue to look the others.
if (groupSites.contains(to))
continue;
// New element in the group.
if (groupMinusI.contains(to))
{
groupSites.add(to);
lastExploredSite = to;
foundNextElement = true;
break;
}
}
if (foundNextElement)
break;
}
sitesExplored.add(site);
k++;
}
}
final boolean oneSingleGroup = (groupSites.size() == groupMinusI.size());
if (oneSingleGroup)
{
boolean isALoop = false;
final TopologyElement siteElement = topology.getGraphElements(realType).get(lastExploredSite);
final List<AbsoluteDirection> directions = dirnChoice.convertToAbsolute(realType, siteElement, null,
null, null, context);
for (final AbsoluteDirection direction : directions)
{
final List<game.util.graph.Step> steps = topology.trajectories().steps(realType,
siteElement.index(), realType, direction);
for (final game.util.graph.Step step : steps)
{
final int to = step.to().id();
if (to == startGroup)
{
isALoop = true;
break;
}
}
if (isALoop)
break;
}
if (isALoop)
minimumGroup.remove(i);
}
}
return minimumGroup;
}
//-------------------------------------------------------------------------
@Override
public String toEnglish(final Game game)
{
return "a loop of pieces is present";
}
//-------------------------------------------------------------------------
}
| 27,762 | 29.210011 | 107 | java |
Ludii | Ludii-master/Core/src/game/functions/booleans/is/path/IsPath.java | package game.functions.booleans.is.path;
import java.util.Arrays;
import java.util.BitSet;
import java.util.List;
import java.util.PriorityQueue;
import java.util.Queue;
import java.util.Stack;
import annotations.Hide;
import annotations.Name;
import annotations.Opt;
import annotations.Or;
import game.Game;
import game.functions.booleans.BaseBooleanFunction;
import game.functions.booleans.BooleanConstant;
import game.functions.booleans.BooleanFunction;
import game.functions.ints.IntFunction;
import game.functions.ints.last.LastTo;
import game.functions.range.RangeFunction;
import game.types.board.SiteType;
import game.types.play.RoleType;
import game.types.state.GameType;
import gnu.trove.list.array.TIntArrayList;
import main.Constants;
import other.context.Context;
import other.state.container.ContainerState;
import other.topology.Cell;
import other.topology.Edge;
import other.topology.Topology;
import other.topology.Vertex;
/**
* Boolean file to test the cycle or path with specific size.
*
* @author tahmina and cambolbro and Eric.Piette
*
* @remarks Used for any GT game.
*/
@Hide
public class IsPath extends BaseBooleanFunction
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/** Type of the element of the graph. */
private final SiteType indexType;
/** The from site. **/
private final IntFunction from;
/** The type of player. **/
private final IntFunction who;
/** The exact size of component. **/
private final RangeFunction range;
/** Closed path or not. **/
private final BooleanFunction closedFlagFn;
//-------------------------------------------------------------------------
/**
*
* @param type The graph element type [default SiteType of the board].
* @param from The site to look the path [(last To)].
* @param who The owner of the pieces on the path.
* @param role The role of the player owning the pieces on the path.
* @param range The range size of the path.
* @param closed It use to detect closed component.
*/
public IsPath
(
final SiteType type,
@Opt final IntFunction from,
@Or final game.util.moves.Player who,
@Or final RoleType role,
final RangeFunction range,
@Opt @Name final BooleanFunction closed
)
{
indexType = type;
this.who = (who == null) ? RoleType.toIntFunction(role) : who.index();
this.range = range;
closedFlagFn = (closed == null) ? new BooleanConstant(false) : closed;
this.from = (from != null) ? from : new LastTo(null);
}
//----------------------------------------------------------------------------------
@Override
public boolean eval(final Context context)
{
final int siteId = from.eval(context);
if(siteId == Constants.OFF)
return false;
switch (indexType)
{
case Vertex:
return evalVertex(context, siteId);
case Edge:
return evalEdge(context, siteId);
case Cell:
return evalCell(context, siteId);
default:
return false;
}
}
//---------------------------------------------------------------------------
/**
* @param context The present context of game board.
* @param siteId The last move.
* @return
*/
private boolean evalEdge(final Context context, final int siteId)
{
final Topology graph = context.topology();
final ContainerState state = context.state().containerStates()[0];
final int whoSiteId = who.eval(context);
final int totalVertices = graph.vertices().size();
final int totalEdges = graph.edges().size();
final int minLength = range.eval(context).min(context);
final int maxLength = range.eval(context).max(context);
final int[] disc = new int[totalVertices];
final int[] low = new int[totalVertices];
final BitSet stackMember = new BitSet(totalVertices);
final Stack<Integer> st = new Stack<Integer>();
final Edge kEdge = graph.edges().get(siteId);
final int v1 = kEdge.vA().index();
final int v2 = kEdge.vB().index();
final int startingVertex = v1;
final BitSet testBitset = new BitSet(totalVertices);
final BitSet edgeBitset = new BitSet(totalEdges);
final BitSet[] adjacencyGraph = new BitSet[totalVertices];
for (int i = 0; i < totalVertices; i++)
adjacencyGraph[i] = new BitSet(totalEdges);
final int strongComponents = strongComponent(context, startingVertex, -1, disc, low, st, stackMember, testBitset, whoSiteId, 1, totalVertices, v1, v2);
final boolean closedFlag = closedFlagFn.eval(context);
if (closedFlag)
{
for (int i = 0; i < totalEdges; i++)
{
if (state.who(i, indexType) == whoSiteId)
{
final Edge iEdge = graph.edges().get(i);
final int vA = iEdge.vA().index();
final int vB = iEdge.vB().index();
adjacencyGraph[vA].set(vB);
adjacencyGraph[vB].set(vA);
if ((testBitset.get(vA)) && (testBitset.get(vB)))
edgeBitset.set(i);
}
}
if (minLength == maxLength) // length
{
if (strongComponents == edgeBitset.cardinality() && (strongComponents == minLength))
return true;
}
else if ((maxLength > 2) && (strongComponents <= maxLength)) // range
if (strongComponents == edgeBitset.cardinality() && (strongComponents > 2))
return true;
if(edgeBitset.cardinality() > strongComponents)
{
final int[] path = findShortestDistance(graph, adjacencyGraph, v1, v2, new BitSet(totalVertices), totalVertices);
int i = v2;
int minDepth = 1;
while(path[i] != i )
{
minDepth++;
i = path[i];
}
if (minLength == maxLength)
if (minDepth == minLength)
return true;
if (maxLength > 2)
if (minDepth <= maxLength)
return true;
}
}
else
{
if (strongComponents != 0)
return false;
for (int i = 0; i < totalEdges; i++)
{
final Edge iEdge = graph.edges().get(i);
if (state.who(iEdge.index(), indexType) == whoSiteId)
edgeBitset.set(i);
}
final BitSet depthBitset1 = new BitSet(totalVertices);
final BitSet depthBitset2 = new BitSet(totalVertices);
final BitSet visitedEdge = new BitSet(totalEdges);
final int componentSz;
if (minLength == maxLength)
componentSz = minLength;
else
componentSz = maxLength;
dfsMinPathEdge(context, graph, kEdge, edgeBitset, visitedEdge, 0, v1, v2, componentSz, depthBitset1, whoSiteId);
dfsMinPathEdge(context, graph, kEdge, edgeBitset, visitedEdge, 0, v2, v1, componentSz, depthBitset2, whoSiteId);
final int pathLength = (depthBitset1.cardinality() - 1) + (depthBitset2.cardinality() - 1) + 1;
if (minLength == maxLength)
if ((pathLength == minLength) && (visitedEdge.cardinality() + 1 == pathLength))
return true;
if (maxLength > minLength)
if ((pathLength <= maxLength) && (visitedEdge.cardinality() + 1 == pathLength))
return true;
}
return false;
}
//---------------------------------------------------------------------------
/**
* @param context The present context of game board.
* @param siteId The last move.
* @return
*/
private boolean evalCell(final Context context, final int siteId)
{
final Topology graph = context.topology();
final int cid = context.containerId()[0];
final ContainerState state = context.state().containerStates()[cid];
final int whoSiteId = who.eval(context);
final int totalCells = graph.cells().size();
final int minLength = range.eval(context).min(context);
final int maxLength = range.eval(context).max(context);
final int[] disc = new int[totalCells];
final int[] low = new int[totalCells];
final BitSet stackMember = new BitSet(totalCells);
final Stack<Integer> st = new Stack<Integer>();
final Cell kCell = graph.cells().get(siteId);
boolean isolated = true;
final List<Cell> nList = kCell.adjacent();
final int v1 = kCell.index();
int v2 = 0;
final int startingVertex = v1;
final boolean closedFlag = closedFlagFn.eval(context);
for (int i = 0; i < nList.size(); i++)
{
final Cell iVertex = nList.get(i);
if(iVertex != kCell)
{
if (state.who(iVertex.index(), indexType) == whoSiteId)
{
v2 = iVertex.index();
isolated = false;
break;
}
}
}
if((isolated) && (closedFlag))
return false;
if((isolated) && (!closedFlag))
if ((minLength == 1) && (maxLength == 1))
return true;
final BitSet testBitset = new BitSet(totalCells);
final int[] vertexIndex = new int [totalCells];
final int[] vertexVisit = new int [totalCells];
final int strongComponents = strongComponent (context, startingVertex, -1, disc, low, st, stackMember, testBitset,
whoSiteId, 1, totalCells, v1, v2);
if (closedFlag)
{
if (minLength == maxLength)
{
if (strongComponents == minLength)
return true;
if (minLength < strongComponents)
{
final TIntArrayList nList2 = new TIntArrayList();
final List<Cell> nList1 = graph.cells().get(kCell.index()).adjacent();
for (int i = 0; i < nList1.size(); i++)
{
final Cell iVertex = nList1.get(i);
if (state.who(iVertex.index(), indexType) == whoSiteId)
{
nList2.add(iVertex.index());
}
}
for(int i = 0; i < nList2.size(); i++)
{
final int minDepth = dfsMinCycleSzVertexCell(context, graph, vertexVisit, vertexIndex, 1, kCell.index(), nList2.get(i), -1, Constants.INFINITY, whoSiteId);
if ((minDepth == minLength) && (minDepth > 2))
return true;
}
}
}
else if (maxLength != 0)
{
if((strongComponents <= maxLength) && (strongComponents > 2))
return true;
if(strongComponents > maxLength)
{
final TIntArrayList nList2 = new TIntArrayList();
final List<Cell> nList1 = graph.cells().get(kCell.index()).adjacent();
for (int i = 0; i < nList1.size(); i++)
{
final Cell iVertex = nList1.get(i);
if (state.who(iVertex.index(), indexType) == whoSiteId)
{
nList2.add(iVertex.index());
}
}
for(int i = 0; i < nList2.size(); i++)
{
final int minDepth = dfsMinCycleSzVertexCell(context, graph, vertexVisit, vertexIndex, 1, kCell.index(), nList2.get(i), -1, Constants.INFINITY, whoSiteId);
if((minDepth <= maxLength) && (minDepth > 2))
return true;
}
}
}
}
else
{
if (strongComponents != 0)
return false;
if(maxLength > 0) return true; //range
final List<Cell> nListVertex = graph.cells().get(kCell.index()).adjacent();
final TIntArrayList nList1 = new TIntArrayList();
for(int i = 0; i< nListVertex.size(); i++)
{
if(state.whoCell(nListVertex.get(i).index()) == whoSiteId)
nList1.add(nListVertex.get(i).index());
}
if((nList1.size() > 2) || (nList1.size() < 1))
return false;
int pathSize1 = 0 ;
if(nList1.size() == 1)
pathSize1 = dfsMinPathSzVertexCell(context, 0, kCell.index(), v1, -1, minLength, whoSiteId) + 1;
if (pathSize1 == minLength)
return true;
int pathSize2 = 0 ;
if(nList1.size() == 2)
{
pathSize1 = dfsMinPathSzVertexCell(context, 1, kCell.index(), nList1.getQuick(0), -1, minLength,
whoSiteId);
pathSize2 = dfsMinPathSzVertexCell(context, 1, kCell.index(), nList1.getQuick(1), nList1.getQuick(0),
minLength, whoSiteId);
final int pathSize = pathSize1 + pathSize2 + 1;
if (pathSize == minLength)
return true;
}
return false;
}
return false;
}
//---------------------------------------------------------------------------
/**
* @param context The present context of game board.
* @param siteId The last move.
* @return
*/
private boolean evalVertex(final Context context, final int siteId)
{
final Topology graph = context.topology();
final int cid = context.containerId()[0];
final ContainerState state = context.state().containerStates()[cid];
final int whoSiteId = who.eval(context);
final int totalVertices = graph.vertices().size();
final int totalEdges = graph.edges().size();
final int minLength = range.eval(context).min(context);
final int maxLength = range.eval(context).max(context);
final int[] disc = new int[totalVertices];
final int[] low = new int[totalVertices];
final BitSet stackMember = new BitSet(totalVertices);
final Stack<Integer> st = new Stack<Integer>();
final Vertex kVertex = graph.vertices().get(siteId);
boolean isolated = true;
final List<Vertex> nList = kVertex.adjacent();
final int v1 = kVertex.index();
int v2 = 0;
final boolean closedFlag = closedFlagFn.eval(context);
final int startingVertex = v1;
for (int i = 0; i < nList.size(); i++)
{
final Vertex iVertex = nList.get(i);
if(iVertex != kVertex)
{
if (state.who(iVertex.index(), indexType) == whoSiteId)
{
v2 = iVertex.index();
isolated = false;
break;
}
}
}
if((isolated) && (closedFlag))
return false;
if((isolated) && (!closedFlag))
if((minLength == 1) ||(maxLength == 1))
return true;
final BitSet testBitset = new BitSet(totalVertices);
final BitSet edgeBitset = new BitSet(totalEdges);
final int[] vertexIndex = new int [totalVertices];
final int[] vertexVisit = new int [totalVertices];
final int strongComponents = strongComponent(context, startingVertex, -1, disc, low, st, stackMember, testBitset, whoSiteId, 1, totalVertices, v1, v2);
if (closedFlag)
{
if (minLength == maxLength) // length
{
if(strongComponents == minLength)
return true;
if(strongComponents > minLength)
{
final TIntArrayList nListVertex = vertexToAdjacentNeighbourVertices1(context, kVertex.index(), whoSiteId);
for(int i = 0; i < nListVertex.size(); i++)
{
final int minDepth = dfsMinCycleSzVertexCell(context, graph, vertexVisit, vertexIndex, 1, kVertex.index(), nListVertex.get(i), -1, Constants.INFINITY, whoSiteId);
if((minDepth == minLength) && (minDepth > 2))
return true;
}
}
}
else if (maxLength > minLength) // range
{
if((strongComponents <= maxLength) && (strongComponents > 2))
return true;
if(strongComponents > maxLength)
{
final TIntArrayList nListVertex = vertexToAdjacentNeighbourVertices1(context, kVertex.index(), whoSiteId);
for(int i = 0; i < nListVertex.size(); i++)
{
final int minDepth = dfsMinCycleSzVertexCell(context, graph, vertexVisit, vertexIndex, 1, kVertex.index(), nListVertex.get(i), -1, Constants.INFINITY, whoSiteId);
if((minDepth <= maxLength) && (minDepth > 2))
return true;
}
}
}
}
else
{
if (strongComponents != 0) return false;
if (maxLength > minLength)
return true; // range
final TIntArrayList nListVertex = vertexToAdjacentNeighbourVertices1(context, kVertex.index(), whoSiteId);
if((nListVertex.size() > 2 ) || (nListVertex.size() < 1 ) )
return false;
for (int i = 0; i < totalEdges; i++)
{
final Edge iEdge = graph.edges().get(i);
if (state.who(iEdge.index(), indexType) == whoSiteId)
edgeBitset.set(i);
}
if (minLength == maxLength)
{
int pathSize = 0;
if(nListVertex.size() == 1)
pathSize = dfsMinPathSzVertexCell(context, 0, kVertex.index(), v1, -1, minLength, whoSiteId) + 1;
if(pathSize == minLength)
return true;
int pathSize1 = 0;
int pathSize2 = 0;
if(nListVertex.size() == 2)
{
pathSize1 = dfsMinPathSzVertexCell(context, 1, kVertex.index(), nListVertex.getQuick(0), -1, minLength, whoSiteId);
pathSize2 = dfsMinPathSzVertexCell(context, 1, kVertex.index(), nListVertex.getQuick(1), nListVertex.getQuick(0), minLength, whoSiteId);
final int path = pathSize1 + pathSize2 + 1;
if(path == minLength)
return true;
}
return false;
}
return false;
}
return false;
}
//----------------------------------------------------------------------------
/**
* @param context The context of present game state.
* @param presentVertex The present position.
* @param parent The parent of the present position.
* @param visit All visited vertices.
* @param low It use to calculated the cycle.
* @param stackInfo It use to stack the visited information.
* @param stackInfoBitset use to get the information about stack.
* @param testBitset1 keep the information about the large cycle of last move.
* @param whoSiteId The last move player's type.
* @param index Dfs iteration counter.
* @param totalItems The total vertices of G.
* @param v1 A vertex.
* @param v2 A vertex.
*
* @remarks This function uses to find a Strong Connected Component(modified - Tarjan's Algorithm), which contains the last move.
*
*/
private int strongComponent
(
final Context context,
final int presentPosition,
final int parent,
final int[] visit,
final int[] low,
final Stack<Integer> stackInfo,
final BitSet stackInfoBitset,
final BitSet testBitset1,
final int whoSiteId,
final int index,
final int totalItems,
final int v1,
final int v2
)
{
final Topology graph = context.topology();
final ContainerState state = context.state().containerStates()[0];
visit[presentPosition] = index;
low[presentPosition] = index;
stackInfo.push(Integer.valueOf(presentPosition));
stackInfoBitset.set(presentPosition);
TIntArrayList nList = new TIntArrayList();
if(indexType.equals(SiteType.Cell))
{
final List<Cell> nList1 = graph.cells().get(presentPosition).adjacent();
for (int i = 0; i < nList1.size(); i++)
{
final Cell iVertex = nList1.get(i);
if (state.who(iVertex.index(), indexType) == whoSiteId)
{
nList.add(iVertex.index());
}
}
}
else if(indexType.equals(SiteType.Vertex))
{
nList = vertexToAdjacentNeighbourVertices1(context, presentPosition, whoSiteId);
}
else if(indexType.equals(SiteType.Edge))
{
nList = vertexToAdjacentNeighbourVertices(context, presentPosition, whoSiteId);
}
for (int i = 0; i != nList.size(); ++i)
{
final int v = nList.get(i);
if(v == parent)
continue;
if (visit[v] == 0)
{
strongComponent(context, v, presentPosition, visit, low, stackInfo, stackInfoBitset, testBitset1, whoSiteId, index + 1, totalItems, v1, v2);
low[presentPosition] = (low[presentPosition] < low[v]) ? low[presentPosition] : low[v];
}
else
{
if (stackInfoBitset.get(v))
{
low[presentPosition] = (low[presentPosition] < visit[v]) ? low[presentPosition] : visit[v];
}
}
}
int w = 0;
final BitSet testBitset = new BitSet(totalItems);
if (low[presentPosition] == visit[presentPosition])
{
while (stackInfo.peek().intValue() != presentPosition)
{
w = stackInfo.peek().intValue();
stackInfoBitset.clear(w);
testBitset.set(w);
stackInfo.pop();
}
w = stackInfo.peek().intValue();
stackInfoBitset.clear(w);
testBitset.set(w);
stackInfo.pop();
}
if((testBitset.get(v1)) && (testBitset.get(v2)))
{
for (int i = testBitset.nextSetBit(0); i >= 0; i = testBitset.nextSetBit(i + 1))
{
testBitset1.set(i);
}
return testBitset.cardinality();
}
return 0;
}
//---------------------------------------------------------------------------
/**
*
* @param graph The board graph.
* @param adjacenceGraph The coloured graph.
* @param from The starting vertex.
* @param to The ending vertex.
* @param visited If the vertex is visited.
* @param totalVertices The total vertices at the board graph.
*
* @return All the path array with a list of parent vertices.
*
* */
public static int[] findShortestDistance
(
final Topology graph,
final BitSet[] adjacenceGraph,
final int from,
final int to,
final BitSet visited,
final int totalVertices
)
{
final Queue<Integer> toVisit = new PriorityQueue<Integer>();
final int[] dist = new int [totalVertices];
final int[] path = new int [totalVertices];
Arrays.fill(dist, Constants.INFINITY);
toVisit.add(Integer.valueOf(from));
dist[from] = 0;
path[from] = from;
while (!toVisit.isEmpty())
{
final int u = toVisit.remove().intValue();
if (u == to)
{
return path;
}
if (visited.get(u))
continue;
visited.set(u);
final Edge kEdge = graph.findEdge(graph.vertices().get(to), graph.vertices().get(from));
for (int v = adjacenceGraph[u].nextSetBit(0); v >= 0; v = adjacenceGraph[u].nextSetBit(v + 1))
{
final Edge uv = graph.findEdge(graph.vertices().get(v), graph.vertices().get(u));
if(uv == kEdge)
continue;
final int weight = 1;
if(dist[v] > (dist[u] + weight))
{
dist[v] = dist[u] + weight;
path[v] = u;
toVisit.add(Integer.valueOf(v));
}
}
}
return path;
}
//---------------------------------------------------------------------------
/**
* @param context The context of present game state.
* @param graph Present status of graph.
* @param vertexIndex minimum distance from the starting point.
* @param index Dfs state counter.
* @param startingVertex The starting point for a cycle.
* @param presentVertex The present position.
* @param parent The parent of the present position.
* @param minDepth It use to store the information about minimum cycle.
* @param whoSiteId The last move player's type.
*
* @remarks dfsMinCycleSzVertex() uses to find minimum cycle within in a strong component.
*
*/
private int dfsMinCycleSzVertexCell
(
final Context context,
final Topology graph,
final int[] vertexVisit,
final int[] vertexIndex,
final int index,
final int startingVertex,
final int presentVertex,
final int parent,
final int minDepth,
final int whoSiteId
)
{
final int cid = context.containerId()[0];
final ContainerState state = context.state().containerStates()[cid];
final int presentDegree = graph.vertices().get(presentVertex).adjacent().size();
int newindex = 0;
int newMinDepth = 0;
vertexVisit[presentVertex]++;
if(vertexVisit[presentVertex] > presentDegree)
return index;
if(minDepth == 3) return minDepth;
if(vertexIndex[presentVertex] == 0)
{
vertexIndex[presentVertex] = index;
newindex = index;
}
else
{
newindex = vertexIndex[presentVertex];
}
newMinDepth = minDepth;
if(startingVertex == presentVertex)
{
if(minDepth > index)
{
newMinDepth = index;
return newMinDepth + 1;
}
}
if(indexType.equals(SiteType.Cell))
{
final List<Cell> nList1 = graph.cells().get(presentVertex).adjacent();
for (int i = 0; i < nList1.size(); i++)
{
final int iVertex = nList1.get(i).index();
if(iVertex != parent)
{
if (state.who(iVertex, indexType) == whoSiteId)
{
dfsMinCycleSzVertexCell(context, graph, vertexVisit, vertexIndex, newindex + 1, startingVertex, iVertex, presentVertex, newMinDepth, whoSiteId);
}
}
}
}
else if(indexType.equals(SiteType.Vertex))
{
final TIntArrayList nListVertex = vertexToAdjacentNeighbourVertices1(context, presentVertex, whoSiteId);
for(int i = 0; i < nListVertex.size(); i++)
{
final int ni = nListVertex.get(i);
if((newindex == 1) && (ni != startingVertex))
if(presentVertex != ni)
dfsMinCycleSzVertexCell(context, graph, vertexVisit, vertexIndex, newindex + 1, startingVertex, ni, presentVertex, newMinDepth, whoSiteId);
}
}
return newindex + 1;
}
//--------------------------------------------------------------------------------------------
/**
* @param context The context of present game state.
* @param graph Present status of graph.
* @param kEdge The last move.
* @param edgeBitset All the edge of the present player.
* @param visitedEdge All the visited edge of the present player.
* @param index Dfs state counter.
* @param presentVertex The present position.
* @param parent The parent of the present position.
* @param mincomponentsz The desire component size.
* @param depthBitset Store the depth of path.
* @param whoSiteId The last move player's type.
*
* @remarks dfsMinPathEdge() uses to find the path length.
*
*/
private int dfsMinPathEdge
(
final Context context,
final Topology graph,
final Edge kEdge,
final BitSet edgeBitset,
final BitSet visitedEdge,
final int index,
final int presentVertex,
final int parent,
final int mincomponentsz,
final BitSet depthBitset,
final int whoSiteId
)
{
if(index == mincomponentsz * 2)
return index;
for (int i = edgeBitset.nextSetBit(0); i >= 0; i = edgeBitset.nextSetBit(i + 1))
{
final Edge nEdge = graph.edges().get(i);
if(nEdge != kEdge)
{
final int nVA = nEdge.vA().index();
final int nVB = nEdge.vB().index();
if(nVA == presentVertex)
{
visitedEdge.set(i);
dfsMinPathEdge(context, graph, nEdge, edgeBitset, visitedEdge, index + 1, nVB, nVA, mincomponentsz, depthBitset, whoSiteId);
}
else if(nVB == presentVertex)
{
visitedEdge.set(i);
dfsMinPathEdge(context, graph, nEdge, edgeBitset, visitedEdge, index + 1, nVA, nVB, mincomponentsz, depthBitset, whoSiteId);
}
}
}
depthBitset.set(index);
return index;
}
//--------------------------------------------------------------------------------------------
/**
* @param context The context of present game state.
* @param index Dfs state counter.
* @param startingVertex The starting point for a Path.
* @param presentVertex The present position.
* @param parent The parent of the present position.
* @param mincomponentsz The desire component size.
* @param whoSiteId The last move player's type.
*
* @remarks dfsMinPathSzVertexCell() uses to find the path length.
*
*/
private int dfsMinPathSzVertexCell
(
final Context context,
final int index,
final int startingVertex,
final int presentVertex,
final int parent,
final int mincomponentsz,
final int whoSiteId
)
{
final Topology graph = context.topology();
final int cid = context.containerId()[0];
final ContainerState state = context.state().containerStates()[cid];
if(index == mincomponentsz * 2)
return index;
TIntArrayList nListVertex = new TIntArrayList();
if(indexType.equals(SiteType.Cell))
{
final List<Cell> nList = graph.cells().get(presentVertex).adjacent();
for(int i = 0; i< nList.size(); i++)
{
if(state.whoCell(nList.get(i).index()) == whoSiteId)
nListVertex.add(nList.get(i).index());
}
}
if(indexType.equals(SiteType.Vertex))
nListVertex = vertexToAdjacentNeighbourVertices1(context, presentVertex, whoSiteId);
if(nListVertex.size() > 2 )
return Constants.INFINITY;
if(nListVertex.size() == 0 )
return index;
for(int i = 0; i < nListVertex.size(); i++)
{
if( nListVertex.getQuick(i) != parent)
if( nListVertex.getQuick(i) != startingVertex)
return dfsMinPathSzVertexCell(context, index + 1, startingVertex, nListVertex.get(i), presentVertex, mincomponentsz, whoSiteId);
}
return index;
}
//-----------------------------------------------------------------------
/**
*
* @param context The context of present game state.
* @param v A vertex of G.
* @param whoSiteId The last move player's type.
* @return
*/
private TIntArrayList vertexToAdjacentNeighbourVertices
(
final Context context,
final int v,
final int whoSiteId
)
{
final ContainerState state = context.state().containerStates()[0];
final int totalEdges = context.topology().edges().size();
final TIntArrayList nList = new TIntArrayList();
for(int k = 0; k < totalEdges; k++)
{
final Edge kEdge = context.topology().edges().get(k);
if(state.who(kEdge.index(), indexType) == whoSiteId)
{
final int vA = kEdge.vA().index();
final int vB = kEdge.vB().index();
if(vA == v)
nList.add(vB);
else
if(vB == v)
nList.add(vA);
}
}
return nList;
}
//-------------------------------------------------------------------------
/**
*
* @param context The context of present game state.
* @param v A vertex of G.
* @param whoSiteId The last move player's type.
* @return
*/
private TIntArrayList vertexToAdjacentNeighbourVertices1
(
final Context context,
final int v,
final int whoSiteId
)
{
final ContainerState state = context.state().containerStates()[0];
final TIntArrayList nList = new TIntArrayList();
final List<Vertex> nList1 = context.topology().vertices().get(v).adjacent();
for(int k = 0; k < nList1.size(); k++)
{
if(nList1.get(k).index() != v)
{
if(state.who(nList1.get(k).index(), indexType) == whoSiteId)
{
nList.add(nList1.get(k).index());
}
}
}
return nList;
}
//-------------------------------------------------------------------------
@Override
public String toString()
{
String str = "";
str += "IsPath( )";
return str;
}
@Override
public boolean isStatic()
{
return false;
}
@Override
public long gameFlags(final Game game)
{
long flags = GameType.Graph;
flags |= from.gameFlags(game);
flags |= closedFlagFn.gameFlags(game);
flags |= range.gameFlags(game);
if (who != null)
flags |= who.gameFlags(game);
return flags;
}
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
concepts.or(super.concepts(game));
concepts.or(from.concepts(game));
concepts.or(closedFlagFn.concepts(game));
concepts.or(range.concepts(game));
if (who != null)
concepts.or(who.concepts(game));
return concepts;
}
@Override
public BitSet writesEvalContextRecursive()
{
final BitSet writeEvalContext = new BitSet();
writeEvalContext.or(super.writesEvalContextRecursive());
writeEvalContext.or(from.writesEvalContextRecursive());
writeEvalContext.or(closedFlagFn.writesEvalContextRecursive());
writeEvalContext.or(range.writesEvalContextRecursive());
if (who != null)
writeEvalContext.or(who.writesEvalContextRecursive());
return writeEvalContext;
}
@Override
public BitSet readsEvalContextRecursive()
{
final BitSet readEvalContext = new BitSet();
readEvalContext.or(super.readsEvalContextRecursive());
readEvalContext.or(from.readsEvalContextRecursive());
readEvalContext.or(closedFlagFn.readsEvalContextRecursive());
readEvalContext.or(range.readsEvalContextRecursive());
if (who != null)
readEvalContext.or(who.readsEvalContextRecursive());
return readEvalContext;
}
@Override
public boolean missingRequirement(final Game game)
{
boolean missingRequirement = false;
missingRequirement |= super.missingRequirement(game);
missingRequirement |= from.missingRequirement(game);
missingRequirement |= closedFlagFn.missingRequirement(game);
missingRequirement |= range.missingRequirement(game);
if (who != null)
missingRequirement |= who.missingRequirement(game);
return missingRequirement;
}
@Override
public boolean willCrash(final Game game)
{
boolean willCrash = false;
willCrash |= super.willCrash(game);
willCrash |= from.willCrash(game);
willCrash |= closedFlagFn.willCrash(game);
willCrash |= range.willCrash(game);
if (who != null)
willCrash |= who.willCrash(game);
return willCrash;
}
@Override
public void preprocess(final Game game)
{
from.preprocess(game);
closedFlagFn.preprocess(game);
range.preprocess(game);
if (who != null)
who.preprocess(game);
}
@Override
public String toEnglish(final Game game)
{
return who.toEnglish(game)+ " "+ indexType.name() + " length is " + range.toEnglish(game) + " and " + "component closed is "+ closedFlagFn.toEnglish(game);
}
}
| 33,814 | 28.378801 | 168 | java |
Ludii | Ludii-master/Core/src/game/functions/booleans/is/pattern/IsPattern.java | package game.functions.booleans.is.pattern;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.List;
import annotations.Hide;
import annotations.Name;
import annotations.Opt;
import annotations.Or;
import game.Game;
import game.functions.booleans.BaseBooleanFunction;
import game.functions.ints.IntConstant;
import game.functions.ints.IntFunction;
import game.functions.ints.last.LastTo;
import game.types.board.SiteType;
import game.types.board.StepType;
import game.util.directions.DirectionFacing;
import game.util.graph.Step;
import main.Constants;
import other.ContainerId;
import other.concept.Concept;
import other.context.Context;
import other.location.FullLocation;
import other.location.Location;
import other.state.container.ContainerState;
/**
* For detecting a specific pattern from a site.
*
* @author Eric.Piette
*/
@Hide
public final class IsPattern extends BaseBooleanFunction
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/** The indices to follow in the pattern. */
private final IntFunction[] whatsFn;
/** The walk describing the pattern. */
private final StepType[] walk;
/** The site from. */
private final IntFunction fromFn;
/** The type of the site from. */
private SiteType type;
//-------------------------------------------------------------------------
/**
* @param walk The walk describing the pattern.
* @param type The type of the site from to detect the pattern.
* @param from The site from to detect the pattern [(from (last To))].
* @param what The piece to check in the pattern.
* @param whats The sequence of pieces to check in the pattern.
*/
public IsPattern
(
final StepType[] walk,
@Opt final SiteType type,
@Opt @Name final IntFunction from,
@Or @Opt @Name final IntFunction what,
@Or @Opt @Name final IntFunction[] whats
)
{
this.walk = walk;
fromFn = (from == null) ? new LastTo(null) : from;
whatsFn = (whats != null) ? whats : (what != null) ? new IntFunction[]
{ what } : null;
this.type = type;
}
//-------------------------------------------------------------------------
@Override
public boolean eval(final Context context)
{
final int from = fromFn.eval(context);
if (from <= Constants.OFF)
return false;
final SiteType realType = (type == null) ? context.board().defaultSite() : type;
final int cid = new ContainerId(null, null, null, null, new IntConstant(from)).eval(context);
final other.topology.Topology graph = context.containers()[cid].topology();
final ContainerState cs = context.containerState(0);
if (from >= graph.getGraphElements(realType).size())
return false;
final int[] whats = (whatsFn != null) ? new int[whatsFn.length] : new int[1];
if (whatsFn != null)
{
for (int i = 0; i < whats.length; i++)
whats[i] = whatsFn[i].eval(context);
}
else
{
final int what = cs.what(from, realType);
if (what == 0)
return false;
whats[0] = what;
}
final List<DirectionFacing> orthogonalSupported = graph.supportedOrthogonalDirections(realType);
List<DirectionFacing> walkDirection;
walkDirection = graph.supportedOrthogonalDirections(realType);
for (final DirectionFacing startDirection : walkDirection)
{
int currentLoc = from;
DirectionFacing currentDirection = startDirection;
int whatIndex = 0;
if (cs.what(from, realType) != whats[whatIndex])
return false;
whatIndex++;
if (whatIndex == whats.length)
whatIndex = 0;
boolean found = true;
for (final StepType step : walk)
{
if (step == StepType.F)
{
final List<Step> stepsDirection = graph.trajectories().steps(realType, currentLoc,
currentDirection.toAbsolute());
int to = Constants.UNDEFINED;
for (final Step stepDirection : stepsDirection)
{
if (stepDirection.from().siteType() != stepDirection.to().siteType())
continue;
to = stepDirection.to().id();
}
currentLoc = to;
// No correct walk with that state or not correct what.
if (to == Constants.UNDEFINED || cs.what(to, realType) != whats[whatIndex])
{
found = false;
break;
}
whatIndex++;
if (whatIndex == whats.length)
whatIndex = 0;
}
else if (step == StepType.R)
{
currentDirection = currentDirection.right();
while (!orthogonalSupported.contains(currentDirection))
currentDirection = currentDirection.right();
}
else if (step == StepType.L)
{
currentDirection = currentDirection.left();
while (!orthogonalSupported.contains(currentDirection))
currentDirection = currentDirection.left();
}
}
if (found)
return true;
}
return false;
}
//-------------------------------------------------------------------------
@Override
public boolean isStatic()
{
return false;
}
@Override
public long gameFlags(final Game game)
{
long flag = 0l;
if (fromFn != null)
flag |= fromFn.gameFlags(game);
if (whatsFn != null)
for (final IntFunction what : whatsFn)
flag |= what.gameFlags(game);
flag |= SiteType.gameFlags(type);
return flag;
}
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
concepts.set(Concept.Pattern.id(), true);
concepts.or(SiteType.concepts(type));
if (fromFn != null)
concepts.or(fromFn.concepts(game));
if (whatsFn != null)
for (final IntFunction what : whatsFn)
concepts.or(what.concepts(game));
return concepts;
}
@Override
public BitSet writesEvalContextRecursive()
{
final BitSet writeEvalContext = new BitSet();
if (fromFn != null)
writeEvalContext.or(fromFn.writesEvalContextRecursive());
if (whatsFn != null)
for (final IntFunction what : whatsFn)
writeEvalContext.or(what.writesEvalContextRecursive());
return writeEvalContext;
}
@Override
public BitSet readsEvalContextRecursive()
{
final BitSet readEvalContext = new BitSet();
if (fromFn != null)
readEvalContext.or(fromFn.readsEvalContextRecursive());
if (whatsFn != null)
for (final IntFunction what : whatsFn)
readEvalContext.or(what.readsEvalContextRecursive());
return readEvalContext;
}
@Override
public void preprocess(final Game game)
{
type = SiteType.use(type, game);
if (fromFn != null)
fromFn.preprocess(game);
if (whatsFn != null)
for (final IntFunction what : whatsFn)
what.preprocess(game);
}
@Override
public boolean missingRequirement(final Game game)
{
boolean missingRequirement = false;
if (fromFn != null)
missingRequirement |= fromFn.missingRequirement(game);
if (whatsFn != null)
for (final IntFunction what : whatsFn)
missingRequirement |= what.missingRequirement(game);
return missingRequirement;
}
@Override
public boolean willCrash(final Game game)
{
boolean willCrash = false;
if (fromFn != null)
willCrash |= fromFn.willCrash(game);
if (whatsFn != null)
for (final IntFunction what : whatsFn)
willCrash |= what.willCrash(game);
return willCrash;
}
//-------------------------------------------------------------------------
@Override
public List<Location> satisfyingSites(final Context context)
{
if (!eval(context))
return new ArrayList<Location>();
final List<Location> winningSites = new ArrayList<Location>();
final int from = fromFn.eval(context);
if (from <= Constants.OFF)
return new ArrayList<Location>();
final SiteType realType = (type == null) ? context.board().defaultSite() : type;
final int cid = new ContainerId(null, null, null, null, new IntConstant(from)).eval(context);
final other.topology.Topology graph = context.containers()[cid].topology();
final ContainerState cs = context.containerState(0);
if (from >= graph.getGraphElements(realType).size())
return new ArrayList<Location>();
final int[] whats = (whatsFn != null) ? new int[whatsFn.length] : new int[1];
if (whatsFn != null)
{
for (int i = 0; i < whats.length; i++)
whats[i] = whatsFn[i].eval(context);
}
else
{
final int what = cs.what(from, realType);
if (what == 0)
return new ArrayList<Location>();
whats[0] = what;
}
final List<DirectionFacing> orthogonalSupported = graph.supportedOrthogonalDirections(realType);
List<DirectionFacing> walkDirection;
walkDirection = graph.supportedOrthogonalDirections(realType);
for (final DirectionFacing startDirection : walkDirection)
{
int currentLoc = from;
DirectionFacing currentDirection = startDirection;
int whatIndex = 0;
if (cs.what(from, realType) != whats[whatIndex])
return new ArrayList<Location>();
whatIndex++;
if (whatIndex == whats.length)
whatIndex = 0;
winningSites.add(new FullLocation(from, 0, realType));
boolean found = true;
for (final StepType step : walk)
{
if (step == StepType.F)
{
final List<Step> stepsDirection = graph.trajectories().steps(realType, currentLoc,
currentDirection.toAbsolute());
int to = Constants.UNDEFINED;
for (final Step stepDirection : stepsDirection)
{
if (stepDirection.from().siteType() != stepDirection.to().siteType())
continue;
to = stepDirection.to().id();
}
currentLoc = to;
winningSites.add(new FullLocation(to, 0, realType));
// No correct walk with that state or not correct what.
if (to == Constants.UNDEFINED || cs.what(to, realType) != whats[whatIndex])
{
found = false;
winningSites.clear();
break;
}
whatIndex++;
if (whatIndex == whats.length)
whatIndex = 0;
}
else if (step == StepType.R)
{
currentDirection = currentDirection.right();
while (!orthogonalSupported.contains(currentDirection))
currentDirection = currentDirection.right();
}
else if (step == StepType.L)
{
currentDirection = currentDirection.left();
while (!orthogonalSupported.contains(currentDirection))
currentDirection = currentDirection.left();
}
}
if (found)
return winningSites;
}
return new ArrayList<Location>();
}
//-------------------------------------------------------------------------
@Override
public String toEnglish(final Game game)
{
String whatArrayString = "any sites";
if (whatsFn != null)
{
whatArrayString = "[";
for (final IntFunction i : whatsFn)
whatArrayString += i.toEnglish(game) + ",";
whatArrayString = "the sites " + whatArrayString.substring(0,whatArrayString.length()-1) + "]";
}
String walkArrayString = "[";
for (final StepType s : walk)
walkArrayString += s.name() + ",";
walkArrayString = walkArrayString.substring(0,walkArrayString.length()-1) + "]";
return "the walk " + walkArrayString + " from " + type.name().toLowerCase() + " " + fromFn.toEnglish(game) + " goes through " + whatArrayString;
}
//-------------------------------------------------------------------------
}
| 11,064 | 25.471292 | 146 | java |
Ludii | Ludii-master/Core/src/game/functions/booleans/is/player/IsActive.java | package game.functions.booleans.is.player;
import java.util.BitSet;
import annotations.Hide;
import annotations.Or;
import game.Game;
import game.functions.booleans.BaseBooleanFunction;
import game.functions.ints.IntFunction;
import game.types.play.RoleType;
import other.context.Context;
/**
* Checks if a player is active.
*
* @author Eric.Piette
*/
@Hide
public final class IsActive extends BaseBooleanFunction
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/** Player Index. */
private final IntFunction playerId;
//-------------------------------------------------------------------------
/**
* @param indexPlayer The index of the player.
* @param role The roleType of the player.
*/
public IsActive
(
@Or final IntFunction indexPlayer,
@Or final RoleType role
)
{
int numNonNull = 0;
if (indexPlayer != null)
numNonNull++;
if (role != null)
numNonNull++;
if (numNonNull != 1)
throw new IllegalArgumentException("Exactly one Or parameter must be non-null.");
if (indexPlayer != null)
playerId = indexPlayer;
else
playerId = RoleType.toIntFunction(role);
}
//-------------------------------------------------------------------------
@Override
public boolean eval(final Context context)
{
final int roleId = playerId.eval(context);
if (roleId == 0 || roleId > context.game().players().count())
return false;
return context.active(roleId);
}
//-------------------------------------------------------------------------
@Override
public boolean isStatic()
{
return false;
}
@Override
public long gameFlags(final Game game)
{
return playerId.gameFlags(game);
}
@Override
public BitSet concepts(final Game game)
{
return playerId.concepts(game);
}
@Override
public BitSet writesEvalContextRecursive()
{
final BitSet writeEvalContext = new BitSet();
writeEvalContext.or(playerId.writesEvalContextRecursive());
return writeEvalContext;
}
@Override
public BitSet readsEvalContextRecursive()
{
final BitSet readEvalContext = new BitSet();
readEvalContext.or(playerId.readsEvalContextRecursive());
return readEvalContext;
}
@Override
public void preprocess(final Game game)
{
playerId.preprocess(game);
}
@Override
public boolean missingRequirement(final Game game)
{
boolean missingRequirement = false;
missingRequirement |= playerId.missingRequirement(game);
return missingRequirement;
}
@Override
public boolean willCrash(final Game game)
{
boolean willCrash = false;
willCrash |= playerId.willCrash(game);
return willCrash;
}
//-------------------------------------------------------------------------
/**
* @return Function of which we're checking if the return value is enemy.
*/
public IntFunction role()
{
return playerId;
}
//-------------------------------------------------------------------------
@Override
public String toEnglish(final Game game)
{
return "Player " + playerId.toEnglish(game) + " is active";
}
//-------------------------------------------------------------------------
}
| 3,174 | 20.598639 | 84 | java |
Ludii | Ludii-master/Core/src/game/functions/booleans/is/player/IsEnemy.java | package game.functions.booleans.is.player;
import java.util.BitSet;
import annotations.Hide;
import annotations.Or;
import game.Game;
import game.functions.booleans.BaseBooleanFunction;
import game.functions.ints.IntFunction;
import game.types.play.RoleType;
import gnu.trove.list.array.TIntArrayList;
import other.concept.Concept;
import other.context.Context;
/**
* Checks if a player is an enemy.
*
* @author Eric.Piette
*/
@Hide
public final class IsEnemy extends BaseBooleanFunction
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/** Player Index. */
private final IntFunction playerId;
//-------------------------------------------------------------------------
/**
* @param indexPlayer The index of the player.
* @param role The roleType of the player.
*/
public IsEnemy
(
@Or final IntFunction indexPlayer,
@Or final RoleType role
)
{
int numNonNull = 0;
if (indexPlayer != null)
numNonNull++;
if (role != null)
numNonNull++;
if (numNonNull != 1)
throw new IllegalArgumentException("Exactly one Or parameter must be non-null.");
if (indexPlayer != null)
playerId = indexPlayer;
else
playerId = RoleType.toIntFunction(role);
}
//-------------------------------------------------------------------------
@Override
public boolean eval(final Context context)
{
final int roleId = playerId.eval(context);
if (roleId == 0)
return false;
if (context.game().requiresTeams())
{
final TIntArrayList teamMembers = new TIntArrayList();
final int tid = context.state().getTeam(context.state().mover());
for (int i = 1; i < context.game().players().size(); i++)
if (context.state().getTeam(i) == tid)
teamMembers.add(i);
return !teamMembers.contains(playerId.eval(context));
}
return roleId != context.state().mover();
}
//-------------------------------------------------------------------------
@Override
public boolean isStatic()
{
return playerId.isStatic();
}
@Override
public long gameFlags(final Game game)
{
return playerId.gameFlags(game);
}
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
concepts.set(Concept.IsEnemy.id(), true);
concepts.or(playerId.concepts(game));
return concepts;
}
@Override
public BitSet writesEvalContextRecursive()
{
final BitSet writeEvalContext = new BitSet();
writeEvalContext.or(playerId.writesEvalContextRecursive());
return writeEvalContext;
}
@Override
public BitSet readsEvalContextRecursive()
{
final BitSet readEvalContext = new BitSet();
readEvalContext.or(playerId.readsEvalContextRecursive());
return readEvalContext;
}
@Override
public void preprocess(final Game game)
{
playerId.preprocess(game);
}
@Override
public boolean missingRequirement(final Game game)
{
boolean missingRequirement = false;
missingRequirement |= playerId.missingRequirement(game);
return missingRequirement;
}
@Override
public boolean willCrash(final Game game)
{
boolean willCrash = false;
willCrash |= playerId.willCrash(game);
return willCrash;
}
@Override
public String toEnglish(final Game game)
{
String text="there is an enemy";
if(playerId != null)
text += " " + playerId.toEnglish(game);
return text;
}
//-------------------------------------------------------------------------
/**
* @return Function of which we're checking if the return value is enemy.
*/
public IntFunction role()
{
return playerId;
}
}
| 3,595 | 21.197531 | 84 | java |
Ludii | Ludii-master/Core/src/game/functions/booleans/is/player/IsFriend.java | package game.functions.booleans.is.player;
import java.util.BitSet;
import annotations.Hide;
import annotations.Or;
import game.Game;
import game.functions.booleans.BaseBooleanFunction;
import game.functions.ints.IntFunction;
import game.types.play.RoleType;
import gnu.trove.list.array.TIntArrayList;
import other.concept.Concept;
import other.context.Context;
/**
* Is used to check if a player is a friend.
*
* @author Eric.Piette
*/
@Hide
public final class IsFriend extends BaseBooleanFunction
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/** Player Index. */
private final IntFunction playerId;
//-------------------------------------------------------------------------
/**
* @param indexPlayer The index of the player.
* @param role The roleType of the player.
*/
public IsFriend
(
@Or final IntFunction indexPlayer,
@Or final RoleType role
)
{
int numNonNull = 0;
if (indexPlayer != null)
numNonNull++;
if (role != null)
numNonNull++;
if (numNonNull != 1)
throw new IllegalArgumentException("Exactly one Or parameter must be non-null.");
playerId = (role != null) ? RoleType.toIntFunction(role) : indexPlayer;
}
//-------------------------------------------------------------------------
@Override
public boolean eval(final Context context)
{
if (context.game().requiresTeams())
{
final TIntArrayList teamMembers = new TIntArrayList();
final int tid = context.state().getTeam(context.state().mover());
for (int i = 1; i < context.game().players().size(); i++)
if (context.state().getTeam(i) == tid)
teamMembers.add(i);
return teamMembers.contains(playerId.eval(context));
}
return (playerId.eval(context) == context.state().mover()
|| context.state().mover() == context.game().players().size());
}
//-------------------------------------------------------------------------
@Override
public boolean isStatic()
{
return playerId.isStatic();
}
@Override
public long gameFlags(final Game game)
{
return playerId.gameFlags(game);
}
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
concepts.set(Concept.IsFriend.id(), true);
concepts.or(playerId.concepts(game));
return concepts;
}
@Override
public BitSet writesEvalContextRecursive()
{
final BitSet writeEvalContext = new BitSet();
writeEvalContext.or(playerId.writesEvalContextRecursive());
return writeEvalContext;
}
@Override
public BitSet readsEvalContextRecursive()
{
final BitSet readEvalContext = new BitSet();
readEvalContext.or(playerId.readsEvalContextRecursive());
return readEvalContext;
}
@Override
public void preprocess(final Game game)
{
playerId.preprocess(game);
}
@Override
public boolean missingRequirement(final Game game)
{
boolean missingRequirement = false;
missingRequirement |= playerId.missingRequirement(game);
return missingRequirement;
}
@Override
public boolean willCrash(final Game game)
{
boolean willCrash = false;
willCrash |= playerId.willCrash(game);
return willCrash;
}
@Override
public String toEnglish(final Game game)
{
return "is a friend";
}
//-------------------------------------------------------------------------
/**
* @return The role of the player.
*/
public IntFunction role()
{
return playerId;
}
}
| 3,439 | 21.933333 | 84 | java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.