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/functions/booleans/is/player/IsMover.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 the mover.
*
* @author Eric.Piette
*/
@Hide
public final class IsMover extends BaseBooleanFunction
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/** The index of the player. */
private final IntFunction who;
//-------------------------------------------------------------------------
/**
* @param who The index of the player.
* @param role The roleType of the player.
*/
public IsMover
(
@Or final IntFunction who,
@Or final RoleType role
)
{
int numNonNull = 0;
if (who != null)
numNonNull++;
if (role != null)
numNonNull++;
if (numNonNull != 1)
throw new IllegalArgumentException("Exactly one Or parameter must be non-null.");
this.who = (role != null) ? RoleType.toIntFunction(role) : who;
}
//-------------------------------------------------------------------------
@Override
public boolean eval(final Context context)
{
return (who.eval(context) == context.state().mover());
}
//-------------------------------------------------------------------------
@Override
public boolean isStatic()
{
return false;
}
@Override
public long gameFlags(final Game game)
{
return who.gameFlags(game);
}
@Override
public BitSet concepts(final Game game)
{
return who.concepts(game);
}
@Override
public BitSet writesEvalContextRecursive()
{
final BitSet writeEvalContext = new BitSet();
writeEvalContext.or(who.writesEvalContextRecursive());
return writeEvalContext;
}
@Override
public BitSet readsEvalContextRecursive()
{
final BitSet readEvalContext = new BitSet();
readEvalContext.or(who.readsEvalContextRecursive());
return readEvalContext;
}
@Override
public void preprocess(final Game game)
{
who.preprocess(game);
}
@Override
public boolean missingRequirement(final Game game)
{
boolean missingRequirement = false;
missingRequirement |= who.missingRequirement(game);
return missingRequirement;
}
@Override
public boolean willCrash(final Game game)
{
boolean willCrash = false;
willCrash |= who.willCrash(game);
return willCrash;
}
@Override
public String toEnglish(final Game game)
{
return who.toEnglish(game) + " is the mover";
}
}
| 2,584 | 19.846774 | 84 | java |
Ludii | Ludii-master/Core/src/game/functions/booleans/is/player/IsNext.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 the next player.
*
* @author Eric.Piette
*/
@Hide
public final class IsNext extends BaseBooleanFunction
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/** The index of the player. */
private final IntFunction who;
//-------------------------------------------------------------------------
/**
* @param who The index of the player.
* @param role The roleType of the player.
*/
public IsNext
(
@Or final IntFunction who,
@Or final RoleType role
)
{
int numNonNull = 0;
if (who != null)
numNonNull++;
if (role != null)
numNonNull++;
if (numNonNull != 1)
throw new IllegalArgumentException("Exactly one Or parameter must be non-null.");
this.who = (role != null) ? RoleType.toIntFunction(role) : who;
}
//-------------------------------------------------------------------------
@Override
public boolean eval(final Context context)
{
return (who.eval(context) == context.state().next());
}
//-------------------------------------------------------------------------
@Override
public boolean isStatic()
{
return false;
}
@Override
public long gameFlags(final Game game)
{
return who.gameFlags(game);
}
@Override
public BitSet concepts(final Game game)
{
return who.concepts(game);
}
@Override
public BitSet writesEvalContextRecursive()
{
final BitSet writeEvalContext = new BitSet();
writeEvalContext.or(who.writesEvalContextRecursive());
return writeEvalContext;
}
@Override
public BitSet readsEvalContextRecursive()
{
final BitSet readEvalContext = new BitSet();
readEvalContext.or(who.readsEvalContextRecursive());
return readEvalContext;
}
@Override
public void preprocess(final Game game)
{
who.preprocess(game);
}
@Override
public boolean missingRequirement(final Game game)
{
boolean missingRequirement = false;
missingRequirement |= who.missingRequirement(game);
return missingRequirement;
}
@Override
public boolean willCrash(final Game game)
{
boolean willCrash = false;
willCrash |= who.willCrash(game);
return willCrash;
}
//-------------------------------------------------------------------------
@Override
public String toEnglish(final Game game)
{
return "Player " + who.toEnglish(game) + " is the next mover";
}
//-------------------------------------------------------------------------
}
| 2,762 | 20.585938 | 84 | java |
Ludii | Ludii-master/Core/src/game/functions/booleans/is/player/IsPrev.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 the previous player.
*
* @author Eric.Piette
* @remarks Used to detect if a specific player is the previous player.
*/
@Hide
public final class IsPrev extends BaseBooleanFunction
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/** The index of the player. */
private final IntFunction who;
//-------------------------------------------------------------------------
/**
* @param who The index of the player.
* @param role The roleType of the player.
*/
public IsPrev
(
@Or final IntFunction who,
@Or final RoleType role
)
{
this.who = (role != null) ? RoleType.toIntFunction(role) : who;
}
//-------------------------------------------------------------------------
@Override
public boolean eval(final Context context)
{
return (who.eval(context) == context.state().prev());
}
//-------------------------------------------------------------------------
@Override
public boolean isStatic()
{
return false;
}
@Override
public long gameFlags(final Game game)
{
return who.gameFlags(game);
}
@Override
public BitSet concepts(final Game game)
{
return who.concepts(game);
}
@Override
public BitSet writesEvalContextRecursive()
{
final BitSet writeEvalContext = new BitSet();
writeEvalContext.or(who.writesEvalContextRecursive());
return writeEvalContext;
}
@Override
public BitSet readsEvalContextRecursive()
{
final BitSet readEvalContext = new BitSet();
readEvalContext.or(who.readsEvalContextRecursive());
return readEvalContext;
}
@Override
public void preprocess(final Game game)
{
who.preprocess(game);
}
@Override
public boolean missingRequirement(final Game game)
{
boolean missingRequirement = false;
missingRequirement |= who.missingRequirement(game);
return missingRequirement;
}
@Override
public boolean willCrash(final Game game)
{
boolean willCrash = false;
willCrash |= who.willCrash(game);
return willCrash;
}
@Override
public String toEnglish(final Game game)
{
return "in the same turn";
}
}
| 2,435 | 20 | 76 | java |
Ludii | Ludii-master/Core/src/game/functions/booleans/is/regularGraph/IsRegularGraph.java | package game.functions.booleans.is.regularGraph;
import java.util.BitSet;
import annotations.Hide;
import annotations.Name;
import annotations.Opt;
import annotations.Or;
import annotations.Or2;
import game.Game;
import game.functions.booleans.BaseBooleanFunction;
import game.functions.booleans.BooleanConstant;
import game.functions.booleans.BooleanFunction;
import game.functions.ints.IntConstant;
import game.functions.ints.IntFunction;
import game.functions.ints.last.LastTo;
import game.types.board.SiteType;
import game.types.play.RoleType;
import game.types.state.GameType;
import game.util.moves.Player;
import main.Constants;
import other.context.Context;
import other.state.container.ContainerState;
import other.topology.Edge;
import other.topology.Topology;
/**
* Test the induced graph (with all the vertices and some of edges) is a regular
* graph or not.
*
* @author tahmina and cambolbro and Eric.Piette
*
* @remarks It uses to check the regular graph (or k-regular) to use all the
* vertices and also possible to check odd degree or even degree
* regular graph.
*/
@Hide
public class IsRegularGraph extends BaseBooleanFunction
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/** The type of player. **/
private final IntFunction who;
/** The flag for check G is single or not. */
private final IntFunction kParameter;
/** The flag for all the degree is odd or not. */
private final BooleanFunction oddFn;
/** The flag for all the degree is odd or not. */
private final BooleanFunction evenFn;
//-------------------------------------------------------------------------
/**
* @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.
*/
public IsRegularGraph
(
@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
)
{
this.who = (who != null) ? who.index() : RoleType.toIntFunction(role);
kParameter = (k == null) ? new IntConstant(0) : k;
oddFn = (odd == null) ? new BooleanConstant(false) : odd;
evenFn = (even == null) ? new BooleanConstant(false) : even;
}
//----------------------------------------------------------------------------------
@Override
public boolean eval(final Context context)
{
final int siteId = new LastTo(null).eval(context);
if(siteId == Constants.OFF)
return false;
final Topology graph = context.topology();
final int cid = context.containerId()[0];
final ContainerState state = context.state().containerStates()[cid];
int whoSiteId = who.eval(context);
final boolean oddFlag = oddFn.eval(context);
final boolean evenFlag = evenFn.eval(context);
final int kValue = kParameter.eval(context);
final int totalVertices = graph.vertices().size();
final int totalEdges = graph.edges().size();
final BitSet[] degreeInfo = new BitSet[totalVertices];
if(whoSiteId == 0)
{
if (state.what(siteId, SiteType.Edge) == 0)
whoSiteId = 1;
else
whoSiteId = state.what(siteId, SiteType.Edge);
}
for (int i = 0; i < totalVertices; i++)
{
degreeInfo[i] = new BitSet(totalEdges);
}
for (int k = 0; k < totalEdges; k++)
{
final Edge kEdge = graph.edges().get(k);
if (state.what(kEdge.index(), SiteType.Edge) == whoSiteId)
{
final int vA = kEdge.vA().index();
final int vB = kEdge.vB().index();
degreeInfo[vA].set(vB);
degreeInfo[vB].set(vA);
}
}
int deg = kValue;
if(kValue == 0)
{
for (int i = 0; i < totalVertices; i++)
{
if (degreeInfo[i].cardinality() != 0)
{
deg = degreeInfo[i].cardinality();
break;
}
}
}
for (int i = 0; i < totalVertices; i++)
{
if (deg != degreeInfo[i].cardinality())
return false;
}
if(oddFlag)
{
if((deg % 2) == 1) return true;
else return false;
}
if(evenFlag)
{
if((deg % 2) == 0) return true;
else return false;
}
return true;
}
//-------------------------------------------------------------------------
@Override
public String toString()
{
String str = "";
str += "IsRegularGraph( )";
return str;
}
@Override
public boolean isStatic()
{
return false;
}
@Override
public long gameFlags(final Game game)
{
long gameFlags = GameType.Graph;
if (who != null)
gameFlags |= who.gameFlags(game);
if (kParameter != null)
gameFlags |= kParameter.gameFlags(game);
if (oddFn != null)
gameFlags |= oddFn.gameFlags(game);
if (evenFn != null)
gameFlags |= evenFn.gameFlags(game);
return gameFlags;
}
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
if (who != null)
concepts.or(who.concepts(game));
if (kParameter != null)
concepts.or(kParameter.concepts(game));
if (oddFn != null)
concepts.or(oddFn.concepts(game));
if (evenFn != null)
concepts.or(evenFn.concepts(game));
return concepts;
}
@Override
public BitSet writesEvalContextRecursive()
{
final BitSet writeEvalContext = new BitSet();
if (who != null)
writeEvalContext.or(who.writesEvalContextRecursive());
if (kParameter != null)
writeEvalContext.or(kParameter.writesEvalContextRecursive());
if (oddFn != null)
writeEvalContext.or(oddFn.writesEvalContextRecursive());
if (evenFn != null)
writeEvalContext.or(evenFn.writesEvalContextRecursive());
return writeEvalContext;
}
@Override
public BitSet readsEvalContextRecursive()
{
final BitSet readEvalContext = new BitSet();
if (who != null)
readEvalContext.or(who.readsEvalContextRecursive());
if (kParameter != null)
readEvalContext.or(kParameter.readsEvalContextRecursive());
if (oddFn != null)
readEvalContext.or(oddFn.readsEvalContextRecursive());
if (evenFn != null)
readEvalContext.or(evenFn.readsEvalContextRecursive());
return readEvalContext;
}
@Override
public void preprocess(final Game game)
{
if (who != null)
who.preprocess(game);
if (kParameter != null)
kParameter.preprocess(game);
if (oddFn != null)
oddFn.preprocess(game);
if (evenFn != null)
evenFn.preprocess(game);
}
@Override
public boolean missingRequirement(final Game game)
{
boolean missingRequirement = false;
if (who != null)
missingRequirement |= who.missingRequirement(game);
if (kParameter != null)
missingRequirement |= kParameter.missingRequirement(game);
if (oddFn != null)
missingRequirement |= oddFn.missingRequirement(game);
if (evenFn != null)
missingRequirement |= evenFn.missingRequirement(game);
return missingRequirement;
}
@Override
public boolean willCrash(final Game game)
{
boolean willCrash = false;
if (who != null)
willCrash |= who.willCrash(game);
if (kParameter != null)
willCrash |= kParameter.willCrash(game);
if (oddFn != null)
willCrash |= oddFn.willCrash(game);
if (evenFn != null)
willCrash |= evenFn.willCrash(game);
return willCrash;
}
//-------------------------------------------------------------------------
@Override
public String toEnglish(final Game game)
{
return "the graph is regular";
}
//-------------------------------------------------------------------------
}
| 7,632 | 25.876761 | 85 | java |
Ludii | Ludii-master/Core/src/game/functions/booleans/is/related/IsRelated.java | package game.functions.booleans.is.related;
import java.util.BitSet;
import annotations.Hide;
import annotations.Opt;
import game.Game;
import game.functions.booleans.BaseBooleanFunction;
import game.functions.ints.IntFunction;
import game.types.board.RelationType;
import game.types.board.SiteType;
import other.IntArrayFromRegion;
import other.context.Context;
import other.topology.Cell;
/**
* Checks if two sites are related by a specific relation. Can also checks if a
* site is related by a specific relation with at least one site of a region.
*
* @author Eric.Piette
*/
@Hide
public final class IsRelated extends BaseBooleanFunction
{
private static final long serialVersionUID = 1L;
//------------------------------------------------------------------------
/** Which site. */
protected final IntFunction site;
/** Which region. */
protected final IntArrayFromRegion region;
/** Add on Cell/Edge/Vertex. */
private SiteType type;
/** Add on Cell/Edge/Vertex. */
private final RelationType relationType;
/** Precomputed boolean. */
private Boolean precomputedBoolean;
//-------------------------------------------------------------------------
/**
*
* @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 regionB The region of the second site.
*/
public IsRelated
(
final RelationType relationType,
@Opt final SiteType type,
final IntFunction siteA,
final IntArrayFromRegion regionB
)
{
site = siteA;
region = regionB;
this.type = type;
this.relationType = relationType;
}
//-------------------------------------------------------------------------
@Override
public boolean eval(final Context context)
{
if (precomputedBoolean != null)
return precomputedBoolean.booleanValue();
final int[] sites = region.eval(context);
final int location = site.eval(context);
final other.topology.Topology graph = context.topology();
if ((type == null && context.game().board().defaultSite() != SiteType.Vertex) || type == SiteType.Cell)
{
final Cell cellA = graph.cells().get(location);
switch (relationType)
{
case Adjacent:
for (final int st : sites)
{
final Cell cellB = graph.cells().get(st);
if (cellB.adjacent().contains(cellA))
return true;
}
break;
case Diagonal:
for (final int st : sites)
{
final Cell cellB = graph.cells().get(st);
if (cellB.diagonal().contains(cellA))
return true;
}
break;
case All:
for (final int st : sites)
{
final Cell cellB = graph.cells().get(st);
if (cellB.neighbours().contains(cellA))
return true;
}
break;
case OffDiagonal:
for (final int st : sites)
{
final Cell cellB = graph.cells().get(st);
if (cellB.off().contains(cellA))
return true;
}
break;
case Orthogonal:
for (final int st : sites)
{
final Cell cellB = graph.cells().get(st);
if (cellB.orthogonal().contains(cellA))
return true;
}
break;
default:
break;
}
}
else if ((type == null && context.game().board().defaultSite() != SiteType.Vertex) || type == SiteType.Vertex)
{
final other.topology.Vertex vertexA = graph.vertices().get(location);
switch (relationType)
{
case Adjacent:
for (final int st : sites)
for (final other.topology.Vertex v : vertexA.adjacent())
if (v.index() == st)
return true;
break;
case Diagonal:
for (final int st : sites)
for (final other.topology.Vertex v : vertexA.diagonal())
if (v.index() == st)
return true;
break;
case All:
for (final int st : sites)
for (final other.topology.Vertex v : vertexA.neighbours())
if (v.index() == st)
return true;
break;
case OffDiagonal:
for (final int st : sites)
for (final other.topology.Vertex v : vertexA.off())
if (v.index() == st)
return true;
break;
case Orthogonal:
for (final int st : sites)
for (final other.topology.Vertex v : vertexA.orthogonal())
if (v.index() == st)
return true;
break;
default:
break;
}
}
else
{
final other.topology.Edge edgeA = graph.edges().get(location);
switch (relationType)
{
case Adjacent:
for (final int st : sites)
{
for (final other.topology.Edge edgeB : edgeA.vA().edges())
if (edgeB.index() == st)
return true;
for (final other.topology.Edge edgeB : edgeA.vB().edges())
if (edgeB.index() == st)
return true;
}
break;
case Diagonal:
return false;
case All:
for (final int st : sites)
{
for (final other.topology.Edge edgeB : edgeA.vA().edges())
if (edgeB.index() == st)
return true;
for (final other.topology.Edge edgeB : edgeA.vB().edges())
if (edgeB.index() == st)
return true;
}
break;
case OffDiagonal:
return false;
case Orthogonal:
for (final int st : sites)
{
for (final other.topology.Edge edgeB : edgeA.vA().edges())
if (edgeB.index() == st)
return true;
for (final other.topology.Edge edgeB : edgeA.vB().edges())
if (edgeB.index() == st)
return true;
}
break;
default:
break;
}
}
return false;
}
//-------------------------------------------------------------------------
@Override
public String toString()
{
return "Related(" + site + "," + region + ")";
}
@Override
public boolean isStatic()
{
return region.isStatic() && site.isStatic();
}
@Override
public long gameFlags(final Game game)
{
long gameFlags = region.gameFlags(game) | site.gameFlags(game);
gameFlags |= SiteType.gameFlags(type);
return gameFlags;
}
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
concepts.or(region.concepts(game));
concepts.or(SiteType.concepts(type));
concepts.or(site.concepts(game));
return concepts;
}
@Override
public BitSet writesEvalContextRecursive()
{
final BitSet writeEvalContext = new BitSet();
writeEvalContext.or(region.writesEvalContextRecursive());
writeEvalContext.or(site.writesEvalContextRecursive());
return writeEvalContext;
}
@Override
public BitSet readsEvalContextRecursive()
{
final BitSet readEvalContext = new BitSet();
readEvalContext.or(region.readsEvalContextRecursive());
readEvalContext.or(site.readsEvalContextRecursive());
return readEvalContext;
}
@Override
public boolean missingRequirement(final Game game)
{
boolean missingRequirement = false;
missingRequirement |= region.missingRequirement(game);
missingRequirement |= site.missingRequirement(game);
return missingRequirement;
}
@Override
public boolean willCrash(final Game game)
{
boolean willCrash = false;
willCrash |= region.willCrash(game);
willCrash |= site.willCrash(game);
return willCrash;
}
@Override
public void preprocess(final Game game)
{
type = SiteType.use(type, game);
site.preprocess(game);
region.preprocess(game);
if (isStatic())
precomputedBoolean = Boolean.valueOf(eval(new Context(game, null)));
}
//-------------------------------------------------------------------------
@Override
public String toEnglish(final Game game)
{
return type.name().toLowerCase() + " " + site.toEnglish(game) + " is " + relationType.name() + " to any site in " + region.toEnglish(game);
}
//-------------------------------------------------------------------------
} | 7,690 | 23.571885 | 141 | java |
Ludii | Ludii-master/Core/src/game/functions/booleans/is/repeat/IsRepeat.java | package game.functions.booleans.is.repeat;
import java.util.BitSet;
import annotations.Hide;
import annotations.Opt;
import game.Game;
import game.functions.booleans.BaseBooleanFunction;
import game.types.play.RepetitionType;
import game.types.state.GameType;
import other.concept.Concept;
import other.context.Context;
/**
* 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 IsRepeat extends BaseBooleanFunction
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/** The repetitionType. */
private final RepetitionType type;
/**
* @param type The component.
*/
public IsRepeat
(
@Opt final RepetitionType type
)
{
this.type = (type == null) ? RepetitionType.Positional : type;
}
//-------------------------------------------------------------------------
@Override
public boolean eval(final Context context)
{
switch (type)
{
case PositionalInTurn:
{
final long hashState = context.state().stateHash();
return context.trial().previousStateWithinATurn().contains(hashState);
}
case SituationalInTurn:
{
final long hashState = context.state().fullHash();
return context.trial().previousStateWithinATurn().contains(hashState);
}
case Positional:
{
final long hashState = context.state().stateHash();
return context.trial().previousState().contains(hashState);
}
case Situational:
{
final long hashState = context.state().fullHash();
return context.trial().previousState().contains(hashState);
}
default:
break;
}
return false;
}
//-------------------------------------------------------------------------
@Override
public String toString()
{
return "IsRepeat(" + type + ")";
}
@Override
public boolean isStatic()
{
return false;
}
@Override
public long gameFlags(final Game game)
{
long gameFlags = 0l;
if (type == RepetitionType.Positional)
gameFlags |= GameType.RepeatPositionalInGame;
if (type == RepetitionType.PositionalInTurn)
gameFlags |= GameType.RepeatPositionalInTurn;
if (type == RepetitionType.Situational)
gameFlags |= GameType.RepeatSituationalInGame;
if (type == RepetitionType.SituationalInTurn)
gameFlags |= GameType.RepeatSituationalInTurn;
return gameFlags;
}
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
concepts.set(Concept.PositionalSuperko.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.
}
}
| 3,002 | 20.45 | 80 | java |
Ludii | Ludii-master/Core/src/game/functions/booleans/is/simple/IsCycle.java | package game.functions.booleans.is.simple;
import java.util.BitSet;
import annotations.Hide;
import game.Game;
import game.functions.booleans.BaseBooleanFunction;
import game.types.state.GameType;
import gnu.trove.list.array.TLongArrayList;
import other.context.Context;
import other.trial.Trial;
/**
* Returns true if the game is repeating the same set of states three times with
* exactly the same moves during these states.
*
* @author Eric.Piette
*/
@Hide
public final class IsCycle extends BaseBooleanFunction
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/**
*
*/
public IsCycle()
{
// Nothing to do.
}
//-------------------------------------------------------------------------
@Override
public boolean eval(final Context context)
{
final Trial trial = context.trial();
final TLongArrayList previousStates = trial.previousState();
final int sizeCycle = context.game().players().count() * context.game().players().count();
if(previousStates.size() < 3 * sizeCycle)
return false;
final TLongArrayList cycleToCheck = new TLongArrayList();
int index = previousStates.size() - 1;
for(; index > (previousStates.size() - 1) - sizeCycle; index--)
cycleToCheck.add(previousStates.get(index));
// Check one loop
int cycleIndex = 0;
for(; index > (previousStates.size() - 1) - (sizeCycle * 2); index--)
{
if(previousStates.get(index) != cycleToCheck.get(cycleIndex))
return false;
cycleIndex++;
}
// Check second loop
cycleIndex = 0;
for(; index > (previousStates.size() - 1) - (sizeCycle * 3); index--)
{
if(previousStates.get(index) != cycleToCheck.get(cycleIndex))
return false;
cycleIndex++;
}
return true;
}
//-------------------------------------------------------------------------
@Override
public String toString()
{
return "AllPass()";
}
//-------------------------------------------------------------------------
@Override
public boolean isStatic()
{
return false;
}
@Override
public long gameFlags(final Game game)
{
long gameFlags = 0l;
gameFlags |= GameType.CycleDetection;
return gameFlags;
}
@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
}
//-------------------------------------------------------------------------
@Override
public String toEnglish(final Game game)
{
return "we have repeated the same state three times";
}
//-------------------------------------------------------------------------
}
| 2,968 | 21.156716 | 92 | java |
Ludii | Ludii-master/Core/src/game/functions/booleans/is/simple/IsFull.java | package game.functions.booleans.is.simple;
import java.util.BitSet;
import annotations.Hide;
import game.Game;
import game.functions.booleans.BaseBooleanFunction;
import other.context.Context;
/**
* Checks if there are no empty cells in the board.
*
* @author Eric.Piette and cambolbro
*/
@Hide
public final class IsFull extends BaseBooleanFunction
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/**
*
*/
public IsFull()
{
}
//-------------------------------------------------------------------------
@Override
public boolean eval(final Context context)
{
return context.state().containerStates()[0].emptyRegion(context.board().defaultSite()).sites().length == 0;
}
//-------------------------------------------------------------------------
@Override
public String toString()
{
String str = "";
str += "Full()";
return str;
}
//-------------------------------------------------------------------------
@Override
public boolean isStatic()
{
return false;
}
@Override
public long gameFlags(final Game game)
{
return 0;
}
@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)
{
// Do Nothing
}
//-------------------------------------------------------------------------
@Override
public String toEnglish(final Game game)
{
return "all board sites are occupied";
}
//-------------------------------------------------------------------------
}
| 1,887 | 18.070707 | 109 | java |
Ludii | Ludii-master/Core/src/game/functions/booleans/is/simple/IsPending.java | package game.functions.booleans.is.simple;
import java.util.BitSet;
import annotations.Hide;
import game.Game;
import game.functions.booleans.BaseBooleanFunction;
import other.context.Context;
/**
* Checks if the current state is a pending state.
*
* @author Eric.Piette
* @remarks A state is in pending if any value is on the pending list.
*/
@Hide
public final class IsPending extends BaseBooleanFunction
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/**
*
*/
public IsPending()
{
// Nothing to do.
}
//-------------------------------------------------------------------------
@Override
public boolean eval(final Context context)
{
return context.state().isPending();
}
//-------------------------------------------------------------------------
@Override
public boolean isStatic()
{
return false;
}
@Override
public long gameFlags(final Game game)
{
return 0L;
}
@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)
{
// Do nothing.
}
//-------------------------------------------------------------------------
@Override
public String toEnglish(final Game game)
{
return "a state is pending";
}
//-------------------------------------------------------------------------
}
| 1,716 | 18.077778 | 76 | java |
Ludii | Ludii-master/Core/src/game/functions/booleans/is/site/IsEmpty.java | package game.functions.booleans.is.site;
import java.util.BitSet;
import annotations.Hide;
import annotations.Opt;
import game.Game;
import game.functions.booleans.BaseBooleanFunction;
import game.functions.ints.IntFunction;
import game.types.board.SiteType;
import other.concept.Concept;
import other.context.Context;
import other.state.container.ContainerState;
/**
* Checks if a site is empty.
*
* @author Eric.Piette
*/
@Hide
public final class IsEmpty extends BaseBooleanFunction
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/** The graph Element type to check. */
private SiteType type;
/** The index of the site. */
private final IntFunction siteFn;
//-------------------------------------------------------------------------
/**
* @param type The graph element type [default SiteType of the board].
* @param site The index of the site.
*/
public IsEmpty
(
@Opt final SiteType type,
final IntFunction site
)
{
this.type = type;
siteFn = site;
}
//-------------------------------------------------------------------------
@Override
public boolean eval(final Context context)
{
final int site = siteFn.eval(context);
if (site < 0)
return false;
final int cid = site < context.containerId().length ? context.containerId()[site] : 0;
if (cid == 0 && site >= context.topology().getGraphElements(type).size())
return false;
final ContainerState cs = context.containerState(cid);
return cs.isEmpty(site, type);
}
//-------------------------------------------------------------------------
@Override
public boolean isStatic()
{
return false;
}
@Override
public long gameFlags(final Game game)
{
long gameFlags = siteFn.gameFlags(game);
gameFlags |= SiteType.gameFlags(type);
return gameFlags;
}
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
concepts.set(Concept.IsEmpty.id(), true);
concepts.or(SiteType.concepts(type));
concepts.or(siteFn.concepts(game));
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)
{
type = SiteType.use(type, 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 "empty";
}
}
| 3,053 | 20.659574 | 88 | java |
Ludii | Ludii-master/Core/src/game/functions/booleans/is/site/IsOccupied.java | package game.functions.booleans.is.site;
import java.util.BitSet;
import annotations.Hide;
import annotations.Opt;
import game.Game;
import game.functions.booleans.BaseBooleanFunction;
import game.functions.ints.IntFunction;
import game.types.board.SiteType;
import other.context.Context;
import other.state.container.ContainerState;
/**
* Checks if a site is occupied.
*
* @author Eric.Piette
*/
@Hide
public final class IsOccupied extends BaseBooleanFunction
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/** The graph Element type to check. */
private SiteType type;
/** The index of the site. */
private final IntFunction siteFn;
//-------------------------------------------------------------------------
/**
* @param type The graph element type [default SiteType of the board].
* @param site The index of the site.
*/
public IsOccupied
(
@Opt final SiteType type,
final IntFunction site
)
{
this.type = type;
siteFn = site;
}
//-------------------------------------------------------------------------
@Override
public boolean eval(final Context context)
{
final int site = siteFn.eval(context);
if (site < 0 || site >= context.containerId().length)
return false;
final ContainerState cs = context.containerState((context.containerId()[site]));
return cs.what(site, type) != 0;
}
//-------------------------------------------------------------------------
@Override
public boolean isStatic()
{
return false;
}
@Override
public long gameFlags(final Game game)
{
long gameFlags = siteFn.gameFlags(game);
gameFlags |= SiteType.gameFlags(type);
return gameFlags;
}
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
concepts.or(SiteType.concepts(type));
concepts.or(siteFn.concepts(game));
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)
{
type = SiteType.use(type, 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)
{
final SiteType realSiteType = (type == null) ? game.board().defaultSite() : type;
return realSiteType.name().toLowerCase() + " " + siteFn.toEnglish(game) + " is occupied" ;
}
//-------------------------------------------------------------------------
}
| 3,189 | 21.94964 | 92 | java |
Ludii | Ludii-master/Core/src/game/functions/booleans/is/string/IsDecided.java | package game.functions.booleans.is.string;
import java.util.BitSet;
import annotations.Hide;
import game.Game;
import game.functions.booleans.BaseBooleanFunction;
import game.types.state.GameType;
import main.Constants;
import other.context.Context;
/**
* Returns true if that decision was made.
*
* @author Eric.Piette
*/
@Hide
public final class IsDecided extends BaseBooleanFunction
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
private final String decision;
/** int representation of the decision */
private int decisionInt;
//-------------------------------------------------------------------------
/**
* @param decision Decision to be decided.
*
* @example (isDecided "End")
*/
public IsDecided
(
final String decision
)
{
this.decision = decision;
decisionInt = Constants.UNDEFINED;
}
//-------------------------------------------------------------------------
@Override
public boolean eval(final Context context)
{
return context.state().isDecided() == decisionInt;
}
//-------------------------------------------------------------------------
@Override
public String toString()
{
return "IsDecided()";
}
//-------------------------------------------------------------------------
@Override
public boolean isStatic()
{
return false;
}
@Override
public long gameFlags(final Game game)
{
return GameType.Vote;
}
@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)
{
decisionInt = game.registerVoteString(decision);
}
//-------------------------------------------------------------------------
@Override
public String toEnglish(final Game game)
{
return decision + " has been made";
}
//-------------------------------------------------------------------------
}
| 2,235 | 18.787611 | 76 | java |
Ludii | Ludii-master/Core/src/game/functions/booleans/is/string/IsProposed.java | package game.functions.booleans.is.string;
import java.util.BitSet;
import annotations.Hide;
import game.Game;
import game.functions.booleans.BaseBooleanFunction;
import game.types.state.GameType;
import main.Constants;
import other.context.Context;
/**
* Returns true if that proposition is proposed.
*
* @author Eric.Piette
*/
@Hide
public final class IsProposed extends BaseBooleanFunction
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
private final String proposition;
/** int representation of the proposition */
private int propositionInt;
//-------------------------------------------------------------------------
/**
* @param proposition Proposition being proposed.
*
* @example (isProposed "End")
*/
public IsProposed(final String proposition)
{
this.proposition = proposition;
propositionInt = Constants.UNDEFINED;
}
//-------------------------------------------------------------------------
@Override
public boolean eval(final Context context)
{
return context.state().propositions().contains(propositionInt);
}
//-------------------------------------------------------------------------
@Override
public String toString()
{
return "IsProposed()";
}
//-------------------------------------------------------------------------
@Override
public boolean isStatic()
{
return false;
}
@Override
public long gameFlags(final Game game)
{
return GameType.Vote;
}
@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)
{
propositionInt = game.registerVoteString(proposition);
}
@Override
public String toEnglish(final Game game)
{
return "The proposed is " +proposition;
}
}
| 2,131 | 19.304762 | 76 | java |
Ludii | Ludii-master/Core/src/game/functions/booleans/is/target/IsTarget.java | package game.functions.booleans.is.target;
import java.util.Arrays;
import java.util.BitSet;
import annotations.Hide;
import annotations.Opt;
import annotations.Or;
import game.Game;
import game.equipment.container.board.Board;
import game.functions.booleans.BaseBooleanFunction;
import game.functions.ints.IntFunction;
import game.types.board.SiteType;
import other.ContainerId;
import other.context.Context;
import other.state.container.ContainerState;
import other.state.stacking.BaseContainerStateStacking;
import other.topology.Cell;
import other.topology.TopologyElement;
/**
* Returns true when a specific configuration is on the board.
*
* @author Eric.Piette
*
* @remarks Used in the ending condition when the goal of the game is to place
* some pieces in a specific configuration.
*/
@Hide
public class IsTarget extends BaseBooleanFunction
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/** Which container. */
private final ContainerId containerId;
/** The configuration. */
private final int[] configuration;
/** The specific sites of the configuration. */
private final int[] specificSites;
//-------------------------------------------------------------------------
/**
* @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.
*/
public IsTarget
(
@Opt @Or final IntFunction containerIdFn,
@Opt @Or final String containerName,
final Integer[] configuration,
@Opt @Or final Integer specificSite,
@Opt @Or final Integer[] specificSites
)
{
containerId = new ContainerId(containerIdFn, containerName, null, null, null);
this.configuration = new int[configuration.length];
for (int i = 0; i < configuration.length; ++i)
this.configuration[i] = configuration[i].intValue();
if (specificSites != null)
{
this.specificSites = new int[specificSites.length];
for (int i = 0; i < specificSites.length; ++i)
this.specificSites[i] = specificSites[i].intValue();
}
else if (specificSite != null)
{
this.specificSites = new int[]
{ specificSite.intValue() };
}
else
{
this.specificSites = null;
}
}
//-------------------------------------------------------------------------
@Override
public boolean eval(final Context context)
{
if (context.game().isStacking())
return evalStack(context);
final int cid = containerId.eval(context);
final ContainerState state = context.state().containerStates()[cid];
final SiteType type = context.board().defaultSite();
if (specificSites == null)
{
final Board board = ((Board) context.containers()[cid]);
final other.topology.Topology graph = board.topology();
if (graph.cells().size() != configuration.length)
{
return false;
}
for (final TopologyElement element : graph.getGraphElements(type))
{
if (state.what(element.index(), type) != configuration[element.index()])
{
return false;
}
}
return true;
}
else if (configuration.length == specificSites.length)
{
for (int i = 0; i < specificSites.length; i++)
{
final int site = specificSites[i];
if (state.what(site, type) != configuration[i])
{
return false;
}
}
return true;
}
else
{
return false;
}
}
//-------------------------------------------------------------------------
/**
* To evaluate the configuration of a stack on each site.
* @param context
* @return
*/
private boolean evalStack(Context context)
{
final int cid = containerId.eval(context);
final Board board = ((Board) context.containers()[cid]);
final other.topology.Topology graph = board.topology();
final BaseContainerStateStacking state = (BaseContainerStateStacking) context.state().containerStates()[cid];
if (specificSites == null)
{
for (final Cell v : graph.cells())
{
if (configuration.length != state.sizeStackCell(v.index()))
{
break;
}
else
{
int i;
for (i = 0; i < configuration.length; i++)
if (state.whatCell(v.index(), i) != configuration[i])
break;
if (i == configuration.length)
return true;
}
}
return false;
}
else
{
for (int j = 0; j < specificSites.length; j++)
{
final int site = specificSites[j];
if (configuration.length != state.sizeStackCell(site))
{
continue;
}
else
{
int i;
for (i = 0 ; i < configuration.length ; i++)
{
if (state.whatCell(site, i) != configuration[i])
{
break;
}
}
if (i == configuration.length)
{
return true;
}
}
}
return false;
}
}
@Override
public String toString()
{
String str = "";
str += "Configuration(" + containerId + ",";
for (int i = 0; i < configuration.length; ++i)
{
str += configuration[i] + "-";
}
str += ")";
return str;
}
//-------------------------------------------------------------------------
@Override
public boolean isStatic()
{
return false;
}
@Override
public long gameFlags(final Game game)
{
return 0l;
}
@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)
{
// Do nothing
}
//-------------------------------------------------------------------------
@Override
public String toEnglish(final Game game)
{
return "the pieces " + Arrays.toString(configuration) + " are on the sites " + Arrays.toString(specificSites);
}
//-------------------------------------------------------------------------
}
| 6,220 | 22.835249 | 112 | java |
Ludii | Ludii-master/Core/src/game/functions/booleans/is/tree/IsCaterpillarTree.java | package game.functions.booleans.is.tree;
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.functions.ints.last.LastTo;
import game.types.board.SiteType;
import game.types.play.RoleType;
import game.types.state.GameType;
import game.util.moves.Player;
import main.Constants;
import other.context.Context;
import other.state.container.ContainerState;
import other.topology.Edge;
import other.topology.Topology;
/**
* Test the induced graph (by adding or deleting edges) is the largest
* caterpillarTree tree or not.
*
* @author tahmina and cambolbro and Eric.Piette
*
* @remarks It is used to check the induced graph (by adding or deleting edges)
* is the largest caterpillarTree tree or not.
*/
@Hide
public class IsCaterpillarTree extends BaseBooleanFunction
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/** The type of player. **/
private final IntFunction who;
//-------------------------------------------------------------------------
/**
* @param who Data about the owner of the tree.
* @param role RoleType of the owner of the tree.
*/
public IsCaterpillarTree
(
@Or final Player who,
@Or final RoleType role
)
{
this.who = (role != null) ? RoleType.toIntFunction(role) : who.index();
}
//----------------------------------------------------------------------------------
@Override
public boolean eval(final Context context)
{
final int siteId = new LastTo(null).eval(context);
if(siteId == Constants.OFF)
return false;
final Topology graph = context.topology();
final int cid = context.containerId()[0];
final ContainerState state = context.state().containerStates()[cid];
int whoSiteId = who.eval(context);
final int totalVertices = graph.vertices().size();
final int totalEdges = graph.edges().size();
final int[] localParent = new int [totalVertices];
int totalExistingedges = 0;
if(whoSiteId == 0)
{
if (state.what(siteId, SiteType.Edge) == 0)
whoSiteId = 1;// for neutral player
else
whoSiteId = state.what(siteId, SiteType.Edge);
}
for (int i = 0; i < totalVertices; i++)
{
localParent[i] = i;
}
for(int k = 0; k < totalEdges; k++)
{
if(state.what(k, SiteType.Edge) == whoSiteId)
{
final Edge kEdge = graph.edges().get(k);
final int vARoot = find(kEdge.vA().index(), localParent);
final int vBRoot = find(kEdge.vB().index(), localParent);
if (vARoot == vBRoot)
return false;
localParent[vARoot] = vBRoot;
totalExistingedges++;
}
}
if(totalExistingedges != (totalVertices - 1))
return false;
int count = 0;
for(int i = 0; i < totalVertices; i++)
{
if(localParent[i] == i)
count++;
}
if(count != 1)
return false;
final BitSet caterpillarBackbone = new BitSet(totalEdges);
for(int k = 0; k < totalEdges; k++)
{
final Edge kEdge = graph.edges().get(k);
if(state.what(k, SiteType.Edge) == whoSiteId)
{
final int kEdgevA = kEdge.vA().index();
int degree1 = 0;
for(int ka = 0; ka < totalEdges; ka++)
{
final Edge kaEdge = graph.edges().get(ka);
if (state.what(ka, SiteType.Edge) == whoSiteId)
{
if((kEdgevA == kaEdge.vA().index())||(kEdgevA == kaEdge.vB().index()))
{
degree1++;
if(degree1 > 1)
break;
}
}
}
if(degree1 < 2)
continue;
final int kEdgevB = kEdge.vB().index();
int degree2 = 0;
for(int kb = 0; kb < totalEdges; kb++)
{
final Edge kbEdge = graph.edges().get(kb);
if (state.what(kb, SiteType.Edge) == whoSiteId)
{
if((kEdgevB == kbEdge.vA().index())||(kEdgevB == kbEdge.vB().index()))
{
degree2++;
if(degree2 > 1)
break;
}
}
}
if((degree1 > 1) && (degree2 > 1))
{
caterpillarBackbone.set(kEdge.index());
}
}
}
final Edge kEdge = graph.edges().get(caterpillarBackbone.nextSetBit(0));
final int v1 = kEdge.vA().index();
final int v2 = kEdge.vB().index();
final BitSet depthBitset1 = new BitSet(totalVertices);
final BitSet depthBitset2 = new BitSet(totalVertices);
final BitSet visitedEdge = new BitSet(totalEdges);
final int componentSz = totalVertices;
dfsMinPathEdge(context, graph, kEdge, caterpillarBackbone, visitedEdge, 0, v1, v2, componentSz, depthBitset1, whoSiteId);
dfsMinPathEdge(context, graph, kEdge, caterpillarBackbone, visitedEdge, 0, v2, v1, componentSz, depthBitset2, whoSiteId);
final int pathLength = (depthBitset1.cardinality() - 1) + (depthBitset2.cardinality() - 1) + 1;
return (pathLength == caterpillarBackbone.cardinality()); // If only one path then caterpillar, otherwise not
}
//--------------------------------------------------------------------------------------------
/**
* @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 position A vertex.
* @param parent The array with parent id.
*
* @return The root of the position.
*/
private int find(final int position, final int[] parent)
{
final int parentId = parent[position];
if (parentId == position)
return position;
return find (parentId, parent);
}
//-------------------------------------------------------------------------
@Override
public String toString()
{
return "IsCaterpillarTree( )";
}
@Override
public boolean isStatic()
{
return false;
}
@Override
public long gameFlags(final Game game)
{
return GameType.Graph | who.gameFlags(game);
}
@Override
public BitSet concepts(final Game game)
{
return who.concepts(game);
}
@Override
public BitSet writesEvalContextRecursive()
{
final BitSet writeEvalContext = new BitSet();
writeEvalContext.or(who.writesEvalContextRecursive());
return writeEvalContext;
}
@Override
public BitSet readsEvalContextRecursive()
{
final BitSet readEvalContext = new BitSet();
readEvalContext.or(who.readsEvalContextRecursive());
return readEvalContext;
}
@Override
public void preprocess(final Game game)
{
who.preprocess(game);
}
@Override
public boolean missingRequirement(final Game game)
{
boolean missingRequirement = false;
missingRequirement |= who.missingRequirement(game);
return missingRequirement;
}
@Override
public boolean willCrash(final Game game)
{
boolean willCrash = false;
willCrash |= who.willCrash(game);
return willCrash;
}
}
| 8,677 | 26.11875 | 134 | java |
Ludii | Ludii-master/Core/src/game/functions/booleans/is/tree/IsSpanningTree.java | package game.functions.booleans.is.tree;
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.functions.ints.last.LastTo;
import game.types.board.SiteType;
import game.types.play.RoleType;
import game.types.state.GameType;
import game.util.moves.Player;
import main.Constants;
import other.context.Context;
import other.state.container.ContainerState;
import other.topology.Edge;
import other.topology.Topology;
/**
* Test the induced graph (by adding or deleting edges) is a spanning tree or
* not.
*
* @author tahmina and cambolbro and Eric.Piette
*
* @remarks It is used for test the induced graph (by adding or deleting edges)
* is a spanning tree or not.
*/
@Hide
public class IsSpanningTree extends BaseBooleanFunction
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/** The type of player. **/
private final IntFunction who;
//------------------------------------------------------------------
/**
* @param who Data about the owner of the tree.
* @param role RoleType of the owner of the tree.
*/
public IsSpanningTree
(
@Or final Player who,
@Or final RoleType role
)
{
this.who = (role != null) ? RoleType.toIntFunction(role) : who.index();
}
//-----------------------------------------------------------------
@Override
public boolean eval(final Context context)
{
final int siteId = new LastTo(null).eval(context);
if(siteId == Constants.OFF)
return false;
final Topology graph = context.topology();
final int cid = context.containerId()[0];
final ContainerState state = context.state().containerStates()[cid];
int whoSiteId = who.eval(context);
final int totalVertices = graph.vertices().size();
final int[] localParent = new int [totalVertices];
int totalExistingedges = 0;
if(whoSiteId == 0)
{
if (state.what(siteId, SiteType.Edge) == 0)
whoSiteId = 1;// for neutral player
else
whoSiteId = state.what(siteId, SiteType.Edge);
}
for (int i = 0; i < totalVertices; i++)
{
localParent[i] = i;
}
for(int k = graph.edges().size() - 1; k >= 0; k--)
{
if(state.what(k, SiteType.Edge) == whoSiteId)
{
final Edge kEdge = graph.edges().get(k);
final int vARoot = find(kEdge.vA().index(), localParent);
final int vBRoot = find(kEdge.vB().index(), localParent);
if (vARoot == vBRoot)
return false;
localParent[vARoot] = vBRoot;
totalExistingedges++;
}
}
if(totalExistingedges != (totalVertices - 1))
return false;
//int count = 0;
//for(int i = 0; i < totalVertices; i++)
//{
// if(localParent[i] == i)
// count++;
//}
//return (count == 1);
return true;
}
//------------------------------------------------------------------------
/**
*
* @param position A vertex.
* @param parent The array with parent id.
*
* @return The root of the position.
*/
private int find(final int position, final int[] parent)
{
final int parentId = parent[position];
if (parentId == position)
return position;
return find (parentId, parent);
}
//------------------------------------------------------------------------
@Override
public String toString()
{
return "IsSpanningTree( )";
}
@Override
public boolean isStatic()
{
return false;
}
@Override
public long gameFlags(final Game game)
{
return GameType.Graph | who.gameFlags(game);
}
@Override
public BitSet concepts(final Game game)
{
return who.concepts(game);
}
@Override
public BitSet writesEvalContextRecursive()
{
final BitSet writeEvalContext = new BitSet();
writeEvalContext.or(who.writesEvalContextRecursive());
return writeEvalContext;
}
@Override
public BitSet readsEvalContextRecursive()
{
final BitSet readEvalContext = new BitSet();
readEvalContext.or(who.readsEvalContextRecursive());
return readEvalContext;
}
@Override
public void preprocess(final Game game)
{
who.preprocess(game);
}
@Override
public boolean missingRequirement(final Game game)
{
boolean missingRequirement = false;
missingRequirement |= who.missingRequirement(game);
return missingRequirement;
}
@Override
public boolean willCrash(final Game game)
{
boolean willCrash = false;
willCrash |= who.willCrash(game);
return willCrash;
}
//-------------------------------------------------------------------------
@Override
public String toEnglish(final Game game)
{
return "Player " + who.toEnglish(game) + "has formed a spanning tree";
}
//-------------------------------------------------------------------------
}
| 4,888 | 23.323383 | 79 | java |
Ludii | Ludii-master/Core/src/game/functions/booleans/is/tree/IsTree.java | package game.functions.booleans.is.tree;
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.functions.ints.last.LastTo;
import game.types.board.SiteType;
import game.types.play.RoleType;
import game.types.state.GameType;
import game.util.moves.Player;
import main.Constants;
import other.context.Context;
import other.state.container.ContainerState;
import other.topology.Edge;
import other.topology.Topology;
/**
* Test the induced graph (by adding or deleting edges) is a tree or not.
*
* @author tahmina and cambolbro and Eric.Piette
*
* @remarks It used for any GT game, where we need to detect a tree.
*/
@Hide
public class IsTree extends BaseBooleanFunction
{
private static final long serialVersionUID = 1L;
//----------------------------------------------------------------------------------
/** The type of player. **/
private final IntFunction who;
/**
* @param who Data about the owner of the tree.
* @param role RoleType of the owner of the tree.
*/
public IsTree
(
@Or final Player who,
@Or final RoleType role
)
{
this.who = (role != null) ? RoleType.toIntFunction(role) : who.index();
}
//----------------------------------------------------------------------------------
@Override
public boolean eval(final Context context)
{
final int siteId = new LastTo(null).eval(context);
if(siteId == Constants.OFF)
return false;
final Topology graph = context.topology();
final int cid = context.containerId()[0];
final ContainerState state = context.state().containerStates()[cid];
int whoSiteId = who.eval(context);
final int totalVertices = graph.vertices().size();
final int[] localParent = new int [totalVertices];
if(whoSiteId == 0)
{
if (state.what(siteId, SiteType.Edge) == 0)
whoSiteId = 1; // for neutral player
else
whoSiteId = state.what(siteId, SiteType.Edge);
}
for (int i = 0; i < totalVertices; i++)
{
localParent[i] = i;
}
for(int k = graph.edges().size() - 1; k >= 0; k--)
{
if(state.what(k, SiteType.Edge) == whoSiteId)
{
final Edge kEdge = graph.edges().get(k);
final int vARoot = find(kEdge.vA().index(), localParent);
final int vBRoot = find(kEdge.vB().index(), localParent);
if (vARoot == vBRoot) return false;
localParent[vARoot] = vBRoot;
}
}
return true;
}
//----------------------------------------------------------------------
/**
*
* @param position A location.
* @param parent The array with parent id.
*
* @return The root of the position.
*/
private int find(final int position, final int[] parent)
{
final int parentId = parent[position];
if (parentId == position)
return position;
return find (parentId, parent);
}
//-------------------------------------------------------------------------
@Override
public String toString()
{
return "IsTree()";
}
@Override
public boolean isStatic()
{
return false;
}
@Override
public long gameFlags(final Game game)
{
return GameType.Graph | who.gameFlags(game);
}
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
concepts.or(who.concepts(game));
return concepts;
}
@Override
public BitSet writesEvalContextRecursive()
{
final BitSet writeEvalContext = new BitSet();
writeEvalContext.or(who.writesEvalContextRecursive());
return writeEvalContext;
}
@Override
public BitSet readsEvalContextRecursive()
{
final BitSet readEvalContext = new BitSet();
readEvalContext.or(who.readsEvalContextRecursive());
return readEvalContext;
}
@Override
public void preprocess(final Game game)
{
who.preprocess(game);
}
@Override
public boolean missingRequirement(final Game game)
{
boolean missingRequirement = false;
missingRequirement |= who.missingRequirement(game);
return missingRequirement;
}
@Override
public boolean willCrash(final Game game)
{
boolean willCrash = false;
willCrash |= who.willCrash(game);
return willCrash;
}
//-------------------------------------------------------------------------
@Override
public String toEnglish(final Game game)
{
return "Player " + who.toEnglish(game) + "has formed a tree";
}
//-------------------------------------------------------------------------
}
| 4,543 | 22.790576 | 85 | java |
Ludii | Ludii-master/Core/src/game/functions/booleans/is/tree/IsTreeCentre.java | package game.functions.booleans.is.tree;
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.functions.ints.last.LastTo;
import game.types.board.SiteType;
import game.types.play.RoleType;
import game.types.state.GameType;
import game.util.moves.Player;
import other.context.Context;
import other.state.container.ContainerState;
import other.topology.Edge;
import other.topology.Topology;
/**
* Tests whether the selected vertex is the center of the tree (or sub tree).
*
* @author tahmina and cambolbro
*
* @remarks It is used to confirm the last move is a center of the tree or not.
*/
@Hide
public class IsTreeCentre extends BaseBooleanFunction
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/** The type of player. **/
private final IntFunction who;
/**
* @param who Data about the owner of the tree.
* @param role RoleType of the owner of the tree.
*/
public IsTreeCentre
(
@Or final Player who,
@Or final RoleType role
)
{
this.who = (role != null) ? RoleType.toIntFunction(role) : who.index();
}
//----------------------------------------------------------------------------------
@Override
public boolean eval(final Context context)
{
final int siteId = new LastTo(null).eval(context);
final Topology graph = context.topology();
final ContainerState state = context.state().containerStates()[0];
final int whoSiteId = who.eval(context);
final int numPlayers = context.game().players().count();
final int totalVertices = graph.vertices().size();
final int totalEdges = graph.edges().size();
final int[] localParent = new int [totalVertices];
final BitSet[] itemsList = new BitSet[totalVertices];
final BitSet[] adjacencyGraph= new BitSet[totalVertices];
//System.out.println(" Who : "+whoSiteId);
for (int i = 0; i < totalVertices; i++)
{
localParent[i] = -1;
itemsList[i] = new BitSet(totalEdges);
adjacencyGraph[i] = new BitSet(totalEdges);
}
for(int k = 0; k < totalEdges; k++)
{
if (((whoSiteId == numPlayers + 1 ) && (state.what(k, SiteType.Edge) != 0))
||((whoSiteId < numPlayers + 1 ) && (state.who(k, SiteType.Edge) == whoSiteId)))
{ //System.out.println(" k : "+k);
final Edge kEdge = graph.edges().get(k);
final int vA = kEdge.vA().index();
final int vB = kEdge.vB().index();
adjacencyGraph[vA].set(vB);
adjacencyGraph[vB].set(vA);
final int vARoot = find(vA, localParent);
final int vBRoot = find(vB, localParent);
if (vARoot == vBRoot) return false;
if(localParent[vARoot] == -1)
{
localParent[vARoot] = vARoot;
itemsList[vARoot].set(vARoot);
}
if(localParent[vBRoot] == -1)
{
localParent[vBRoot] = vBRoot;
itemsList[vBRoot].set(vBRoot);
}
localParent[vARoot] = vBRoot;
itemsList[vBRoot].or(itemsList[vARoot]);
}
}
final BitSet siteIdList = new BitSet(totalVertices);
int centre = 0;
final BitSet subTree = new BitSet(totalVertices);
siteIdList.set(siteId);
for(int i = 0; i < totalVertices; i++)
{
if(localParent[i] == i)
{
if(siteIdList.intersects(itemsList[i]))
{
centre = build(itemsList[i].nextSetBit(0), -1, adjacencyGraph, totalVertices);
subTree.or(itemsList[i]);
break;
}
}
}
if(siteId == centre)
return true;
else
{
if((adjacencyGraph[centre].cardinality() == adjacencyGraph[siteId].cardinality())
&& (adjacencyGraph[centre].cardinality() == 1))
return true;
boolean adjcentVertices = false;
for(int k = 0; k < totalEdges; k++)
{
if (((whoSiteId == numPlayers + 1 ) && (state.what(k, SiteType.Edge) != 0))
||((whoSiteId < numPlayers + 1 ) && (state.who(k, SiteType.Edge) == whoSiteId)))
{
final Edge kEdge = graph.edges().get(k);
final int vA = kEdge.vA().index();
final int vB = kEdge.vB().index();
if(((vA == siteId) && (vB == centre))||((vB == siteId) && (vA == centre)))
{
adjcentVertices = true;
break;
}
}
}
if(adjcentVertices)
{
final int level1, level2;
final BitSet subTree1 = (BitSet) subTree.clone();
level1 = depthLimit(siteId, 0, 0, subTree1, adjacencyGraph);
final BitSet subTree2 = (BitSet) subTree.clone();
level2 = depthLimit(centre, 0, 0, subTree2, adjacencyGraph);
if(level1 == level2)
return true;
}
}
return false;
}
//----------------------------------------------------------------------
/**
*
* @param u A vertex.
* @param parent The parent of u.
* @param adjacencyGraph The general Graph info.
* @param totalVertices The total number of vertex in the global tree.
*
* @return Returns all possible subTees information.
*/
private int build
(
final int u,
final int parent,
final BitSet[] adjacencyGraph,
final int totalVertices
)
{
final BitSet[] sub = new BitSet[totalVertices];
final BitSet n = dfs_subTreesGenerator(u, parent, adjacencyGraph, sub, totalVertices);
return dfsCenter(u, parent, n.cardinality(), adjacencyGraph, sub);
}
//----------------------------------------------------------------------
/**
*
* @param u A vertex.
* @param parent The parent of u.
* @param adjacencyGraph The general Graph info.
* @param sub Uses to store all possible subtree information.
* @return Returns all possible subTees information.
*/
private BitSet dfs_subTreesGenerator
(
final int u,
final int parent,
final BitSet[] adjacenceGraph,
final BitSet[] sub,
final int totalVertices
)
{
sub[u] = new BitSet(totalVertices);
sub[u].set(u);
for (int v = adjacenceGraph[u].nextSetBit(0); v >= 0; v = adjacenceGraph[u].nextSetBit(v + 1))
{
if(u != v)
{
if(v!= parent)
{
sub[u].or(dfs_subTreesGenerator(v, u, adjacenceGraph, sub, totalVertices));
}
}
}
return sub[u];
}
//----------------------------------------------------------------------
/**
*
* @param u A vertex.
* @param parent The parent of u.
* @param totalItems The total number of Items of the present tree.
* @param adjacencyGraph The general Graph info.
* @param sub Uses to store all possible subtree information.
* @return The center of a present tree.
*/
private int dfsCenter
(
final int u,
final int parent,
final int totalItems,
final BitSet[] adjacencyGraph,
final BitSet[] sub
)
{
for (int v = adjacencyGraph[u].nextSetBit(0); v >= 0; v = adjacencyGraph[u].nextSetBit(v + 1))
{
if(u != v)
{
if(v!= parent)
{
if(sub[v].cardinality() > totalItems/2)
{
return dfsCenter(v, u, totalItems, adjacencyGraph, sub);
}
}
}
}
return u;
}
//----------------------------------------------------------------------
/**
*
* @param u A vertex.
* @param index The iterator for depth.
* @param maxIndex The maxdepth.
* @param subTree The Tree or subTree, where we will search the depth.
* @param adjacencyGraph The general Graph info.
* @return The depth from any specific point.
*/
private int depthLimit
(
final int u,
final int index,
final int max,
final BitSet subTree,
final BitSet[] adjacencyGraph
)
{
subTree.clear(u);
final int newIndex = index + 1;
int newMax = max;
if (newIndex > newMax)
newMax = newIndex;
if (subTree.cardinality() == 0)
return newMax;
for (int v = adjacencyGraph[u].nextSetBit(0); v >= 0; v = adjacencyGraph[u].nextSetBit(v + 1))
{
if(subTree.get(v))
{
return depthLimit(v, newIndex, newMax, subTree, adjacencyGraph);
}
}
return newMax;
}
//----------------------------------------------------------------------
/**
*
* @param position A vertex.
* @param parent The array with parent id.
*
* @return The root of the position.
*/
private int find(final int position, final int[] parent)
{
final int parentId = parent[position];
if ((parentId ==position) || (parentId == -1))
return position;
return find (parentId, parent);
}
//-------------------------------------------------------------------------
@Override
public String toString()
{
return "IsTreeCenter( )";
}
@Override
public boolean isStatic()
{
return false;
}
@Override
public long gameFlags(final Game game)
{
return GameType.Graph | who.gameFlags(game);
}
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
concepts.or(who.concepts(game));
return concepts;
}
@Override
public BitSet writesEvalContextRecursive()
{
final BitSet writeEvalContext = new BitSet();
writeEvalContext.or(who.writesEvalContextRecursive());
return writeEvalContext;
}
@Override
public BitSet readsEvalContextRecursive()
{
final BitSet readEvalContext = new BitSet();
readEvalContext.or(who.readsEvalContextRecursive());
return readEvalContext;
}
@Override
public void preprocess(final Game game)
{
who.preprocess(game);
}
@Override
public boolean missingRequirement(final Game game)
{
boolean missingRequirement = false;
missingRequirement |= who.missingRequirement(game);
return missingRequirement;
}
@Override
public boolean willCrash(final Game game)
{
boolean willCrash = false;
willCrash |= who.willCrash(game);
return willCrash;
}
//-------------------------------------------------------------------------
@Override
public String toEnglish(final Game game)
{
return "Player " + who.toEnglish(game) + "'s last move is the centre of a tree";
}
//-------------------------------------------------------------------------
} | 10,018 | 25.159269 | 97 | java |
Ludii | Ludii-master/Core/src/game/functions/booleans/is/triggered/IsTriggered.java | package game.functions.booleans.is.triggered;
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.concept.Concept;
import other.context.Context;
/**
* Checks if a player was triggered before.
*
* @author Eric.Piette
*/
@Hide
public final class IsTriggered extends BaseBooleanFunction
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/** The player index. */
private final IntFunction playerId;
/** The event. */
private final String event;
//-------------------------------------------------------------------------
/**
* @param event The event triggered.
* @param indexPlayer The index of the player.
* @param role The roleType of the player.
*/
public IsTriggered
(
final String event,
@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);
this.event = event;
}
//-------------------------------------------------------------------------
@Override
public final boolean eval(final Context context)
{
final int pid = playerId.eval(context);
return context.active(pid) && context.state().isTriggered(event, pid);
}
//-------------------------------------------------------------------------
@Override
public boolean isStatic()
{
return false;
}
@Override
public long gameFlags(final Game game)
{
return playerId.gameFlags(game);
}
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
concepts.or(playerId.concepts(game));
if(event.equals("Connected"))
concepts.set(Concept.Connection.id(), true);
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 playerId.toEnglish(game) +" is "+ event;
}
}
| 3,086 | 21.05 | 84 | java |
Ludii | Ludii-master/Core/src/game/functions/booleans/math/And.java | package game.functions.booleans.math;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.List;
import game.Game;
import game.functions.booleans.BaseBooleanFunction;
import game.functions.booleans.BooleanConstant.FalseConstant;
import game.functions.booleans.BooleanConstant.TrueConstant;
import game.functions.booleans.BooleanFunction;
import other.concept.Concept;
import other.context.Context;
import other.location.Location;
/**
* Returns whether all specified conditions are true.
*
* @author cambolbro and Eric.Piette
*
* @remarks This test returns false as soon as any of its conditions return false,
* so it pays to test conditions that are faster and more likely to fail first.
*/
public final class And extends BaseBooleanFunction
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/** The list of booleanFunction. */
private final BooleanFunction[] list;
/** Precomputed boolean. */
private Boolean precomputedBoolean;
//-------------------------------------------------------------------------
/**
* For an and between two booleans.
*
* @param a First condition.
* @param b Second condition.
*
* @example (and (= (who at:(last To)) (mover)) (!= (who at:(last From))
* (mover)))
*/
public And
(
final BooleanFunction a,
final BooleanFunction b
)
{
list = new BooleanFunction[] {a, b};
}
/**
* For an and between many booleans.
*
* @param list The list of conditions to check.
*
* @example (and {(= (who at:(last To)) (mover)) (!= (who at:(last From))
* (mover)) (is Pending)})
*/
public And
(
final BooleanFunction[] list
)
{
this.list = list;
}
//-------------------------------------------------------------------------
@Override
public boolean eval(final Context context)
{
if (precomputedBoolean != null)
return precomputedBoolean.booleanValue();
for (final BooleanFunction elem : list)
if (!elem.eval(context))
return false;
return true;
}
//-------------------------------------------------------------------------
@Override
public boolean isStatic()
{
for (final BooleanFunction elem: list)
if (!elem.isStatic())
return false;
return true;
}
@Override
public long gameFlags(final Game game)
{
long gameFlags = 0L;
for (final BooleanFunction elem : list)
gameFlags |= elem.gameFlags(game);
return gameFlags;
}
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
for (final BooleanFunction elem : list)
concepts.or(elem.concepts(game));
// No need to look the contains flag used for the ReachGoal detection if it only
// a part of another test.
if (concepts.get(Concept.Contains.id()))
concepts.set(Concept.Contains.id(), false);
concepts.set(Concept.Conjunction.id(), true);
boolean fillCheck = true;
for (final BooleanFunction elem : list)
if(!elem.concepts(game).get(Concept.IsPieceAt.id()))
{
fillCheck = false;
break;
}
if (fillCheck)
concepts.set(Concept.Fill.id(), true);
return concepts;
}
@Override
public BitSet writesEvalContextRecursive()
{
final BitSet writeEvalContext = new BitSet();
for (final BooleanFunction elem : list)
writeEvalContext.or(elem.writesEvalContextRecursive());
return writeEvalContext;
}
@Override
public BitSet readsEvalContextRecursive()
{
final BitSet readEvalContext = new BitSet();
for (final BooleanFunction elem : list)
readEvalContext.or(elem.readsEvalContextRecursive());
return readEvalContext;
}
@Override
public boolean missingRequirement(final Game game)
{
boolean missingRequirement = false;
for (final BooleanFunction cond : list)
{
if (cond instanceof FalseConstant)
{
game.addRequirementToReport("One of the condition in an (and ...) ludeme is \"false\".");
missingRequirement = true;
break;
}
}
for (final BooleanFunction cond : list)
{
if (cond instanceof TrueConstant)
{
game.addRequirementToReport("One of the condition in an (and ...) ludeme is \"true\".");
missingRequirement = true;
break;
}
}
for (final BooleanFunction elem : list)
missingRequirement |= elem.missingRequirement(game);
return missingRequirement;
}
@Override
public boolean willCrash(final Game game)
{
boolean willCrash = false;
for (final BooleanFunction elem : list)
willCrash |= elem.willCrash(game);
return willCrash;
}
@Override
public void preprocess(final Game game)
{
for (final BooleanFunction elem : list)
elem.preprocess(game);
if (isStatic())
precomputedBoolean = Boolean.valueOf(eval(new Context(game, null)));
}
//-------------------------------------------------------------------------
/**
* @return Our list of Boolean Functions
*/
public BooleanFunction[] list()
{
return list;
}
//-------------------------------------------------------------------------
@Override
public List<Location> satisfyingSites(final Context context)
{
if (!eval(context))
return new ArrayList<Location>();
final List<Location> winningSites = new ArrayList<Location>();
for (final BooleanFunction cond : list)
winningSites.addAll(cond.satisfyingSites(context));
return winningSites;
}
@Override
public String toEnglish(final Game game)
{
String text = "";
int count=0;
for (final BooleanFunction func : list)
{
text += func.toEnglish(game);
count++;
if(count == list.length-1)
text+=" and ";
else if(count < list.length)
text+=", ";
}
return text;
}
}
| 5,716 | 22.052419 | 93 | java |
Ludii | Ludii-master/Core/src/game/functions/booleans/math/Equals.java | package game.functions.booleans.math;
import java.util.BitSet;
import annotations.Alias;
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.count.component.CountPieces;
import game.functions.ints.state.Counter;
import game.functions.region.RegionFunction;
import game.types.play.RoleType;
import game.util.equipment.Region;
import gnu.trove.list.array.TIntArrayList;
import main.Constants;
import other.concept.Concept;
import other.context.Context;
import other.trial.Trial;
/**
* Tests if valueA = valueB, if all the integers in the list are equals, or if
* the result of the two regions functions are equals.
*
* @author Eric.Piette and cambolbro
*/
@Alias(alias = "=")
public final class Equals extends BaseBooleanFunction
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/** Which value A. */
private final IntFunction valueA;
/** Which value B. */
private final IntFunction valueB;
/** Which region A. */
private final RegionFunction regionA;
/** Which region B. */
private final RegionFunction regionB;
/** Precomputed boolean. */
private Boolean precomputedBoolean;
//-------------------------------------------------------------------------
/**
* For testing if two int functions are equals. Also use to test if the index of
* a roletype is equal to an int function.
*
* @param valueA The first value.
* @param valueB The second value.
* @param roleB The second owner value of this role.
*
* @example (= (mover) 1)
*/
public Equals
(
final IntFunction valueA,
@Or final IntFunction valueB,
@Or final RoleType roleB
)
{
int numNonNull2 = 0;
if (valueB != null)
numNonNull2++;
if (roleB != null)
numNonNull2++;
if (numNonNull2 != 1)
throw new IllegalArgumentException("Only one Or should be non-null.");
this.valueA = valueA;
this.valueB = (valueB != null) ? valueB : RoleType.toIntFunction(roleB);
regionA = null;
regionB = null;
}
/**
* For test if two regions are equals.
*
* @param regionA The first region function.
* @param regionB The second region function.
*
* @example (= (sites Occupied by:Mover) (sites Next))
*/
public Equals
(
final RegionFunction regionA,
final RegionFunction regionB
)
{
valueA = null;
valueB = null;
this.regionA = regionA;
this.regionB = regionB;
}
//-------------------------------------------------------------------------
@Override
public boolean eval(final Context context)
{
if (precomputedBoolean != null)
return precomputedBoolean.booleanValue();
if (regionA == null)
{
return valueA.eval(context) == valueB.eval(context);
}
else
{
final Region rA = regionA.eval(context);
final Region rB = regionB.eval(context);
final TIntArrayList listA = new TIntArrayList(rA.sites());
final TIntArrayList listB = new TIntArrayList(rB.sites());
if (listA.size() != listB.size())
return false;
for (int i = 0; i < listA.size(); i++)
{
final int siteA = listA.getQuick(i);
if (!listB.contains(siteA))
return false;
}
return true;
}
}
//-------------------------------------------------------------------------
/**
* @return The first value.
*/
public IntFunction valueA()
{
return valueA;
}
/**
* @return The second value.
*/
public IntFunction valueB()
{
return valueB;
}
//-------------------------------------------------------------------------
@Override
public String toString()
{
String str = "";
if (regionA == null)
str += "Equal(" + valueA + ", " + valueB + ")";
else
str += "Equal(" + regionA + ", " + regionB + ")";
return str;
}
//-------------------------------------------------------------------------
@Override
public boolean isStatic()
{
if (regionA == null)
return valueA.isStatic() && valueB.isStatic();
else
return regionA.isStatic() && regionB.isStatic();
}
@Override
public long gameFlags(final Game game)
{
if (regionA == null)
return valueA.gameFlags(game) | valueB.gameFlags(game);
else
return regionA.gameFlags(game) | regionB.gameFlags(game);
}
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
if (regionA == null)
{
concepts.or(valueA.concepts(game));
concepts.or(valueB.concepts(game));
}
else
{
concepts.or(regionA.concepts(game));
concepts.or(regionB.concepts(game));
}
final Trial trial = new Trial(game);
if (valueA instanceof CountPieces && valueB instanceof IntConstant
&& 0 == valueB.eval(new Context(game, trial)))
{
concepts.set(Concept.NoPiece.id(), true);
final CountPieces countPieces = (CountPieces) valueA;
if(countPieces.roleType() != null)
{
if(countPieces.roleType().equals(RoleType.Mover))
concepts.set(Concept.NoPieceMover.id(), true);
else if(countPieces.roleType().equals(RoleType.Next))
concepts.set(Concept.NoPieceNext.id(), true);
}
}
else if (valueB instanceof CountPieces && valueA instanceof IntConstant
&& 0 == valueA.eval(new Context(game, trial)))
{
concepts.set(Concept.NoPiece.id(), true);
final CountPieces countPieces = (CountPieces) valueB;
if(countPieces.roleType() != null)
{
if(countPieces.roleType().equals(RoleType.Mover))
concepts.set(Concept.NoPieceMover.id(), true);
else if(countPieces.roleType().equals(RoleType.Next))
concepts.set(Concept.NoPieceNext.id(), true);
}
}
if (valueA instanceof CountPieces)
{
concepts.set(Concept.CountPiecesComparison.id(), true);
final CountPieces countPieces = (CountPieces) valueA;
if(countPieces.roleType() != null)
{
if(countPieces.roleType().equals(RoleType.Mover))
concepts.set(Concept.CountPiecesMoverComparison.id(), true);
else if(countPieces.roleType().equals(RoleType.Next) || countPieces.roleType().equals(RoleType.Player))
concepts.set(Concept.CountPiecesNextComparison.id(), true);
}
}
else if (valueB instanceof CountPieces)
{
concepts.set(Concept.CountPiecesComparison.id(), true);
final CountPieces countPieces = (CountPieces) valueB;
if(countPieces.roleType() != null)
{
if(countPieces.roleType().equals(RoleType.Mover))
concepts.set(Concept.CountPiecesMoverComparison.id(), true);
else if(countPieces.roleType().equals(RoleType.Next) || countPieces.roleType().equals(RoleType.Player))
concepts.set(Concept.CountPiecesNextComparison.id(), true);
}
}
if (valueA instanceof Counter && valueB instanceof IntConstant)
concepts.set(Concept.ProgressCheck.id(), true);
else if (valueB instanceof Counter && valueA instanceof IntConstant)
concepts.set(Concept.ProgressCheck.id(), true);
if (valueA != null && valueB != null)
{
if (valueA.getClass().toString().contains("Where") && valueB instanceof IntConstant
&& Constants.OFF == valueB.eval(new Context(game, trial)))
concepts.set(Concept.NoTargetPiece.id(), true);
else if (valueB.getClass().toString().contains("Where") && valueA instanceof IntConstant
&& Constants.OFF == valueA.eval(new Context(game, trial)))
concepts.set(Concept.NoTargetPiece.id(), true);
else if (valueA.getClass().toString().contains("Where") && valueB.getClass().toString().contains("MapEntry"))
concepts.set(Concept.Contains.id(), true);
else if (valueB.getClass().toString().contains("Where") && valueA.getClass().toString().contains("MapEntry"))
concepts.set(Concept.Contains.id(), true);
else if (valueB.getClass().toString().contains("What") && valueA.getClass().toString().contains("Id"))
concepts.set(Concept.IsPieceAt.id(), true);
else if (valueA.getClass().toString().contains("What") && valueB.getClass().toString().contains("Id"))
concepts.set(Concept.IsPieceAt.id(), true);
}
if (regionA != null && regionB != null)
concepts.set(Concept.Fill.id(), true);
concepts.set(Concept.Equal.id(), true);
return concepts;
}
@Override
public BitSet writesEvalContextRecursive()
{
final BitSet writeEvalContext = new BitSet();
if (regionA == null)
{
writeEvalContext.or(valueA.writesEvalContextRecursive());
writeEvalContext.or(valueB.writesEvalContextRecursive());
}
else
{
writeEvalContext.or(regionA.writesEvalContextRecursive());
writeEvalContext.or(regionB.writesEvalContextRecursive());
}
return writeEvalContext;
}
@Override
public BitSet readsEvalContextRecursive()
{
final BitSet readEvalContext = new BitSet();
if (regionA == null)
{
readEvalContext.or(valueA.readsEvalContextRecursive());
readEvalContext.or(valueB.readsEvalContextRecursive());
}
else
{
readEvalContext.or(regionA.readsEvalContextRecursive());
readEvalContext.or(regionB.readsEvalContextRecursive());
}
return readEvalContext;
}
@Override
public boolean missingRequirement(final Game game)
{
boolean missingRequirement = false;
if (regionA == null)
{
missingRequirement |= valueA.missingRequirement(game);
missingRequirement |= valueB.missingRequirement(game);
}
else
{
missingRequirement |= regionA.missingRequirement(game);
missingRequirement |= regionB.missingRequirement(game);
}
return missingRequirement;
}
@Override
public boolean willCrash(final Game game)
{
boolean willCrash = false;
if (regionA == null)
{
willCrash |= valueA.willCrash(game);
willCrash |= valueB.willCrash(game);
}
else
{
willCrash |= regionA.willCrash(game);
willCrash |= regionB.willCrash(game);
}
return willCrash;
}
@Override
public void preprocess(final Game game)
{
if (regionA == null)
{
valueA.preprocess(game);
valueB.preprocess(game);
}
else
{
regionA.preprocess(game);
regionB.preprocess(game);
}
if (isStatic())
precomputedBoolean = Boolean.valueOf(eval(new Context(game, null)));
}
@Override
public String toEnglish(final Game game)
{
String valueAEnglish = "null";
String valueBEnglish = "null";
if (valueA != null)
valueAEnglish = valueA.toEnglish(game);
if (valueB != null)
valueBEnglish = valueB.toEnglish(game);
return valueAEnglish + " is equal to " + valueBEnglish;
}
}
| 10,370 | 25.729381 | 112 | java |
Ludii | Ludii-master/Core/src/game/functions/booleans/math/Ge.java | package game.functions.booleans.math;
import java.util.BitSet;
import annotations.Alias;
import game.Game;
import game.functions.booleans.BaseBooleanFunction;
import game.functions.ints.IntFunction;
import game.functions.ints.count.component.CountPieces;
import game.types.board.SiteType;
import game.types.play.RoleType;
import other.concept.Concept;
import other.context.Context;
import other.state.puzzle.ContainerDeductionPuzzleState;
/**
* Tests if valueA $\\geq$ valueB.
*
* @author Eric.Piette
*
*/
@Alias(alias = ">=")
public final class Ge extends BaseBooleanFunction
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/** Which value A. */
private final IntFunction valueA;
/** Which value B. */
private final IntFunction valueB;
/** Precomputed boolean. */
private Boolean precomputedBoolean;
//-------------------------------------------------------------------------
/**
* @param valueA The left value.
* @param valueB The right value.
* @example (>= (mover) (next))
*/
public Ge
(
final IntFunction valueA,
final IntFunction valueB
)
{
this.valueA = valueA;
this.valueB = valueB;
}
//-------------------------------------------------------------------------
@Override
public boolean eval(final Context context)
{
if (precomputedBoolean != null)
return precomputedBoolean.booleanValue();
if (!context.game().isDeductionPuzzle())
{
return valueA.eval(context) >= valueB.eval(context);
}
else
{
final ContainerDeductionPuzzleState ps = ((ContainerDeductionPuzzleState) context.state().containerStates()[0]);
final SiteType type = context.board().defaultSite();
final int indexA = valueA.eval(context);
final int indexB = valueB.eval(context);
if (!ps.isResolved(indexA, type) || !ps.isResolved(indexB, type))
return true;
final int vA = ps.what(indexA, type);
final int vB = ps.what(indexB, type);
return vA >= vB;
}
}
//-------------------------------------------------------------------------
/**
* @return The first value.
*/
public IntFunction valueA()
{
return valueA;
}
/**
* @return The second value.
*/
public IntFunction valueB()
{
return valueB;
}
//-------------------------------------------------------------------------
@Override
public String toString()
{
String str = "";
str += "GreaterThanOrEqual(" + valueA + ", " + valueB + ")";
return str;
}
@Override
public boolean isStatic()
{
return valueA.isStatic() && valueB.isStatic();
}
@Override
public long gameFlags(final Game game)
{
return valueA.gameFlags(game) | valueB.gameFlags(game);
}
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
concepts.or(valueA.concepts(game));
concepts.or(valueB.concepts(game));
concepts.set(Concept.GreaterThanOrEqual.id(), true);
if (valueA instanceof CountPieces)
{
concepts.set(Concept.CountPiecesComparison.id(), true);
final CountPieces countPieces = (CountPieces) valueA;
if(countPieces.roleType() != null)
{
if(countPieces.roleType().equals(RoleType.Mover))
concepts.set(Concept.CountPiecesMoverComparison.id(), true);
else if(countPieces.roleType().equals(RoleType.Next) || countPieces.roleType().equals(RoleType.Player))
concepts.set(Concept.CountPiecesNextComparison.id(), true);
}
}
else if (valueB instanceof CountPieces)
{
concepts.set(Concept.CountPiecesComparison.id(), true);
final CountPieces countPieces = (CountPieces) valueB;
if(countPieces.roleType() != null)
{
if(countPieces.roleType().equals(RoleType.Mover))
concepts.set(Concept.CountPiecesMoverComparison.id(), true);
else if(countPieces.roleType().equals(RoleType.Next) || countPieces.roleType().equals(RoleType.Player))
concepts.set(Concept.CountPiecesNextComparison.id(), true);
}
}
return concepts;
}
@Override
public BitSet writesEvalContextRecursive()
{
final BitSet writeEvalContext = new BitSet();
writeEvalContext.or(valueA.writesEvalContextRecursive());
writeEvalContext.or(valueB.writesEvalContextRecursive());
return writeEvalContext;
}
@Override
public BitSet readsEvalContextRecursive()
{
final BitSet readEvalContext = new BitSet();
readEvalContext.or(valueA.readsEvalContextRecursive());
readEvalContext.or(valueB.readsEvalContextRecursive());
return readEvalContext;
}
@Override
public void preprocess(final Game game)
{
valueA.preprocess(game);
valueB.preprocess(game);
if (isStatic())
precomputedBoolean = Boolean.valueOf(eval(new Context(game, null)));
}
@Override
public boolean missingRequirement(final Game game)
{
boolean missingRequirement = false;
missingRequirement |= valueA.missingRequirement(game);
missingRequirement |= valueB.missingRequirement(game);
return missingRequirement;
}
@Override
public boolean willCrash(final Game game)
{
boolean willCrash = false;
willCrash |= valueA.willCrash(game);
willCrash |= valueB.willCrash(game);
return willCrash;
}
@Override
public String toEnglish(final Game game)
{
String valueAEnglish = "null";
String valueBEnglish = "null";
if (valueA != null)
valueAEnglish = valueA.toEnglish(game);
if (valueB != null)
valueBEnglish = valueB.toEnglish(game);
return valueAEnglish + " is greater than or equal to " + valueBEnglish;
}
}
| 5,457 | 24.152074 | 115 | java |
Ludii | Ludii-master/Core/src/game/functions/booleans/math/Gt.java | package game.functions.booleans.math;
import java.util.BitSet;
import annotations.Alias;
import game.Game;
import game.functions.booleans.BaseBooleanFunction;
import game.functions.ints.IntFunction;
import game.functions.ints.count.component.CountPieces;
import game.types.board.SiteType;
import game.types.play.RoleType;
import other.concept.Concept;
import other.context.Context;
import other.state.puzzle.ContainerDeductionPuzzleState;
/**
* Tests if valueA $>$ valueB.
*
* @author Eric.Piette
*
*/
@Alias(alias = ">")
public final class Gt extends BaseBooleanFunction
{
private static final long serialVersionUID = 1L;
/** Which value A. */
private final IntFunction valueA;
/** Which value B. */
private final IntFunction valueB;
/** Precomputed boolean. */
private Boolean precomputedBoolean;
//-------------------------------------------------------------------------
/**
* @param valueA The left value.
* @param valueB The right value.
* @example (> (mover) (next))
*/
public Gt
(
final IntFunction valueA,
final IntFunction valueB
)
{
this.valueA = valueA;
this.valueB = valueB;
}
//-------------------------------------------------------------------------
@Override
public boolean eval(final Context context)
{
if (precomputedBoolean != null)
return precomputedBoolean.booleanValue();
if (!context.game().isDeductionPuzzle())
{
return valueA.exceeds(context, valueB);
}
else
{
final ContainerDeductionPuzzleState ps = ((ContainerDeductionPuzzleState) context.state().containerStates()[0]);
final SiteType type = context.board().defaultSite();
final int indexA = valueA.eval(context);
final int indexB = valueB.eval(context);
if (!ps.isResolved(indexA, type) || !ps.isResolved(indexB, type))
return true;
final int vA = ps.what(indexA, type);
final int vB = ps.what(indexB, type);
return vA > vB;
}
}
//-------------------------------------------------------------------------
/**
* @return The first value.
*/
public IntFunction valueA()
{
return valueA;
}
/**
* @return The second value.
*/
public IntFunction valueB()
{
return valueB;
}
//-------------------------------------------------------------------------
@Override
public String toString()
{
String str = "";
str += "GreaterThan(" + valueA + ", " + valueB + ")";
return str;
}
@Override
public boolean isStatic()
{
return valueA.isStatic() && valueB.isStatic();
}
@Override
public long gameFlags(final Game game)
{
return valueA.gameFlags(game) | valueB.gameFlags(game);
}
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
concepts.or(valueA.concepts(game));
concepts.or(valueB.concepts(game));
concepts.set(Concept.GreaterThan.id(), true);
if (valueA instanceof CountPieces)
{
concepts.set(Concept.CountPiecesComparison.id(), true);
final CountPieces countPieces = (CountPieces) valueA;
if(countPieces.roleType() != null)
{
if(countPieces.roleType().equals(RoleType.Mover))
concepts.set(Concept.CountPiecesMoverComparison.id(), true);
else if(countPieces.roleType().equals(RoleType.Next) || countPieces.roleType().equals(RoleType.Player))
concepts.set(Concept.CountPiecesNextComparison.id(), true);
}
}
else if (valueB instanceof CountPieces)
{
concepts.set(Concept.CountPiecesComparison.id(), true);
final CountPieces countPieces = (CountPieces) valueB;
if(countPieces.roleType() != null)
{
if(countPieces.roleType().equals(RoleType.Mover))
concepts.set(Concept.CountPiecesMoverComparison.id(), true);
else if(countPieces.roleType().equals(RoleType.Next) || countPieces.roleType().equals(RoleType.Player))
concepts.set(Concept.CountPiecesNextComparison.id(), true);
}
}
return concepts;
}
@Override
public BitSet writesEvalContextRecursive()
{
final BitSet writeEvalContext = new BitSet();
writeEvalContext.or(valueA.writesEvalContextRecursive());
writeEvalContext.or(valueB.writesEvalContextRecursive());
return writeEvalContext;
}
@Override
public BitSet readsEvalContextRecursive()
{
final BitSet readEvalContext = new BitSet();
readEvalContext.or(valueA.readsEvalContextRecursive());
readEvalContext.or(valueB.readsEvalContextRecursive());
return readEvalContext;
}
@Override
public void preprocess(final Game game)
{
valueA.preprocess(game);
valueB.preprocess(game);
if (isStatic())
precomputedBoolean = Boolean.valueOf(eval(new Context(game, null)));
}
@Override
public boolean missingRequirement(final Game game)
{
boolean missingRequirement = false;
missingRequirement |= valueA.missingRequirement(game);
missingRequirement |= valueB.missingRequirement(game);
return missingRequirement;
}
@Override
public boolean willCrash(final Game game)
{
boolean willCrash = false;
willCrash |= valueA.willCrash(game);
willCrash |= valueB.willCrash(game);
return willCrash;
}
@Override
public String toEnglish(final Game game)
{
String valueAEnglish = "null";
String valueBEnglish = "null";
if (valueA != null)
valueAEnglish = valueA.toEnglish(game);
if (valueB != null)
valueBEnglish = valueB.toEnglish(game);
return valueAEnglish + " is greater than " + valueBEnglish;
}
}
| 5,334 | 23.929907 | 115 | java |
Ludii | Ludii-master/Core/src/game/functions/booleans/math/If.java | package game.functions.booleans.math;
import java.util.BitSet;
import annotations.Opt;
import game.Game;
import game.functions.booleans.BaseBooleanFunction;
import game.functions.booleans.BooleanConstant.FalseConstant;
import game.functions.booleans.BooleanFunction;
import other.concept.Concept;
import other.context.Context;
/**
* Tests if the condition is true, the function returns the first value, if not
* it returns the second value.
*
* @author Eric.Piette and cambolbro
*/
public final class If extends BaseBooleanFunction
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/** Boolean condition. */
private final BooleanFunction cond;
/** If condition is true. */
private final BooleanFunction ok;
/** If condition is false. */
private final BooleanFunction notOk;
/**
* @param cond The condition to check.
* @param ok The boolean returned if the condition is true.
* @param notOk The boolean returned if the condition is false.
*
* @example (if (is Mover (next)) (is Pending))
*/
public If
(
final BooleanFunction cond,
final BooleanFunction ok,
@Opt final BooleanFunction notOk
)
{
this.cond = cond;
this.ok = ok;
this.notOk = notOk;
}
//-------------------------------------------------------------------------
@Override
public boolean eval(final Context context)
{
if (cond.eval(context))
return (ok.eval(context));
if (notOk != null)
return notOk.eval(context);
return false;
}
//-------------------------------------------------------------------------
/**
* @return Condition to check
*/
public BooleanFunction cond()
{
return cond;
}
/**
* @return Boolean function to evaluate if condition holds
*/
public BooleanFunction ok()
{
return ok;
}
/**
* @return Boolean function to evaluate if condition does not hold
*/
public BooleanFunction notOk()
{
return notOk;
}
//-------------------------------------------------------------------------
@Override
public boolean isStatic()
{
if (ok != null && !ok.isStatic())
return false;
if (notOk != null && !notOk.isStatic())
return false;
return cond.isStatic();
}
@Override
public long gameFlags(final Game game)
{
long gameFlags = cond.gameFlags(game);
if (ok != null)
gameFlags |= ok.gameFlags(game);
if (notOk != null)
gameFlags |= notOk.gameFlags(game);
return gameFlags;
}
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
concepts.or(cond.concepts(game));
if (ok != null)
concepts.or(ok.concepts(game));
if (notOk != null)
concepts.or(notOk.concepts(game));
concepts.set(Concept.ConditionalStatement.id(), true);
return concepts;
}
@Override
public BitSet writesEvalContextRecursive()
{
final BitSet writeEvalContext = new BitSet();
writeEvalContext.or(cond.writesEvalContextRecursive());
if (ok != null)
writeEvalContext.or(ok.writesEvalContextRecursive());
if (notOk != null)
writeEvalContext.or(notOk.writesEvalContextRecursive());
return writeEvalContext;
}
@Override
public BitSet readsEvalContextRecursive()
{
final BitSet readEvalContext = new BitSet();
readEvalContext.or(cond.readsEvalContextRecursive());
if (ok != null)
readEvalContext.or(ok.readsEvalContextRecursive());
if (notOk != null)
readEvalContext.or(notOk.readsEvalContextRecursive());
return readEvalContext;
}
@Override
public boolean missingRequirement(final Game game)
{
boolean missingRequirement = false;
missingRequirement |= cond.missingRequirement(game);
if (cond instanceof FalseConstant)
{
game.addRequirementToReport("One of the condition of a (if ...) ludeme is \"false\" which is wrong.");
missingRequirement = true;
}
if (ok != null)
missingRequirement |= ok.missingRequirement(game);
if (notOk != null)
missingRequirement |= notOk.missingRequirement(game);
return missingRequirement;
}
@Override
public boolean willCrash(final Game game)
{
boolean willCrash = false;
willCrash |= cond.willCrash(game);
if (ok != null)
willCrash |= ok.willCrash(game);
if (notOk != null)
willCrash |= notOk.willCrash(game);
return willCrash;
}
@Override
public void preprocess(final Game game)
{
cond.preprocess(game);
if (ok != null)
ok.preprocess(game);
if (notOk != null)
notOk.preprocess(game);
}
//-------------------------------------------------------------------------
@Override
public String toString()
{
final StringBuilder sb = new StringBuilder();
sb.append("[If ");
sb.append("cond=" + cond);
sb.append(", ok=" + ok);
sb.append(", notOk" + notOk);
sb.append("]");
return sb.toString();
}
//-------------------------------------------------------------------------
@Override
public BitSet stateConcepts(final Context context)
{
if (cond.eval(context))
return ok.stateConcepts(context);
if (notOk != null)
notOk.stateConcepts(context);
return new BitSet();
}
//-------------------------------------------------------------------------
@Override
public String toEnglish(final Game game)
{
String elseString = "";
if (notOk != null)
elseString = " else " + notOk.toEnglish(game);
return "if " + cond.toEnglish(game) + " then " + ok.toEnglish(game) + elseString;
}
//-------------------------------------------------------------------------
}
| 5,514 | 20.459144 | 105 | java |
Ludii | Ludii-master/Core/src/game/functions/booleans/math/Le.java | package game.functions.booleans.math;
import java.util.BitSet;
import annotations.Alias;
import game.Game;
import game.functions.booleans.BaseBooleanFunction;
import game.functions.ints.IntFunction;
import game.functions.ints.count.component.CountPieces;
import game.types.board.SiteType;
import game.types.play.RoleType;
import other.concept.Concept;
import other.context.Context;
import other.state.puzzle.ContainerDeductionPuzzleState;
/**
* Tests if valueA $\\leq$ valueB.
*
* @author Eric.Piette
*
*/
@Alias(alias = "<=")
public final class Le extends BaseBooleanFunction
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/** Which value A. */
private final IntFunction valueA;
/** Which value B. */
private final IntFunction valueB;
/** Precomputed boolean. */
private Boolean precomputedBoolean;
//-------------------------------------------------------------------------
/**
* @param valueA The left value.
* @param valueB The right value.
* @example (<= (mover) (next))
*/
public Le
(
final IntFunction valueA,
final IntFunction valueB
)
{
this.valueA = valueA;
this.valueB = valueB;
}
//-------------------------------------------------------------------------
@Override
public boolean eval(final Context context)
{
if (precomputedBoolean != null)
return precomputedBoolean.booleanValue();
if (!context.game().isDeductionPuzzle())
{
return valueA.eval(context) <= valueB.eval(context);
}
else
{
final ContainerDeductionPuzzleState ps = ((ContainerDeductionPuzzleState) context.state().containerStates()[0]);
final SiteType type = context.board().defaultSite();
final int indexA = valueA.eval(context);
final int indexB = valueB.eval(context);
if (!ps.isResolved(indexA, type) || !ps.isResolved(indexB, type))
return true;
final int vA = ps.what(indexA, type);
final int vB = ps.what(indexB, type);
return vA <= vB;
}
}
//-------------------------------------------------------------------------
/**
* @return The first value.
*/
public IntFunction valueA()
{
return valueA;
}
/**
* @return The second value.
*/
public IntFunction valueB()
{
return valueB;
}
//-------------------------------------------------------------------------
@Override
public String toString()
{
String str = "";
str += "LesserThanOrEqual(" + valueA + ", " + valueB + ")";
return str;
}
@Override
public boolean isStatic()
{
return valueA.isStatic() && valueB.isStatic();
}
@Override
public long gameFlags(final Game game)
{
return valueA.gameFlags(game) | valueB.gameFlags(game);
}
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
concepts.or(valueA.concepts(game));
concepts.or(valueB.concepts(game));
concepts.set(Concept.LesserThanOrEqual.id(), true);
if (valueA instanceof CountPieces)
{
concepts.set(Concept.CountPiecesComparison.id(), true);
final CountPieces countPieces = (CountPieces) valueA;
if(countPieces.roleType() != null)
{
if(countPieces.roleType().equals(RoleType.Mover))
concepts.set(Concept.CountPiecesMoverComparison.id(), true);
else if(countPieces.roleType().equals(RoleType.Next) || countPieces.roleType().equals(RoleType.Player))
concepts.set(Concept.CountPiecesNextComparison.id(), true);
}
}
else if (valueB instanceof CountPieces)
{
concepts.set(Concept.CountPiecesComparison.id(), true);
final CountPieces countPieces = (CountPieces) valueB;
if(countPieces.roleType() != null)
{
if(countPieces.roleType().equals(RoleType.Mover))
concepts.set(Concept.CountPiecesMoverComparison.id(), true);
else if(countPieces.roleType().equals(RoleType.Next) || countPieces.roleType().equals(RoleType.Player))
concepts.set(Concept.CountPiecesNextComparison.id(), true);
}
}
return concepts;
}
@Override
public BitSet writesEvalContextRecursive()
{
final BitSet writeEvalContext = new BitSet();
writeEvalContext.or(valueA.writesEvalContextRecursive());
writeEvalContext.or(valueB.writesEvalContextRecursive());
return writeEvalContext;
}
@Override
public BitSet readsEvalContextRecursive()
{
final BitSet readEvalContext = new BitSet();
readEvalContext.or(valueA.readsEvalContextRecursive());
readEvalContext.or(valueB.readsEvalContextRecursive());
return readEvalContext;
}
@Override
public void preprocess(final Game game)
{
valueA.preprocess(game);
valueB.preprocess(game);
if (isStatic())
precomputedBoolean = Boolean.valueOf(eval(new Context(game, null)));
}
@Override
public boolean missingRequirement(final Game game)
{
boolean missingRequirement = false;
missingRequirement |= valueA.missingRequirement(game);
missingRequirement |= valueB.missingRequirement(game);
return missingRequirement;
}
@Override
public boolean willCrash(final Game game)
{
boolean willCrash = false;
willCrash |= valueA.willCrash(game);
willCrash |= valueB.willCrash(game);
return willCrash;
}
@Override
public String toEnglish(final Game game)
{
String valueAEnglish = "null";
String valueBEnglish = "null";
if (valueA != null)
valueAEnglish = valueA.toEnglish(game);
if (valueB != null)
valueBEnglish = valueB.toEnglish(game);
return valueAEnglish + " is less than or equal to " + valueBEnglish;
}
}
| 5,455 | 23.913242 | 115 | java |
Ludii | Ludii-master/Core/src/game/functions/booleans/math/Lt.java | package game.functions.booleans.math;
import java.util.BitSet;
import annotations.Alias;
import game.Game;
import game.functions.booleans.BaseBooleanFunction;
import game.functions.ints.IntFunction;
import game.functions.ints.count.component.CountPieces;
import game.types.board.SiteType;
import game.types.play.RoleType;
import other.concept.Concept;
import other.context.Context;
import other.state.puzzle.ContainerDeductionPuzzleState;
/**
* Tests if valueA $<$ valueB.
*
* @author Eric.Piette
*
*/
@Alias(alias = "<")
public final class Lt extends BaseBooleanFunction
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/** Which value A. */
private final IntFunction valueA;
/** Which value B. */
private final IntFunction valueB;
/** Precomputed boolean. */
private Boolean precomputedBoolean;
//-------------------------------------------------------------------------
/**
* @param valueA The left value.
* @param valueB The right value.
* @example (< (mover) (next))
*/
public Lt
(
final IntFunction valueA,
final IntFunction valueB
)
{
this.valueA = valueA;
this.valueB = valueB;
}
//-------------------------------------------------------------------------
@Override
public boolean eval(final Context context)
{
if (precomputedBoolean != null)
return precomputedBoolean.booleanValue();
if (!context.game().isDeductionPuzzle())
{
return valueA.eval(context) < valueB.eval(context);
}
else
{
final ContainerDeductionPuzzleState ps = ((ContainerDeductionPuzzleState) context.state().containerStates()[0]);
final SiteType type = context.board().defaultSite();
final int indexA = valueA.eval(context);
final int indexB = valueB.eval(context);
if (!ps.isResolved(indexA, type) || !ps.isResolved(indexB, type))
return true;
final int vA = ps.what(indexA, type);
final int vB = ps.what(indexB, type);
return vA < vB;
}
}
//-------------------------------------------------------------------------
/**
* @return The first value.
*/
public IntFunction valueA()
{
return valueA;
}
/**
* @return The second value.
*/
public IntFunction valueB()
{
return valueB;
}
//-------------------------------------------------------------------------
@Override
public String toString()
{
String str = "";
str += "LessThan(" + valueA + ", " + valueB + ")";
return str;
}
@Override
public boolean isStatic()
{
return valueA.isStatic() && valueB.isStatic();
}
@Override
public long gameFlags(final Game game)
{
return valueA.gameFlags(game) | valueB.gameFlags(game);
}
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
concepts.or(valueA.concepts(game));
concepts.or(valueB.concepts(game));
concepts.set(Concept.LesserThan.id(), true);
if (valueA instanceof CountPieces)
{
concepts.set(Concept.CountPiecesComparison.id(), true);
final CountPieces countPieces = (CountPieces) valueA;
if(countPieces.roleType() != null)
{
if(countPieces.roleType().equals(RoleType.Mover))
concepts.set(Concept.CountPiecesMoverComparison.id(), true);
else if(countPieces.roleType().equals(RoleType.Next) || countPieces.roleType().equals(RoleType.Player))
concepts.set(Concept.CountPiecesNextComparison.id(), true);
}
}
else if (valueB instanceof CountPieces)
{
concepts.set(Concept.CountPiecesComparison.id(), true);
final CountPieces countPieces = (CountPieces) valueB;
if(countPieces.roleType() != null)
{
if(countPieces.roleType().equals(RoleType.Mover))
concepts.set(Concept.CountPiecesMoverComparison.id(), true);
else if(countPieces.roleType().equals(RoleType.Next) || countPieces.roleType().equals(RoleType.Player))
concepts.set(Concept.CountPiecesNextComparison.id(), true);
}
}
return concepts;
}
@Override
public BitSet writesEvalContextRecursive()
{
final BitSet writeEvalContext = new BitSet();
writeEvalContext.or(valueA.writesEvalContextRecursive());
writeEvalContext.or(valueB.writesEvalContextRecursive());
return writeEvalContext;
}
@Override
public BitSet readsEvalContextRecursive()
{
final BitSet readEvalContext = new BitSet();
readEvalContext.or(valueA.readsEvalContextRecursive());
readEvalContext.or(valueB.readsEvalContextRecursive());
return readEvalContext;
}
@Override
public void preprocess(final Game game)
{
valueA.preprocess(game);
valueB.preprocess(game);
if (isStatic())
precomputedBoolean = Boolean.valueOf(eval(new Context(game, null)));
}
@Override
public boolean missingRequirement(final Game game)
{
boolean missingRequirement = false;
missingRequirement |= valueA.missingRequirement(game);
missingRequirement |= valueB.missingRequirement(game);
return missingRequirement;
}
@Override
public boolean willCrash(final Game game)
{
boolean willCrash = false;
willCrash |= valueA.willCrash(game);
willCrash |= valueB.willCrash(game);
return willCrash;
}
@Override
public String toEnglish(final Game game)
{
String valueAEnglish = "null";
String valueBEnglish = "null";
if (valueA != null)
valueAEnglish = valueA.toEnglish(game);
if (valueB != null)
valueBEnglish = valueB.toEnglish(game);
return valueAEnglish + " is less than " + valueBEnglish;
}
}
| 5,419 | 23.748858 | 115 | java |
Ludii | Ludii-master/Core/src/game/functions/booleans/math/Not.java | package game.functions.booleans.math;
import java.util.BitSet;
import annotations.Anon;
import game.Game;
import game.functions.booleans.BaseBooleanFunction;
import game.functions.booleans.BooleanFunction;
import other.concept.Concept;
import other.context.Context;
/**
* Tests the not condition.
*
* @author Eric.Piette
*
*/
public final class Not extends BaseBooleanFunction
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/** The boolean Function to reverse */
private final BooleanFunction a;
/** Precomputed boolean. */
private Boolean precomputedBoolean;
//-------------------------------------------------------------------------
/**
* @param a The condition.
* @example (not (is In (last To) (sites Mover)))
*/
public Not(@Anon final BooleanFunction a)
{
this.a = a;
}
//-------------------------------------------------------------------------
@Override
public boolean eval(final Context context)
{
if (precomputedBoolean != null)
return precomputedBoolean.booleanValue();
return !a.eval(context);
}
//-------------------------------------------------------------------------
/**
* @return The condition.
*/
public BooleanFunction a()
{
return a;
}
@Override
public String toString()
{
return "Not(" + a.toString() + ")";
}
@Override
public boolean isStatic()
{
return a.isStatic();
}
@Override
public long gameFlags(final Game game)
{
return a.gameFlags(game);
}
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
concepts.or(a.concepts(game));
if (concepts.get(Concept.CanMove.id()))
{
concepts.set(Concept.CanMove.id(), false);
concepts.set(Concept.CanNotMove.id(), true);
}
concepts.set(Concept.Negation.id(), true);
if (concepts.get(Concept.IsFriend.id()))
{
concepts.set(Concept.IsFriend.id(), false);
concepts.set(Concept.IsEmpty.id(), true);
concepts.set(Concept.IsEnemy.id(), true);
}
else if (concepts.get(Concept.IsEnemy.id()))
{
concepts.set(Concept.IsEnemy.id(), false);
concepts.set(Concept.IsEmpty.id(), true);
concepts.set(Concept.IsFriend.id(), true);
}
else if (concepts.get(Concept.IsEmpty.id()))
{
concepts.set(Concept.IsEmpty.id(), false);
concepts.set(Concept.IsEnemy.id(), true);
concepts.set(Concept.IsFriend.id(), true);
}
if(concepts.get(Concept.NoTargetPiece.id()))
concepts.set(Concept.NoTargetPiece.id(), false);
return concepts;
}
@Override
public BitSet writesEvalContextRecursive()
{
final BitSet writeEvalContext = new BitSet();
writeEvalContext.or(a.writesEvalContextRecursive());
return writeEvalContext;
}
@Override
public BitSet readsEvalContextRecursive()
{
final BitSet readEvalContext = new BitSet();
readEvalContext.or(a.readsEvalContextRecursive());
return readEvalContext;
}
@Override
public void preprocess(final Game game)
{
a.preprocess(game);
if (isStatic())
precomputedBoolean = Boolean.valueOf(eval(new Context(game, null)));
}
@Override
public boolean missingRequirement(final Game game)
{
boolean missingRequirement = false;
missingRequirement |= a.missingRequirement(game);
return missingRequirement;
}
@Override
public boolean willCrash(final Game game)
{
boolean willCrash = false;
willCrash |= a.willCrash(game);
return willCrash;
}
@Override
public boolean autoFails()
{
return a.autoSucceeds();
}
@Override
public boolean autoSucceeds()
{
return a.autoFails();
}
@Override
public String toEnglish(final Game game)
{
return "not " + a.toEnglish(game);
}
}
| 3,687 | 19.836158 | 76 | java |
Ludii | Ludii-master/Core/src/game/functions/booleans/math/NotEqual.java | package game.functions.booleans.math;
import java.util.BitSet;
import annotations.Alias;
import annotations.Or;
import game.Game;
import game.functions.booleans.BaseBooleanFunction;
import game.functions.ints.IntFunction;
import game.functions.region.RegionFunction;
import game.types.play.RoleType;
import game.util.equipment.Region;
import gnu.trove.list.array.TIntArrayList;
import other.concept.Concept;
import other.context.Context;
/**
* Tests if valueA $\\neq$ valueB.
*
* @author cambolbro and Eric.Piette
*/
@Alias(alias = "!=")
public final class NotEqual extends BaseBooleanFunction
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/** Which value A. */
private final IntFunction valueA;
/** Which value B. */
private final IntFunction valueB;
/** Which region A. */
private final RegionFunction regionA;
/** Which region B. */
private final RegionFunction regionB;
/** Precomputed boolean. */
private Boolean precomputedBoolean;
//-------------------------------------------------------------------------
/**
* For testing if two int functions are not equals. Also use to test if the
* index of a roletype is not equal to an int function.
*
* @param valueA The first value.
* @param valueB The second value.
* @param roleB The second owner value of this role.
*
* @example (!= (mover) (next))
*/
public NotEqual
(
final IntFunction valueA,
@Or final IntFunction valueB,
@Or final RoleType roleB
)
{
int numNonNull2 = 0;
if (valueB != null)
numNonNull2++;
if (roleB != null)
numNonNull2++;
if (numNonNull2 != 1)
throw new IllegalArgumentException("Only one Or2 should be non-null.");
this.valueA = valueA;
this.valueB = (valueB != null) ? valueB : RoleType.toIntFunction(roleB);
regionA = null;
regionB = null;
}
/**
* For test if two regions are not equals.
*
* @param regionA The left value.
* @param regionB The right value.
*
* @example (!= (sites Occupied by:Mover) (sites Mover))
*/
public NotEqual
(
final RegionFunction regionA,
final RegionFunction regionB
)
{
valueA = null;
valueB = null;
this.regionA = regionA;
this.regionB = regionB;
}
//-------------------------------------------------------------------------
@Override
public boolean eval(final Context context)
{
if (precomputedBoolean != null)
return precomputedBoolean.booleanValue();
if (regionA == null)
{
return valueA.eval(context) != valueB.eval(context);
}
else
{
final Region rA = regionA.eval(context);
final Region rB = regionB.eval(context);
final TIntArrayList listA = new TIntArrayList(rA.sites());
final TIntArrayList listB = new TIntArrayList(rB.sites());
if (listA.size() != listB.size())
return true;
for (int i = 0; i < listA.size(); i++)
{
final int siteA = listA.getQuick(i);
if (!listB.contains(siteA))
return true;
}
return false;
}
}
//-------------------------------------------------------------------------
/**
* @return The first value.
*/
public IntFunction valueA()
{
return valueA;
}
/**
* @return The second value.
*/
public IntFunction valueB()
{
return valueB;
}
//-------------------------------------------------------------------------
@Override
public String toString()
{
String str = "";
if (regionA == null)
str += "NotEqual(" + valueA + ", " + valueB + ")";
else
str += "NotEqual(" + regionA + ", " + regionB + ")";
return str;
}
//-------------------------------------------------------------------------
@Override
public boolean isStatic()
{
if (regionA == null)
return valueA.isStatic() && valueB.isStatic();
else
return regionA.isStatic() && regionB.isStatic();
}
@Override
public long gameFlags(final Game game)
{
if (regionA == null)
return valueA.gameFlags(game) | valueB.gameFlags(game);
else
return regionA.gameFlags(game) | regionB.gameFlags(game);
}
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
if (regionA == null)
{
concepts.or(valueA.concepts(game));
concepts.or(valueB.concepts(game));
}
else
{
concepts.or(regionA.concepts(game));
concepts.or(regionB.concepts(game));
}
concepts.set(Concept.NotEqual.id(), true);
return concepts;
}
@Override
public BitSet writesEvalContextRecursive()
{
final BitSet writeEvalContext = new BitSet();
if (regionA == null)
{
writeEvalContext.or(valueA.writesEvalContextRecursive());
writeEvalContext.or(valueB.writesEvalContextRecursive());
}
else
{
writeEvalContext.or(regionA.writesEvalContextRecursive());
writeEvalContext.or(regionB.writesEvalContextRecursive());
}
return writeEvalContext;
}
@Override
public BitSet readsEvalContextRecursive()
{
final BitSet readEvalContext = new BitSet();
if (regionA == null)
{
readEvalContext.or(valueA.readsEvalContextRecursive());
readEvalContext.or(valueB.readsEvalContextRecursive());
}
else
{
readEvalContext.or(regionA.readsEvalContextRecursive());
readEvalContext.or(regionB.readsEvalContextRecursive());
}
return readEvalContext;
}
@Override
public boolean missingRequirement(final Game game)
{
boolean missingRequirement = false;
if (regionA == null)
{
missingRequirement |= valueA.missingRequirement(game);
missingRequirement |= valueB.missingRequirement(game);
}
else
{
missingRequirement |= regionA.missingRequirement(game);
missingRequirement |= regionB.missingRequirement(game);
}
return missingRequirement;
}
@Override
public boolean willCrash(final Game game)
{
boolean willCrash = false;
if (regionA == null)
{
willCrash |= valueA.willCrash(game);
willCrash |= valueB.willCrash(game);
}
else
{
willCrash |= regionA.willCrash(game);
willCrash |= regionB.willCrash(game);
}
return willCrash;
}
@Override
public void preprocess(final Game game)
{
if (regionA == null)
{
valueA.preprocess(game);
valueB.preprocess(game);
}
else
{
regionA.preprocess(game);
regionB.preprocess(game);
}
if (isStatic())
precomputedBoolean = Boolean.valueOf(eval(new Context(game, null)));
}
@Override
public String toEnglish(final Game game)
{
String valueAEnglish = "null";
String valueBEnglish = "null";
if (valueA != null)
valueAEnglish = valueA.toEnglish(game);
if (valueB != null)
valueBEnglish = valueB.toEnglish(game);
return valueAEnglish + " is not equal to " + valueBEnglish;
}
}
| 6,639 | 20.986755 | 76 | java |
Ludii | Ludii-master/Core/src/game/functions/booleans/math/Or.java | package game.functions.booleans.math;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.List;
import game.Game;
import game.functions.booleans.BaseBooleanFunction;
import game.functions.booleans.BooleanConstant.FalseConstant;
import game.functions.booleans.BooleanConstant.TrueConstant;
import game.functions.booleans.BooleanFunction;
import other.concept.Concept;
import other.context.Context;
import other.location.Location;
/**
* Tests the Or boolean node. True if at least one condition is true between the two conditions.
*
* @author cambolbro
*/
public final class Or extends BaseBooleanFunction
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/**
* List of BooleanFunction.
*/
private final BooleanFunction[] list;
/**
* Precomputed boolean.
*/
private Boolean precomputedBoolean;
//-------------------------------------------------------------------------
/**
* For an or between two booleans.
*
* @param a First condition.
* @param b Second condition.
*
* @example (or (= (who at:(last To)) (mover) )(!= (who at:(last From))
* (mover)))
*/
public Or
(
final BooleanFunction a,
final BooleanFunction b
)
{
list = new BooleanFunction[] {a, b};
}
/**
* For an or between many booleans.
*
* @param list The list of conditions.
*
* @example (or {(= (who at:(last To)) (mover)) (!= (who at:(last From))
* (mover)) (is Pending)})
*/
public Or
(
final BooleanFunction[] list
)
{
this.list = list;
}
//-------------------------------------------------------------------------
@Override
public boolean eval(final Context context)
{
if (precomputedBoolean != null)
return precomputedBoolean.booleanValue();
for (final BooleanFunction elem: list)
if (elem.eval(context))
return true;
return false;
}
//-------------------------------------------------------------------------
@Override
public boolean isStatic()
{
for (final BooleanFunction elem: list)
if (!elem.isStatic())
return false;
return true;
}
@Override
public long gameFlags(final Game game)
{
long gameFlags = 0;
for (final BooleanFunction elem : list)
gameFlags |= elem.gameFlags(game);
return gameFlags;
}
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
for (final BooleanFunction elem : list)
concepts.or(elem.concepts(game));
concepts.set(Concept.Disjunction.id(), true);
return concepts;
}
@Override
public BitSet writesEvalContextRecursive()
{
final BitSet writeEvalContext = new BitSet();
for (final BooleanFunction elem : list)
writeEvalContext.or(elem.writesEvalContextRecursive());
return writeEvalContext;
}
@Override
public BitSet readsEvalContextRecursive()
{
final BitSet readEvalContext = new BitSet();
for (final BooleanFunction elem : list)
readEvalContext.or(elem.readsEvalContextRecursive());
return readEvalContext;
}
@Override
public void preprocess(final Game game)
{
for (final BooleanFunction elem : list)
elem.preprocess(game);
if (isStatic())
precomputedBoolean = Boolean.valueOf(eval(new Context(game, null)));
}
@Override
public boolean missingRequirement(final Game game)
{
boolean missingRequirement = false;
for (final BooleanFunction cond : list)
if (cond instanceof FalseConstant)
{
game.addRequirementToReport("One of the condition in an (or ...) ludeme is \"false\".");
missingRequirement = true;
break;
}
for (final BooleanFunction cond : list)
{
if (cond instanceof TrueConstant)
{
game.addRequirementToReport("One of the condition in an (or ...) ludeme is \"true\".");
missingRequirement = true;
break;
}
}
for (final BooleanFunction elem : list)
missingRequirement |= elem.missingRequirement(game);
return missingRequirement;
}
@Override
public boolean willCrash(final Game game)
{
boolean willCrash = false;
for (final BooleanFunction elem : list)
willCrash |= elem.willCrash(game);
return willCrash;
}
/**
* @return Our list of Boolean Functions
*/
public BooleanFunction[] list()
{
return list;
}
//-------------------------------------------------------------------------
@Override
public List<Location> satisfyingSites(final Context context)
{
if (!eval(context))
return new ArrayList<Location>();
for (final BooleanFunction cond : list)
if (cond.eval(context))
return cond.satisfyingSites(context);
return new ArrayList<Location>();
}
@Override
public BitSet stateConcepts(final Context context)
{
final BitSet stateConcepts = new BitSet();
for (final BooleanFunction elem : list)
if(elem.eval(context))
stateConcepts.or(elem.stateConcepts(context));
return stateConcepts;
}
@Override
public String toEnglish(final Game game)
{
String text = "";
int count=0;
for (final BooleanFunction func : list)
{
text += func.toEnglish(game);
count++;
if(count == list.length-1)
text += " or ";
else if(count < list.length)
text += ", ";
}
return text;
}
}
| 5,263 | 21.117647 | 96 | java |
Ludii | Ludii-master/Core/src/game/functions/booleans/math/Xor.java | package game.functions.booleans.math;
import java.util.BitSet;
import game.Game;
import game.functions.booleans.BaseBooleanFunction;
import game.functions.booleans.BooleanFunction;
import other.concept.Concept;
import other.context.Context;
/**
* Tests the Xor boolean node.
*
* @author cambolbro
*
*/
public final class Xor extends BaseBooleanFunction
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/**
* The first condition.
*/
private final BooleanFunction a;
/**
* The second condition.
*/
private final BooleanFunction b;
/** Precomputed boolean. */
private Boolean precomputedBoolean;
//-------------------------------------------------------------------------
/**
* @param a First condition.
* @param b Second condition.
* @example (xor (= (who at:(last To)) (mover)) (!= (who at:(last From))
* (mover)))
*/
public Xor
(
final BooleanFunction a,
final BooleanFunction b
)
{
this.a = a;
this.b = b;
}
//-------------------------------------------------------------------------
@Override
public boolean eval(final Context context)
{
if (precomputedBoolean != null)
return precomputedBoolean.booleanValue();
final boolean evalA = a.eval(context);
final boolean evalB = b.eval(context);
return (evalA && !evalB || !evalA && evalB);
}
//-------------------------------------------------------------------------
@Override
public boolean isStatic()
{
return a.isStatic() && b.isStatic();
}
@Override
public long gameFlags(final Game game)
{
return a.gameFlags(game) | b.gameFlags(game);
}
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
concepts.or(a.concepts(game));
concepts.or(b.concepts(game));
concepts.set(Concept.ExclusiveDisjunction.id(), true);
return concepts;
}
@Override
public BitSet writesEvalContextRecursive()
{
final BitSet writeEvalContext = new BitSet();
writeEvalContext.or(a.writesEvalContextRecursive());
writeEvalContext.or(b.writesEvalContextRecursive());
return writeEvalContext;
}
@Override
public BitSet readsEvalContextRecursive()
{
final BitSet readEvalContext = new BitSet();
readEvalContext.or(a.readsEvalContextRecursive());
readEvalContext.or(b.readsEvalContextRecursive());
return readEvalContext;
}
@Override
public boolean missingRequirement(final Game game)
{
boolean missingRequirement = false;
missingRequirement |= a.missingRequirement(game);
missingRequirement |= b.missingRequirement(game);
return missingRequirement;
}
@Override
public boolean willCrash(final Game game)
{
boolean willCrash = false;
willCrash |= a.willCrash(game);
willCrash |= b.willCrash(game);
return willCrash;
}
@Override
public void preprocess(final Game game)
{
a.preprocess(game);
b.preprocess(game);
if (isStatic())
precomputedBoolean = Boolean.valueOf(eval(new Context(game, null)));
}
@Override
public String toEnglish(final Game game)
{
return a.toEnglish(game) + " or " + b.toEnglish(game) + " but not both";
}
}
| 3,165 | 20.684932 | 76 | java |
Ludii | Ludii-master/Core/src/game/functions/booleans/math/package-info.java | /**
* Math queries return a boolean result based on given inputs.
*/
package game.functions.booleans.math;
| 109 | 21 | 62 | java |
Ludii | Ludii-master/Core/src/game/functions/booleans/no/No.java | package game.functions.booleans.no;
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.booleans.no.moves.NoMoves;
import game.functions.booleans.no.pieces.NoPieces;
import game.functions.ints.IntFunction;
import game.functions.region.RegionFunction;
import game.types.board.SiteType;
import game.types.play.RoleType;
import other.context.Context;
/**
* Returns whether a certain query about the game state is false.
*
* @author Eric.Piette
*/
@SuppressWarnings("javadoc")
public class No extends BaseBooleanFunction
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/**
* For checking if a piece type (or all piece types) are not placed.
*
* @param noType The type of query to perform.
* @param type The graph element type [default SiteType of the board].
* @param role The role of the player [All].
* @param of The index of the player.
* @param name The name of the container from which to count the number of
* sites or the name of the piece to count only pieces of that
* type.
* @param in The region where to count the pieces.
*
* @example (no Pieces Mover)
*/
public static BooleanFunction construct
(
final NoPieceType noType,
@Opt final SiteType type,
@Opt @Or final RoleType role,
@Opt @Or @Name final IntFunction of,
@Opt final String name,
@Opt @Name final RegionFunction in
)
{
switch (noType)
{
case Pieces:
return new NoPieces(type, role, of, name, in);
default:
break;
}
// We should never reach that except if we forget some codes.
throw new IllegalArgumentException("No(): A NoPieceType is not implemented.");
}
//-------------------------------------------------------------------------
/**
* For checking if a specific player (or all players) have no moves.
*
* @param noType The type of query to perform.
* @param playerFn The role of the player.
*
* @example (no Moves Mover)
*/
public static BooleanFunction construct
(
final NoMoveType noType,
final RoleType playerFn
)
{
switch (noType)
{
case Moves:
return new NoMoves(playerFn);
default:
break;
}
// We should never reach that except if we forget some codes.
throw new IllegalArgumentException("No(): A NoMoveType is not implemented.");
}
//-------------------------------------------------------------------------
private No()
{
// 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("No.eval(): Should never be called directly.");
// return false;
}
}
| 3,255 | 24.24031 | 89 | java |
Ludii | Ludii-master/Core/src/game/functions/booleans/no/NoMoveType.java | package game.functions.booleans.no;
/**
* Defines the types of query to check the non existence of moves.
*/
public enum NoMoveType
{
/** Returns whether a specified player (or All players) has no moves. */
Moves,
}
| 221 | 19.181818 | 73 | java |
Ludii | Ludii-master/Core/src/game/functions/booleans/no/NoPieceType.java | package game.functions.booleans.no;
/**
* Defines the types of query to check the non existence of pieces.
*/
public enum NoPieceType
{
/** Returns whether some pieces (or all) are not placed. */
Pieces,
}
| 211 | 18.272727 | 67 | java |
Ludii | Ludii-master/Core/src/game/functions/booleans/no/package-info.java | /**
* The {\tt (no ...)} `super' ludeme returns whether a given query about the game state is false.
* Such queries might include whether there are no moves available to the current player.
*/
package game.functions.booleans.no;
| 234 | 38.166667 | 98 | java |
Ludii | Ludii-master/Core/src/game/functions/booleans/no/moves/NoMoves.java | package game.functions.booleans.no.moves;
import java.util.BitSet;
import java.util.function.Supplier;
import annotations.Hide;
import game.Game;
import game.functions.booleans.BaseBooleanFunction;
import game.functions.ints.board.Id;
import game.types.play.RoleType;
import other.concept.Concept;
import other.context.Context;
import other.state.State;
import other.translation.LanguageUtils;
/**
* To check if one specific or all players can just pass.
*
* @author Eric.Piette
*/
@Hide
public final class NoMoves extends BaseBooleanFunction
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/** Role of the player under investigation. */
private final RoleType role;
/** 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 playerFn The roleType to check.
*/
public NoMoves(final RoleType playerFn)
{
role = playerFn;
}
//-------------------------------------------------------------------------
@Override
public boolean eval(final Context context)
{
if (role == RoleType.Next)
{
if (autoFail.get().booleanValue())
return false;
// (stalemated Next) is a common special case which we expect
// to return true if the next player will be stalemated in the
// turn that directly follows the current turn.
//
// The normal Ludii code only sets the stalemated flag correctly
// AFTER we switch over to the next player and compute their legal
// moves. So, to get the expected behaviour in this special case,
// we have to temporarily switch over to the next player and compute
// their legal moves
final State state = context.state();
final int currentPrevious = state.prev();
final int currentMover = state.mover();
final int nextMover = state.next();
if (!context.trial().over() && context.active())
{
context.setMoverAndImpliedPrevAndNext(state.next());
state.setPrev(currentMover);
}
autoFail.set(Boolean.TRUE); // Avoid recursive calls
context.game().computeStalemated(context);
autoFail.set(Boolean.FALSE);
// and switch mover back
state.setPrev(currentPrevious);
state.setMover(currentMover);
state.setNext(nextMover);
}
return context.state().isStalemated(new Id(null, role).eval(context));
}
//-------------------------------------------------------------------------
@Override
public String toString()
{
return "Stalemated(" + role + ")";
}
//-------------------------------------------------------------------------
@Override
public boolean isStatic()
{
return false;
}
@Override
public long gameFlags(final Game game)
{
return 0;
}
@Override
public boolean missingRequirement(final Game game)
{
boolean missingRequirement = false;
// We check if the role is correct.
final int indexOwnerPhase = role.owner();
if ((indexOwnerPhase < 1 && !role.equals(RoleType.Mover) && !role.equals(RoleType.Player) && !role.equals(RoleType.Prev)
&& !role.equals(RoleType.Next)) || indexOwnerPhase > game.players().count())
{
game.addRequirementToReport(
"In the ludeme (no Moves ...) a wrong RoleType is used: " + role + ".");
missingRequirement = true;
}
return missingRequirement;
}
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
concepts.set(Concept.NoMoves.id(), true);
if(role.equals(RoleType.Mover))
concepts.set(Concept.NoMovesMover.id(), true);
if(role.equals(RoleType.Next))
concepts.set(Concept.NoMovesNext.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 boolean autoFails()
{
return autoFail.get().booleanValue();
}
@Override
public String toEnglish(final Game game)
{
return LanguageUtils.RoleTypeAsText(role, false) + " cannot move";
}
}
| 4,469 | 23.833333 | 122 | java |
Ludii | Ludii-master/Core/src/game/functions/booleans/no/pieces/NoPieces.java | package game.functions.booleans.no.pieces;
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.component.Component;
import game.functions.booleans.BaseBooleanFunction;
import game.functions.ints.IntFunction;
import game.functions.region.RegionFunction;
import game.types.board.SiteType;
import game.types.play.RoleType;
import gnu.trove.list.array.TIntArrayList;
import other.PlayersIndices;
import other.concept.Concept;
import other.context.Context;
import other.location.Location;
import other.state.container.ContainerState;
/**
* To check if one specific piece type or all are not placed.
*
* @author Eric.Piette
*/
@Hide
public final class NoPieces extends BaseBooleanFunction
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/** Cell/Edge/Vertex. */
private final SiteType type;
/** The index of the player. */
private final IntFunction whoFn;
/** The name of the item (Container or Component) to count. */
private final String name;
/** The RoleType of the player. */
private final RoleType role;
/** The region to count the pieces. */
private final RegionFunction whereFn;
//-------------------------------------------------------------------------
/**
* @param type The graph element type [default SiteType of the board].
* @param role The role of the player [All].
* @param of The index of the player.
* @param name The name of the piece to count only these pieces.
* @param in The region where to count the pieces.
*/
public NoPieces
(
@Opt final SiteType type,
@Opt @Or final RoleType role,
@Opt @Or @Name final IntFunction of,
@Opt final String name,
@Opt @Name final RegionFunction in
)
{
this.type = type;
this.role = (role != null) ? role : (of == null ? RoleType.All : null);
whoFn = (of != null) ? of : RoleType.toIntFunction(this.role);
this.name = name;
whereFn = in;
}
//-------------------------------------------------------------------------
@Override
public boolean eval(final Context context)
{
final int whoId = whoFn.eval(context);
// Get the player condition.
final TIntArrayList idPlayers = PlayersIndices.getIdPlayers(context, role, whoId);
// Get the region condition.
final TIntArrayList whereSites = (whereFn != null) ? new TIntArrayList(whereFn.eval(context).sites()) : null;
// Get the component condition.
TIntArrayList componentIds = null;
if (name != null)
{
componentIds = new TIntArrayList();
for (int compId = 1; compId < context.components().length; compId++)
{
final Component component = context.components()[compId];
if (component.name().contains(name))
componentIds.add(compId);
}
}
for (int index = 0; index < idPlayers.size(); index++)
{
final int pid = idPlayers.get(index);
final BitSet alreadyLooked = new BitSet();
final List<? extends Location>[] positions = context.state().owned().positions(pid);
for (final List<? extends Location> locs : positions)
{
for (final Location loc : locs)
{
if (type == null || type != null && type.equals(loc.siteType()))
{
final int site = loc.site();
if (!alreadyLooked.get(site))
{
alreadyLooked.set(site);
// Check region condition
if (whereSites != null && !whereSites.contains(site))
continue;
SiteType realType = type;
int cid = 0;
if (type == null)
{
cid = site >= context.containerId().length ? 0 : context.containerId()[site];
if (cid > 0)
realType = SiteType.Cell;
else
realType = context.board().defaultSite();
}
final ContainerState cs = context.containerState(cid);
if (context.game().isStacking())
{
for (int level = 0 ; level < cs.sizeStack(site, realType); level++)
{
final int who = cs.who(site, level, realType);
if (!idPlayers.contains(who))
continue;
// Check component condition
if (componentIds != null)
{
final int what = cs.what(site, level, realType);
if (!componentIds.contains(what))
continue;
}
return false;
}
}
else
{
final int who = cs.who(site, realType);
if (!idPlayers.contains(who))
continue;
// Check component condition
if (componentIds != null)
{
final int what = cs.what(site, realType);
if (!componentIds.contains(what))
continue;
}
return false;
}
}
}
}
}
}
return true;
}
//-------------------------------------------------------------------------
@Override
public boolean isStatic()
{
return false;
}
@Override
public long gameFlags(final Game game)
{
long gameFlags = whoFn.gameFlags(game);
if (whereFn != null)
gameFlags |= whereFn.gameFlags(game);
gameFlags |= SiteType.gameFlags(type);
return gameFlags;
}
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
concepts.or(SiteType.concepts(type));
concepts.set(Concept.NoPiece.id(), true);
concepts.or(whoFn.concepts(game));
if(role != null)
{
if(role.equals(RoleType.Mover))
concepts.set(Concept.NoPieceMover.id(), true);
else if(role.equals(RoleType.Next))
concepts.set(Concept.NoPieceNext.id(), true);
}
if (whereFn != null)
concepts.or(whereFn.concepts(game));
return concepts;
}
@Override
public BitSet writesEvalContextRecursive()
{
final BitSet writeEvalContext = new BitSet();
writeEvalContext.or(whoFn.writesEvalContextRecursive());
if (whereFn != null)
writeEvalContext.or(whereFn.writesEvalContextRecursive());
return writeEvalContext;
}
@Override
public BitSet readsEvalContextRecursive()
{
final BitSet readEvalContext = new BitSet();
readEvalContext.or(whoFn.readsEvalContextRecursive());
if (whereFn != null)
readEvalContext.or(whereFn.readsEvalContextRecursive());
return readEvalContext;
}
@Override
public boolean missingRequirement(final Game game)
{
boolean missingRequirement = false;
missingRequirement |= whoFn.missingRequirement(game);
if (whereFn != null)
missingRequirement |= whereFn.missingRequirement(game);
return missingRequirement;
}
@Override
public boolean willCrash(final Game game)
{
boolean willCrash = false;
willCrash |= whoFn.willCrash(game);
if (whereFn != null)
willCrash |= whereFn.willCrash(game);
return willCrash;
}
@Override
public void preprocess(final Game game)
{
whoFn.preprocess(game);
if (whereFn != null)
whereFn.preprocess(game);
}
//-------------------------------------------------------------------------
@Override
public String toEnglish(final Game game)
{
String pieceName = "piece";
if (name != null)
pieceName = name;
String who = "";
if (whoFn != null)
who = " owned by Player " + whoFn.toEnglish(game);
else if (role != null)
who = " owned by " + role.name();
String typeString = "";
if (type != null)
typeString = " on the " + type.name().toLowerCase() + "s";
String whereString = "";
if (whereFn != null)
whereString = " of " + whereFn.toEnglish(game);
return "there are no " + pieceName + "s" + who + typeString + whereString;
}
//-------------------------------------------------------------------------
}
| 7,753 | 24.422951 | 111 | java |
Ludii | Ludii-master/Core/src/game/functions/booleans/was/Was.java | package game.functions.booleans.was;
import game.Game;
import game.functions.booleans.BaseBooleanFunction;
import game.functions.booleans.BooleanFunction;
import other.context.Context;
/**
* Returns whether a specified event has occurred in the game.
*
* @author Eric.Piette
*/
@SuppressWarnings("javadoc")
public class Was extends BaseBooleanFunction
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/**
* @param wasType The event to query.
*
* @example (was Pass)
*/
public static BooleanFunction construct
(
final WasType wasType
)
{
switch (wasType)
{
case Pass:
return new WasPass();
default:
break;
}
// We should never reach that except if we forget some codes.
throw new IllegalArgumentException("Was(): A wasType is not implemented.");
}
//-------------------------------------------------------------------------
private Was()
{
// 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("Was.eval(): Should never be called directly.");
// return false;
}
}
| 1,530 | 18.628205 | 90 | java |
Ludii | Ludii-master/Core/src/game/functions/booleans/was/WasPass.java | package game.functions.booleans.was;
import java.util.BitSet;
import annotations.Hide;
import game.Game;
import game.functions.booleans.BaseBooleanFunction;
import other.context.Context;
/**
* Checks if the last move was a pass move.
*
* @author Eric.Piette
*/
@Hide
public final class WasPass extends BaseBooleanFunction
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/**
*
*/
public WasPass()
{
// Nothing to do.
}
//-------------------------------------------------------------------------
@Override
public boolean eval(final Context context)
{
return context.trial().lastMove().isPass();
}
//-------------------------------------------------------------------------
@Override
public boolean isStatic()
{
return false;
}
@Override
public long gameFlags(final Game game)
{
return 0l;
}
@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.
}
//-------------------------------------------------------------------------
@Override
public String toString()
{
final String str = "(WasPass)";
return str;
}
//-------------------------------------------------------------------------
@Override
public String toEnglish(final Game game)
{
return "the last move was a pass move";
}
//-------------------------------------------------------------------------
}
| 1,820 | 17.393939 | 76 | java |
Ludii | Ludii-master/Core/src/game/functions/booleans/was/WasType.java | package game.functions.booleans.was;
/**
* Defines the types of events that can be queried.
*/
public enum WasType
{
/** Whether the last move was a pass. */
Pass,
}
| 171 | 14.636364 | 51 | java |
Ludii | Ludii-master/Core/src/game/functions/booleans/was/package-info.java | /**
* The {\tt (was ...)} `super' ludeme returns a true/false result as to whether a certain
* event has occurred in the game, for example whether the last move was a pass.
*/
package game.functions.booleans.was;
| 218 | 35.5 | 90 | java |
Ludii | Ludii-master/Core/src/game/functions/dim/BaseDimFunction.java | package game.functions.dim;
import annotations.Alias;
import game.Game;
import other.BaseLudeme;
/**
* Common functionality for DimFunction - override where necessary.
*
* @author Eric.Piette and cambolbro
*/
@Alias(alias = "dim")
public abstract class BaseDimFunction extends BaseLudeme implements DimFunction
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
@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
}
}
| 658 | 16.810811 | 79 | java |
Ludii | Ludii-master/Core/src/game/functions/dim/DimConstant.java | package game.functions.dim;
import annotations.Hide;
/**
* Constant dim value.
*
* @author Eric.Piette and cambolbro
*/
@Hide
public final class DimConstant extends BaseDimFunction
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/** Constant value. */
private final int a;
//-------------------------------------------------------------------------
/**
* @param a The integer value.
*/
public DimConstant(final int a)
{
this.a = a;
}
//-------------------------------------------------------------------------
@Override
public int eval()
{
return a;
}
//-------------------------------------------------------------------------
@Override
public String toString()
{
final String str = "" + a;
return str;
}
}
| 833 | 16.744681 | 76 | java |
Ludii | Ludii-master/Core/src/game/functions/dim/DimFunction.java | package game.functions.dim;
import game.Game;
import game.types.state.GameType;
/**
* Returns an integer corresponding to a dimension.
*
* @author Eric.Piette and cambolbro
*/
// **
// ** Do not @Hide, or loses mapping in grammar!
// **
public interface DimFunction extends GameType
{
/**
* @return The result of the function.
*/
int eval();
/**
* @param game
* @return This Function in English.
*/
String toEnglish(Game game);
}
| 457 | 13.774194 | 51 | java |
Ludii | Ludii-master/Core/src/game/functions/dim/package-info.java | /**
* @chapter Dim functions are ludemes that return a single integer value
* according to mathematical operations.
*/
package game.functions.dim;
| 159 | 25.666667 | 72 | java |
Ludii | Ludii-master/Core/src/game/functions/dim/math/Abs.java | package game.functions.dim.math;
import game.Game;
import game.functions.dim.BaseDimFunction;
import game.functions.dim.DimFunction;
/**
* Return the absolute value of a dim.
*
* @author Eric Piette
*/
public final class Abs extends BaseDimFunction
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/** Which value. */
protected final DimFunction value;
//-------------------------------------------------------------------------
/**
* Return the absolute value of a value.
*
* @param value The value.
* @example (abs (- 8 5))
*/
public Abs
(
final DimFunction value
)
{
this.value = value;
}
//-------------------------------------------------------------------------
@Override
public int eval()
{
return Math.abs(value.eval());
}
@Override
public String toEnglish(final Game game)
{
return "The absolute value of " + value.toEnglish(game);
}
}
| 978 | 18.196078 | 76 | java |
Ludii | Ludii-master/Core/src/game/functions/dim/math/Add.java | package game.functions.dim.math;
import annotations.Alias;
import game.Game;
import game.functions.dim.BaseDimFunction;
import game.functions.dim.DimFunction;
/**
* Adds many values.
*
* @author Eric.Piette
*/
@Alias(alias = "+")
public final class Add extends BaseDimFunction
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/** The first value. */
private final DimFunction a;
/** The second value. */
private final DimFunction b;
/** The list of values. */
protected final DimFunction[] list;
//-------------------------------------------------------------------------
/**
* To add two values.
*
* @param a The first value.
* @param b The second value.
* @example (+ 5 2)
*/
public Add
(
final DimFunction a,
final DimFunction b
)
{
this.a = a;
this.b = b;
list = null;
}
/**
* To add all the values of a list.
*
* @param list The list of the values.
* @example (+ {10 2 5})
*/
public Add
(
final DimFunction[] list
)
{
a = null;
b = null;
this.list = list;
}
//-------------------------------------------------------------------------
@Override
public int eval()
{
if (list == null)
{
return a.eval() + b.eval();
}
int sum = 0;
for (final DimFunction elem : list)
sum += elem.eval();
return sum;
}
@Override
public String toEnglish(final Game game)
{
return a.toEnglish(game) + " + " + b.toEnglish(game);
}
}
| 1,504 | 16.102273 | 76 | java |
Ludii | Ludii-master/Core/src/game/functions/dim/math/Div.java | package game.functions.dim.math;
import annotations.Alias;
import game.functions.dim.BaseDimFunction;
import game.functions.dim.DimFunction;
/**
* To divide a value by another.
*
* @author Eric.Piette and cambolbro
* @remarks The result will be an integer and round down the result.
*/
@Alias(alias = "/")
public final class Div extends BaseDimFunction
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/** The value to divide. */
private final DimFunction a;
/** To divide by b. */
private final DimFunction b;
//-------------------------------------------------------------------------
/**
* To divide a value by another.
*
* @param a The value to divide.
* @param b To divide by b.
* @example (/ 4 2)
*/
public Div
(
final DimFunction a,
final DimFunction b
)
{
this.a = a;
this.b = b;
}
//-------------------------------------------------------------------------
@Override
public int eval()
{
final int evalB = b.eval();
if (evalB == 0)
throw new IllegalArgumentException("Division by zero.");
return a.eval() / evalB;
}
}
| 1,169 | 19.526316 | 76 | java |
Ludii | Ludii-master/Core/src/game/functions/dim/math/Max.java | package game.functions.dim.math;
import game.functions.dim.BaseDimFunction;
import game.functions.dim.DimFunction;
/**
* Returns the maximum of two specified values.
*
* @author Eric Piette
*/
public final class Max extends BaseDimFunction
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/** Value A . */
private final DimFunction valueA;
/** Value B. */
private final DimFunction valueB;
//-------------------------------------------------------------------------
/**
* @param valueA The first value.
* @param valueB The second value.
* @example (max 9 3)
*/
public Max
(
final DimFunction valueA,
final DimFunction valueB
)
{
this.valueA = valueA;
this.valueB = valueB;
}
//-------------------------------------------------------------------------
@Override
public int eval()
{
return Math.max(valueA.eval(), valueB.eval());
}
}
| 961 | 19.041667 | 76 | java |
Ludii | Ludii-master/Core/src/game/functions/dim/math/Min.java | package game.functions.dim.math;
import game.functions.dim.BaseDimFunction;
import game.functions.dim.DimFunction;
/**
* Returns the minimum of two specified values.
*
* @author Eric Piette
*/
public final class Min extends BaseDimFunction
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/** Value A . */
private final DimFunction valueA;
/** Value B. */
private final DimFunction valueB;
//-------------------------------------------------------------------------
/**
* @param valueA The first value.
* @param valueB The second value.
* @example (min 20 3)
*/
public Min
(
final DimFunction valueA,
final DimFunction valueB
)
{
this.valueA = valueA;
this.valueB = valueB;
}
//-------------------------------------------------------------------------
@Override
public int eval()
{
return Math.min(valueA.eval(), valueB.eval());
}
}
| 961 | 19.041667 | 76 | java |
Ludii | Ludii-master/Core/src/game/functions/dim/math/Mul.java | package game.functions.dim.math;
import annotations.Alias;
import game.functions.dim.BaseDimFunction;
import game.functions.dim.DimFunction;
/**
* Returns to multiple of values.
*
* @author Eric.Piette
*/
@Alias(alias = "*")
public final class Mul extends BaseDimFunction
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/** Value a. */
private final DimFunction a;
/** Value b. */
private final DimFunction b;
/** List of values. */
private final DimFunction[] list;
//-------------------------------------------------------------------------
/**
* For a product of two values.
*
* @param a The first value.
* @param b The second value.
*
* @example (* 6 2)
*/
public Mul
(
final DimFunction a,
final DimFunction b
)
{
this.a = a;
this.b = b;
this.list = null;
}
/**
* For a product of many values.
*
* @param list The list of values.
* @example (* {3 2 5})
*/
public Mul(final DimFunction[] list)
{
this.list = list;
this.a = null;
this.b = null;
}
//-------------------------------------------------------------------------
@Override
public int eval()
{
if (list == null)
{
return a.eval() * b.eval();
}
else
{
int mul = 1;
for (final DimFunction elem : list)
mul *= elem.eval();
return mul;
}
}
}
| 1,392 | 16.197531 | 76 | java |
Ludii | Ludii-master/Core/src/game/functions/dim/math/Pow.java | package game.functions.dim.math;
import annotations.Alias;
import game.Game;
import game.functions.dim.BaseDimFunction;
import game.functions.dim.DimFunction;
/**
* Computes the first parameter to the power of the second parameter.
*
* @author Eric.Piette
*/
@Alias(alias = "^")
public final class Pow extends BaseDimFunction
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/** The value. */
private final DimFunction a;
/** The power. */
private final DimFunction b;
//-------------------------------------------------------------------------
/**
* @param a The value.
* @param b The power.
* @example (^ 2 2)
*/
public Pow
(
final DimFunction a,
final DimFunction b
)
{
this.a = a;
this.b = b;
}
//-------------------------------------------------------------------------
@Override
public int eval()
{
return (int) (Math.pow(a.eval(), b.eval()));
}
//-------------------------------------------------------------------------
@Override
public String toEnglish(final Game game)
{
return a.toEnglish(game) + " to the power of " + b.toEnglish(game);
}
//-------------------------------------------------------------------------
}
| 1,276 | 19.596774 | 76 | java |
Ludii | Ludii-master/Core/src/game/functions/dim/math/Sub.java | package game.functions.dim.math;
import annotations.Alias;
import game.functions.dim.BaseDimFunction;
import game.functions.dim.DimFunction;
/**
* Returns the subtraction A minus B.
*
* @author Eric Piette
*/
@Alias(alias = "-")
public final class Sub extends BaseDimFunction
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/** Which value A. */
private final DimFunction valueA;
/** Which value B. */
private final DimFunction valueB;
//-------------------------------------------------------------------------
/**
* @param valueA The value A.
* @param valueB The value B.
* @example (- 5 1)
*/
public Sub
(
final DimFunction valueA,
final DimFunction valueB
)
{
this.valueA = valueA;
this.valueB = valueB;
}
//-------------------------------------------------------------------------
@Override
public int eval()
{
return valueA.eval() - valueB.eval();
}
}
| 988 | 18.78 | 76 | java |
Ludii | Ludii-master/Core/src/game/functions/dim/math/package-info.java | /**
* Math functions return an integer value based on given inputs.
*/
package game.functions.dim.math;
| 106 | 20.4 | 64 | java |
Ludii | Ludii-master/Core/src/game/functions/directions/Difference.java | package game.functions.directions;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.List;
import game.Game;
import game.equipment.component.Component;
import game.types.board.RelationType;
import game.types.board.SiteType;
import game.util.directions.AbsoluteDirection;
import game.util.directions.Direction;
import game.util.directions.DirectionFacing;
import other.context.Context;
import other.topology.TopologyElement;
/**
* Returns the difference of two set of directions.
*
* @author Eric.Piette
*/
public class Difference extends DirectionsFunction
{
/** The original set of directions. */
final DirectionsFunction originalDirection;
/** The directions to remove from the original set of directions. */
final DirectionsFunction removedDirection;
//-------------------------------------------------------------------------
/**
* @param directions The original directions.
* @param directionsToRemove The directions to remove.
*
* @example (difference Orthogonal N)
*/
public Difference
(
final Direction directions,
final Direction directionsToRemove
)
{
originalDirection = directions.directionsFunctions();
removedDirection = directionsToRemove.directionsFunctions();
}
//-------------------------------------------------------------------------
/**
* Trick ludeme into joining the grammar.
* @param context Current game context.
* @return Nuthin'! Absolutely nuthin'.
*/
@SuppressWarnings("static-method")
public Direction eval(final Context context)
{
return null;
}
//-------------------------------------------------------------------------
@Override
public long gameFlags(final Game game)
{
long gameFlags = 0;
gameFlags |= originalDirection.gameFlags(game);
gameFlags |= removedDirection.gameFlags(game);
return gameFlags;
}
@Override
public boolean isStatic()
{
return originalDirection.isStatic() && removedDirection.isStatic();
}
@Override
public void preprocess(final Game game)
{
originalDirection.preprocess(game);
removedDirection.preprocess(game);
}
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
concepts.or(originalDirection.concepts(game));
concepts.or(removedDirection.concepts(game));
return concepts;
}
@Override
public boolean missingRequirement(final Game game)
{
boolean missingRequirement = false;
missingRequirement |= originalDirection.missingRequirement(game);
missingRequirement |= removedDirection.missingRequirement(game);
return missingRequirement;
}
@Override
public boolean willCrash(final Game game)
{
boolean willCrash = false;
willCrash |= originalDirection.willCrash(game);
willCrash |= removedDirection.willCrash(game);
return willCrash;
}
//-------------------------------------------------------------------------
@Override
public String toString()
{
return "";
}
//-------------------------------------------------------------------------
@Override
public List<AbsoluteDirection> convertToAbsolute(final SiteType graphType, final TopologyElement element,
final Component newComponent, final DirectionFacing newFacing, final Integer newRotation,
final Context context)
{
final List<AbsoluteDirection> directionsReturned = new ArrayList<AbsoluteDirection>();
final List<AbsoluteDirection> originalDir = originalDirection.convertToAbsolute(graphType, element,
newComponent, newFacing, newRotation,
context);
final List<AbsoluteDirection> originalAfterConv = new ArrayList<AbsoluteDirection>();
final List<AbsoluteDirection> directionsToRemove = removedDirection.convertToAbsolute(graphType, element,
newComponent, newFacing, newRotation,
context);
final List<AbsoluteDirection> removedAfterConv = new ArrayList<AbsoluteDirection>();
// Convert in AbsoluteDirection with equivalent in FacingDirection
for (final AbsoluteDirection dir : originalDir)
{
final RelationType relation = AbsoluteDirection.converToRelationType(dir);
if(relation != null)
{
final List<DirectionFacing> directionsFacing = element.supportedDirections(relation);
for(final DirectionFacing dirFacing : directionsFacing)
if(!originalAfterConv.contains(dirFacing.toAbsolute()))
originalAfterConv.add(dirFacing.toAbsolute());
}
else
originalAfterConv.add(dir);
}
for (final AbsoluteDirection dir : directionsToRemove)
{
final RelationType relation = AbsoluteDirection.converToRelationType(dir);
if(relation != null)
{
final List<DirectionFacing> directionsFacing = element.supportedDirections(relation);
for(final DirectionFacing dirFacing : directionsFacing)
if(!removedAfterConv.contains(dirFacing.toAbsolute()))
removedAfterConv.add(dirFacing.toAbsolute());
}
else
removedAfterConv.add(dir);
}
for (final AbsoluteDirection dir : originalAfterConv)
if (!removedAfterConv.contains(dir))
directionsReturned.add(dir);
return directionsReturned;
}
//-------------------------------------------------------------------------
@Override
public String toEnglish(final Game game)
{
return "the difference between directions " + originalDirection.toEnglish(game) + " and " + removedDirection.directionsFunctions();
}
//-------------------------------------------------------------------------
}
| 5,384 | 28.108108 | 133 | java |
Ludii | Ludii-master/Core/src/game/functions/directions/Directions.java | package game.functions.directions;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.BitSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import annotations.Name;
import annotations.Opt;
import annotations.Or;
import game.Game;
import game.equipment.component.Component;
import game.functions.ints.IntFunction;
import game.functions.ints.last.LastFrom;
import game.functions.ints.last.LastTo;
import game.types.board.RelationType;
import game.types.board.SiteType;
import game.types.state.GameType;
import game.util.directions.AbsoluteDirection;
import game.util.directions.CompassDirection;
import game.util.directions.Direction;
import game.util.directions.DirectionFacing;
import game.util.directions.RelativeDirection;
import game.util.graph.Radial;
import main.collections.ArrayUtils;
import other.concept.Concept;
import other.context.Context;
import other.state.container.ContainerState;
import other.topology.Topology;
import other.topology.TopologyElement;
import other.translation.LanguageUtils;
/**
* Converts the directions with absolute directions or relative directions
* according to the direction of the piece/player to a list of integers.
*
* @author Eric.Piette
*/
public class Directions extends DirectionsFunction implements Serializable
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/** Relative direction. */
private final RelativeDirection[] relativeDirections;
/** The type of the relative direction type. */
private final RelationType relativeDirectionType;
/**
* If true, the directions to return are computed according to the supported
* directions of the site and if not according to all the directions supported
* by the board.
*/
private final boolean bySite;
/**
* Map of cached lists of absolute directions for facing directions.
* One map per thread, for thread-safety.
* Only used for relative directions without SameDirection and OppositeDirection,
* and only if bySite is false.
*/
private final ThreadLocal<Map<DirectionFacing, List<AbsoluteDirection>>> cachedAbsDirs;
//-------------------------------------------------------------------------
/** In static cases, we precomputed the outcome of convertToAbsolute() once and can immediately return. */
private List<AbsoluteDirection> precomputedDirectionsToReturn = null;
/** Absolute directions. */
private final AbsoluteDirection[] absoluteDirections;
//-------------------------------------------------------------------------
/** The type of the sites. */
private final SiteType siteType;
/** The from site. */
private final IntFunction fromFn;
/** The to site. */
private final IntFunction toFn;
//-------------------------------------------------------------------------
/** The set of directions. */
private final Direction randomDirections;
/** The number of directions to return if possible. */
private final IntFunction numDirection;
//-------------------------------------------------------------------------
/**
* For defining directions with absolute directions.
*
* @param absoluteDirection The absolute direction.
* @param absoluteDirections The absolute directions.
*
* @example (directions Orthogonal)
*/
public Directions
(
@Or final AbsoluteDirection absoluteDirection,
@Or final AbsoluteDirection[] absoluteDirections
)
{
int numNonNull = 0;
if (absoluteDirection != null)
numNonNull++;
if (absoluteDirections != null)
numNonNull++;
if (numNonNull > 1)
throw new IllegalArgumentException(
"Only zero or one absoluteDirection, absoluteDirections parameter can be non-null.");
relativeDirections = null;
this.absoluteDirections = (absoluteDirections != null) ? absoluteDirections : new AbsoluteDirection[]
{ absoluteDirection };
relativeDirectionType = RelationType.Adjacent;
bySite = false;
cachedAbsDirs = null;
siteType = null;
fromFn = null;
toFn = null;
randomDirections = null;
numDirection = null;
}
/**
* For defining directions with relative directions.
*
* @param relativeDirection The relative direction.
* @param relativeDirections The relative directions.
* @param of The type of directions to return [Adjacent].
* @param bySite If true, the directions to return are computed
* according to the supported directions of the site
* and if not according to all the directions
* supported by the board [False].
*
* @example (directions Forwards)
*/
public Directions
(
@Opt @Or final RelativeDirection relativeDirection,
@Opt @Or final RelativeDirection[] relativeDirections,
@Opt @Name final RelationType of,
@Opt @Name final Boolean bySite
)
{
int numNonNull = 0;
if (relativeDirection != null)
numNonNull++;
if (relativeDirections != null)
numNonNull++;
if (numNonNull > 1)
throw new IllegalArgumentException(
"Only zero or one relativeDirection, relativeDirections parameter can be non-null.");
absoluteDirections = null;
if (relativeDirections != null)
this.relativeDirections = relativeDirections;
else
this.relativeDirections = (relativeDirection == null) ? new RelativeDirection[]
{ RelativeDirection.Forward } : new RelativeDirection[]
{ relativeDirection };
relativeDirectionType = (of != null) ? of : RelationType.Adjacent;
this.bySite = (bySite == null) ? false : bySite.booleanValue();
if
(
!this.bySite &&
!ArrayUtils.contains(this.relativeDirections, RelativeDirection.SameDirection) &&
!ArrayUtils.contains(this.relativeDirections, RelativeDirection.OppositeDirection)
)
{
cachedAbsDirs = ThreadLocal.withInitial(() -> new HashMap<DirectionFacing, List<AbsoluteDirection>>());
}
else
{
cachedAbsDirs = null;
}
siteType = null;
fromFn = null;
toFn = null;
randomDirections = null;
numDirection = null;
}
/**
* For returning a direction between two sites of the same type.
*
* @param type The type of the graph element.
* @param from The 'from' site.
* @param to The 'to' site.
*
* @example (directions Cell from:(last To) to:(last From)))
*/
public Directions
(
final SiteType type,
@Name final IntFunction from,
@Name final IntFunction to
)
{
siteType = type;
fromFn = from;
toFn = to;
bySite = false;
relativeDirections = null;
relativeDirectionType = null;
absoluteDirections = null;
cachedAbsDirs = null;
randomDirections = null;
numDirection = null;
}
/**
* For returning a direction between two sites of the same type.
*
* @param type The type of random direction.
* @param directions The direction function.
* @param num The number of directions to return (if possible).
*
* @example (directions Random Orthogonal num:2)
*/
public Directions
(
final RandomDirectionType type,
final Direction directions,
@Name final IntFunction num
)
{
siteType = null;
fromFn = null;
toFn = null;
bySite = false;
relativeDirections = null;
relativeDirectionType = null;
absoluteDirections = null;
cachedAbsDirs = null;
randomDirections = directions;
numDirection = num;
}
//-------------------------------------------------------------------------
@Override
public long gameFlags(final Game game)
{
long gameFlags = 0l;
if (siteType != null)
gameFlags |= SiteType.gameFlags(siteType);
if (fromFn != null)
gameFlags = gameFlags | fromFn.gameFlags(game);
if (toFn != null)
gameFlags = gameFlags | toFn.gameFlags(game);
if (numDirection != null)
gameFlags = gameFlags | numDirection.gameFlags(game);
if (randomDirections != null)
gameFlags = gameFlags | GameType.Stochastic;
return gameFlags;
}
@Override
public boolean isStatic()
{
return (absoluteDirections != null);
}
@Override
public void preprocess(final Game game)
{
if (fromFn != null)
fromFn.preprocess(game);
if (toFn != null)
toFn.preprocess(game);
if (numDirection != null)
numDirection.preprocess(game);
if (isStatic())
precomputedDirectionsToReturn = convertToAbsolute(null, null, null, null, null, null);
}
//-------------------------------------------------------------------------
/**
* @return If the ludeme corresponds to all the directions.
*/
public boolean isAll()
{
return (absoluteDirections != null && absoluteDirections[0].equals(AbsoluteDirection.All));
}
@Override
public RelativeDirection[] getRelativeDirections()
{
return relativeDirections;
}
/**
* @return The absolute direction.
*/
public AbsoluteDirection absoluteDirection()
{
if (absoluteDirections == null)
return null;
return absoluteDirections[0];
}
@Override
public List<AbsoluteDirection> convertToAbsolute
(
final SiteType graphType,
final TopologyElement element,
final Component newComponent,
final DirectionFacing newFacing,
final Integer newRotation,
final Context context
)
{
if (precomputedDirectionsToReturn != null)
return precomputedDirectionsToReturn;
if(randomDirections != null)
{
int num = numDirection.eval(context);
final List<AbsoluteDirection> directions = randomDirections.directionsFunctions()
.convertToAbsolute(graphType, element, newComponent, newFacing, newRotation, context);
final List<AbsoluteDirection> realDirectionToCheck = new ArrayList<AbsoluteDirection>();
for (int i = directions.size() - 1; i >= 0; i--)
{
final AbsoluteDirection absoluteDirection = directions.get(i);
if (absoluteDirection.equals(AbsoluteDirection.Adjacent))
{
final List<DirectionFacing> supportedDirection = element.supportedAdjacentDirections();
for (final DirectionFacing facingDirection : supportedDirection)
if (!directions.contains(facingDirection.toAbsolute()))
realDirectionToCheck.add(facingDirection.toAbsolute());
}
else if (absoluteDirection.equals(AbsoluteDirection.Orthogonal))
{
final List<DirectionFacing> supportedDirection = element.supportedOrthogonalDirections();
for (final DirectionFacing facingDirection : supportedDirection)
if (!directions.contains(facingDirection.toAbsolute()))
realDirectionToCheck.add(facingDirection.toAbsolute());
}
else if (absoluteDirection.equals(AbsoluteDirection.Diagonal))
{
final List<DirectionFacing> supportedDirection = element.supportedDiagonalDirections();
for (final DirectionFacing facingDirection : supportedDirection)
if (!directions.contains(facingDirection.toAbsolute()))
realDirectionToCheck.add(facingDirection.toAbsolute());
}
else if (absoluteDirection.equals(AbsoluteDirection.OffDiagonal))
{
final List<DirectionFacing> supportedDirection = element.supportedOffDirections();
for (final DirectionFacing facingDirection : supportedDirection)
if (!directions.contains(facingDirection.toAbsolute()))
realDirectionToCheck.add(facingDirection.toAbsolute());
}
else if (absoluteDirection.equals(AbsoluteDirection.All))
{
final List<DirectionFacing> supportedDirection = element.supportedDirections();
for (final DirectionFacing facingDirection : supportedDirection)
if (!directions.contains(facingDirection.toAbsolute()))
realDirectionToCheck.add(facingDirection.toAbsolute());
}
else
realDirectionToCheck.add(absoluteDirection);
}
if (num > realDirectionToCheck.size())
num = realDirectionToCheck.size();
final List<AbsoluteDirection> directionsToReturn = new ArrayList<AbsoluteDirection>();
if (num == 0)
return directionsToReturn;
while (directionsToReturn.size() != num)
{
final AbsoluteDirection absoluteDirection = realDirectionToCheck
.get(context.rng().nextInt(realDirectionToCheck.size()));
if (!directionsToReturn.contains(absoluteDirection))
directionsToReturn.add(absoluteDirection);
}
return directionsToReturn;
}
if (siteType != null)
{
final Topology topology = context.topology();
final int from = fromFn.eval(context);
final int to = toFn.eval(context);
final int maxSize = topology.getGraphElements(siteType).size();
if (from < 0 || from >= maxSize || to < 0 || to >= maxSize)
return new ArrayList<AbsoluteDirection>();
final TopologyElement fromV = topology.getGraphElements(siteType).get(from);
final List<DirectionFacing> directionsSupported = topology.supportedDirections(RelationType.All, siteType);
final List<AbsoluteDirection> directionList = new ArrayList<AbsoluteDirection>();
for (final DirectionFacing facingDirection : directionsSupported)
{
final AbsoluteDirection absDirection = facingDirection.toAbsolute();
final List<Radial> radials = topology.trajectories().radials(siteType, fromV.index(), absDirection);
for (final Radial radial : radials)
{
for (int toIdx = 1; toIdx < radial.steps().length; toIdx++)
{
final int toRadial = radial.steps()[toIdx].id();
if (toRadial == to)
{
directionList.add(absDirection);
break;
}
}
}
}
return directionList;
}
if (absoluteDirections != null)
{
return Arrays.asList(absoluteDirections);
}
else if (element != null)
{
final Topology topology = context.topology();
final int site = element.index();
final int containerId = (graphType != SiteType.Cell ? 0 : context.containerId()[site]);
final ContainerState cs = context.containerState(containerId);
final int what = cs.what(site, graphType);
// if ( &newComponent == null) // we need a component to return a relative direction according to it.
// return new ArrayList<AbsoluteDirection>();
final Component component = (newComponent != null) ? newComponent : (what >= 1) ? context.components()[what] : null;
final List<DirectionFacing> directionsSupported = (bySite) ? element.supportedDirections(relativeDirectionType)
: topology.supportedDirections(relativeDirectionType, graphType);
// If no facing direction, we consider the piece to face to the north.
DirectionFacing facingDirection = (newFacing != null) ? newFacing
: (component != null) ? ((component.getDirn() != null) ? component.getDirn() : CompassDirection.N) : CompassDirection.N;
// We apply the rotation here.
int rotation = (newRotation == null) ? cs.rotation(site, graphType) : newRotation.intValue();
while (rotation != 0)
{
facingDirection = RelativeDirection.FR.directions(facingDirection, directionsSupported).get(0);
rotation--;
}
final Map<DirectionFacing, List<AbsoluteDirection>> cachedDirs;
if (cachedAbsDirs == null)
{
cachedDirs = null;
}
else
{
cachedDirs = cachedAbsDirs.get();
final List<AbsoluteDirection> cachedList = cachedDirs.get(facingDirection);
if (cachedList != null)
return cachedList;
}
final List<AbsoluteDirection> directionsToReturn = new ArrayList<AbsoluteDirection>();
for (final RelativeDirection relativeDirection : relativeDirections)
{
// Special case for the same direction.
if (relativeDirection.equals(RelativeDirection.SameDirection))
{
final int lastFrom = new LastFrom(null).eval(context);
final int lastTo = new LastTo(null).eval(context);
boolean found = false;
for (final DirectionFacing direction : directionsSupported)
{
final AbsoluteDirection absDirection = direction.toAbsolute();
final List<Radial> radials = topology.trajectories().radials(graphType, lastFrom, absDirection);
for (final Radial radial : radials)
{
for (int toIdx = 1; toIdx < radial.steps().length; toIdx++)
{
final int toSite = radial.steps()[toIdx].id();
if (toSite == lastTo)
{
directionsToReturn.add(absDirection);
found = true;
break;
}
}
}
if (found)
break;
}
}
else if (relativeDirection.equals(RelativeDirection.OppositeDirection))
{
final int lastFrom = new LastFrom(null).eval(context);
final int lastTo = new LastTo(null).eval(context);
boolean found = false;
for (final DirectionFacing direction : directionsSupported)
{
final AbsoluteDirection absDirection = direction.toAbsolute();
final List<Radial> radials = topology.trajectories().radials(graphType, lastTo, absDirection);
for (final Radial radial : radials)
{
for (int toIdx = 1; toIdx < radial.steps().length; toIdx++)
{
final int toSite = radial.steps()[toIdx].id();
if (toSite == lastFrom)
{
directionsToReturn.add(absDirection);
found = true;
break;
}
}
}
if (found)
break;
}
}
else
{
// All the other relative directions are converted here.
final List<DirectionFacing> supportedDirections = (bySite)
? element.supportedDirections(relativeDirectionType)
: topology.supportedDirections(relativeDirectionType, graphType);
final List<DirectionFacing> directions = relativeDirection.directions(facingDirection,
supportedDirections);
for (final DirectionFacing direction : directions)
directionsToReturn.add(direction.toAbsolute());
}
}
// Cache result if allowed
if (cachedDirs != null)
cachedDirs.put(facingDirection, directionsToReturn);
return directionsToReturn;
}
else
{
return new ArrayList<AbsoluteDirection>();
}
}
@Override
public String toString()
{
String str = "DirectionChoice(";
if (absoluteDirections != null)
for (final AbsoluteDirection absoluteDirection : absoluteDirections)
str += absoluteDirection.name() + ", ";
else if (relativeDirections != null)
for (final RelativeDirection relativeDirection : relativeDirections)
str += relativeDirection.name() + ", ";
str += ")";
return str;
}
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
if (relativeDirections != null)
for (final RelativeDirection relativeDirection : relativeDirections)
concepts.or(RelativeDirection.concepts(relativeDirection));
if (absoluteDirections != null)
for (final AbsoluteDirection absoluteDirection : absoluteDirections)
concepts.or(AbsoluteDirection.concepts(absoluteDirection));
if (siteType != null)
concepts.or(SiteType.concepts(siteType));
if (fromFn != null)
concepts.or(fromFn.concepts(game));
if (toFn != null)
concepts.or(toFn.concepts(game));
if (numDirection != null)
concepts.or(numDirection.concepts(game));
if (randomDirections != null)
concepts.set(Concept.Stochastic.id(), true);
return concepts;
}
@Override
public String toEnglish(final Game game)
{
String text = "";
int count=0;
if (absoluteDirections != null)
{
for (final AbsoluteDirection absoluteDirection : absoluteDirections)
{
text += LanguageUtils.GetDirection(absoluteDirection.name());
count++;
if(count == absoluteDirections.length-1)
text+=" or ";
else if(count < absoluteDirections.length)
text+=", ";
}
}
else if (relativeDirections != null)
{
for (final RelativeDirection relativeDirection : relativeDirections)
{
text += LanguageUtils.GetDirection(relativeDirection.name());
count++;
if(count == relativeDirections.length-1)
text+=" or ";
else if(count < relativeDirections.length)
text+=", ";
}
}
return text;
}
}
| 19,924 | 29.05279 | 125 | java |
Ludii | Ludii-master/Core/src/game/functions/directions/DirectionsFunction.java | package game.functions.directions;
import java.util.List;
import game.Game;
import game.equipment.component.Component;
import game.types.board.SiteType;
import game.util.directions.AbsoluteDirection;
import game.util.directions.Direction;
import game.util.directions.DirectionFacing;
import game.util.directions.RelativeDirection;
import other.BaseLudeme;
import other.context.Context;
import other.topology.TopologyElement;
/**
* Provides common functionality for direction functions.
*
* @author Eric.Piette and cambolbro
*/
// **
// ** Do not @Hide, or loses mapping in grammar!
// **
public abstract class DirectionsFunction extends BaseLudeme implements Direction
{
/**
* @return The relative directions.
*/
@SuppressWarnings("static-method")
public RelativeDirection[] getRelativeDirections()
{
return null;
}
/**
* @param graphType The type of the site.
* @param element The graph element.
* @param newComponent The component on the site (used in case of temporary
* modification of the state (forEachDirection)
* @param newFacing The new direction faced by the component on the site
* (used in case of temporary modification of the state
* (forEachDirection)
* @param newRotation The new rotation in case of a modification of the
* rotation by a tile piece (the path of tiles pieces).
* @param context The context.
*
* @return the corresponding absolute directions.
*/
public abstract List<AbsoluteDirection> convertToAbsolute(final SiteType graphType, final TopologyElement element,
final Component newComponent, final DirectionFacing newFacing, final Integer newRotation,
final Context context);
/**
* @param game The game.
* @return Accumulated flags for this state type.
*/
public abstract long gameFlags(final Game game);
/**
* @return true of the function is immutable, allowing extra optimisations.
*/
public abstract boolean isStatic();
/**
* Called once after a game object has been created. Allows for any game-
* specific preprocessing (e.g. precomputing and caching of static results).
*
* @param game
*/
public abstract void preprocess(final Game game);
@Override
public DirectionsFunction directionsFunctions()
{
return this;
}
}
| 2,343 | 28.3 | 115 | java |
Ludii | Ludii-master/Core/src/game/functions/directions/If.java | package game.functions.directions;
import java.util.BitSet;
import java.util.List;
import game.Game;
import game.equipment.component.Component;
import game.functions.booleans.BooleanConstant.FalseConstant;
import game.functions.booleans.BooleanFunction;
import game.types.board.SiteType;
import game.util.directions.AbsoluteDirection;
import game.util.directions.Direction;
import game.util.directions.DirectionFacing;
import other.context.Context;
import other.topology.TopologyElement;
/**
* Returns whether the specified directions are satisfied for the current game.
*
* @author Eric.Piette
*/
public class If extends DirectionsFunction
{
/** Direction function if the condition is verified. */
private final DirectionsFunction directionFunctionOk;
/** Direction function if the condition is not verified. */
private final DirectionsFunction directionFunctionNotOk;
/** The condition. */
private final BooleanFunction condition;
//-------------------------------------------------------------------------
/**
* @param condition The condition to verify.
* @param directionsOk The directions if the condition is verified.
* @param directionsNotOk The directions if the condition is not verified.
*
* @example (if (is Mover P1) Orthogonal Diagonal)
*/
public If
(
final BooleanFunction condition,
final Direction directionsOk,
final Direction directionsNotOk
)
{
directionFunctionOk = directionsOk.directionsFunctions();
directionFunctionNotOk = directionsNotOk.directionsFunctions();
this.condition = condition;
}
//-------------------------------------------------------------------------
@Override
public long gameFlags(final Game game)
{
long gameFlags = 0;
gameFlags |= condition.gameFlags(game);
gameFlags |= directionFunctionOk.gameFlags(game);
gameFlags |= directionFunctionNotOk.gameFlags(game);
return gameFlags;
}
@Override
public boolean isStatic()
{
return condition.isStatic() && directionFunctionOk.isStatic() && directionFunctionNotOk.isStatic();
}
@Override
public void preprocess(final Game game)
{
condition.preprocess(game);
directionFunctionOk.preprocess(game);
directionFunctionNotOk.preprocess(game);
}
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
concepts.or(directionFunctionOk.concepts(game));
concepts.or(directionFunctionNotOk.concepts(game));
concepts.or(condition.concepts(game));
return concepts;
}
@Override
public boolean missingRequirement(final Game game)
{
boolean missingRequirement = false;
if (condition instanceof FalseConstant)
{
game.addRequirementToReport("One of the condition of a (if ...) ludeme is \"false\" which is wrong.");
missingRequirement = true;
}
missingRequirement |= directionFunctionOk.missingRequirement(game);
missingRequirement |= directionFunctionNotOk.missingRequirement(game);
return missingRequirement;
}
@Override
public boolean willCrash(final Game game)
{
boolean willCrash = false;
willCrash |= directionFunctionOk.willCrash(game);
willCrash |= directionFunctionNotOk.willCrash(game);
return willCrash;
}
//-------------------------------------------------------------------------
@Override
public String toString()
{
return "";
}
//-------------------------------------------------------------------------
@Override
public List<AbsoluteDirection> convertToAbsolute
(
final SiteType graphType,
final TopologyElement element,
final Component newComponent,
final DirectionFacing newFacing,
final Integer newRotation,
final Context context
)
{
if (condition.eval(context))
return directionFunctionOk.convertToAbsolute(graphType, element, newComponent, newFacing, newRotation,
context);
return directionFunctionNotOk.convertToAbsolute(graphType, element, newComponent, newFacing, newRotation,
context);
}
//-------------------------------------------------------------------------
@Override
public String toEnglish(final Game game)
{
return "if " + condition.toEnglish(game) + " then " + directionFunctionOk.toEnglish(game) + " else " + directionFunctionNotOk.toEnglish(game);
}
//-------------------------------------------------------------------------
}
| 4,301 | 26.576923 | 144 | java |
Ludii | Ludii-master/Core/src/game/functions/directions/RandomDirectionType.java | package game.functions.directions;
/**
* Defines the types of random direction to choose.
*/
public enum RandomDirectionType
{
/** Random directions from a set of direction. */
Random,
}
| 192 | 16.545455 | 51 | java |
Ludii | Ludii-master/Core/src/game/functions/directions/Union.java | package game.functions.directions;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.List;
import game.Game;
import game.equipment.component.Component;
import game.types.board.RelationType;
import game.types.board.SiteType;
import game.util.directions.AbsoluteDirection;
import game.util.directions.Direction;
import game.util.directions.DirectionFacing;
import other.context.Context;
import other.topology.TopologyElement;
/**
* Returns the union of two set of directions.
*
* @author Eric.Piette
*/
public class Union extends DirectionsFunction
{
/** The first set of directions. */
final DirectionsFunction directionSet1;
/** The second set of directions. */
final DirectionsFunction directionSet2;
//-------------------------------------------------------------------------
/**
* @param directions The first set of directions.
* @param directionsToRemove The second set of directions.
*
* @example (union Orthogonal Diagonal)
*/
public Union
(
final Direction directions,
final Direction directionsToRemove
)
{
directionSet1 = directions.directionsFunctions();
directionSet2 = directionsToRemove.directionsFunctions();
}
//-------------------------------------------------------------------------
/**
* Trick ludeme into joining the grammar.
* @param context Current game context.
* @return Nuthin'! Absolutely nuthin'.
*/
@SuppressWarnings("static-method")
public Direction eval(final Context context)
{
return null;
}
//-------------------------------------------------------------------------
@Override
public long gameFlags(final Game game)
{
long gameFlags = 0;
gameFlags |= directionSet1.gameFlags(game);
gameFlags |= directionSet2.gameFlags(game);
return gameFlags;
}
@Override
public boolean isStatic()
{
return directionSet1.isStatic() && directionSet2.isStatic();
}
@Override
public void preprocess(final Game game)
{
directionSet1.preprocess(game);
directionSet2.preprocess(game);
}
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
concepts.or(directionSet1.concepts(game));
concepts.or(directionSet2.concepts(game));
return concepts;
}
@Override
public boolean missingRequirement(final Game game)
{
boolean missingRequirement = false;
missingRequirement |= directionSet1.missingRequirement(game);
missingRequirement |= directionSet2.missingRequirement(game);
return missingRequirement;
}
@Override
public boolean willCrash(final Game game)
{
boolean willCrash = false;
willCrash |= directionSet1.willCrash(game);
willCrash |= directionSet2.willCrash(game);
return willCrash;
}
//-------------------------------------------------------------------------
@Override
public String toString()
{
return "";
}
//-------------------------------------------------------------------------
@Override
public List<AbsoluteDirection> convertToAbsolute(final SiteType graphType, final TopologyElement element,
final Component newComponent, final DirectionFacing newFacing, final Integer newRotation,
final Context context)
{
final List<AbsoluteDirection> directionsReturned = new ArrayList<AbsoluteDirection>();
final List<AbsoluteDirection> firstDirecitons = directionSet1.convertToAbsolute(graphType, element,
newComponent, newFacing, newRotation,
context);
final List<AbsoluteDirection> firstDirectionAfterConv = new ArrayList<AbsoluteDirection>();
final List<AbsoluteDirection> secondDirections = directionSet2.convertToAbsolute(graphType, element,
newComponent, newFacing, newRotation,
context);
final List<AbsoluteDirection> secondDirectionsAfterConv = new ArrayList<AbsoluteDirection>();
// Convert in AbsoluteDirection with equivalent in FacingDirection
for (final AbsoluteDirection dir : firstDirecitons)
{
final RelationType relation = AbsoluteDirection.converToRelationType(dir);
if(relation != null)
{
final List<DirectionFacing> directionsFacing = element.supportedDirections(relation);
for(final DirectionFacing dirFacing : directionsFacing)
if(!firstDirectionAfterConv.contains(dirFacing.toAbsolute()))
firstDirectionAfterConv.add(dirFacing.toAbsolute());
}
else
firstDirectionAfterConv.add(dir);
}
for (final AbsoluteDirection dir : secondDirections)
{
final RelationType relation = AbsoluteDirection.converToRelationType(dir);
if(relation != null)
{
final List<DirectionFacing> directionsFacing = element.supportedDirections(relation);
for(final DirectionFacing dirFacing : directionsFacing)
if(!secondDirectionsAfterConv.contains(dirFacing.toAbsolute()))
secondDirectionsAfterConv.add(dirFacing.toAbsolute());
}
else
secondDirectionsAfterConv.add(dir);
}
directionsReturned.addAll(firstDirectionAfterConv);
for (final AbsoluteDirection dir : secondDirectionsAfterConv)
if (!directionsReturned.contains(dir))
directionsReturned.add(dir);
return directionsReturned;
}
//-------------------------------------------------------------------------
@Override
public String toEnglish(final Game game)
{
return "the union of " + directionSet1.toEnglish(game) + " and " + directionSet2.toEnglish(game);
}
//-------------------------------------------------------------------------
}
| 5,378 | 27.764706 | 106 | java |
Ludii | Ludii-master/Core/src/game/functions/directions/package-info.java | /**
* @chapter Direction functions are ludemes that return an array of integers representing known direction types,
* according to some specified criteria. All types listed in this chapter may be used for
* \\texttt{<directionsFunction>} parameters in other ludemes.
*
* @section The base {\tt directions} function converts input directions to player-centric equivalents.
*/
package game.functions.directions;
| 436 | 47.555556 | 113 | java |
Ludii | Ludii-master/Core/src/game/functions/floats/BaseFloatFunction.java | package game.functions.floats;
import other.BaseLudeme;
/**
* Common functionality for FloatFunction - override where necessary.
*
* @author cambolbro
*/
public abstract class BaseFloatFunction extends BaseLudeme implements FloatFunction
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
}
| 377 | 22.625 | 83 | java |
Ludii | Ludii-master/Core/src/game/functions/floats/FloatConstant.java | package game.functions.floats;
import annotations.Hide;
import game.Game;
import other.context.Context;
/**
* Sets a constant int value.
*
* @author cambolbro
*/
@Hide
public final class FloatConstant extends BaseFloatFunction
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/** Constant value. */
private final float a;
//-------------------------------------------------------------------------
/**
* Constant int value.
*
* @param a The int value.
*/
public FloatConstant
(
final float a
)
{
this.a = a;
}
//-------------------------------------------------------------------------
@Override
public float 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
}
}
| 1,149 | 14.972222 | 76 | java |
Ludii | Ludii-master/Core/src/game/functions/floats/FloatFunction.java | package game.functions.floats;
import java.util.BitSet;
import game.Game;
import game.types.state.GameType;
import other.context.Context;
/**
* Returns a float.
*
* @author cambolbro
*/
// **
// ** Do not @Hide, or loses mapping in grammar!
// **
public interface FloatFunction extends GameType
{
/**
* @param context
* @return The result of applying this function to this trial.
*/
float eval(final Context context);
/**
* @param game The game.
* @return Accumulated flags corresponding to the game concepts.
*/
BitSet concepts(final Game game);
/**
* @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 game
* @return This Function in English.
*/
String toEnglish(Game game);
}
| 945 | 17.54902 | 66 | java |
Ludii | Ludii-master/Core/src/game/functions/floats/ToFloat.java | package game.functions.floats;
import java.util.BitSet;
import annotations.Or;
import game.Game;
import game.functions.booleans.BooleanFunction;
import game.functions.ints.IntFunction;
import other.context.Context;
/**
* Converts a BooleanFunction or an IntFunction to a float.
*
* @author Eric.Piette
*/
public final class ToFloat extends BaseFloatFunction
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/** The boolean function. */
private final BooleanFunction boolFn;
/** The int function. */
private final IntFunction intFn;
//-------------------------------------------------------------------------
/**
* @param boolFn The boolean function.
* @param intFn The int function.
*
* @example (toFloat (is Full))
* @example (toFloat (count Moves))
*/
public ToFloat
(
@Or final BooleanFunction boolFn,
@Or final IntFunction intFn
)
{
int numNonNull = 0;
if (boolFn != null)
numNonNull++;
if (intFn != null)
numNonNull++;
if (numNonNull != 1)
throw new IllegalArgumentException(
"ToFloat(): One boolFn or intFn parameter must be non-null.");
this.boolFn = boolFn;
this.intFn = intFn;
}
//-------------------------------------------------------------------------
@Override
public float eval(final Context context)
{
if (boolFn != null)
{
final boolean result = boolFn.eval(context);
if (result)
return 1;
return 0;
}
return intFn.eval(context);
}
//-------------------------------------------------------------------------
@Override
public boolean isStatic()
{
if (boolFn != null)
return boolFn.isStatic();
if (intFn != null)
return intFn.isStatic();
return false;
}
@Override
public long gameFlags(final Game game)
{
long gameFlags = 0l;
if (boolFn != null)
gameFlags |= boolFn.gameFlags(game);
if (intFn != null)
gameFlags |= intFn.gameFlags(game);
return gameFlags;
}
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
if (boolFn != null)
concepts.or(boolFn.concepts(game));
if (intFn != null)
concepts.or(intFn.concepts(game));
return concepts;
}
@Override
public BitSet writesEvalContextRecursive()
{
final BitSet writeEvalContext = new BitSet();
if (boolFn != null)
writeEvalContext.or(boolFn.writesEvalContextRecursive());
if (intFn != null)
writeEvalContext.or(intFn.writesEvalContextRecursive());
return writeEvalContext;
}
@Override
public BitSet readsEvalContextRecursive()
{
final BitSet readEvalContext = new BitSet();
if (boolFn != null)
readEvalContext.or(boolFn.readsEvalContextRecursive());
if (intFn != null)
readEvalContext.or(intFn.readsEvalContextRecursive());
return readEvalContext;
}
@Override
public void preprocess(final Game game)
{
if (boolFn != null)
boolFn.preprocess(game);
if (intFn != null)
intFn.preprocess(game);
}
@Override
public boolean missingRequirement(final Game game)
{
boolean missingRequirement = false;
if (boolFn != null)
missingRequirement |= boolFn.missingRequirement(game);
if (intFn != null)
missingRequirement |= intFn.missingRequirement(game);
return missingRequirement;
}
@Override
public boolean willCrash(final Game game)
{
boolean willCrash = false;
if (boolFn != null)
willCrash |= boolFn.willCrash(game);
if (intFn != null)
willCrash |= intFn.willCrash(game);
return willCrash;
}
}
| 3,527 | 20.512195 | 76 | java |
Ludii | Ludii-master/Core/src/game/functions/floats/package-info.java | /**
* @chapter Float functions are ludemes that return a single floating point value produced by a specified function.
* They specify the {\it amount} of certain aspects of the game state, in a continuous rather than discrete space.
* Float parameters are always shown with their decimal point, e.g. 12.0, to clearly distinguish them from integer values.
*/
package game.functions.floats;
| 396 | 55.714286 | 124 | java |
Ludii | Ludii-master/Core/src/game/functions/floats/math/Abs.java | package game.functions.floats.math;
import java.util.BitSet;
import game.Game;
import game.functions.floats.BaseFloatFunction;
import game.functions.floats.FloatFunction;
import other.concept.Concept;
import other.context.Context;
/**
* Return the absolute value of a float.
*
* @author Eric Piette
*/
public final class Abs extends BaseFloatFunction
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/** Which value. */
protected final FloatFunction value;
//-------------------------------------------------------------------------
/**
* Return the absolute value of a value.
*
* @param value The value.
* @example (abs (- 8.2 5.1))
*/
public Abs
(
final FloatFunction value
)
{
this.value = value;
}
//-------------------------------------------------------------------------
@Override
public float eval(final Context context)
{
return Math.abs(value.eval(context));
}
@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.Float.id(), true);
concepts.set(Concept.Absolute.id(), true);
return concepts;
}
@Override
public boolean isStatic()
{
return false;
}
@Override
public void preprocess(final Game game)
{
value.preprocess(game);
}
@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 "The absolute value of " + value.toEnglish(game);
}
}
| 1,938 | 18.585859 | 76 | java |
Ludii | Ludii-master/Core/src/game/functions/floats/math/Add.java | package game.functions.floats.math;
import java.util.BitSet;
import annotations.Alias;
import game.Game;
import game.functions.floats.BaseFloatFunction;
import game.functions.floats.FloatFunction;
import other.concept.Concept;
import other.context.Context;
/**
* Adds many values.
*
* @author Eric.Piette
*/
@Alias(alias = "+")
public final class Add extends BaseFloatFunction
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/** The first value. */
private final FloatFunction a;
/** The second value. */
private final FloatFunction b;
/** The list of values. */
protected final FloatFunction[] list;
//-------------------------------------------------------------------------
/**
* To add two values.
*
* @param a The first value.
* @param b The second value.
* @example (+ 5.5 2.32)
*/
public Add
(
final FloatFunction a,
final FloatFunction b
)
{
this.a = a;
this.b = b;
list = null;
}
/**
* To add all the values of a list.
*
* @param list The list of the values.
* @example (+ {10.1 2.8 5.1})
*/
public Add(final FloatFunction[] list)
{
a = null;
b = null;
this.list = list;
}
//-------------------------------------------------------------------------
@Override
public float eval(final Context context)
{
if (list == null)
{
return a.eval(context) + b.eval(context);
}
float sum = 0f;
for (final FloatFunction elem : list)
sum += elem.eval(context);
return sum;
}
@Override
public long gameFlags(final Game game)
{
long flag = 0l;
if (a != null)
flag |= a.gameFlags(game);
if (b != null)
flag |= b.gameFlags(game);
if (list != null)
for (final FloatFunction elem : list)
flag |= elem.gameFlags(game);
return flag;
}
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
if (a != null)
concepts.or(a.concepts(game));
if (b != null)
concepts.or(b.concepts(game));
if (list != null)
for (final FloatFunction elem : list)
concepts.or(elem.concepts(game));
concepts.set(Concept.Float.id(), true);
concepts.set(Concept.Addition.id(), true);
return concepts;
}
@Override
public boolean missingRequirement(final Game game)
{
boolean missingRequirement = false;
if (a != null)
missingRequirement |= a.missingRequirement(game);
if (b != null)
missingRequirement |= b.missingRequirement(game);
if (list != null)
for (final FloatFunction elem : list)
missingRequirement |= elem.missingRequirement(game);
return missingRequirement;
}
@Override
public boolean willCrash(final Game game)
{
boolean willCrash = false;
if (a != null)
willCrash |= a.willCrash(game);
if (b != null)
willCrash |= b.willCrash(game);
if (willCrash)
for (final FloatFunction elem : list)
willCrash |= elem.willCrash(game);
return willCrash;
}
@Override
public boolean isStatic()
{
return false;
}
@Override
public void preprocess(final Game game)
{
if (a != null)
a.preprocess(game);
if (b != null)
b.preprocess(game);
if (list != null)
for (final FloatFunction elem : list)
elem.preprocess(game);
}
@Override
public String toEnglish(final Game game)
{
return a.toEnglish(game) + " + " + b.toEnglish(game);
}
}
| 3,356 | 18.747059 | 76 | java |
Ludii | Ludii-master/Core/src/game/functions/floats/math/Cos.java | package game.functions.floats.math;
import java.util.BitSet;
import game.Game;
import game.functions.floats.BaseFloatFunction;
import game.functions.floats.FloatFunction;
import other.concept.Concept;
import other.context.Context;
/**
* Computes the cosine of a value.
*
* @author Eric.Piette
*/
public final class Cos extends BaseFloatFunction
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/** The value. */
private final FloatFunction a;
//-------------------------------------------------------------------------
/**
* @param a The value.
* @example (cos 5.5)
*/
public Cos(final FloatFunction a)
{
this.a = a;
}
//-------------------------------------------------------------------------
@Override
public float eval(Context context)
{
return (float) Math.cos(a.eval(context));
}
@Override
public long gameFlags(Game game)
{
long flag = 0l;
if (a != null)
flag |= a.gameFlags(game);
return flag;
}
@Override
public BitSet concepts(Game game)
{
final BitSet concepts = new BitSet();
if (a != null)
concepts.or(a.concepts(game));
concepts.set(Concept.Float.id(), true);
concepts.set(Concept.Cosine.id(), true);
return concepts;
}
@Override
public boolean isStatic()
{
return false;
}
@Override
public void preprocess(Game game)
{
if (a != null)
a.preprocess(game);
}
@Override
public boolean missingRequirement(final Game game)
{
boolean missingRequirement = false;
missingRequirement |= a.missingRequirement(game);
return missingRequirement;
}
@Override
public boolean willCrash(final Game game)
{
boolean willCrash = false;
willCrash |= a.willCrash(game);
return willCrash;
}
}
| 1,776 | 17.132653 | 76 | java |
Ludii | Ludii-master/Core/src/game/functions/floats/math/Div.java | package game.functions.floats.math;
import java.util.BitSet;
import annotations.Alias;
import game.Game;
import game.functions.floats.BaseFloatFunction;
import game.functions.floats.FloatFunction;
import other.concept.Concept;
import other.context.Context;
/**
* To divide a value by another.
*
* @author Eric.Piette
*/
@Alias(alias = "/")
public final class Div extends BaseFloatFunction
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/** The first value. */
private final FloatFunction a;
/** The second value. */
private final FloatFunction b;
//-------------------------------------------------------------------------
/**
* To divide a value by another.
*
* @param a The first value.
* @param b The second value.
* @example (/ 5.5 2.32)
*/
public Div
(
final FloatFunction a,
final FloatFunction b
)
{
this.a = a;
this.b = b;
}
//-------------------------------------------------------------------------
@Override
public float eval(Context context)
{
final float evalB = b.eval(context);
if (evalB == 0)
throw new IllegalArgumentException("Division by zero.");
return a.eval(context) / evalB;
}
@Override
public long gameFlags(Game game)
{
long flag = 0l;
if (a != null)
flag |= a.gameFlags(game);
if (b != null)
flag |= b.gameFlags(game);
return flag;
}
@Override
public BitSet concepts(Game game)
{
final BitSet concepts = new BitSet();
if (a != null)
concepts.or(a.concepts(game));
if (b != null)
concepts.or(b.concepts(game));
concepts.set(Concept.Float.id(), true);
concepts.set(Concept.Division.id(), true);
return concepts;
}
@Override
public boolean isStatic()
{
return false;
}
@Override
public void preprocess(Game game)
{
if (a != null)
a.preprocess(game);
if (b != null)
b.preprocess(game);
}
@Override
public boolean missingRequirement(final Game game)
{
boolean missingRequirement = false;
if (a != null)
missingRequirement |= a.missingRequirement(game);
if (b != null)
missingRequirement |= b.missingRequirement(game);
return missingRequirement;
}
@Override
public boolean willCrash(final Game game)
{
boolean willCrash = false;
if (a != null)
willCrash |= a.willCrash(game);
if (b != null)
willCrash |= b.willCrash(game);
return willCrash;
}
}
| 2,417 | 18.03937 | 76 | java |
Ludii | Ludii-master/Core/src/game/functions/floats/math/Exp.java | package game.functions.floats.math;
import java.util.BitSet;
import game.Game;
import game.functions.floats.BaseFloatFunction;
import game.functions.floats.FloatFunction;
import other.concept.Concept;
import other.context.Context;
/**
* Computes the exponential of a value.
*
* @author Eric.Piette
*/
public final class Exp extends BaseFloatFunction
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/** The value. */
private final FloatFunction a;
//-------------------------------------------------------------------------
/**
* @param a The value.
* @example (exp 5.5)
*/
public Exp(final FloatFunction a)
{
this.a = a;
}
//-------------------------------------------------------------------------
@Override
public float eval(Context context)
{
return (float) Math.exp(a.eval(context));
}
@Override
public long gameFlags(Game game)
{
long flag = 0l;
if (a != null)
flag |= a.gameFlags(game);
return flag;
}
@Override
public BitSet concepts(Game game)
{
final BitSet concepts = new BitSet();
if (a != null)
concepts.or(a.concepts(game));
concepts.set(Concept.Float.id(), true);
concepts.set(Concept.Exponential.id(), true);
return concepts;
}
@Override
public boolean isStatic()
{
return false;
}
@Override
public void preprocess(Game game)
{
if (a != null)
a.preprocess(game);
}
@Override
public boolean missingRequirement(final Game game)
{
boolean missingRequirement = false;
missingRequirement |= a.missingRequirement(game);
return missingRequirement;
}
@Override
public boolean willCrash(final Game game)
{
boolean willCrash = false;
willCrash |= a.willCrash(game);
return willCrash;
}
}
| 1,786 | 17.234694 | 76 | java |
Ludii | Ludii-master/Core/src/game/functions/floats/math/Log.java | package game.functions.floats.math;
import java.util.BitSet;
import game.Game;
import game.functions.floats.BaseFloatFunction;
import game.functions.floats.FloatFunction;
import other.concept.Concept;
import other.context.Context;
/**
* Computes the logarithm of a value.
*
* @author Eric.Piette
*/
public final class Log extends BaseFloatFunction
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/** The value. */
private final FloatFunction a;
//-------------------------------------------------------------------------
/**
* @param a The value.
* @example (log 5.5)
*/
public Log(final FloatFunction a)
{
this.a = a;
}
//-------------------------------------------------------------------------
@Override
public float eval(Context context)
{
final float value = a.eval(context);
if (value == 0)
throw new IllegalArgumentException("Logarithm of zero is undefined.");
return (float) Math.log(value);
}
@Override
public long gameFlags(Game game)
{
long flag = 0l;
if (a != null)
flag |= a.gameFlags(game);
return flag;
}
@Override
public BitSet concepts(Game game)
{
final BitSet concepts = new BitSet();
if (a != null)
concepts.or(a.concepts(game));
concepts.set(Concept.Float.id(), true);
concepts.set(Concept.Logarithm.id(), true);
return concepts;
}
@Override
public boolean isStatic()
{
return false;
}
@Override
public void preprocess(Game game)
{
if (a != null)
a.preprocess(game);
}
@Override
public boolean missingRequirement(final Game game)
{
boolean missingRequirement = false;
missingRequirement |= a.missingRequirement(game);
return missingRequirement;
}
@Override
public boolean willCrash(final Game game)
{
boolean willCrash = false;
willCrash |= a.willCrash(game);
return willCrash;
}
}
| 1,904 | 17.676471 | 76 | java |
Ludii | Ludii-master/Core/src/game/functions/floats/math/Log10.java | package game.functions.floats.math;
import java.util.BitSet;
import game.Game;
import game.functions.floats.BaseFloatFunction;
import game.functions.floats.FloatFunction;
import other.concept.Concept;
import other.context.Context;
/**
* Computes the logarithm 10 of a value.
*
* @author Eric.Piette
*/
public final class Log10 extends BaseFloatFunction
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/** The value. */
private final FloatFunction a;
//-------------------------------------------------------------------------
/**
* @param a The value.
* @example (log10 5.5)
*/
public Log10(final FloatFunction a)
{
this.a = a;
}
//-------------------------------------------------------------------------
@Override
public float eval(Context context)
{
final float value = a.eval(context);
if (value == 0)
throw new IllegalArgumentException("Logarithm 10 of zero is undefined.");
return (float) Math.log10(value);
}
@Override
public long gameFlags(Game game)
{
long flag = 0l;
if (a != null)
flag |= a.gameFlags(game);
return flag;
}
@Override
public BitSet concepts(Game game)
{
final BitSet concepts = new BitSet();
if (a != null)
concepts.or(a.concepts(game));
concepts.set(Concept.Float.id(), true);
concepts.set(Concept.Logarithm.id(), true);
return concepts;
}
@Override
public boolean isStatic()
{
return false;
}
@Override
public void preprocess(Game game)
{
if (a != null)
a.preprocess(game);
}
@Override
public boolean missingRequirement(final Game game)
{
boolean missingRequirement = false;
missingRequirement |= a.missingRequirement(game);
return missingRequirement;
}
@Override
public boolean willCrash(final Game game)
{
boolean willCrash = false;
willCrash |= a.willCrash(game);
return willCrash;
}
}
| 1,918 | 17.813725 | 76 | java |
Ludii | Ludii-master/Core/src/game/functions/floats/math/Max.java | package game.functions.floats.math;
import java.util.BitSet;
import game.Game;
import game.functions.floats.BaseFloatFunction;
import game.functions.floats.FloatFunction;
import other.concept.Concept;
import other.context.Context;
/**
* Returns the maximum of specified values.
*
* @author Eric.Piette
*/
public final class Max extends BaseFloatFunction
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/** The first value. */
private final FloatFunction a;
/** The second value. */
private final FloatFunction b;
/** The list of values. */
protected final FloatFunction[] list;
//-------------------------------------------------------------------------
/**
* To get the maximum value between two.
*
* @param a The first value.
* @param b The second value.
* @example (max 5.5 2.32)
*/
public Max
(
final FloatFunction a,
final FloatFunction b
)
{
this.a = a;
this.b = b;
this.list = null;
}
/**
* To get the maximum value in a list.
*
* @param list The list of the values.
* @example (max {10.1 2.8 5.1})
*/
public Max(final FloatFunction[] list)
{
this.a = null;
this.b = null;
this.list = list;
}
//-------------------------------------------------------------------------
@Override
public float eval(Context context)
{
if (list == null)
{
return Math.max(a.eval(context),b.eval(context));
}
float max = list[0].eval(context);
for (int i = 1 ; i < list.length; i++)
max = Math.max(max, list[i].eval(context));
return max;
}
@Override
public long gameFlags(Game game)
{
long flag = 0l;
if (a != null)
flag |= a.gameFlags(game);
if (b != null)
flag |= b.gameFlags(game);
if (list != null)
for (final FloatFunction elem : list)
flag |= elem.gameFlags(game);
return flag;
}
@Override
public BitSet concepts(Game game)
{
final BitSet concepts = new BitSet();
if (a != null)
concepts.or(a.concepts(game));
if (b != null)
concepts.or(b.concepts(game));
if (list != null)
for (final FloatFunction elem : list)
concepts.or(elem.concepts(game));
concepts.set(Concept.Float.id(), true);
concepts.set(Concept.Maximum.id(), true);
return concepts;
}
@Override
public boolean isStatic()
{
return false;
}
@Override
public void preprocess(Game game)
{
if (a != null)
a.preprocess(game);
if (b != null)
b.preprocess(game);
if (list != null)
for (final FloatFunction elem : list)
elem.preprocess(game);
}
@Override
public boolean missingRequirement(final Game game)
{
boolean missingRequirement = false;
if (a != null)
missingRequirement |= a.missingRequirement(game);
if (b != null)
missingRequirement |= b.missingRequirement(game);
b.preprocess(game);
if (list != null)
for (final FloatFunction elem : list)
missingRequirement |= elem.missingRequirement(game);
return missingRequirement;
}
@Override
public boolean willCrash(final Game game)
{
boolean willCrash = false;
if (a != null)
willCrash |= a.willCrash(game);
if (b != null)
willCrash |= b.willCrash(game);
b.preprocess(game);
if (list != null)
for (final FloatFunction elem : list)
willCrash |= elem.willCrash(game);
return willCrash;
}
}
| 3,323 | 19.268293 | 76 | java |
Ludii | Ludii-master/Core/src/game/functions/floats/math/Min.java | package game.functions.floats.math;
import java.util.BitSet;
import game.Game;
import game.functions.floats.BaseFloatFunction;
import game.functions.floats.FloatFunction;
import other.concept.Concept;
import other.context.Context;
/**
* Returns the minimum of specified values.
*
* @author Eric.Piette
*/
public final class Min extends BaseFloatFunction
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/** The first value. */
private final FloatFunction a;
/** The second value. */
private final FloatFunction b;
/** The list of values. */
protected final FloatFunction[] list;
//-------------------------------------------------------------------------
/**
* To get the minimum value between two.
*
* @param a The first value.
* @param b The second value.
* @example (min 5.5 2.32)
*/
public Min
(
final FloatFunction a,
final FloatFunction b
)
{
this.a = a;
this.b = b;
this.list = null;
}
/**
* To get the maximum value in a list.
*
* @param list The list of the values.
* @example (min {10.1 2.8 5.1})
*/
public Min(final FloatFunction[] list)
{
this.a = null;
this.b = null;
this.list = list;
}
//-------------------------------------------------------------------------
@Override
public float eval(Context context)
{
if (list == null)
{
return Math.min(a.eval(context),b.eval(context));
}
float max = list[0].eval(context);
for (int i = 1 ; i < list.length; i++)
max = Math.min(max, list[i].eval(context));
return max;
}
@Override
public long gameFlags(Game game)
{
long flag = 0l;
if (a != null)
flag |= a.gameFlags(game);
if (b != null)
flag |= b.gameFlags(game);
if (list != null)
for (final FloatFunction elem : list)
flag |= elem.gameFlags(game);
return flag;
}
@Override
public BitSet concepts(Game game)
{
final BitSet concepts = new BitSet();
if (a != null)
concepts.or(a.concepts(game));
if (b != null)
concepts.or(b.concepts(game));
if (list != null)
for (final FloatFunction elem : list)
concepts.or(elem.concepts(game));
concepts.set(Concept.Float.id(), true);
concepts.set(Concept.Minimum.id(), true);
return concepts;
}
@Override
public boolean isStatic()
{
return false;
}
@Override
public void preprocess(Game game)
{
if (a != null)
a.preprocess(game);
if (b != null)
b.preprocess(game);
if (list != null)
for (final FloatFunction elem : list)
elem.preprocess(game);
}
@Override
public boolean missingRequirement(final Game game)
{
boolean missingRequirement = false;
if (a != null)
missingRequirement |= a.missingRequirement(game);
if (b != null)
missingRequirement |= b.missingRequirement(game);
b.preprocess(game);
if (list != null)
for (final FloatFunction elem : list)
missingRequirement |= elem.missingRequirement(game);
return missingRequirement;
}
@Override
public boolean willCrash(final Game game)
{
boolean willCrash = false;
if (a != null)
willCrash |= a.willCrash(game);
if (b != null)
willCrash |= b.willCrash(game);
b.preprocess(game);
if (list != null)
for (final FloatFunction elem : list)
willCrash |= elem.willCrash(game);
return willCrash;
}
}
| 3,323 | 19.268293 | 76 | java |
Ludii | Ludii-master/Core/src/game/functions/floats/math/Mul.java | package game.functions.floats.math;
import java.util.BitSet;
import annotations.Alias;
import game.Game;
import game.functions.floats.BaseFloatFunction;
import game.functions.floats.FloatFunction;
import other.concept.Concept;
import other.context.Context;
/**
* Multiply many values.
*
* @author Eric.Piette
*/
@Alias(alias = "*")
public final class Mul extends BaseFloatFunction
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/** The first value. */
private final FloatFunction a;
/** The second value. */
private final FloatFunction b;
/** The list of values. */
protected final FloatFunction[] list;
//-------------------------------------------------------------------------
/**
* To multiply two values.
*
* @param a The first value.
* @param b The second value.
* @example (* 5.5 2.32)
*/
public Mul
(
final FloatFunction a,
final FloatFunction b
)
{
this.a = a;
this.b = b;
this.list = null;
}
/**
* To multiply all the values of a list.
*
* @param list The list of the values.
* @example (* {10.1 2.8 5.1})
*/
public Mul(final FloatFunction[] list)
{
this.a = null;
this.b = null;
this.list = list;
}
//-------------------------------------------------------------------------
@Override
public float eval(Context context)
{
if (list == null)
{
return a.eval(context) * b.eval(context);
}
float product = 1;
for (final FloatFunction elem : list)
product *= elem.eval(context);
return product;
}
@Override
public long gameFlags(Game game)
{
long flag = 0l;
if (a != null)
flag |= a.gameFlags(game);
if (b != null)
flag |= b.gameFlags(game);
if (list != null)
for (final FloatFunction elem : list)
flag |= elem.gameFlags(game);
return flag;
}
@Override
public BitSet concepts(Game game)
{
final BitSet concepts = new BitSet();
if (a != null)
concepts.or(a.concepts(game));
if (b != null)
concepts.or(b.concepts(game));
if (list != null)
for (final FloatFunction elem : list)
concepts.or(elem.concepts(game));
concepts.set(Concept.Float.id(), true);
concepts.set(Concept.Multiplication.id(), true);
return concepts;
}
@Override
public boolean isStatic()
{
return false;
}
@Override
public void preprocess(Game game)
{
if (a != null)
a.preprocess(game);
if (b != null)
b.preprocess(game);
if (list != null)
for (final FloatFunction elem : list)
elem.preprocess(game);
}
@Override
public boolean missingRequirement(final Game game)
{
boolean missingRequirement = false;
if (a != null)
missingRequirement |= a.missingRequirement(game);
if (b != null)
missingRequirement |= b.missingRequirement(game);
b.preprocess(game);
if (list != null)
for (final FloatFunction elem : list)
missingRequirement |= elem.missingRequirement(game);
return missingRequirement;
}
@Override
public boolean willCrash(final Game game)
{
boolean willCrash = false;
if (a != null)
willCrash |= a.willCrash(game);
if (b != null)
willCrash |= b.willCrash(game);
b.preprocess(game);
if (list != null)
for (final FloatFunction elem : list)
willCrash |= elem.willCrash(game);
return willCrash;
}
}
| 3,307 | 18.927711 | 76 | java |
Ludii | Ludii-master/Core/src/game/functions/floats/math/Pow.java | package game.functions.floats.math;
import java.util.BitSet;
import annotations.Alias;
import game.Game;
import game.functions.floats.BaseFloatFunction;
import game.functions.floats.FloatFunction;
import other.concept.Concept;
import other.context.Context;
/**
* Computes the first parameter to the power of the second parameter.
*
* @author Eric.Piette
*/
@Alias(alias = "^")
public final class Pow extends BaseFloatFunction
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/** The first value. */
private final FloatFunction a;
/** The second value. */
private final FloatFunction b;
//-------------------------------------------------------------------------
/**
* @param a The first value.
* @param b The second value.
* @example (^ 5.5 2.32)
*/
public Pow
(
final FloatFunction a,
final FloatFunction b
)
{
this.a = a;
this.b = b;
}
//-------------------------------------------------------------------------
@Override
public float eval(Context context)
{
return (float) Math.pow(a.eval(context), b.eval(context));
}
@Override
public long gameFlags(Game game)
{
long flag = 0l;
if (a != null)
flag |= a.gameFlags(game);
if (b != null)
flag |= b.gameFlags(game);
return flag;
}
@Override
public BitSet concepts(Game game)
{
final BitSet concepts = new BitSet();
if (a != null)
concepts.or(a.concepts(game));
if (b != null)
concepts.or(b.concepts(game));
concepts.set(Concept.Float.id(), true);
concepts.set(Concept.Exponentiation.id(), true);
return concepts;
}
@Override
public boolean isStatic()
{
return false;
}
@Override
public void preprocess(Game game)
{
if (a != null)
a.preprocess(game);
if (b != null)
b.preprocess(game);
}
@Override
public boolean missingRequirement(final Game game)
{
boolean missingRequirement = false;
if (a != null)
missingRequirement |= a.missingRequirement(game);
if (b != null)
missingRequirement |= b.missingRequirement(game);
return missingRequirement;
}
@Override
public boolean willCrash(final Game game)
{
boolean willCrash = false;
if (a != null)
willCrash |= a.willCrash(game);
if (b != null)
willCrash |= b.willCrash(game);
return willCrash;
}
//-------------------------------------------------------------------------
@Override
public String toEnglish(final Game game)
{
return a.toEnglish(game) + " to the power of " + b.toEnglish(game);
}
//-------------------------------------------------------------------------
}
| 2,622 | 18.871212 | 76 | java |
Ludii | Ludii-master/Core/src/game/functions/floats/math/Sin.java | package game.functions.floats.math;
import java.util.BitSet;
import game.Game;
import game.functions.floats.BaseFloatFunction;
import game.functions.floats.FloatFunction;
import other.concept.Concept;
import other.context.Context;
/**
* Computes the sine of a value.
*
* @author Eric.Piette
*/
public final class Sin extends BaseFloatFunction
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/** The value. */
private final FloatFunction a;
//-------------------------------------------------------------------------
/**
* @param a The value.
* @example (sin 5.5)
*/
public Sin(final FloatFunction a)
{
this.a = a;
}
//-------------------------------------------------------------------------
@Override
public float eval(Context context)
{
return (float) Math.sin(a.eval(context));
}
@Override
public long gameFlags(Game game)
{
long flag = 0l;
if (a != null)
flag |= a.gameFlags(game);
return flag;
}
@Override
public BitSet concepts(Game game)
{
final BitSet concepts = new BitSet();
if (a != null)
concepts.or(a.concepts(game));
concepts.set(Concept.Float.id(), true);
concepts.set(Concept.Sine.id(), true);
return concepts;
}
@Override
public boolean isStatic()
{
return false;
}
@Override
public void preprocess(Game game)
{
if (a != null)
a.preprocess(game);
}
@Override
public boolean missingRequirement(final Game game)
{
boolean missingRequirement = false;
missingRequirement |= a.missingRequirement(game);
return missingRequirement;
}
@Override
public boolean willCrash(final Game game)
{
boolean willCrash = false;
willCrash |= a.willCrash(game);
return willCrash;
}
}
| 1,772 | 17.091837 | 76 | java |
Ludii | Ludii-master/Core/src/game/functions/floats/math/Sqrt.java | package game.functions.floats.math;
import java.util.BitSet;
import game.Game;
import game.functions.floats.BaseFloatFunction;
import game.functions.floats.FloatFunction;
import other.concept.Concept;
import other.context.Context;
/**
* Computes the square root of a value.
*
* @author Eric.Piette
*/
public final class Sqrt extends BaseFloatFunction
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/** The value. */
private final FloatFunction a;
//-------------------------------------------------------------------------
/**
* @param a The first value.
* @example (sqrt 5.5)
*/
public Sqrt(final FloatFunction a)
{
this.a = a;
}
//-------------------------------------------------------------------------
@Override
public float eval(Context context)
{
final float value = a.eval(context);
if (value < 0)
throw new IllegalArgumentException("Sqrt of a negative value is undefined.");
return (float) Math.sqrt(value);
}
@Override
public long gameFlags(Game game)
{
long flag = 0l;
if (a != null)
flag |= a.gameFlags(game);
return flag;
}
@Override
public BitSet concepts(Game game)
{
final BitSet concepts = new BitSet();
if (a != null)
concepts.or(a.concepts(game));
concepts.set(Concept.Float.id(), true);
concepts.set(Concept.Roots.id(), true);
return concepts;
}
@Override
public boolean isStatic()
{
return false;
}
@Override
public void preprocess(Game game)
{
if (a != null)
a.preprocess(game);
}
@Override
public boolean missingRequirement(final Game game)
{
boolean missingRequirement = false;
missingRequirement |= a.missingRequirement(game);
return missingRequirement;
}
@Override
public boolean willCrash(final Game game)
{
boolean willCrash = false;
willCrash |= a.willCrash(game);
return willCrash;
}
}
| 1,918 | 17.813725 | 80 | java |
Ludii | Ludii-master/Core/src/game/functions/floats/math/Sub.java | package game.functions.floats.math;
import java.util.BitSet;
import annotations.Alias;
import game.Game;
import game.functions.floats.BaseFloatFunction;
import game.functions.floats.FloatFunction;
import other.concept.Concept;
import other.context.Context;
/**
* Returns the subtraction A minus B.
*
* @author Eric Piette
*/
@Alias(alias = "-")
public final class Sub extends BaseFloatFunction
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/** Which value A. */
private final FloatFunction valueA;
/** Which value B. */
private final FloatFunction valueB;
//-------------------------------------------------------------------------
/**
* @param valueA The value A.
* @param valueB The value B.
* @example (- 5.6 1.1)
*/
public Sub
(
final FloatFunction valueA,
final FloatFunction valueB
)
{
this.valueA = valueA;
this.valueB = valueB;
}
//-------------------------------------------------------------------------
@Override
public float eval(Context context)
{
return valueA.eval(context) - valueB.eval(context);
}
@Override
public long gameFlags(Game game)
{
return valueA.gameFlags(game) | valueB.gameFlags(game);
}
@Override
public BitSet concepts(Game game)
{
final BitSet concepts = new BitSet();
concepts.or(valueA.concepts(game));
concepts.or(valueB.concepts(game));
concepts.set(Concept.Float.id(), true);
concepts.set(Concept.Subtraction.id(), true);
return concepts;
}
@Override
public boolean isStatic()
{
return false;
}
@Override
public void preprocess(Game game)
{
valueA.preprocess(game);
valueB.preprocess(game);
}
@Override
public boolean missingRequirement(final Game game)
{
boolean missingRequirement = false;
missingRequirement |= valueA.missingRequirement(game);
missingRequirement |= valueB.missingRequirement(game);
return missingRequirement;
}
@Override
public boolean willCrash(final Game game)
{
boolean willCrash = false;
willCrash |= valueA.willCrash(game);
willCrash |= valueB.willCrash(game);
return willCrash;
}
}
| 2,145 | 19.834951 | 76 | java |
Ludii | Ludii-master/Core/src/game/functions/floats/math/Tan.java | package game.functions.floats.math;
import java.util.BitSet;
import game.Game;
import game.functions.floats.BaseFloatFunction;
import game.functions.floats.FloatFunction;
import other.concept.Concept;
import other.context.Context;
/**
* Computes the tangent of a value.
*
* @author Eric.Piette
*/
public final class Tan extends BaseFloatFunction
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/** The value. */
private final FloatFunction a;
//-------------------------------------------------------------------------
/**
* @param a The value.
* @example (tan 5.5)
*/
public Tan(final FloatFunction a)
{
this.a = a;
}
//-------------------------------------------------------------------------
@Override
public float eval(Context context)
{
return (float) Math.tan(a.eval(context));
}
@Override
public long gameFlags(Game game)
{
long flag = 0l;
if (a != null)
flag |= a.gameFlags(game);
return flag;
}
@Override
public BitSet concepts(Game game)
{
final BitSet concepts = new BitSet();
if (a != null)
concepts.or(a.concepts(game));
concepts.set(Concept.Float.id(), true);
concepts.set(Concept.Tangent.id(), true);
return concepts;
}
@Override
public boolean isStatic()
{
return false;
}
@Override
public void preprocess(Game game)
{
if (a != null)
a.preprocess(game);
}
@Override
public boolean missingRequirement(final Game game)
{
boolean missingRequirement = false;
missingRequirement |= a.missingRequirement(game);
return missingRequirement;
}
@Override
public boolean willCrash(final Game game)
{
boolean willCrash = false;
willCrash |= a.willCrash(game);
return willCrash;
}
}
| 1,778 | 17.153061 | 76 | java |
Ludii | Ludii-master/Core/src/game/functions/floats/math/package-info.java | /**
* Math functions return a float value based on given inputs.
*/
package game.functions.floats.math;
| 106 | 20.4 | 61 | java |
Ludii | Ludii-master/Core/src/game/functions/graph/BaseGraphFunction.java | package game.functions.graph;
import java.util.ArrayList;
import java.util.List;
import annotations.Hide;
import game.types.board.BasisType;
import game.types.board.ShapeType;
import game.types.board.SiteType;
import game.util.graph.Graph;
import main.math.MathRoutines;
import other.BaseLudeme;
import other.context.Context;
/**
* Default implementations of graph functions - override where necessary.
*
* @author cambolbro
*/
@Hide
public abstract class BaseGraphFunction extends BaseLudeme implements GraphFunction
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
protected BasisType basis = null;
protected ShapeType shape = null;
protected int[] dim;
protected static final double unit = 1.0;
protected final double tolerance = 0.001;
//-------------------------------------------------------------------------
/**
* @return Known tiling, else null.
*/
public BasisType basis()
{
return basis;
}
/**
* @return Known shape, else null.
*/
public ShapeType shape()
{
return shape;
}
// public void setBasisAndShape(final BasisType bt, final ShapeType st)
// {
// basis = bt;
// shape = st;
// }
/**
* Reset the basis.
*/
public void resetBasis()
{
basis = BasisType.NoBasis;
}
/**
* Reset the shape.
*/
public void resetShape()
{
shape = ShapeType.NoShape;
}
/**
* @return The dimensions of the shape.
*/
@Override
public int[] dim()
{
return dim;
}
/**
* @return Maximum dimension of this shape.
*/
public int maxDim()
{
int max = 0;
for (int d = 0; d < dim.length; d++)
if (dim[d] > max)
max = dim[d];
return max;
}
//-------------------------------------------------------------------------
//public abstract Point2D xy(final int row, final int col);
//-------------------------------------------------------------------------
@Override
public Graph eval(final Context context, final SiteType siteType)
{
System.out.println("BaseGraphFunction.eval(): Should not be called directly; call subclass e.g. RectangleOnSquare.eval().");
return null;
}
//-------------------------------------------------------------------------
/**
* Only applies to graph with uniform edge lengths.
*
* @param vertexList The list of the vertices.
* @param u The unit.
* @param basisIn The basis.
* @param shapeIn The shape.
*
* @return Graph generated by this vertex list.
*/
public static Graph createGraphFromVertexList
(
final List<double[]> vertexList,
final double u,
final BasisType basisIn,
final ShapeType shapeIn
)
{
// Create edges
final List<int[]> edgeList = new ArrayList<int[]>();
for (int aid = 0; aid < vertexList.size(); aid++)
{
final double[] ptA = vertexList.get(aid);
final double ax = ptA[0];
final double ay = ptA[1];
// Check for edges 1 unit away
for (int bid = aid + 1; bid < vertexList.size(); bid++)
{
final double[] ptB = vertexList.get(bid);
final double dist = MathRoutines.distance(ptB[0], ptB[1], ax, ay);
if (Math.abs(dist - u) < 0.01)
edgeList.add(new int[] { aid, bid });
}
}
final Graph graph = game.util.graph.Graph.createFromLists(vertexList, edgeList);
graph.setBasisAndShape(basisIn, shapeIn);
// System.out.println("result has " + result.vertices().size() + " vertices, " +
// result.edges().size() + " edges and " +
// result.faces().size() + " faces.");
return graph;
}
/**
* Only applies to graph with uniform edge lengths.
*
* @param vertexList The list of the vertices.
* @param u The unit.
* @param basisIn The basis.
* @param shapeIn The shape.
*
* @return Graph generated by this vertex list (3D version).
*/
public static Graph createGraphFromVertexList3D
(
final List<double[]> vertexList,
final double u,
final BasisType basisIn,
final ShapeType shapeIn
)
{
// Create edges
final List<int[]> edgeList = new ArrayList<int[]>();
for (int aid = 0; aid < vertexList.size(); aid++)
{
final double[] ptA = vertexList.get(aid);
final double ax = ptA[0];
final double ay = ptA[1];
final double az = (ptA.length > 2) ? ptA[2] : 0;
// Check for edges 1 unit away
for (int bid = aid + 1; bid < vertexList.size(); bid++)
{
final double[] ptB = vertexList.get(bid);
final double bx = ptB[0];
final double by = ptB[1];
final double bz = (ptB.length > 2) ? ptB[2] : 0;
final double dist = MathRoutines.distance(ax, ay, az, bx, by, bz);
if (Math.abs(dist - u) < 0.01)
{
edgeList.add(new int[] { aid, bid });
}
}
}
final Graph graph = game.util.graph.Graph.createFromLists(vertexList, edgeList);
graph.setBasisAndShape(basisIn, shapeIn);
// System.out.println("result has " + result.vertices().size() + " vertices, " +
// result.edges().size() + " edges and " +
// result.faces().size() + " faces.");
return graph;
}
//-------------------------------------------------------------------------
@Override
public boolean isStatic()
{
return true;
}
//-------------------------------------------------------------------------
}
| 5,254 | 22.565022 | 128 | java |
Ludii | Ludii-master/Core/src/game/functions/graph/GraphFunction.java | package game.functions.graph;
import java.util.BitSet;
import game.Game;
import game.types.board.SiteType;
import game.types.state.GameType;
import game.util.graph.Graph;
import other.context.Context;
/**
* Returns a graph defined by lists of vertices, edges and faces.
*
* @author cambolbro
*/
// **
// ** Do not @Hide, or loses mapping in grammar!
// **
public interface GraphFunction extends GameType
{
/**
* @param context The context.
* @param siteType The graph element type.
* @return The result of applying this function to this trial.
*/
Graph eval(final Context context, final SiteType siteType);
/**
* @return Original board dimension settings of graph.
*/
int[] dim();
/**
* @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
* @return This Function in English.
*/
String toEnglish(Game game);
}
| 1,191 | 19.912281 | 73 | java |
Ludii | Ludii-master/Core/src/game/functions/graph/package-info.java | /**
* @chapter Graph functions are ludemes that define operations that can be applied to arbitrary graph objects.
* These are typically used to transform or modify simpler graphs into more complex ones, for use as game boards.
*/
package game.functions.graph;
| 264 | 43.166667 | 114 | java |
Ludii | Ludii-master/Core/src/game/functions/graph/generators/basis/Basis.java | package game.functions.graph.generators.basis;
import game.Game;
import game.functions.graph.BaseGraphFunction;
import game.types.board.SiteType;
import game.util.graph.Graph;
import other.context.Context;
//-----------------------------------------------------------------------------
/**
* Defines known basis types (i.e. tilings) for board graphs.
*
* @author cambolbro
*/
public abstract class Basis extends BaseGraphFunction
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
@Override
public Graph eval(final Context context, final SiteType siteType)
{
// Null placeholder to make the grammar recognise Basis
return null;
}
//-------------------------------------------------------------------------
// Ludeme overrides
@Override
public String toEnglish(final Game game)
{
return basis.name() + " " + shape.name();
}
//-------------------------------------------------------------------------
}
| 1,016 | 23.804878 | 79 | java |
Ludii | Ludii-master/Core/src/game/functions/graph/generators/basis/package-info.java | /**
* This section contains the supported basis types (i.e. tilings) used for boards.
*/
package game.functions.graph.generators.basis;
| 138 | 26.8 | 82 | java |
Ludii | Ludii-master/Core/src/game/functions/graph/generators/basis/brick/Brick.java | package game.functions.graph.generators.basis.brick;
import annotations.Name;
import annotations.Opt;
import game.Game;
import game.functions.dim.DimConstant;
import game.functions.dim.DimFunction;
import game.functions.dim.math.Add;
import game.functions.graph.GraphFunction;
import game.functions.graph.generators.basis.Basis;
import game.types.board.SiteType;
import game.util.graph.Graph;
import game.util.graph.Vertex;
import other.context.Context;
/**
* Defines a board on a brick tiling using 1x2 rectangular brick tiles.
*
* @author cambolbro
*/
public class Brick extends Basis
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/**
* @param shape Board shape [Square].
* @param dimA First board dimension (size or number of rows).
* @param dimB Second dimension (columns) [rows].
* @param trim Whether to clip exposed half bricks [False].
*
* @example (brick Diamond 4 trim:True)
*/
@SuppressWarnings("javadoc")
public static GraphFunction construct
(
@Opt final BrickShapeType shape,
final DimFunction dimA,
@Opt final DimFunction dimB,
@Opt @Name final Boolean trim
)
{
final BrickShapeType st = (shape != null)
? shape
: (dimB == null || dimB == dimA)
? BrickShapeType.Square
: BrickShapeType.Rectangle;
switch (st)
{
case Square:
case Rectangle:
return new SquareOrRectangleOnBrick(dimA, dimB, trim);
case Limping:
final DimFunction dimAplus1 = new Add(dimA, new DimConstant(1));
return new SquareOrRectangleOnBrick(dimA, dimAplus1, trim);
case Diamond:
return new DiamondOrPrismOnBrick(dimA, null, trim);
case Prism:
return new DiamondOrPrismOnBrick(dimA, (dimB == null ? dimA : dimB), trim);
case Spiral:
return new SpiralOnBrick(dimA);
// case Circle:
// return new CircleOnBrick(dimA);
default:
throw new IllegalArgumentException("Shape " + st + " not supported for Brick tiling.");
}
}
//-------------------------------------------------------------------------
private Brick()
{
// Ensure that compiler does not pick up default constructor
}
//-------------------------------------------------------------------------
@Override
public Graph eval(final Context context, final SiteType siteType)
{
// Null placeholder to make the grammar recognise Brick
return null;
}
//-------------------------------------------------------------------------
static void addBrick(final Graph graph, final int row, final int col)
{
final Vertex vertexA = graph.findOrAddVertex(col, row);
final Vertex vertexB = graph.findOrAddVertex(col, row+1);
final Vertex vertexC = graph.findOrAddVertex(col+1, row+1);
final Vertex vertexD = graph.findOrAddVertex(col+2, row+1);
final Vertex vertexE = graph.findOrAddVertex(col+2, row);
final Vertex vertexF = graph.findOrAddVertex(col+1, row);
graph.findOrAddEdge(vertexA.id(), vertexB.id());
graph.findOrAddEdge(vertexB.id(), vertexC.id());
graph.findOrAddEdge(vertexC.id(), vertexD.id());
graph.findOrAddEdge(vertexD.id(), vertexE.id());
graph.findOrAddEdge(vertexE.id(), vertexF.id());
graph.findOrAddEdge(vertexF.id(), vertexA.id());
graph.findOrAddFace(vertexA.id(), vertexB.id(), vertexC.id(), vertexD.id(), vertexE.id(), vertexF.id());
}
static void addHalfBrick(final Graph graph, final int row, final int col)
{
final Vertex vertexA = graph.findOrAddVertex(col, row);
final Vertex vertexB = graph.findOrAddVertex(col, row+1);
final Vertex vertexC = graph.findOrAddVertex(col+1, row+1);
final Vertex vertexD = graph.findOrAddVertex(col+1, row);
graph.findOrAddEdge(vertexA.id(), vertexB.id());
graph.findOrAddEdge(vertexB.id(), vertexC.id());
graph.findOrAddEdge(vertexC.id(), vertexD.id());
graph.findOrAddEdge(vertexD.id(), vertexA.id());
graph.findOrAddFace(vertexA.id(), vertexB.id(), vertexC.id(), vertexD.id());
}
static void addVerticalBrick(final Graph graph, final int row, final int col)
{
final Vertex vertexA = graph.findOrAddVertex(col, row);
final Vertex vertexB = graph.findOrAddVertex(col, row+1);
final Vertex vertexC = graph.findOrAddVertex(col, row+2);
final Vertex vertexD = graph.findOrAddVertex(col+1, row+2);
final Vertex vertexE = graph.findOrAddVertex(col+1, row+1);
final Vertex vertexF = graph.findOrAddVertex(col+1, row);
graph.findOrAddEdge(vertexA.id(), vertexB.id());
graph.findOrAddEdge(vertexB.id(), vertexC.id());
graph.findOrAddEdge(vertexC.id(), vertexD.id());
graph.findOrAddEdge(vertexD.id(), vertexE.id());
graph.findOrAddEdge(vertexE.id(), vertexF.id());
graph.findOrAddEdge(vertexF.id(), vertexA.id());
graph.findOrAddFace(vertexA.id(), vertexB.id(), vertexC.id(), vertexD.id(), vertexE.id(), vertexF.id());
}
//-------------------------------------------------------------------------
@Override
public long gameFlags(Game game)
{
return 0;
}
@Override
public void preprocess(Game game)
{
// Nothing to do.
}
//-------------------------------------------------------------------------
}
| 5,189 | 31.848101 | 106 | java |
Ludii | Ludii-master/Core/src/game/functions/graph/generators/basis/brick/BrickShapeType.java | package game.functions.graph.generators.basis.brick;
/**
* Defines known shapes for the square tiling.
*
* @author cambolbro
*/
public enum BrickShapeType
{
// /** No shape; custom graph. */
// NoShape,
/** Square board shape. */
Square,
/** Rectangular board shape. */
Rectangle,
/** Diamond board shape. */
Diamond,
/** Prism board shape. */
Prism,
// /** Triangular board shape. */
// Triangle,
//
// /** Hexagonal board shape. */
// Hexagon,
//
// /** Cross board shape. */
// Cross,
//
// /** Rhombus board shape. */
// Rhombus,
//
// /** Wheel board shape. */
// Wheel,
// /** Circular board shape. */
// Circle,
/** Spiral board shape. */
Spiral,
// /** Shape is derived from another graph. */
// Dual,
//
// /** Wedge shape of height N with 1 vertex at the top and 3 vertices on the bottom, for Alquerque boards. */
// Wedge,
//
// /** Multi-pointed star shape. */
// Star,
/** Alternating sides are staggered. */
Limping,
;
}
| 979 | 15.610169 | 110 | java |
Ludii | Ludii-master/Core/src/game/functions/graph/generators/basis/brick/DiamondOrPrismOnBrick.java | package game.functions.graph.generators.basis.brick;
import java.util.BitSet;
import annotations.Hide;
import game.Game;
import game.functions.dim.DimFunction;
import game.functions.graph.generators.basis.Basis;
import game.types.board.BasisType;
import game.types.board.ShapeType;
import game.types.board.SiteType;
import game.util.graph.Graph;
import other.concept.Concept;
import other.context.Context;
//-----------------------------------------------------------------------------
/**
* Defines a square or rectangular brick board.
*
* @author cambolbro
*
*/
@Hide
public class DiamondOrPrismOnBrick extends Basis
{
private static final long serialVersionUID = 1L;
private final boolean trim;
//-------------------------------------------------------------------------
/**
* Hidden constructor, is a helper for Square.
*
* @param dimA The dimension A.
* @param dimB The dimension B.
* @param trim True if this is trimmed.
*/
public DiamondOrPrismOnBrick
(
final DimFunction dimA,
final DimFunction dimB,
final Boolean trim
)
{
this.basis = BasisType.Brick;
this.shape = (dimB == null) ? ShapeType.Diamond : ShapeType.Prism;
if (dimB == null)
this.dim = new int[] { dimA.eval(), dimA.eval() };
else
this.dim = new int[] { dimA.eval(), dimB.eval() };
this.trim = (trim == null) ? false : trim.booleanValue();
}
//-------------------------------------------------------------------------
@Override
public Graph eval(final Context context, final SiteType siteType)
{
//final double tolerance = 0.0001;
final int side = dim[0];
final int mid = (shape == ShapeType.Diamond) ? 0 : dim[1];
final int rows = 2 * side + 2 * mid;
final int cols = 2 * side;
// Create the graph on-the-fly
final Graph graph = new Graph();
for (int r = 0; r < rows; r++)
for (int c = (r + 1) % 2; c < cols; c += 2)
{
if (r + c < side - 1)
continue;
if (c - r >= side)
continue;
if (r + c >= 3 * side - 1)
continue;
if (r - c > side)
continue;
if (trim && c == 0)
Brick.addHalfBrick(graph, r, c+1);
else if (trim && c >= cols - 1)
Brick.addHalfBrick(graph, r, c);
else
Brick.addBrick(graph, r, c);
}
graph.setBasisAndShape(basis, shape);
graph.reorder();
return graph;
}
//-------------------------------------------------------------------------
@Override
public long gameFlags(Game game)
{
return 0;
}
@Override
public void preprocess(Game game)
{
// Nothing to do.
}
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
concepts.or(super.concepts(game));
concepts.set(Concept.BrickTiling.id(), true);
if (shape.equals(ShapeType.Diamond))
concepts.set(Concept.DiamondShape.id(), true);
else
concepts.set(Concept.PrismShape.id(), true);
concepts.set(Concept.PolygonShape.id(), true);
return concepts;
}
//-------------------------------------------------------------------------
}
| 3,061 | 21.514706 | 79 | java |
Ludii | Ludii-master/Core/src/game/functions/graph/generators/basis/brick/SpiralOnBrick.java | package game.functions.graph.generators.basis.brick;
import java.util.BitSet;
import annotations.Hide;
import game.Game;
import game.functions.dim.DimFunction;
import game.functions.graph.generators.basis.Basis;
import game.types.board.BasisType;
import game.types.board.ShapeType;
import game.types.board.SiteType;
import game.util.graph.Graph;
import other.concept.Concept;
import other.context.Context;
//-----------------------------------------------------------------------------
/**
* Defines a square or rectangular brick board.
*
* @author cambolbro
*
*/
@Hide
public class SpiralOnBrick extends Basis
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/**
* Hidden constructor, is a helper for Square.
*
* @param dimA The dimension A.
*/
public SpiralOnBrick
(
final DimFunction dimA
)
{
this.basis = BasisType.Brick;
this.shape = ShapeType.Spiral;
this.dim = new int[] { dimA.eval() };
}
//-------------------------------------------------------------------------
@Override
public Graph eval(final Context context, final SiteType siteType)
{
//final double tolerance = 0.0001;
final int rings = dim[0];
// Create the graph on-the-fly
final Graph graph = new Graph();
for (int ring = 0; ring < rings; ring++)
{
if (ring == 0)
{
Brick.addHalfBrick(graph, rings-1, rings-1);
}
else
{
for (int n = 0; n < 2 * ring; n += 2)
{
Brick.addVerticalBrick(graph, rings-ring + n, rings-ring-1);
Brick.addBrick(graph, rings+ring-1, rings-ring+n);
Brick.addVerticalBrick(graph, rings-ring-1+n, rings+ring-1);
Brick.addBrick(graph, rings-ring-1, rings-ring-1+n);
}
}
}
graph.setBasisAndShape(basis, shape);
graph.reorder();
return graph;
}
//-------------------------------------------------------------------------
@Override
public long gameFlags(Game game)
{
return 0;
}
@Override
public void preprocess(Game game)
{
// Nothing to do.
}
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
concepts.or(super.concepts(game));
concepts.set(Concept.BrickTiling.id(), true);
concepts.set(Concept.SpiralShape.id(), true);
concepts.set(Concept.PolygonShape.id(), true);
return concepts;
}
//-------------------------------------------------------------------------
}
| 2,459 | 21.162162 | 79 | java |
Ludii | Ludii-master/Core/src/game/functions/graph/generators/basis/brick/SquareOrRectangleOnBrick.java | package game.functions.graph.generators.basis.brick;
import java.util.BitSet;
import annotations.Hide;
import game.Game;
import game.functions.dim.DimFunction;
import game.functions.graph.generators.basis.Basis;
import game.types.board.BasisType;
import game.types.board.ShapeType;
import game.types.board.SiteType;
import game.util.graph.Graph;
import other.concept.Concept;
import other.context.Context;
//-----------------------------------------------------------------------------
/**
* Defines a square or rectangular brick board.
*
* @author cambolbro
*
*/
@Hide
public class SquareOrRectangleOnBrick extends Basis
{
private static final long serialVersionUID = 1L;
private final boolean trim;
//-------------------------------------------------------------------------
/**
* Hidden constructor, is a helper for Square.
*
* @param dimA The dimension A.
* @param dimB The dimension B.
* @param trim True if this is trimmed.
*/
public SquareOrRectangleOnBrick
(
final DimFunction dimA,
final DimFunction dimB,
final Boolean trim
)
{
this.basis = BasisType.Brick;
this.shape = (dimB == null || dimB == dimA) ? ShapeType.Square : ShapeType.Rectangle;
if (dimB == null || dimA == dimB)
this.dim = new int[] { dimA.eval(), dimA.eval() };
else
this.dim = new int[] { dimA.eval(), dimB.eval() };
this.trim = (trim == null) ? false : trim.booleanValue();
}
//-------------------------------------------------------------------------
@Override
public Graph eval(final Context context, final SiteType siteType)
{
//final double tolerance = 0.0001;
final int rows = dim[0];
final int cols = dim[1] * 2 + 1;
// Create the graph on-the-fly
final Graph graph = new Graph();
for (int r = 0; r < rows; r++)
for (int c = r % 2; c < cols; c += 2)
{
if (trim && c == 0)
Brick.addHalfBrick(graph, r, c+1);
else if (trim && c >= cols - 1)
Brick.addHalfBrick(graph, r, c);
else
Brick.addBrick(graph, r, c);
}
graph.setBasisAndShape(basis, shape);
graph.reorder();
return graph;
}
//-------------------------------------------------------------------------
@Override
public long gameFlags(Game game)
{
return 0;
}
@Override
public void preprocess(Game game)
{
// Nothing to do.
}
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
concepts.or(super.concepts(game));
concepts.set(Concept.BrickTiling.id(), true);
if (shape.equals(ShapeType.Square))
concepts.set(Concept.SquareShape.id(), true);
else
concepts.set(Concept.RectangleShape.id(), true);
concepts.set(Concept.PolygonShape.id(), true);
return concepts;
}
//-------------------------------------------------------------------------
}
| 2,817 | 22.680672 | 88 | java |
Ludii | Ludii-master/Core/src/game/functions/graph/generators/basis/brick/package-info.java | /**
* This section contains the boards based on a square tiling.
*
*/
package game.functions.graph.generators.basis.brick;
| 127 | 20.333333 | 61 | java |
Ludii | Ludii-master/Core/src/game/functions/graph/generators/basis/celtic/Celtic.java | package game.functions.graph.generators.basis.celtic;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.util.BitSet;
import java.util.List;
import annotations.Opt;
import annotations.Or;
import game.Game;
import game.functions.dim.DimFunction;
import game.functions.graph.generators.basis.Basis;
import game.types.board.BasisType;
import game.types.board.ShapeType;
import game.types.board.SiteType;
import game.util.graph.Graph;
import game.util.graph.GraphElement;
import game.util.graph.MeasureGraph;
import game.util.graph.Poly;
import game.util.graph.Vertex;
import gnu.trove.list.array.TIntArrayList;
import main.math.MathRoutines;
import main.math.Polygon;
import main.math.Vector;
import other.concept.Concept;
import other.context.Context;
//-----------------------------------------------------------------------------
/**
* Defines a board based on Celtic knotwork.
*
* @author cambolbro
*
* @remarks Celtic knotwork typically has a small number of continuous paths
* crossing the entire area -- usually just one -- making these
* designs an interesting choice for path-based games.
*/
public class Celtic extends Basis
{
private static final long serialVersionUID = 1L;
private final Polygon polygon = new Polygon();
private final TIntArrayList sides = new TIntArrayList();
//-------------------------------------------------------------------------
/**
* For defining a celtic tiling with the number of rows and the number of
* columns.
*
* @param rows Number of rows.
* @param columns Number of columns.
*
* @example (celtic 3)
*/
public Celtic
(
final DimFunction rows,
@Opt final DimFunction columns
)
{
this.basis = BasisType.Celtic;
this.shape = (columns == null || rows == columns) ? ShapeType.Square : ShapeType.Rectangle;
if (columns == null)
this.dim = new int[] { rows.eval(), rows.eval() };
else
this.dim = new int[] { rows.eval(), columns.eval() };
}
/**
* For defining a celtic tiling with a polygon or the number of sides.
*
* @param poly Points defining the board shape.
* @param sides Length of consecutive sides of outline shape.
*
* @example (celtic (poly { {1 2} {1 6} {3 6} {3 4} {4 4} {4 2} }))
* @example (celtic { 4 3 -1 2 3 })
*/
public Celtic
(
@Or final Poly poly,
@Or final DimFunction[] sides
)
{
int numNonNull = 0;
if (poly != null)
numNonNull++;
if (sides != null)
numNonNull++;
if (numNonNull > 1)
throw new IllegalArgumentException("Exactly one array parameter must be non-null.");
this.basis = BasisType.Celtic;
this.shape = ShapeType.NoShape;
if (poly != null)
{
this.polygon.setFrom(poly.polygon());
}
else
{
for (int n = 0; n < sides.length; n++)
this.sides.add(sides[n].eval());
}
}
//-------------------------------------------------------------------------
@Override
public Graph eval(final Context context, final SiteType siteType)
{
//final double tolerance = 0.001;
final double uu = unit / Math.sqrt(2);
final double uu2 = 2 * uu;
final double[][] steps = { {uu2, 0}, {0, uu2}, {-uu2, 0}, {0, -uu2} };
final double[][] ref = { {uu, 0}, {0, uu}, {-uu, 0}, {0, -uu} };
int fromCol = 0;
int fromRow = 0;
int toCol = 0;
int toRow = 0;
if (polygon.isEmpty() && !sides.isEmpty())
polygon.fromSides(sides, steps);
if (polygon.isEmpty())
{
toCol = dim[1] - 1;
toRow = dim[0] - 1;
}
else
{
polygon.inflate(0.1);
final Rectangle2D bounds = polygon.bounds();
fromCol = (int)bounds.getMinX() - 1;
fromRow = (int)bounds.getMinY() - 1;
toCol = (int)bounds.getMaxX() + 1;
toRow = (int)bounds.getMaxY() + 1;
}
final Graph graph = new Graph();
for (int row = fromRow; row < toRow + 1; row++)
for (int col = fromCol; col < toCol + 1; col++)
{
// Determine reference octagon position
final Point2D ptRef = new Point2D.Double(col * uu2, row * uu2);
if (!polygon.isEmpty() && !polygon.contains(ptRef))
continue;
// Add satellite points (vertices of octagon)
for (int n = 0; n < ref.length; n++)
{
final double x = ptRef.getX() + ref[n][0];
final double y = ptRef.getY() + ref[n][1];
graph.findOrAddVertex(x, y);
}
}
graph.makeEdges();
graph.makeFaces(true);
// Get list of perimeter vertices
MeasureGraph.measurePerimeter(graph);
final List<GraphElement> list = graph.perimeters().get(0).elements();
// Determine which perimeter points to add curves to
final BitSet keypoints = new BitSet();
int flatRun = 0;
for (int n = 0; n < list.size(); n++)
{
final Vertex vl = (Vertex)list.get((n - 1 + list.size()) % list.size());
final Vertex vm = (Vertex)list.get(n);
final Vertex vn = (Vertex)list.get((n + 1) % list.size());
final double diff = MathRoutines.angleDifference(vl.pt2D(), vm.pt2D(), vn.pt2D());
if (diff > 0.25 * Math.PI)
{
// Convex corner
keypoints.set(n);
flatRun = 0;
}
else if (Math.abs(diff) < 0.1 * Math.PI)
{
// Flat step
flatRun++;
if (flatRun % 2 == 0)
keypoints.set(n);
}
}
// Add curves for relevant keypoints
for (int n = keypoints.nextSetBit(0); n >= 0; n = keypoints.nextSetBit(n + 1))
{
final Vertex vb = (Vertex)list.get((n - 1 + list.size()) % list.size());
final Vertex vc = (Vertex)list.get(n);
final Vertex vd = (Vertex)list.get((n + 1) % list.size());
final Vertex ve = (Vertex)list.get((n + 2) % list.size());
final double diffC = MathRoutines.angleDifference(vb.pt2D(), vc.pt2D(), vd.pt2D());
final double diffD = MathRoutines.angleDifference(vc.pt2D(), vd.pt2D(), ve.pt2D());
if (diffD < -0.25 * Math.PI)
{
// Double step: join C to E
// System.out.println("Joining V" + vc.id() + " to V" + ve.id() + " (double step)...");
final Vector tangentA = new Vector(vd.pt(), ve.pt());
final Vector tangentB = new Vector(vd.pt(), vc.pt());
tangentA.normalise();
tangentB.normalise();
tangentA.scale(1.25);
tangentB.scale(1.25);
graph.addEdge(vc.id(), ve.id(), tangentA, tangentB);
graph.findOrAddFace(vd.id(), vc.id(), ve.id());
}
else
{
// Single step: join C to D and add a corner
// System.out.println("Joining V" + vc.id() + " to V" + vd.id() + " (single step)...");
// Add corner
Vector tangentAX = new Vector(vb.pt2D(), vc.pt2D());
Vector tangentBX = new Vector(vb.pt2D(), vc.pt2D());
if (Math.abs(diffC) < 0.1 * Math.PI)
{
// Is flat step: override tangents
tangentAX = new Vector(vc.pt2D(), vd.pt2D());
tangentBX = new Vector(vc.pt2D(), vd.pt2D());
tangentAX.perpendicular();
tangentBX.perpendicular();
tangentAX.reverse();
tangentBX.reverse();
}
final Point2D midCD = new Point2D.Double((vc.pt().x() + vd.pt().x()) / 2, (vc.pt().y() + vd.pt().y()) / 2);
final Point2D ptV = new Point2D.Double(midCD.getX() + 0.5 * tangentAX.x(), midCD.getY() + 0.5 * tangentAX.y());
final Point2D ptX = new Point2D.Double(midCD.getX() + 0.9 * tangentAX.x(), midCD.getY() + 0.9 * tangentAX.y());
final Vertex vx = graph.addVertex(ptX);
tangentAX.normalise();
tangentBX.normalise();
tangentAX.scale(1.333);
tangentBX.scale(1.333);
final Vector tangentXA = new Vector(ptV, vc.pt2D());
final Vector tangentXB = new Vector(ptV, vd.pt2D());
tangentXA.normalise();
tangentXB.normalise();
graph.addEdge(vc.id(), vx.id(), tangentAX, tangentXA);
graph.addEdge(vx.id(), vd.id(), tangentXB, tangentBX);
graph.findOrAddFace(vc.id(), vx.id(), vd.id());
}
}
graph.setBasisAndShape(basis, shape);
graph.reorder();
return graph;
}
//-------------------------------------------------------------------------
@Override
public long gameFlags(Game game)
{
return 0;
}
@Override
public void preprocess(Game game)
{
// Nothing to do.
}
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
concepts.or(super.concepts(game));
concepts.set(Concept.CelticTiling.id(), true);
if (shape.equals(ShapeType.Square))
concepts.set(Concept.SquareShape.id(), true);
else
concepts.set(Concept.RectangleShape.id(), true);
concepts.set(Concept.PolygonShape.id(), true);
return concepts;
}
//-------------------------------------------------------------------------
}
| 8,539 | 26.025316 | 115 | java |
Ludii | Ludii-master/Core/src/game/functions/graph/generators/basis/celtic/package-info.java | /**
* This section contains boards based on a Celtic knotwork designs.
*/
package game.functions.graph.generators.basis.celtic;
| 130 | 25.2 | 67 | java |
Ludii | Ludii-master/Core/src/game/functions/graph/generators/basis/hex/CustomOnHex.java | package game.functions.graph.generators.basis.hex;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.List;
import annotations.Hide;
import game.Game;
import game.functions.dim.DimFunction;
import game.functions.graph.BaseGraphFunction;
import game.functions.graph.generators.basis.Basis;
import game.types.board.BasisType;
import game.types.board.ShapeType;
import game.types.board.SiteType;
import game.util.graph.Graph;
import gnu.trove.list.array.TIntArrayList;
import main.math.MathRoutines;
import main.math.Polygon;
import other.concept.Concept;
import other.context.Context;
//-----------------------------------------------------------------------------
/**
* Defines a custom board shape on the hexagonal tiling.
*
* @author cambolbro
*
*/
@Hide
public class CustomOnHex extends Basis
{
private static final long serialVersionUID = 1L;
private final Polygon polygon = new Polygon();
private final TIntArrayList sides = new TIntArrayList();
//-------------------------------------------------------------------------
/**
* Hidden constructor, is a helper for Hexagonal.
*
* @param polygon The polygon.
*/
public CustomOnHex
(
final Polygon polygon
)
{
this.basis = BasisType.Hexagonal;
this.shape = ShapeType.Custom;
this.polygon.setFrom(polygon);
}
/**
* Hidden constructor, is a helper for Square.
*
* @param sides The indices of the sides.
*/
public CustomOnHex
(
final DimFunction[] sides
)
{
this.basis = BasisType.Hexagonal;
this.shape = (sides.length == 2 && sides[0].eval() == sides[1].eval() - 1)
? ShapeType.Limping
: ShapeType.Custom;
for (int n = 0; n < sides.length; n++)
this.sides.add(sides[n].eval());
}
//-------------------------------------------------------------------------
@Override
public Graph eval(final Context context, final SiteType siteType)
{
if (polygon.isEmpty() && !sides.isEmpty())
//polygon.fromSides(sides, Hex.steps);
polygonFromSides();
polygon.inflate(0.1);
final Rectangle2D bounds = polygon.bounds();
// If limping boards (or any other shapes) have missing cells,
// then increase the following margins.
final int fromCol = (int)bounds.getMinX() - 3;
final int fromRow = (int)bounds.getMinY() - 3;
final int toCol = (int)bounds.getMaxX() + 3;
final int toRow = (int)bounds.getMaxY() + 3;
// Create vertices
final List<double[]> vertexList = new ArrayList<double[]>();
for (int r = fromRow; r <= toRow; r++)
for (int c = fromCol; c <= toCol; c++)
{
final Point2D ptRef = Hex.xy(r, c);
if (!polygon.contains(ptRef))
continue;
for (int n = 0; n < 6; n++)
{
final double x = ptRef.getX() + Hex.ref[n][0];
final double y = ptRef.getY() + Hex.ref[n][1];
// See if vertex already created
int vid;
for (vid = 0; vid < vertexList.size(); vid++)
{
final double[] ptV = vertexList.get(vid);
final double dist = MathRoutines.distance(ptV[0], ptV[1], x, y);
if (dist < 0.1)
break;
}
if (vid >= vertexList.size())
vertexList.add(new double[]{ x, y });
}
}
final Graph graph = BaseGraphFunction.createGraphFromVertexList(vertexList, unit, basis, shape);
graph.reorder();
// if (this.shape == ShapeType.Limping)
// {
// final int expected = 3 * sides.get(0) * sides.get(0);
// System.out.println("Limping hex board: " + graph.faces().size() + " found (" + expected + " expected).");
// }
return graph;
}
//-------------------------------------------------------------------------
/**
* Generate polygon from the description of sides.
*
* Can't really distinguish Cell from Vertex versions here (-ve turns make
* ambiguous cases) so treat both the same.
*/
void polygonFromSides()
{
final int[][] steps = { {1, 0}, {1, 1}, {0, 1}, {-1, 0}, {-1, -1}, {0, -1} };
int step = 1;
int row = 0;
int col = 0;
polygon.clear();
polygon.add(Hex.xy(row, col));
for (int n = 0; n < Math.max(5, sides.size()); n++)
{
int nextStep = sides.get(n % sides.size());
// Always reduce by 1
if (nextStep < 0)
nextStep += 1;
else
nextStep -= 1;
if (nextStep < 0)
step -= 1;
else
step += 1;
step = (step + 6) % 6; // keep in range
if (nextStep > 0)
{
row += nextStep * steps[step][0];
col += nextStep * steps[step][1];
//System.out.println("Hex.xy(row, col) is: " + Hex.xy(row, col));
polygon.add(Hex.xy(row, col));
}
}
}
//-------------------------------------------------------------------------
@Override
public long gameFlags(Game game)
{
return 0;
}
@Override
public void preprocess(Game game)
{
// Nothing to do.
}
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
concepts.or(super.concepts(game));
concepts.set(Concept.HexTiling.id(), true);
concepts.set(Concept.PolygonShape.id(), true);
return concepts;
}
//-------------------------------------------------------------------------
}
| 5,179 | 22.870968 | 110 | java |
Ludii | Ludii-master/Core/src/game/functions/graph/generators/basis/hex/DiamondOnHex.java | package game.functions.graph.generators.basis.hex;
import java.awt.geom.Point2D;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.List;
import annotations.Hide;
import annotations.Opt;
import game.Game;
import game.functions.dim.DimFunction;
import game.functions.graph.BaseGraphFunction;
import game.functions.graph.generators.basis.Basis;
import game.types.board.BasisType;
import game.types.board.ShapeType;
import game.types.board.SiteType;
import game.util.graph.Graph;
import main.math.MathRoutines;
import other.concept.Concept;
import other.context.Context;
//-----------------------------------------------------------------------------
/**
* Defines a diamond (i.e. rhombus) shaped hex board on a hexagonal tiling.
*
* @author cambolbro
*
* @remarks A diamond on a hexagonal grid is a rhombus, as used in the game Hex.
*/
@Hide
public class DiamondOnHex extends Basis
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/**
* Hidden constructor, is a helper for Hex.
*
* @param dimA The dimension A.
* @param dimB The dimension B.
*/
public DiamondOnHex
(
final DimFunction dimA,
@Opt final DimFunction dimB
)
{
this.basis = BasisType.Hexagonal;
this.shape = (dimB == null) ? ShapeType.Diamond : ShapeType.Prism;
this.dim = (dimB == null)
? new int[]{ dimA.eval() }
: new int[]{ dimA.eval(), dimB.eval() };
}
//-------------------------------------------------------------------------
@Override
public Graph eval(final Context context, final SiteType siteType)
{
final boolean isPrism = (shape == ShapeType.Prism);
final int rows = dim[0];
final int cols = (isPrism ? dim[1] : dim[0]);
// Create vertices
final List<double[]> vertexList = new ArrayList<double[]>();
final int maxRows = (isPrism) ? rows + cols - 1 : rows;
final int maxCols = (isPrism) ? rows + cols - 1 : cols;
for (int row = 0; row < maxRows; row++)
for (int col = 0; col < maxCols; col++)
{
if (isPrism && Math.abs(row - col) >= rows)
continue;
final Point2D ptRef = xy(row, col);
for (int n = 0; n < Hex.ref.length; n++)
{
final double x = ptRef.getX() + Hex.ref[n][1];
final double y = ptRef.getY() + Hex.ref[n][0];
// See if vertex already created
int vid;
for (vid = 0; vid < vertexList.size(); vid++)
{
final double[] ptV = vertexList.get(vid);
final double dist = MathRoutines.distance(ptV[0], ptV[1], x, y);
if (dist < 0.1)
break;
}
if (vid >= vertexList.size())
vertexList.add(new double[]{ x, y });
}
}
final Graph graph = BaseGraphFunction.createGraphFromVertexList(vertexList, unit, basis, shape);
graph.reorder();
return graph;
}
//-------------------------------------------------------------------------
static Point2D xy(final int row, final int col)
{
final double hx = unit * Math.sqrt(3);
final double hy = unit * 3 / 2;
return new Point2D.Double(hy * (col - row), hx * (row + col) * 0.5);
}
//-------------------------------------------------------------------------
@Override
public long gameFlags(Game game)
{
return 0;
}
@Override
public void preprocess(Game game)
{
// Nothing to do.
}
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
concepts.or(super.concepts(game));
concepts.set(Concept.HexTiling.id(), true);
if (shape.equals(ShapeType.Diamond))
concepts.set(Concept.DiamondShape.id(), true);
else
concepts.set(Concept.PrismShape.id(), true);
concepts.set(Concept.PolygonShape.id(), true);
concepts.set(Concept.RegularShape.id(), true);
return concepts;
}
//-------------------------------------------------------------------------
}
| 3,883 | 24.721854 | 98 | java |
Ludii | Ludii-master/Core/src/game/functions/graph/generators/basis/hex/Hex.java | package game.functions.graph.generators.basis.hex;
import java.awt.geom.Point2D;
import annotations.Opt;
import annotations.Or;
import game.Game;
import game.functions.dim.DimConstant;
import game.functions.dim.DimFunction;
import game.functions.dim.math.Add;
import game.functions.graph.GraphFunction;
import game.functions.graph.generators.basis.Basis;
import game.types.board.SiteType;
import game.util.graph.Graph;
import game.util.graph.Poly;
import other.context.Context;
//-----------------------------------------------------------------------------
/**
* Defines a board on a hexagonal tiling.
*
* @author cambolbro
*/
public class Hex extends Basis
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/**
* The unit on x.
*/
public static final double ux = Math.sqrt(3) / 2;
/**
* The unit on y.
*/
public static final double uy = unit;
/**
* The references.
*/
public static final double[][] ref =
{
{ 0.0 * ux, 1.0 * uy },
{ 1.0 * ux, 0.5 * uy },
{ 1.0 * ux, -0.5 * uy },
{ 0.0 * ux, -1.0 * uy },
{ -1.0 * ux, -0.5 * uy },
{ -1.0 * ux, 0.5 * uy },
};
//-------------------------------------------------------------------------
/**
* For defining a hex tiling with two dimensions.
*
* @param shape Board shape [Hexagon].
* @param dimA Primary board dimension; cells or vertices per side.
* @param dimB Secondary Board dimension; cells or vertices per side.
*
* @example (hex 5)
* @example (hex Diamond 11)
* @example (hex Rectangle 4 6)
*/
@SuppressWarnings("javadoc")
public static GraphFunction construct
(
@Opt final HexShapeType shape,
final DimFunction dimA,
@Opt final DimFunction dimB
// @Opt @Name final Boolean pyramidal
)
{
final HexShapeType st = (shape == null) ? HexShapeType.Hexagon : shape;
switch (st)
{
case Hexagon:
if (dimB != null)
return new CustomOnHex(new DimFunction[]
{ dimA, dimB });
else
return new HexagonOnHex(dimA);
case Triangle:
return new TriangleOnHex(dimA);
case Diamond:
return new DiamondOnHex(dimA, null);
case Prism:
return new DiamondOnHex(dimA, (dimB != null ? dimB : dimA));
case Star:
return new StarOnHex(dimA);
case Limping:
final DimFunction dimAplus1 = new Add(dimA, new DimConstant(1));
return new CustomOnHex(new DimFunction[] { dimA, dimAplus1 } );
case Square:
return new RectangleOnHex(dimA, dimA);
// return new CustomOnHex(new Float[][]
// {
// { 0f, 0f },
// { 0f, (float)dimA },
// { (float)dimA, (float)dimA },
// { (float)dimA, 0f }
// }
// );
case Rectangle:
return new RectangleOnHex(dimA, (dimB != null ? dimB : dimA));
//$CASES-OMITTED$
default:
throw new IllegalArgumentException("Shape " + st + " not supported for hex tiling.");
}
}
/**
* For defining a hex tiling with a polygon or the number of sides.
*
* @param poly Points defining the board shape.
* @param sides Side lengths around board in clockwise order.
*
* @example (hex (poly { {1 2} {1 6} {3 6} } ))
* @example (hex { 4 3 -1 2 3 })
*/
@SuppressWarnings("javadoc")
public static GraphFunction construct
(
@Or final Poly poly,
@Or final DimFunction[] sides
)
{
int numNonNull = 0;
if (poly != null)
numNonNull++;
if (sides != null)
numNonNull++;
if (numNonNull > 1)
throw new IllegalArgumentException("Exactly one array parameter must be non-null.");
if (poly != null)
return new CustomOnHex(poly.polygon());
else
return new CustomOnHex(sides);
}
//-------------------------------------------------------------------------
private Hex()
{
// Ensure that compiler does not pick up default constructor
}
//-------------------------------------------------------------------------
@Override
public Graph eval(final Context context, final SiteType siteType)
{
// Null placeholder to make the grammar recognise Hex
return null;
}
//-------------------------------------------------------------------------
/**
* @param row The row.
* @param col The column.
* @return The Point2D of the centroid.
*/
public static Point2D xy(final int row, final int col)
{
final double hx = unit * Math.sqrt(3);
final double hy = unit * 3 / 2;
return new Point2D.Double(hx * (col - 0.5 * row), hy * row);
}
//-------------------------------------------------------------------------
@Override
public long gameFlags(Game game)
{
return 0;
}
@Override
public void preprocess(Game game)
{
// Nothing to do.
}
//-------------------------------------------------------------------------
}
| 4,779 | 23.766839 | 88 | java |
Ludii | Ludii-master/Core/src/game/functions/graph/generators/basis/hex/HexShapeType.java | package game.functions.graph.generators.basis.hex;
/**
* Defines known shapes for the hexagonal tiling.
*
* @author cambolbro
*/
public enum HexShapeType
{
/** No shape; custom graph. */
NoShape,
/** Square board shape. */
Square,
/** Rectangular board shape. */
Rectangle,
/** Diamond board shape. */
Diamond,
/** Triangular board shape. */
Triangle,
/** Hexagonal board shape. */
Hexagon,
// /** Cross board shape. */
// Cross,
//
// /** Rhombus board shape. */
// Rhombus,
//
// /** Wheel board shape. */
// Wheel,
//
// /** Spiral board shape. */
// Spiral,
//
// /** Shape is derived from another graph. */
// Dual,
//
// /** Wedge shape of height N with 1 vertex at the top and 3 vertices on the bottom, for Alquerque boards. */
// Wedge,
/** Multi-pointed star shape. */
Star,
/** Alternating sides are staggered. */
Limping,
/** Diamond shape extended vertically. */
Prism,
;
}
| 944 | 15.875 | 110 | java |
Ludii | Ludii-master/Core/src/game/functions/graph/generators/basis/hex/HexagonOnHex.java | package game.functions.graph.generators.basis.hex;
import java.awt.geom.Point2D;
import java.util.BitSet;
import annotations.Hide;
import game.Game;
import game.functions.dim.DimFunction;
import game.functions.graph.generators.basis.Basis;
import game.types.board.BasisType;
import game.types.board.ShapeType;
import game.types.board.SiteType;
import game.util.graph.Graph;
import game.util.graph.Vertex;
import other.concept.Concept;
import other.context.Context;
//-----------------------------------------------------------------------------
/**
* Defines a hexhex board.
*
* @author cambolbro
*/
@Hide
public class HexagonOnHex extends Basis
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/**
* Hidden constructor, is a helper for Hex.
*
* @param dim The dimension.
*/
public HexagonOnHex(final DimFunction dim)
{
this.basis = BasisType.Hexagonal;
this.shape = ShapeType.Hexagon;
this.dim = new int[]{ dim.eval() };
}
//-------------------------------------------------------------------------
@Override
public Graph eval(final Context context, final SiteType siteType)
{
final int rows = 2 * dim[0] - 1;
final int cols = 2 * dim[0] - 1;
// // Create vertices
// final List<double[]> vertexList = new ArrayList<double[]>();
// for (int row = 0; row < rows; row++)
// for (int col = 0; col < cols; col++)
// {
// if (col > cols / 2 + row || row - col > cols / 2)
// continue;
//
// final Point2D ptRef = Hex.xy(row, col);
//
// for (int n = 0; n < Hex.ref.length; n++)
// {
// final double x = ptRef.getX() + Hex.ref[n][0];
// final double y = ptRef.getY() + Hex.ref[n][1];
//
// // See if vertex already created
// int vid;
// for (vid = 0; vid < vertexList.size(); vid++)
// {
// final double[] ptV = vertexList.get(vid);
// final double dist = MathRoutines.distance(ptV[0], ptV[1], x, y);
// if (dist < 0.1)
// break;
// }
//
// if (vid >= vertexList.size())
// vertexList.add(new double[]{ x, y });
// }
// }
//
// final Graph graph = BaseGraphFunction.createGraphFromVertexList(vertexList, unit, basis, shape);
final Graph graph = new Graph();
final double[][] pts = new double[6][2];
final Vertex[] verts = new Vertex[6];
for (int row = 0; row <= rows / 2; row++)
for (int col = 0; col < cols; col++)
{
if (col > cols / 2 + row || row - col > cols / 2)
continue;
final Point2D ptRef = Hex.xy(row, col);
for (int n = 0; n < Hex.ref.length; n++)
{
pts[n][0] = ptRef.getX() + Hex.ref[n][0];
pts[n][1] = ptRef.getY() + Hex.ref[n][1];
}
verts[4] = graph.addVertex(pts[4][0], pts[4][1]);
verts[3] = graph.addVertex(pts[3][0], pts[3][1]);
if (col + 1 > cols / 2 + row)
verts[2] = graph.addVertex(pts[2][0], pts[2][1]);
//graph.addEdge(verts[3].id(), verts[4].id());
}
for (int row = rows / 2; row < rows; row++)
for (int col = 0; col < cols; col++)
{
if (col > cols / 2 + row || row - col > cols / 2)
continue;
final Point2D ptRef = Hex.xy(row, col);
for (int n = 0; n < Hex.ref.length; n++)
{
pts[n][0] = ptRef.getX() + Hex.ref[n][0];
pts[n][1] = ptRef.getY() + Hex.ref[n][1];
}
verts[5] = graph.addVertex(pts[5][0], pts[5][1]);
verts[0] = graph.addVertex(pts[0][0], pts[0][1]);
if (col == cols - 1)
verts[1] = graph.addVertex(pts[1][0], pts[1][1]);
//graph.addEdge(verts[5].id(), verts[0].id());
}
// Edges along rows (bottom half)
int vid = 0;
for (int row = 0; row <= rows / 2; row++)
{
for (int col = 0; col < cols / 2 + 1 + row; col++)
{
graph.addEdge(graph.vertices().get(vid), graph.vertices().get(vid + 1));
vid++;
graph.addEdge(graph.vertices().get(vid), graph.vertices().get(vid + 1));
vid++;
}
vid++;
}
// Edges along rows (top half)
for (int row = rows / 2; row < rows; row++)
{
for (int col = 0; col < cols + rows / 2 - row; col++)
{
graph.addEdge(graph.vertices().get(vid), graph.vertices().get(vid + 1));
vid++;
graph.addEdge(graph.vertices().get(vid), graph.vertices().get(vid + 1));
vid++;
}
vid++;
}
// Edges between rows (bottom half)
vid = 0;
for (int row = 0; row < rows / 2; row++)
{
final int off = rows + 2 * row + 3;
for (int col = 0; col <= cols / 2 + 1 + row; col++)
{
graph.addEdge(graph.vertices().get(vid), graph.vertices().get(vid + off));
vid += 2;
}
vid--;
}
// Edges along middle
final int offM = 2 * rows + 1;
for (int col = 0; col < cols + 1; col++)
{
graph.addEdge(graph.vertices().get(vid), graph.vertices().get(vid + offM));
vid+=2;
}
// Edges between rows (upper half)
for (int row = rows / 2; row < rows; row++)
{
final int off = 3 * rows - 1 - 2 * row;
for (int col = 0; col < cols + rows / 2 - row; col++)
{
if (vid + off < graph.vertices().size())
graph.addEdge(graph.vertices().get(vid), graph.vertices().get(vid + off));
vid += 2;
}
vid++;
}
graph.makeFaces(false);
graph.reorder();
return graph;
}
//-------------------------------------------------------------------------
@Override
public long gameFlags(Game game)
{
return 0;
}
@Override
public void preprocess(Game game)
{
// Nothing to do.
}
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
concepts.or(super.concepts(game));
concepts.set(Concept.HexTiling.id(), true);
concepts.set(Concept.HexShape.id(), true);
concepts.set(Concept.PolygonShape.id(), true);
concepts.set(Concept.RegularShape.id(), true);
return concepts;
}
//-------------------------------------------------------------------------
}
| 5,905 | 24.5671 | 100 | java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.