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/rules/start/forEach/package-info.java | /**
* The {\tt forEach} rules to initially run many starting rules in modifying a
* value parameter.
*/
package game.rules.start.forEach;
| 141 | 22.666667 | 78 | java |
Ludii | Ludii-master/Core/src/game/rules/start/forEach/player/ForEachPlayer.java | package game.rules.start.forEach.player;
import java.util.BitSet;
import annotations.Hide;
import game.Game;
import game.functions.intArray.IntArrayFunction;
import game.rules.start.StartRule;
import other.concept.Concept;
import other.context.Context;
import other.context.EvalContextData;
/**
* Applies a move for each value from a value to another (included).
*
* @author Eric.Piette
*/
@Hide
public final class ForEachPlayer extends StartRule
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/** The starting rule to apply. */
private final StartRule startRule;
/** The list of players. */
private final IntArrayFunction playersFn;
/**
* @param startRule The starting rule to apply.
*/
public ForEachPlayer
(
final StartRule startRule
)
{
this.startRule = startRule;
playersFn = null;
}
/**
* @param players The list of players.
* @param startRule The starting rule to apply.
*/
public ForEachPlayer
(
final IntArrayFunction players,
final StartRule startRule
)
{
playersFn = players;
this.startRule = startRule;
}
@Override
public void eval(final Context context)
{
final int savedPlayer = context.player();
if (playersFn == null)
{
for (int pid = 1; pid < context.game().players().size(); pid++)
{
context.setPlayer(pid);
startRule.eval(context);
}
}
else
{
final int[] players = playersFn.eval(context);
for (int i = 0 ; i < players.length ;i++)
{
final int pid = players[i];
if (pid < 0 || pid > context.game().players().size())
continue;
context.setPlayer(pid);
startRule.eval(context);
}
}
context.setPlayer(savedPlayer);
}
//-------------------------------------------------------------------------
@Override
public long gameFlags(final Game game)
{
long gameFlags = startRule.gameFlags(game);
if (playersFn != null)
gameFlags |= playersFn.gameFlags(game);
return gameFlags;
}
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
concepts.or(super.concepts(game));
if (playersFn != null)
concepts.or(playersFn.concepts(game));
concepts.or(startRule.concepts(game));
concepts.set(Concept.ControlFlowStatement.id(), true);
return concepts;
}
@Override
public BitSet writesEvalContextRecursive()
{
final BitSet writeEvalContext = writesEvalContextFlat();
if (playersFn != null)
writeEvalContext.or(playersFn.writesEvalContextRecursive());
writeEvalContext.or(startRule.writesEvalContextRecursive());
return writeEvalContext;
}
@Override
public BitSet writesEvalContextFlat()
{
final BitSet writeEvalContext = new BitSet();
writeEvalContext.set(EvalContextData.Player.id(), true);
return writeEvalContext;
}
@Override
public BitSet readsEvalContextRecursive()
{
final BitSet readEvalContext = new BitSet();
readEvalContext.or(super.readsEvalContextRecursive());
if (playersFn != null)
readEvalContext.or(playersFn.readsEvalContextRecursive());
readEvalContext.or(startRule.readsEvalContextRecursive());
return readEvalContext;
}
@Override
public boolean missingRequirement(final Game game)
{
boolean missingRequirement = false;
missingRequirement |= super.missingRequirement(game);
if (playersFn != null)
missingRequirement |= (playersFn.missingRequirement(game));
missingRequirement |= startRule.missingRequirement(game);
return missingRequirement;
}
@Override
public boolean willCrash(final Game game)
{
boolean willCrash = false;
willCrash |= super.willCrash(game);
if (playersFn != null)
willCrash |= (playersFn.willCrash(game));
willCrash |= startRule.willCrash(game);
return willCrash;
}
@Override
public boolean isStatic()
{
return false;
}
@Override
public void preprocess(final Game game)
{
startRule.preprocess(game);
if (playersFn != null)
playersFn.preprocess(game);
}
//-------------------------------------------------------------------------
@Override
public String toEnglish(final Game game)
{
return "for each player in " + playersFn.toEnglish(game) + " " + startRule.toEnglish(game);
}
//-------------------------------------------------------------------------
}
| 4,326 | 20.635 | 93 | java |
Ludii | Ludii-master/Core/src/game/rules/start/forEach/site/ForEachSite.java | package game.rules.start.forEach.site;
import java.util.BitSet;
import annotations.Hide;
import annotations.Name;
import annotations.Opt;
import game.Game;
import game.functions.booleans.BooleanConstant;
import game.functions.booleans.BooleanFunction;
import game.functions.region.RegionFunction;
import game.rules.start.StartRule;
import gnu.trove.list.array.TIntArrayList;
import other.concept.Concept;
import other.context.Context;
import other.context.EvalContextData;
/**
* Applies a move for each value from a value to another (included).
*
* @author Eric.Piette
*/
@Hide
public final class ForEachSite extends StartRule
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/** Region to filter. */
private final RegionFunction region;
/** Condition to check. */
private final BooleanFunction condition;
/** The starting rule to apply. */
private final StartRule startRule;
/**
* @param regionFn The original region.
* @param If The condition to satisfy.
* @param startingRule The starting rule to apply.
*/
public ForEachSite
(
final RegionFunction regionFn,
@Opt @Name final BooleanFunction If,
final StartRule startingRule
)
{
this.region = regionFn;
this.condition = If == null ? new BooleanConstant(true) : If;
this.startRule = startingRule;
}
@Override
public void eval(final Context context)
{
final TIntArrayList sites = new TIntArrayList(region.eval(context).sites());
final int originSiteValue = context.site();
for (int i = 0; i < sites.size(); i++)
{
final int site = sites.getQuick(i);
context.setSite(site);
if (condition.eval(context))
startRule.eval(context);
}
context.setSite(originSiteValue);
}
//-------------------------------------------------------------------------
@Override
public boolean isStatic()
{
return condition.isStatic() && region.isStatic() && startRule.isStatic();
}
@Override
public long gameFlags(final Game game)
{
return condition.gameFlags(game) | region.gameFlags(game) | startRule.gameFlags(game);
}
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
concepts.or(condition.concepts(game));
concepts.or(startRule.concepts(game));
concepts.or(region.concepts(game));
concepts.set(Concept.ControlFlowStatement.id(), true);
return concepts;
}
@Override
public BitSet writesEvalContextRecursive()
{
final BitSet writeEvalContext = writesEvalContextFlat();
writeEvalContext.or(condition.writesEvalContextRecursive());
writeEvalContext.or(region.writesEvalContextRecursive());
writeEvalContext.or(startRule.writesEvalContextRecursive());
return writeEvalContext;
}
@Override
public BitSet writesEvalContextFlat()
{
final BitSet writeEvalContext = new BitSet();
writeEvalContext.set(EvalContextData.Site.id(), true);
return writeEvalContext;
}
@Override
public BitSet readsEvalContextRecursive()
{
final BitSet readEvalContext = new BitSet();
readEvalContext.or(condition.readsEvalContextRecursive());
readEvalContext.or(region.readsEvalContextRecursive());
readEvalContext.or(startRule.readsEvalContextRecursive());
return readEvalContext;
}
@Override
public void preprocess(final Game game)
{
condition.preprocess(game);
region.preprocess(game);
startRule.preprocess(game);
}
@Override
public boolean missingRequirement(final Game game)
{
boolean missingRequirement = false;
missingRequirement |= condition.missingRequirement(game);
missingRequirement |= region.missingRequirement(game);
missingRequirement |= startRule.missingRequirement(game);
return missingRequirement;
}
@Override
public boolean willCrash(final Game game)
{
boolean willCrash = false;
willCrash |= condition.willCrash(game);
willCrash |= region.willCrash(game);
willCrash |= startRule.willCrash(game);
return willCrash;
}
}
| 3,984 | 24.382166 | 88 | java |
Ludii | Ludii-master/Core/src/game/rules/start/forEach/team/ForEachTeam.java | package game.rules.start.forEach.team;
import java.util.BitSet;
import annotations.Hide;
import game.Game;
import game.rules.start.StartRule;
import gnu.trove.list.array.TIntArrayList;
import other.concept.Concept;
import other.context.Context;
import other.context.EvalContextData;
/**
* Applies a move for each value from a value to another (included).
*
* @author Eric.Piette
*/
@Hide
public final class ForEachTeam extends StartRule
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/** The starting rule to apply. */
private final StartRule startRule;
/**
* @param startingRule The starting rule to apply.
*/
public ForEachTeam
(
final StartRule startingRule
)
{
this.startRule = startingRule;
}
@Override
public void eval(final Context context)
{
final int[] savedTeam = context.team();
for (int tid = 1; tid < context.game().players().size(); tid++)
{
final TIntArrayList team = new TIntArrayList();
for (int pid = 1; pid < context.game().players().size(); pid++)
{
if (context.state().playerInTeam(pid, tid))
team.add(pid);
}
if (!team.isEmpty())
{
context.setTeam(team.toArray());
startRule.eval(context);
}
}
context.setTeam(savedTeam);
}
//-------------------------------------------------------------------------
@Override
public boolean isStatic()
{
return startRule.isStatic();
}
@Override
public long gameFlags(final Game game)
{
return startRule.gameFlags(game);
}
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
concepts.or(startRule.concepts(game));
concepts.set(Concept.ControlFlowStatement.id(), true);
return concepts;
}
@Override
public BitSet writesEvalContextRecursive()
{
final BitSet writeEvalContext = writesEvalContextFlat();
writeEvalContext.or(startRule.writesEvalContextRecursive());
return writeEvalContext;
}
@Override
public BitSet writesEvalContextFlat()
{
final BitSet writeEvalContext = new BitSet();
writeEvalContext.set(EvalContextData.Team.id(), true);
return writeEvalContext;
}
@Override
public BitSet readsEvalContextRecursive()
{
final BitSet readEvalContext = new BitSet();
readEvalContext.or(startRule.readsEvalContextRecursive());
return readEvalContext;
}
@Override
public void preprocess(final Game game)
{
startRule.preprocess(game);
}
@Override
public boolean missingRequirement(final Game game)
{
boolean missingRequirement = false;
missingRequirement |= startRule.missingRequirement(game);
return missingRequirement;
}
@Override
public boolean willCrash(final Game game)
{
boolean willCrash = false;
willCrash |= startRule.willCrash(game);
return willCrash;
}
}
| 2,810 | 20.458015 | 76 | java |
Ludii | Ludii-master/Core/src/game/rules/start/forEach/value/ForEachValue.java | package game.rules.start.forEach.value;
import java.util.BitSet;
import annotations.Hide;
import annotations.Name;
import game.Game;
import game.functions.ints.IntFunction;
import game.rules.start.StartRule;
import other.concept.Concept;
import other.context.Context;
import other.context.EvalContextData;
/**
* Applies a move for each value from a value to another (included).
*
* @author Eric.Piette
*/
@Hide
public final class ForEachValue extends StartRule
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/** The value from. */
private final IntFunction minFn;
/** The value to. */
private final IntFunction maxFn;
/** The starting rule to apply. */
private final StartRule startRule;
/**
* @param min The minimal value.
* @param max The maximal value.
* @param startRule The starting rule to apply.
*/
public ForEachValue
(
@Name final IntFunction min,
@Name final IntFunction max,
final StartRule startRule
)
{
minFn = min;
maxFn = max;
this.startRule = startRule;
}
@Override
public void eval(final Context context)
{
final int savedValue = context.value();
final int min = minFn.eval(context);
final int max = maxFn.eval(context);
for (int to = min; to <= max; to++)
{
context.setValue(to);
startRule.eval(context);
}
context.setValue(savedValue);
}
//-------------------------------------------------------------------------
@Override
public long gameFlags(final Game game)
{
long gameFlags = 0l;
if (maxFn != null)
gameFlags |= maxFn.gameFlags(game);
if (minFn != null)
gameFlags |= minFn.gameFlags(game);
return gameFlags;
}
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
concepts.or(super.concepts(game));
if (minFn != null)
concepts.or(minFn.concepts(game));
if (maxFn != null)
concepts.or(maxFn.concepts(game));
concepts.set(Concept.ControlFlowStatement.id(), true);
return concepts;
}
@Override
public BitSet writesEvalContextRecursive()
{
final BitSet writeEvalContext = writesEvalContextFlat();
if (minFn != null)
writeEvalContext.or(minFn.writesEvalContextRecursive());
if (maxFn != null)
writeEvalContext.or(maxFn.writesEvalContextRecursive());
return writeEvalContext;
}
@Override
public BitSet writesEvalContextFlat()
{
final BitSet writeEvalContext = new BitSet();
writeEvalContext.set(EvalContextData.Value.id(), true);
return writeEvalContext;
}
@Override
public BitSet readsEvalContextRecursive()
{
final BitSet readEvalContext = new BitSet();
readEvalContext.or(super.readsEvalContextRecursive());
if (minFn != null)
readEvalContext.or(minFn.readsEvalContextRecursive());
if (maxFn != null)
readEvalContext.or(maxFn.readsEvalContextRecursive());
return readEvalContext;
}
@Override
public boolean missingRequirement(final Game game)
{
boolean missingRequirement = false;
missingRequirement |= super.missingRequirement(game);
if (minFn != null)
missingRequirement |= minFn.missingRequirement(game);
if (maxFn != null)
missingRequirement |= maxFn.missingRequirement(game);
return missingRequirement;
}
@Override
public boolean willCrash(final Game game)
{
boolean willCrash = false;
willCrash |= super.willCrash(game);
if (minFn != null)
willCrash |= minFn.willCrash(game);
if (maxFn != null)
willCrash |= maxFn.willCrash(game);
return willCrash;
}
@Override
public boolean isStatic()
{
return false;
}
@Override
public void preprocess(final Game game)
{
if (minFn != null)
minFn.preprocess(game);
if (maxFn != null)
maxFn.preprocess(game);
}
//------------------------------------------------------------------------
@Override
public String toEnglish(final Game game)
{
return "for all values " + "between " + minFn.toEnglish(game) + " and " + maxFn.toEnglish(game) + " " + startRule.toEnglish(game);
}
//--------------------------------------------------------------------------
}
| 4,103 | 21.8 | 132 | java |
Ludii | Ludii-master/Core/src/game/rules/start/place/Place.java | package game.rules.start.place;
import annotations.Name;
import annotations.Opt;
import annotations.Or;
import annotations.Or2;
import game.Game;
import game.functions.ints.IntFunction;
import game.functions.region.RegionFunction;
import game.rules.Rule;
import game.rules.start.StartRule;
import game.rules.start.place.item.PlaceItem;
import game.rules.start.place.random.PlaceRandom;
import game.rules.start.place.stack.PlaceCustomStack;
import game.rules.start.place.stack.PlaceMonotonousStack;
import game.types.board.SiteType;
import other.context.Context;
/**
* Sets some aspect of the initial game state.
*
* @author Eric.Piette
*/
@SuppressWarnings("javadoc")
public final class Place extends StartRule
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/**
* For placing an item to a site.
*
* @param item The name of the item.
* @param container The name of the container.
* @param type The graph element type [default SiteType of the board].
* @param loc The location to place a piece.
* @param coord The coordinate of the location to place a piece.
* @param count The number of the same piece to place [1].
* @param state The local state value of the piece to place [Off].
* @param rotation The rotation value of the piece to place [Off].
* @param value The piece value to place [Undefined].
*
* @example (place "Pawn1" 0)
*/
public static Rule construct
(
final String item,
@Opt final String container,
@Opt final SiteType type,
@Opt final IntFunction loc,
@Opt @Name final String coord,
@Opt @Name final IntFunction count,
@Opt @Name final IntFunction state,
@Opt @Name final IntFunction rotation,
@Opt @Name final IntFunction value
)
{
return new PlaceItem(item, container, type, loc, coord, count, state, rotation, value);
}
//-------------------------------------------------------------------------
/**
* For placing item(s) to sites.
*
* @param item The item to place.
* @param type The graph element type [default SiteType of the board].
* @param locs The sites to fill.
* @param region The region to fill.
* @param coords The coordinates of the sites to fill.
* @param counts The number of pieces on the state.
* @param state The local state value to put on each site.
* @param rotation The rotation value to put on each site.
* @param value The piece value to place [Undefined].
* @param invisibleTo The list of the players where these locations will be
* invisible.
*
* @example (place "Pawn1" (sites Bottom))
*/
public static Rule construct
(
final String item,
@Opt final SiteType type,
@Opt final IntFunction[] locs,
@Opt final RegionFunction region,
@Opt final String[] coords,
@Opt @Name final IntFunction[] counts,
@Opt @Name final IntFunction state,
@Opt @Name final IntFunction rotation,
@Opt @Name final IntFunction value
)
{
return new PlaceItem(item, type, locs, region, coords, counts, state, rotation, value);
}
//-------------------------------------------------------------------------
/**
* For placing items into a stack.
*
* @param placeType The property to place.
* @param item The item to place on the stack.
* @param items The name of the items on the stack to place.
* @param container The name of the container.
* @param type The graph element type [default SiteType of the board].
* @param loc The location to place the stack.
* @param locs The locations to place the stacks.
* @param region The region to place the stacks.
* @param coord The coordinate of the location to place the stack.
* @param coords The coordinates of the sites to place the stacks.
* @param count The number of the same piece to place on the stack [1].
* @param counts The number of pieces on the stack.
* @param state The local state value of the piece on the stack to place
* [Undefined].
* @param rotation The rotation value of the piece on the stack to place
* [Undefined].
* @param value The piece value to place [Undefined].
*
* @example (place Stack items:{"Counter2" "Counter1"} 0)
*
* @example (place Stack "Disc1" coord:"A1" count:5)
*/
public static Rule construct
(
final PlaceStackType placeType,
@Or final String item,
@Or @Name final String[] items,
@Opt final String container,
@Opt final SiteType type,
@Or @Opt final IntFunction loc,
@Or @Opt final IntFunction[] locs,
@Or @Opt final RegionFunction region,
@Or @Opt @Name final String coord,
@Or @Opt final String[] coords,
@Or2 @Opt @Name final IntFunction count,
@Or2 @Opt @Name final IntFunction[] counts,
@Opt @Name final IntFunction state,
@Opt @Name final IntFunction rotation,
@Opt @Name final IntFunction value
)
{
int numNonNull = 0;
if (item != null)
numNonNull++;
if (items != null)
numNonNull++;
if (numNonNull != 1)
throw new IllegalArgumentException(
"Place(): With PlaceStackType exactly one item or items parameter must be non-null.");
numNonNull = 0;
if (count != null)
numNonNull++;
if (counts != null)
numNonNull++;
if (numNonNull > 1)
throw new IllegalArgumentException(
"Place(): With PlaceStackType zero or one count or counts parameter must be non-null.");
numNonNull = 0;
if (coord != null)
numNonNull++;
if (coords != null)
numNonNull++;
if (loc != null)
numNonNull++;
if (locs != null)
numNonNull++;
if (region != null)
numNonNull++;
if (numNonNull > 1)
throw new IllegalArgumentException(
"Place(): With PlaceStackType zero or one coord or coords or loc or locs or region parameter must be non-null.");
if (items == null && (locs != null || region != null || coord != null || counts != null))
return new PlaceMonotonousStack(item, type, locs, region, coords, count, counts, state, rotation, value);
else
return new PlaceCustomStack(item, items, container, type, loc, coord, count, state, rotation, value);
}
//-------------------------------------------------------------------------
/**
* For placing randomly pieces.
*
* @param placeType The property to place.
* @param region The region in which to randomly place piece(s).
* @param item The names of the item to place.
* @param count The number of items to place [1].
* @param state The state value to place [Undefined].
* @param value The piece value to place [Undefined].
* @param type The graph element type [default SiteType of the board].
*
* @example (place Random {"Pawn1" "Pawn2"})
*/
public static Rule construct
(
final PlaceRandomType placeType,
@Opt final RegionFunction region,
final String[] item,
@Opt @Name final IntFunction count,
@Opt @Name final IntFunction state,
@Opt @Name final IntFunction value,
@Opt final SiteType type
)
{
return new PlaceRandom(region, item, count, value, state, type);
}
//-------------------------------------------------------------------------
/**
* For placing randomly a stack.
*
* @param placeType The property to place.
* @param pieces The names of each type of piece in the stack.
* @param count The number of pieces of each piece in the stack.
* @param state The state value to place [Undefined].
* @param value The piece value to place [Undefined].
* @param where The site on which to place the stack.
* @param type The graph element type [default SiteType of the board].
*
* @example (place Random {"Ball1"} count:29)
*/
public static Rule construct
(
final PlaceRandomType placeType,
final String[] pieces,
@Opt @Name final IntFunction[] count,
@Opt @Name final IntFunction state,
@Opt @Name final IntFunction value,
final IntFunction where,
@Opt final SiteType type
)
{
return new PlaceRandom(pieces, count, value, state, where, type);
}
//-------------------------------------------------------------------------
/**
* For placing randomly a stack with specific number of each type of pieces.
*
* @param placeType The property to place.
* @param items The items to be placed, with counts.
* @param where The site on which to place the stack.
* @param type The graph element type [default SiteType of the board].
*
* @example (place Random { (count "Pawn1" 8) (count "Rook1" 2) (count "Knight1"
* 2) (count "Bishop1" 2) (count "Queen1" 1) (count "King1" 1) }
* (handSite 1) )
*/
public static Rule construct
(
final PlaceRandomType placeType,
final game.util.math.Count[] items,
final IntFunction where,
@Opt final SiteType type
)
{
return new PlaceRandom(items, where, type);
}
private Place()
{
// Ensure that compiler does pick up default constructor
}
@Override
public void eval(final Context context)
{
// Should not be called, should only be called on subclasses
throw new UnsupportedOperationException("Place.eval(): Should never be called directly.");
}
//-------------------------------------------------------------------------
@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.
}
} | 10,007 | 32.249169 | 118 | java |
Ludii | Ludii-master/Core/src/game/rules/start/place/PlaceRandomType.java | package game.rules.start.place;
/**
* Defines properties that can be place randomly in the starting rules.
*/
public enum PlaceRandomType
{
/** To randomly place components. */
Random,
}
| 192 | 16.545455 | 71 | java |
Ludii | Ludii-master/Core/src/game/rules/start/place/PlaceStackType.java | package game.rules.start.place;
/**
* Defines properties that can be place as a stack in the starting rules.
*/
public enum PlaceStackType
{
/** To place a stack. */
Stack,
}
| 180 | 15.454545 | 73 | java |
Ludii | Ludii-master/Core/src/game/rules/start/place/package-info.java | /**
* The {\tt place} rules to initially place items into playing sites.
*/
package game.rules.start.place;
| 110 | 21.2 | 69 | java |
Ludii | Ludii-master/Core/src/game/rules/start/place/item/PlaceItem.java | package game.rules.start.place.item;
import java.util.BitSet;
import annotations.Hide;
import annotations.Name;
import annotations.Opt;
import game.Game;
import game.equipment.component.Component;
import game.equipment.container.Container;
import game.functions.ints.IntConstant;
import game.functions.ints.IntFunction;
import game.functions.region.RegionFunction;
import game.rules.start.Start;
import game.rules.start.StartRule;
import game.types.board.SiteType;
import game.types.play.RoleType;
import game.types.state.GameType;
import game.util.equipment.Region;
import main.Constants;
import other.action.BaseAction;
import other.action.puzzle.ActionSet;
import other.concept.Concept;
import other.context.Context;
import other.move.Move;
import other.state.container.ContainerState;
import other.topology.SiteFinder;
import other.topology.TopologyElement;
import other.translation.LanguageUtils;
import other.trial.Trial;
/**
* Places a piece at a particular site or to a region.
*
* @author Eric.Piette
*/
@Hide
public final class PlaceItem extends StartRule
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/** Which item to add. */
private final String item;
/** Which container. */
private final String container;
/** Which cell. */
private final IntFunction siteId;
/** Which coord. */
private final String coord;
/** Number to add. */
private final IntFunction countFn;
/** State of the item. */
private final IntFunction stateFn;
/** State of the item. */
private final IntFunction rotationFn;
/** Piece value of the item. */
private final IntFunction valueFn;
/** Cell, Edge or Vertex. */
private SiteType type;
//-----------------Data to fill a region------------------------------------
/** Which cells. */
private final IntFunction[] locationIds;
/** Which region. */
private final RegionFunction region;
/** Which coords. */
private final String[] coords;
/** Numbers to add for each position. */
private final IntFunction[] countsFn;
//-------------------------------------------------------------------------
/**
* @param item The name of the item.
* @param container The name of the container.
* @param type The graph element type [default SiteType of the board].
* @param loc The location to place a piece.
* @param coord The coordinate of the location to place a piece.
* @param count The number of the same piece to place [1].
* @param state The local state value of the piece to place [Undefined].
* @param rotation The rotation value of the piece to place [Undefined].
* @param value The piece value to place [Undefined].
*/
public PlaceItem
(
final String item,
@Opt final String container,
@Opt final SiteType type,
@Opt final IntFunction loc,
@Opt @Name final String coord,
@Opt @Name final IntFunction count,
@Opt @Name final IntFunction state,
@Opt @Name final IntFunction rotation,
@Opt @Name final IntFunction value
)
{
this.item = (item == null) ? null : item;
this.container = (container == null) ? null : container;
siteId = (loc == null) ? null : loc;
this.coord = (coord == null) ? null : coord;
countFn = (count == null) ? new IntConstant(1) : count;
stateFn = (state == null) ? new IntConstant(Constants.OFF) : state;
rotationFn = (rotation == null) ? new IntConstant(Constants.OFF) : rotation;
valueFn = (value == null) ? new IntConstant(Constants.OFF) : value;
locationIds = null;
region = null;
coords = null;
countsFn = null;
this.type = type;
}
/**
* @param item The item to place.
* @param type The graph element type [default SiteType of the board].
* @param locs The sites to fill.
* @param region The region to fill.
* @param coords The coordinates of the sites to fill.
* @param counts The number of pieces on the state.
* @param state The local state value to put on each site.
* @param rotation The rotation value to put on each site.
* @param value The piece value to place [Undefined].
*/
public PlaceItem
(
final String item,
@Opt final SiteType type,
@Opt final IntFunction[] locs,
@Opt final RegionFunction region,
@Opt final String[] coords,
@Opt @Name final IntFunction[] counts,
@Opt @Name final IntFunction state,
@Opt @Name final IntFunction rotation,
@Opt @Name final IntFunction value
)
{
this.item = (item == null) ? null : item;
container = null;
locationIds = (locs == null) ? null : locs;
this.region = (region == null) ? null : region;
this.coords = (coords == null) ? null : coords;
countFn = (counts == null) ? new IntConstant(1) : counts[0];
if (counts == null)
{
countsFn = new IntFunction[0];
}
else
{
countsFn = new IntFunction[counts.length];
for (int i = 0; i < counts.length; i++)
countsFn[i] = counts[i];
}
stateFn = (state == null) ? new IntConstant(Constants.OFF) : state;
rotationFn = (rotation == null) ? new IntConstant(Constants.OFF) : rotation;
valueFn = (value == null) ? new IntConstant(Constants.OFF) : value;
coord = null;
siteId = null;
this.type = type;
}
//-------------------------------------------------------------------------
@Override
public void eval(final Context context)
{
// Check if the goal is to fill a region
if (locationIds != null || region != null || coords != null || countsFn != null)
{
evalFill(context);
}
else if (context.game().isDeductionPuzzle())
{
evalPuzzle(context);
}
else
{
final int count = countFn.eval(context);
final int state = stateFn.eval(context);
final int rotation = rotationFn.eval(context);
final int value = valueFn.eval(context);
final Component testComponent = context.game().getComponent(item);
if
(
stringWitoutNumber(item) && container != null && container.equals("Hand")
&&
(testComponent == null || !testComponent.role().equals(RoleType.Shared))
)
{
// System.out.println("Placing items for player in hand, count is " + count + "...");
for (int pid = 1; pid <= context.game().players().count(); pid++)
{
final String itemPlayer = item + pid;
final String handPlayer = container + pid;
final Component component = context.game().getComponent(itemPlayer);
if (component == null)
throw new RuntimeException
(
"In the starting rules (place) the component " + itemPlayer + " is not defined (A)."
);
final Container c = context.game().mapContainer().get(handPlayer);
final ContainerState cs = context.containerState(c.index());
int site = context.game().equipment().sitesFrom()[c.index()];
while (!cs.isEmpty(site, type))
site++;
Start.placePieces(context, site, component.index(), count, state, rotation, value, false, type);
}
return;
}
final Component component = context.game().getComponent(item);
if (component == null)
throw new RuntimeException
(
"In the starting rules (place) the component " + item + " is not defined (B)."
);
final int what = component.index();
if (container != null)
{
// Place on a specific container
// Place with coords
final Container c = context.game().mapContainer().get(container);
final int siteFrom = context.game().equipment().sitesFrom()[c.index()];
final Component comp = context.game().equipment().components()[what];
// SPECIAL STATE INIT FOR DICE
if (comp.isDie())
{
for (int pos = siteFrom; pos < siteFrom + c.numSites(); pos++)
{
if (context.state().containerStates()[c.index()].what(pos, type) == 0)
{
Start.placePieces(context, pos, what, count, state, rotation, value, false, type);
break;
}
}
}
else if (container.contains("Hand"))
{
Start.placePieces(context, siteFrom, c.index(), count, state, rotation, value, false, type);
return;
}
else
{
Start.placePieces(context, siteId.eval(context) + siteFrom, what, count, state, rotation, value,
false, type);
}
}
else
{
if (siteId == null && coord == null)
return;
int site = Constants.UNDEFINED;
if (coord != null)
{
final TopologyElement element = SiteFinder.find(context.board(), coord, type);
if (element == null)
throw new RuntimeException(
"In the starting rules (place) the coordinate " + coord + " not found.");
site = element.index();
}
else if (siteId != null)
{
site = siteId.eval(context);
}
Start.placePieces(context, site, what, count, state, rotation, value, false, type);
}
}
}
/**
* To eval the place ludeme for a region/list of sites.
*
* @param context The context of the game.
*/
private void evalFill(final Context context)
{
final Component component = context.game().getComponent(item);
if (component == null)
throw new RuntimeException("In the starting rules (place) the component " + item + " is not defined (C).");
final int what = component.index();
final int count = countFn.eval(context);
final int state = stateFn.eval(context);
final int rotation = rotationFn.eval(context);
final int value = valueFn.eval(context);
// place on a specific container
if (container != null)
{
final Container c = context.game().mapContainer().get(container);
final int siteFrom = context.game().equipment().sitesFrom()[c.index()];
if (region != null)
{
final int[] locs = region.eval(context).sites();
for (final int loc : locs)
{
Start.placePieces(context, loc + siteFrom, what, count, state, rotation, value, false, type);
}
}
else if (locationIds != null)
{
for (final IntFunction loc : locationIds)
{
Start.placePieces(context, loc.eval(context) + siteFrom, what, count, state, rotation, value, false, type);
}
}
else
{
for (int pos = siteFrom; pos < siteFrom + c.numSites(); pos++)
{
if (context.state().containerStates()[c.index()].what(pos, type) == 0)
{
Start.placePieces(context, pos, what, count, state, rotation, value, false, type);
break;
}
}
}
}
else
{
// place with coords
if (coords != null)
{
for (final String coordinate : coords)
{
final TopologyElement element = SiteFinder.find(context.board(), coordinate, type);
if (element == null)
System.out.println("** Coord " + coordinate + " not found.");
else
Start.placePieces(context, element.index(), what, count, state, rotation, value, false, type);
}
}
// place with regions
else if (region != null)
{
final Region regionEval = region.eval(context);
if(regionEval != null)
{
final int[] locs = regionEval.sites();
for (final int loc : locs)
Start.placePieces(context, loc, what, count, state, rotation, value, false, type);
}
}
// place with locs
else if (locationIds != null)
for (final IntFunction loc : locationIds)
Start.placePieces(context, loc.eval(context), what, count, state, rotation, value, false, type);
}
}
/**
* @param str
* @return True if str does not have any number.
*/
private static boolean stringWitoutNumber(final String str)
{
for (int i = 0; i < str.length(); i++)
if (str.charAt(i) >= '0' && str.charAt(i) <= '9')
return false;
return true;
}
private void evalPuzzle(final Context context)
{
final Component component = context.game().getComponent(item);
if (component == null)
throw new RuntimeException(
"In the starting rules (place) the component " + item + " is not defined.");
final int what = component.index();
final BaseAction actionAtomic = new ActionSet(SiteType.Cell, siteId.eval(context), what);
actionAtomic.apply(context, true);
context.trial().addMove(new Move(actionAtomic));
context.trial().addInitPlacement();
}
//-------------------------------------------------------------------------
/**
* @return item
*/
public String item()
{
return item;
}
/**
* @return posn
*/
public IntFunction posn()
{
return siteId;
}
/**
* @return containerName
*/
public String container()
{
return container;
}
@Override
public int count(final Game game)
{
return countFn.eval(new Context(game, new Trial(game)));
}
@Override
public int state(final Game game)
{
return stateFn.eval(new Context(game, new Trial(game)));
}
@Override
public int howManyPlace(final Game game)
{
if (region != null)
{
// region may not yet have been preprocessed, so do that first
// if (region.isStatic())
// {
// region.preprocess(game);
// return region.eval(new Context(game, null)).sites().length;
// }
// else
return game.board().numSites();
}
if (locationIds != null)
return locationIds.length;
else
return 1;
}
//-------------------------------------------------------------------------
@Override
public boolean isStatic()
{
return false;
}
@Override
public long gameFlags(final Game game)
{
long flags = 0L;
flags |= SiteType.gameFlags(type);
if (siteId != null)
flags |= siteId.gameFlags(game);
if (stateFn.eval(new Context(game, new Trial(game))) != Constants.UNDEFINED)
flags |= GameType.SiteState;
if (rotationFn.eval(new Context(game, new Trial(game))) != Constants.UNDEFINED)
flags |= GameType.Rotation;
if (valueFn.eval(new Context(game, new Trial(game))) != Constants.UNDEFINED)
flags |= GameType.Value;
if (countFn.eval(new Context(game, new Trial(game))) > 1)
flags |= GameType.Count;
if (region != null)
flags |= region.gameFlags(game);
flags |= countFn.gameFlags(game);
flags |= rotationFn.gameFlags(game);
flags |= stateFn.gameFlags(game);
flags |= valueFn.gameFlags(game);
if (countsFn != null)
for (final IntFunction function : countsFn)
flags |= function.gameFlags(game);
return flags;
}
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
concepts.or(SiteType.concepts(type));
if (countFn.eval(new Context(game, new Trial(game))) > 1)
concepts.set(Concept.PieceCount.id(), true);
if (valueFn.eval(new Context(game, new Trial(game))) != Constants.UNDEFINED)
concepts.set(Concept.PieceValue.id(), true);
final int maxSiteOnBoard = (type == null)
? game.board().topology().getGraphElements(game.board().defaultSite()).size()
: (type.equals(SiteType.Cell)) ? game.board().topology().getGraphElements(SiteType.Cell).size()
: (type.equals(SiteType.Vertex))
? game.board().topology().getGraphElements(SiteType.Vertex).size()
: game.board().topology().getGraphElements(SiteType.Edge).size();
if (locationIds != null)
for (final IntFunction loc : locationIds)
{
concepts.or(loc.concepts(game));
final int site = loc.eval(new Context(game, new Trial(game)));
if (site < maxSiteOnBoard)
concepts.set(Concept.PiecesPlacedOnBoard.id(), true);
else
concepts.set(Concept.PiecesPlacedOutsideBoard.id(), true);
}
if (region != null)
{
concepts.or(region.concepts(game));
final Region regionEval = region.eval(new Context(game, new Trial(game)));
if(regionEval != null)
{
final int[] sitesRegion = regionEval.sites();
for (final int site : sitesRegion)
{
if (site < maxSiteOnBoard)
concepts.set(Concept.PiecesPlacedOnBoard.id(), true);
else
concepts.set(Concept.PiecesPlacedOutsideBoard.id(), true);
}
}
}
if (siteId != null)
{
concepts.or(siteId.concepts(game));
final int site = siteId.eval(new Context(game, new Trial(game)));
if (site < maxSiteOnBoard)
concepts.set(Concept.PiecesPlacedOnBoard.id(), true);
else
concepts.set(Concept.PiecesPlacedOutsideBoard.id(), true);
}
if (coords != null)
concepts.set(Concept.PiecesPlacedOnBoard.id(), true);
if (container != null)
if (container.contains("Hand"))
concepts.set(Concept.PiecesPlacedOutsideBoard.id(), true);
if (region != null)
concepts.or(region.concepts(game));
if (stateFn.eval(new Context(game, new Trial(game))) > Constants.UNDEFINED)
concepts.set(Concept.SiteState.id(), true);
if (rotationFn.eval(new Context(game, new Trial(game))) > Constants.UNDEFINED)
{
concepts.set(Concept.PieceRotation.id(), true);
concepts.set(Concept.SetRotation.id(), true);
}
concepts.or(countFn.concepts(game));
concepts.or(rotationFn.concepts(game));
concepts.or(stateFn.concepts(game));
concepts.or(valueFn.concepts(game));
if (countsFn != null)
for (final IntFunction function : countsFn)
concepts.or(function.concepts(game));
return concepts;
}
@Override
public BitSet writesEvalContextRecursive()
{
final BitSet writeEvalContext = new BitSet();
if (locationIds != null)
for (final IntFunction loc : locationIds)
writeEvalContext.or(loc.writesEvalContextRecursive());
if (region != null)
writeEvalContext.or(region.writesEvalContextRecursive());
if (siteId != null)
writeEvalContext.or(siteId.writesEvalContextRecursive());
writeEvalContext.or(countFn.writesEvalContextRecursive());
writeEvalContext.or(rotationFn.writesEvalContextRecursive());
writeEvalContext.or(stateFn.writesEvalContextRecursive());
writeEvalContext.or(valueFn.writesEvalContextRecursive());
if (countsFn != null)
for (final IntFunction function : countsFn)
writeEvalContext.or(function.writesEvalContextRecursive());
return writeEvalContext;
}
@Override
public BitSet readsEvalContextRecursive()
{
final BitSet readEvalContext = new BitSet();
if (locationIds != null)
for (final IntFunction loc : locationIds)
readEvalContext.or(loc.readsEvalContextRecursive());
if (region != null)
readEvalContext.or(region.readsEvalContextRecursive());
if (siteId != null)
readEvalContext.or(siteId.readsEvalContextRecursive());
readEvalContext.or(countFn.readsEvalContextRecursive());
readEvalContext.or(rotationFn.readsEvalContextRecursive());
readEvalContext.or(stateFn.readsEvalContextRecursive());
readEvalContext.or(valueFn.readsEvalContextRecursive());
if (countsFn != null)
for (final IntFunction function : countsFn)
readEvalContext.or(function.readsEvalContextRecursive());
return readEvalContext;
}
@Override
public void preprocess(final Game game)
{
// Some tests about the expected items of that ludeme.
if (item != null)
{
boolean found = false;
for (int i = 1; i < game.equipment().components().length; i++)
{
final String nameComponent = game.equipment().components()[i].name();
if (nameComponent.contains(item))
{
found = true;
break;
}
}
if (!found)
{
throw new RuntimeException("Place: The component " + item
+ " is expected but the corresponding component is not defined in the equipment.");
}
}
if (container != null)
{
boolean found = false;
for (int i = 1; i < game.equipment().containers().length; i++)
{
final String nameContainer = game.equipment().containers()[i].name();
if (nameContainer.contains(container))
{
found = true;
break;
}
}
if (!found)
{
throw new RuntimeException("Place: The container " + container
+ " is expected but the corresponding container is not defined in the equipment.");
}
}
type = SiteType.use(type, game);
if (siteId != null)
siteId.preprocess(game);
if (locationIds != null)
for (final IntFunction locationId : locationIds)
locationId.preprocess(game);
if (region != null)
region.preprocess(game);
countFn.preprocess(game);
rotationFn.preprocess(game);
stateFn.preprocess(game);
valueFn.preprocess(game);
if (countsFn != null)
for (final IntFunction function : countsFn)
function.preprocess(game);
}
//-------------------------------------------------------------------------
@Override
public String toString()
{
String str = "(place " + item;
if(container != null)
str += " on cont: " + container;
if(siteId != null)
str += " at: " + siteId;
str += " count: " + countFn;
str += " state: " + stateFn;
str+=")";
return str;
}
//-------------------------------------------------------------------------
@Override
public String toEnglish(final Game game)
{
String text = "";
final String[] splitPieceName = LanguageUtils.SplitPieceName(item);
final String pieceName = splitPieceName[0];
final int piecePlayer = Integer.parseInt(splitPieceName[1]);
String pieceText = pieceName;
if(piecePlayer != -1)
pieceText += " for player " + LanguageUtils.NumberAsText(piecePlayer);
if(coord != null)
{
text += "Place a " + pieceText + " on site " + coord + ".";
}
else if(coords != null && coords.length > 0)
{
final int count = coords.length;
text += "Place a " + pieceText + " on site" + (count == 1 ? " " : "s: ");
for (int i = 0; i < count; i++)
{
if(i == count - 1)
text += " and ";
else if(i > 0)
text += ", ";
text += coords[i];
}
text += ".";
}
else if (region != null)
{
text += "Place a " + pieceText + " at " + region.toEnglish(game) + ".";
}
return text;
}
//-------------------------------------------------------------------------
}
| 21,561 | 26.502551 | 112 | java |
Ludii | Ludii-master/Core/src/game/rules/start/place/random/PlaceRandom.java | package game.rules.start.place.random;
import java.util.Arrays;
import java.util.BitSet;
import annotations.Hide;
import annotations.Name;
import annotations.Opt;
import game.Game;
import game.equipment.component.Component;
import game.functions.ints.IntConstant;
import game.functions.ints.IntFunction;
import game.functions.region.RegionFunction;
import game.functions.region.sites.simple.SitesBoard;
import game.rules.start.Start;
import game.rules.start.StartRule;
import game.types.board.SiteType;
import game.types.state.GameType;
import game.util.math.Count;
import gnu.trove.list.array.TIntArrayList;
import main.Constants;
import other.concept.Concept;
import other.context.Context;
import other.state.container.ContainerState;
import other.trial.Trial;
/**
* Places pieces randomly in a specified container.
*
* @author Eric.Piette
*/
@Hide
public final class PlaceRandom extends StartRule
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------
/** In which region. */
private final RegionFunction region;
/** Which item to add. */
private final String[] item;
/** How many to add. */
private final IntFunction countFn;
/** Piece value of the item. */
private final IntFunction valueFn;
/** Piece state of the item. */
private final IntFunction stateFn;
//------------------ For a stack ------------------------------------------
/** To place a random stack to a specific site. */
private final boolean stack;
/** Which site */
private final IntFunction where;
/** The pieces to shuffle in the stack */
private final String[] pieces;
/** The number of each piece in the stack */
private final IntFunction[] counts;
/** Cell, Edge or Vertex. */
private SiteType type;
//-------------------------------------------------------------------------
/**
* @param region The region in which to randomly place piece(s).
* @param item The names of the item to place.
* @param count The number of items to place [1].
* @param value The piece value to place [Undefined].
* @param state The state value to place [Undefined].PlaceRandom
* @param type The graph element type [default SiteType of the board].
*/
public PlaceRandom
(
@Opt final RegionFunction region,
final String[] item,
@Opt @Name final IntFunction count,
@Opt @Name final IntFunction value,
@Opt @Name final IntFunction state,
@Opt final SiteType type
)
{
this.region = (region == null ? new SitesBoard(type) : region);
countFn = (count == null) ? new IntConstant(1) : count;
this.item = item;
where = null;
pieces = null;
counts = null;
stack = false;
stateFn = (state == null) ? new IntConstant(Constants.OFF) : state;
valueFn = (value == null) ? new IntConstant(Constants.OFF) : value;
this.type = type;
}
//-------------------------------------------------------------------------
/**
* @param pieces The names of each type of piece in the stack.
* @param count The number of pieces of each piece in the stack.
* @param value The piece value to place [Undefined].
* @param state The state value to place [Undefined].
* @param where The site on which to place the stack.
* @param type The graph element type [default SiteType of the board].
*/
public PlaceRandom
(
final String[] pieces,
@Opt @Name final IntFunction[] count,
@Opt @Name final IntFunction value,
@Opt @Name final IntFunction state,
final IntFunction where,
@Opt final SiteType type
)
{
region = new SitesBoard(type);
item = null;
countFn = new IntConstant(1);
this.pieces = pieces;
this.where = where;
counts = count;
stack = true;
stateFn = (state == null) ? new IntConstant(Constants.OFF) : state;
valueFn = (value == null) ? new IntConstant(Constants.OFF) : value;
this.type = type;
}
//-------------------------------------------------------------------------
/**
* @param items The items to be placed, with counts.
* @param where The site on which to place the stack.
* @param type The graph element type [default SiteType of the board].
*/
public PlaceRandom
(
final Count[] items,
final IntFunction where,
@Opt final SiteType type
)
{
region = new SitesBoard(type);
item = null;
countFn = new IntConstant(1);
this.where = where;
stack = true;
this.type = type;
stateFn = new IntConstant(Constants.OFF);
valueFn = new IntConstant(Constants.OFF);
pieces = new String[items.length];
counts = new IntFunction[items.length];
for (int i = 0; i < items.length; i++)
{
pieces[i] = items[i].item();
counts[i] = items[i].count();
}
}
//-------------------------------------------------------------------------
@Override
public void eval(final Context context)
{
if (stack)
{
evalStack(context);
}
else
{
final SiteType realType = (type == null) ? context.board().defaultSite() : type;
for (final String it : item)
{
final TIntArrayList sites = new TIntArrayList(region.eval(context).sites());
final Component component = context.game().getComponent(it);
if (component == null)
throw new RuntimeException("Component " + item + " is not defined.");
final int what = component.index();
// remove the non empty sites in that region.
for (int index = sites.size() - 1; index >= 0; index--)
{
final int site = sites.get(index);
final int cid = realType.equals(SiteType.Cell) ? context.containerId()[site] : 0;
final ContainerState cs = context.containerState(cid);
if (cs.what(site, realType) != 0)
sites.removeAt(index);
}
final int state = stateFn.eval(context);
final int value = valueFn.eval(context);
for (int i = 0; i < countFn.eval(context); i++)
{
final int[] emptySites = sites.toArray();
// If no empty site we stop here.
if (emptySites.length == 0)
break;
// We randomly take an empty site.
final int site = emptySites[context.rng().nextInt(emptySites.length)];
sites.remove(site);
Start.placePieces(context, site, what, 1, state, Constants.OFF, value, false, realType);
}
}
}
}
//-------------------------------------------------------------------------
private void evalStack(Context context)
{
final SiteType realType = (type == null) ? context.board().defaultSite() : type;
final int site = where.eval(context);
final TIntArrayList toPlace = new TIntArrayList();
for (int i = 0; i < pieces.length; i++)
{
final String piece = pieces[i];
for (int pieceIndex = 1; pieceIndex < context.components().length; pieceIndex++)
{
if (context.components()[pieceIndex].name().equals(piece))
{
if (counts == null)
{
toPlace.add(pieceIndex);
}
else
{
for (int j = 0; j < counts[i].eval(context); j++)
toPlace.add(pieceIndex);
}
break;
}
}
}
final int state = stateFn.eval(context);
final int value = valueFn.eval(context);
while (!toPlace.isEmpty())
{
final int index = context.rng().nextInt(toPlace.size());
final int what = toPlace.getQuick(index);
Start.placePieces(context, site, what, 1, state, Constants.OFF, value, true, realType);
toPlace.removeAt(index);
}
}
//-------------------------------------------------------------------------
@Override
public int count(final Game game)
{
return 1;
}
@Override
public int state(final Game game)
{
return stateFn.eval(new Context(game, new Trial(game)));
}
@Override
public int howManyPlace(final Game game)
{
return 1;
}
@Override
public boolean isStatic()
{
return false;
}
@Override
public long gameFlags(final Game game)
{
long flags = GameType.Stochastic;
flags |= SiteType.gameFlags(type);
if (region != null)
flags |= region.gameFlags(game);
if(stack)
flags |= GameType.Stacking;
if (where != null)
flags |= where.gameFlags(game);
if (counts != null)
for (final IntFunction func : counts)
flags |= func.gameFlags(game);
if (valueFn.eval(new Context(game, new Trial(game))) != Constants.UNDEFINED)
flags |= GameType.Value;
if (stateFn.eval(new Context(game, new Trial(game))) != Constants.UNDEFINED)
flags |= GameType.SiteState;
flags |= stateFn.gameFlags(game);
flags |= valueFn.gameFlags(game);
flags |= countFn.gameFlags(game);
return flags;
}
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
concepts.or(SiteType.concepts(type));
concepts.set(Concept.InitialRandomPlacement.id(), true);
concepts.set(Concept.Stochastic.id(), true);
if (valueFn.eval(new Context(game, new Trial(game))) != Constants.UNDEFINED)
concepts.set(Concept.PieceValue.id(), true);
if (stateFn.eval(new Context(game, new Trial(game))) > Constants.UNDEFINED)
concepts.set(Concept.SiteState.id(), true);
if (countFn.eval(new Context(game, new Trial(game))) > Constants.UNDEFINED)
concepts.set(Concept.PieceCount.id(), true);
final int maxSiteOnBoard = (type == null)
? game.board().topology().getGraphElements(game.board().defaultSite()).size()
: (type.equals(SiteType.Cell)) ? game.board().topology().getGraphElements(SiteType.Cell).size()
: (type.equals(SiteType.Vertex))
? game.board().topology().getGraphElements(SiteType.Vertex).size()
: game.board().topology().getGraphElements(SiteType.Edge).size();
if (where != null)
{
concepts.or(where.concepts(game));
final int site = where.eval(new Context(game, new Trial(game)));
if (site < maxSiteOnBoard)
concepts.set(Concept.PiecesPlacedOnBoard.id(), true);
else
concepts.set(Concept.PiecesPlacedOutsideBoard.id(), true);
}
else if (region != null)
concepts.or(region.concepts(game));
if (counts != null)
for (final IntFunction func : counts)
concepts.or(func.concepts(game));
concepts.or(countFn.concepts(game));
concepts.or(stateFn.concepts(game));
concepts.or(valueFn.concepts(game));
return concepts;
}
@Override
public BitSet writesEvalContextRecursive()
{
final BitSet writeEvalContext = new BitSet();
if (where != null)
writeEvalContext.or(where.writesEvalContextRecursive());
else if (region != null)
writeEvalContext.or(region.writesEvalContextRecursive());
if (counts != null)
for (final IntFunction func : counts)
writeEvalContext.or(func.writesEvalContextRecursive());
writeEvalContext.or(countFn.writesEvalContextRecursive());
writeEvalContext.or(stateFn.writesEvalContextRecursive());
writeEvalContext.or(valueFn.writesEvalContextRecursive());
return writeEvalContext;
}
@Override
public BitSet readsEvalContextRecursive()
{
final BitSet readEvalContext = new BitSet();
if (where != null)
readEvalContext.or(where.readsEvalContextRecursive());
else if (region != null)
readEvalContext.or(region.readsEvalContextRecursive());
if (counts != null)
for (final IntFunction func : counts)
readEvalContext.or(func.readsEvalContextRecursive());
readEvalContext.or(countFn.readsEvalContextRecursive());
readEvalContext.or(stateFn.readsEvalContextRecursive());
readEvalContext.or(valueFn.readsEvalContextRecursive());
return readEvalContext;
}
@Override
public void preprocess(final Game game)
{
if (region != null)
region.preprocess(game);
type = SiteType.use(type, game);
if (where != null)
where.preprocess(game);
if (counts != null)
{
for (final IntFunction func : counts)
func.preprocess(game);
}
countFn.preprocess(game);
stateFn.preprocess(game);
valueFn.preprocess(game);
}
//-------------------------------------------------------------------------
@Override
public String toEnglish(final Game game)
{
String regionString = "";
if (region != null)
regionString = region.toEnglish(game);
String valueString = "";
if (valueFn != null)
valueString = " with value " + valueFn;
String stateString = "";
if (stateFn != null)
stateString = " with state " + stateFn;
return "randomly place " + countFn.toEnglish(game) + " " + Arrays.toString(item) + " within " + type.name().toLowerCase() + " " + regionString + valueString + stateString;
}
//-------------------------------------------------------------------------
}
| 12,438 | 26.398678 | 174 | java |
Ludii | Ludii-master/Core/src/game/rules/start/place/stack/PlaceCustomStack.java | package game.rules.start.place.stack;
import java.util.Arrays;
import java.util.BitSet;
import annotations.Hide;
import annotations.Name;
import annotations.Opt;
import annotations.Or;
import game.Game;
import game.equipment.component.Component;
import game.equipment.container.Container;
import game.functions.ints.IntConstant;
import game.functions.ints.IntFunction;
import game.rules.start.Start;
import game.rules.start.StartRule;
import game.types.board.SiteType;
import game.types.state.GameType;
import main.Constants;
import other.action.die.ActionUpdateDice;
import other.concept.Concept;
import other.context.Context;
import other.move.Move;
import other.topology.SiteFinder;
import other.topology.TopologyElement;
import other.trial.Trial;
/**
* Places a stack with different pieces to a site.
*
* @author Eric.Piette
*/
@Hide
public final class PlaceCustomStack extends StartRule
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/** Which stack to add. */
protected final String[] items;
/** Which container. */
protected final String container;
/** Which cell. */
protected final IntFunction siteId;
/** Which coord. */
protected final String coord;
/** Number to add. */
protected final IntFunction countFn;
/** State of the item. */
protected final IntFunction stateFn;
/** State of the item. */
protected final IntFunction rotationFn;
/** Piece value of the item. */
private final IntFunction valueFn;
/** Cell, Edge or Vertex. */
private SiteType type;
//-------------------------------------------------------------------------
/**
* @param item The item to place.
* @param items The name of the items on the stack to place.
* @param container The name of the container.
* @param type The graph element type [default SiteType of the board].
* @param loc The location to place a piece.
* @param coord The coordinate of the location to place a piece.
* @param count The number of the same piece to place [1].
* @param state The local state value of the piece to place [Off].
* @param rotation The rotation value of the piece to place [Off].
* @param value The piece value to place [Undefined].
*/
public PlaceCustomStack
(
@Or final String item,
@Or @Name final String[] items,
@Opt final String container,
@Opt final SiteType type,
@Opt final IntFunction loc,
@Opt @Name final String coord,
@Opt @Name final IntFunction count,
@Opt @Name final IntFunction state,
@Opt @Name final IntFunction rotation,
@Opt @Name final IntFunction value
)
{
this.items = (items == null) ? new String[] {item} : items;
this.container = (container == null) ? null : container;
siteId = (loc == null) ? null : loc;
this.coord = (coord == null) ? null : coord;
countFn = (count == null) ? new IntConstant(1) : count;
stateFn = (state == null) ? new IntConstant(Constants.OFF) : state;
rotationFn = (rotation == null) ? new IntConstant(Constants.OFF) : rotation;
valueFn = (value == null) ? new IntConstant(Constants.OFF) : value;
this.type = type;
}
//-------------------------------------------------------------------------
@Override
public void eval(final Context context)
{
final int count = countFn.eval(context);
final int state = stateFn.eval(context);
final int rotation = rotationFn.eval(context);
final int value = valueFn.eval(context);
if (items.length > 1)
{
for (final String it : items)
{
final Component component = context.game().getComponent(it);
if (component == null)
throw new RuntimeException(
"In the starting rules (place) the component " + it + " is not defined.");
final int what = component.index();
if (container != null)
{
final Container c = context.game().mapContainer().get(container);
final int siteFrom = context.game().equipment().sitesFrom()[c.index()];
if (siteId != null)
Start.placePieces(context, siteId.eval(context) + siteFrom, what, count, state, rotation, value,
true, type);
else
for (int pos = siteFrom; pos < siteFrom + c.numSites(); pos++)
Start.placePieces(context, pos, what, count, state, rotation, value, true, type);
}
else
{
int site = Constants.UNDEFINED;
if (coord != null)
{
final TopologyElement element = SiteFinder.find(context.board(), coord, type);
if (element == null)
throw new RuntimeException(
"In the starting rules (place) the Coordinates " + coord + " not found.");
site = element.index();
}
else
site = siteId.eval(context);
for (int i = 0; i < count; i++)
Start.placePieces(context, site, what, count, state, rotation, value, true, type);
}
}
}
else
{
final String item = items[0];
final Component component = context.game().getComponent(item);
if (component == null)
throw new RuntimeException("In the starting rules (place) the component " + item + " is not defined.");
final int what = component.index();
if (container != null)
{
final Container c = context.game().mapContainer().get(container);
final int siteFrom = context.game().equipment().sitesFrom()[c.index()];
// SPECIAL STATE INIT FOR DICE
if (component.isDie())
{
for (int pos = siteFrom; pos < siteFrom + c.numSites(); pos++)
{
if (context.state().containerStates()[c.index()].what(pos, type) == 0)
{
Start.placePieces(context, pos, what, count, state, rotation, value, true, type);
final int newState = component.roll(context);
final ActionUpdateDice actionChangeState = new ActionUpdateDice(pos,
newState);
actionChangeState.apply(context, true);
context.trial().addMove(new Move(actionChangeState));
context.trial().addInitPlacement();
break;
}
}
}
else if (siteId != null)
{
Start.placePieces(context, siteId.eval(context) + siteFrom, what, count, state, rotation, value, true, type);
}
else
{
for (int pos = siteFrom; pos < siteFrom + c.numSites(); pos++)
Start.placePieces(context, pos, what, count, state, rotation, value, true, type);
}
}
else
{
int site = Constants.UNDEFINED;
if (coord != null)
{
final TopologyElement element = SiteFinder.find(context.board(), coord, type);
if (element == null)
throw new RuntimeException(
"In the starting rules (place) the Coordinates " + coord + " not found.");
site = element.index();
}
else
site = siteId.eval(context);
for (int i = 0; i < count; i++)
Start.placePieces(context, site, what, count, state, rotation, value, true, type);
}
}
}
//-------------------------------------------------------------------------
/**
* @return posn
*/
public IntFunction posn()
{
return siteId;
}
/**
* @return containerName
*/
public String container()
{
return container;
}
@Override
public int count(final Game game)
{
return countFn.eval(new Context(game, new Trial(game)));
}
@Override
public int state(final Game game)
{
return stateFn.eval(new Context(game, new Trial(game)));
}
@Override
public int howManyPlace(final Game game)
{
return 1;
}
//-------------------------------------------------------------------------
@Override
public boolean isStatic()
{
return false;
}
@Override
public long gameFlags(final Game game)
{
long flags = GameType.Stacking;
flags |= SiteType.gameFlags(type);
if (siteId != null)
flags |= siteId.gameFlags(game);
if (stateFn.eval(new Context(game, new Trial(game))) != Constants.UNDEFINED)
flags |= GameType.SiteState;
if (rotationFn.eval(new Context(game, new Trial(game))) != Constants.UNDEFINED)
flags |= GameType.Rotation;
if (valueFn.eval(new Context(game, new Trial(game))) != Constants.UNDEFINED)
flags |= GameType.Value;
// if (countFn.eval(new Context(game, new Trial(game))) > 1)
// flags |= GameType.Count;
flags |= countFn.gameFlags(game);
flags |= rotationFn.gameFlags(game);
flags |= stateFn.gameFlags(game);
flags |= valueFn.gameFlags(game);
return flags;
}
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
concepts.or(SiteType.concepts(type));
if (stateFn.eval(new Context(game, new Trial(game))) > Constants.UNDEFINED)
concepts.set(Concept.SiteState.id(), true);
if (valueFn.eval(new Context(game, new Trial(game))) != Constants.UNDEFINED)
concepts.set(Concept.PieceValue.id(), true);
if (countFn.eval(new Context(game, new Trial(game))) > 1)
concepts.set(Concept.PieceCount.id(), true);
final int maxSiteOnBoard = (type == null)
? game.board().topology().getGraphElements(game.board().defaultSite()).size()
: (type.equals(SiteType.Cell)) ? game.board().topology().getGraphElements(SiteType.Cell).size()
: (type.equals(SiteType.Vertex))
? game.board().topology().getGraphElements(SiteType.Vertex).size()
: game.board().topology().getGraphElements(SiteType.Edge).size();
if (siteId != null)
{
concepts.or(siteId.concepts(game));
final int site = siteId.eval(new Context(game, new Trial(game)));
if (site < maxSiteOnBoard)
concepts.set(Concept.PiecesPlacedOnBoard.id(), true);
else
concepts.set(Concept.PiecesPlacedOutsideBoard.id(), true);
}
if (coord != null)
concepts.set(Concept.PiecesPlacedOnBoard.id(), true);
if (container != null)
if (container.contains("Hand"))
concepts.set(Concept.PiecesPlacedOutsideBoard.id(), true);
if (rotationFn.eval(new Context(game, new Trial(game))) > Constants.UNDEFINED)
{
concepts.set(Concept.PieceRotation.id(), true);
concepts.set(Concept.SetRotation.id(), true);
}
return concepts;
}
@Override
public BitSet writesEvalContextRecursive()
{
final BitSet writeEvalContext = new BitSet();
if (siteId != null)
writeEvalContext.or(siteId.writesEvalContextRecursive());
writeEvalContext.or(countFn.writesEvalContextRecursive());
writeEvalContext.or(rotationFn.writesEvalContextRecursive());
writeEvalContext.or(stateFn.writesEvalContextRecursive());
writeEvalContext.or(valueFn.writesEvalContextRecursive());
return writeEvalContext;
}
@Override
public BitSet readsEvalContextRecursive()
{
final BitSet readEvalContext = new BitSet();
if (siteId != null)
readEvalContext.or(siteId.readsEvalContextRecursive());
readEvalContext.or(countFn.readsEvalContextRecursive());
readEvalContext.or(rotationFn.readsEvalContextRecursive());
readEvalContext.or(stateFn.readsEvalContextRecursive());
readEvalContext.or(valueFn.readsEvalContextRecursive());
return readEvalContext;
}
@Override
public void preprocess(final Game game)
{
// Some tests about the expected items of that ludeme.
for (final String it : items)
{
boolean found = false;
for (int i = 1; i < game.equipment().components().length; i++)
{
final String nameComponent = game.equipment().components()[i].name();
if (nameComponent.contains(it))
{
found = true;
break;
}
}
if (!found)
{
throw new RuntimeException("Place: The component " + it
+ " is expected but the corresponding component is not defined in the equipment.");
}
}
if (container != null)
{
boolean found = false;
for (int i = 1; i < game.equipment().containers().length; i++)
{
final String nameContainer = game.equipment().containers()[i].name();
if (nameContainer.contains(container))
{
found = true;
break;
}
}
if (!found)
{
throw new RuntimeException("Place: The container " + container
+ " is expected but the corresponding container is not defined in the equipment.");
}
}
type = SiteType.use(type, game);
if (siteId != null)
siteId.preprocess(game);
countFn.preprocess(game);
rotationFn.preprocess(game);
stateFn.preprocess(game);
valueFn.preprocess(game);
}
//-------------------------------------------------------------------------
@Override
public String toString()
{
return "";
}
@Override
public String toEnglish(final Game game)
{
return "place stack of " +
Arrays.toString(items) +
" at " + type.name().toLowerCase() +
" " + (siteId == null ? coord : siteId.toEnglish(game));
}
//-------------------------------------------------------------------------
}
| 12,609 | 27.400901 | 114 | java |
Ludii | Ludii-master/Core/src/game/rules/start/place/stack/PlaceMonotonousStack.java | package game.rules.start.place.stack;
import java.util.Arrays;
import java.util.BitSet;
import annotations.Hide;
import annotations.Name;
import annotations.Opt;
import game.Game;
import game.equipment.component.Component;
import game.equipment.container.Container;
import game.functions.ints.IntConstant;
import game.functions.ints.IntFunction;
import game.functions.region.RegionFunction;
import game.rules.start.Start;
import game.rules.start.StartRule;
import game.types.board.SiteType;
import game.types.state.GameType;
import main.Constants;
import other.concept.Concept;
import other.context.Context;
import other.trial.Trial;
/**
* Places a stack with the same pieces on all the stack.
*
* @author Eric.Piette
*/
@Hide
public final class PlaceMonotonousStack extends StartRule
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/** Which stack to add. */
protected final String[] items;
/** Which container. */
protected final String container;
/** Number to add. */
protected final IntFunction countFn;
/** State of the item. */
protected final IntFunction stateFn;
/** State of the item. */
protected final IntFunction rotationFn;
/** Piece value of the item. */
private final IntFunction valueFn;
/** Cell, Edge or Vertex. */
private SiteType type;
//-----------------Data to fill a region------------------------------------
/** Which cells. */
protected final IntFunction[] locationIds;
/** Which region. */
protected final RegionFunction region;
/** Which coords. */
protected final String[] coords;
/** Numbers to add for each position. */
protected final IntFunction[] countsFn;
//-------------------------------------------------------------------------
/**
* @param item The item to place.
* @param type The graph element type [default SiteType of the board].
* @param locs The sites to fill.
* @param region The region to fill.
* @param coords The coordinates of the sites to fill.
* @param count The number of pieces on the stack to place.
* @param counts The number of each piece on the stack to place.
* @param state The local state value to put on each site.
* @param rotation The rotation value to put on each site.
* @param value The piece value to place [Undefined].
*/
public PlaceMonotonousStack
(
final String item,
@Opt final SiteType type,
@Opt final IntFunction[] locs,
@Opt final RegionFunction region,
@Opt final String[] coords,
@Opt @Name final IntFunction count,
@Opt @Name final IntFunction[] counts,
@Opt @Name final IntFunction state,
@Opt @Name final IntFunction rotation,
@Opt @Name final IntFunction value
)
{
items = new String[]
{ item };
container = null;
locationIds = (locs == null) ? null : locs;
this.region = (region == null) ? null : region;
this.coords = (coords == null) ? null : coords;
countFn = (counts == null) ? ((count != null) ? count : new IntConstant(1)) : counts[0];
if (counts == null)
{
countsFn = new IntFunction[0];
}
else
{
countsFn = new IntFunction[counts.length];
for (int i = 0; i < counts.length; i++)
countsFn[i] = counts[i];
}
stateFn = (state == null) ? new IntConstant(Constants.OFF) : state;
rotationFn = (rotation == null) ? new IntConstant(Constants.OFF) : rotation;
valueFn = (value == null) ? new IntConstant(Constants.OFF) : value;
this.type = type;
}
//-------------------------------------------------------------------------
@Override
public void eval(final Context context)
{
final String item = items[0];
final Component component = context.game().getComponent(item);
if (component == null)
throw new RuntimeException("In the starting rules (place) the component " + item + " is not defined.");
final int what = component.index();
final int count = countFn.eval(context);
final int state = stateFn.eval(context);
final int rotation = rotationFn.eval(context);
final int value = valueFn.eval(context);
if (container != null)
{
final Container c = context.game().mapContainer().get(container);
final int siteFrom = context.game().equipment().sitesFrom()[c.index()];
for (int pos = siteFrom; pos < siteFrom + c.numSites(); pos++)
Start.placePieces(context, pos, what, count, state, rotation, value, true, type);
}
else
{
final int[] locs = region.eval(context).sites();
if (countsFn.length != 0 && locs.length != countsFn.length)
throw new RuntimeException(
"In the starting rules (place) the region size is greater than the size of the array counts.");
for (int k = 0; k < locs.length; k++)
{
final int loc = locs[k];
for (int i = 0; i < ((countsFn.length == 0) ? countFn.eval(context) : countsFn[k].eval(context)); i++)
Start.placePieces(context, loc, what, count, state, rotation, value, true, type);
}
}
}
//-------------------------------------------------------------------------
/**
* @return containerName
*/
public String container()
{
return container;
}
@Override
public int count(final Game game)
{
return countFn.eval(new Context(game, new Trial(game)));
}
@Override
public int state(final Game game)
{
return stateFn.eval(new Context(game, new Trial(game)));
}
@Override
public int howManyPlace(final Game game)
{
if (region != null)
return region.eval(new Context(game, null)).sites().length;
if (locationIds != null)
return locationIds.length;
else
return 1;
}
//-------------------------------------------------------------------------
@Override
public boolean isStatic()
{
return false;
}
@Override
public long gameFlags(final Game game)
{
long flags = GameType.Stacking;
flags |= SiteType.gameFlags(type);
if (stateFn.eval(new Context(game, new Trial(game))) != Constants.UNDEFINED)
flags |= GameType.SiteState;
if (rotationFn.eval(new Context(game, new Trial(game))) != Constants.UNDEFINED)
flags |= GameType.Rotation;
if (valueFn.eval(new Context(game, new Trial(game))) != Constants.UNDEFINED)
flags |= GameType.Value;
if (countFn.eval(new Context(game, new Trial(game))) > 1)
flags |= GameType.Count;
if (region != null)
flags |= region.gameFlags(game);
flags |= countFn.gameFlags(game);
flags |= rotationFn.gameFlags(game);
flags |= stateFn.gameFlags(game);
flags |= valueFn.gameFlags(game);
if (countsFn != null)
for (final IntFunction function : countsFn)
flags |= function.gameFlags(game);
return flags;
}
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
concepts.or(SiteType.concepts(type));
if (countFn.eval(new Context(game, new Trial(game))) > 1)
concepts.set(Concept.PieceCount.id(), true);
if (valueFn.eval(new Context(game, new Trial(game))) != Constants.UNDEFINED)
concepts.set(Concept.PieceValue.id(), true);
final int maxSiteOnBoard = (type == null)
? game.board().topology().getGraphElements(game.board().defaultSite()).size()
: (type.equals(SiteType.Cell)) ? game.board().topology().getGraphElements(SiteType.Cell).size()
: (type.equals(SiteType.Vertex))
? game.board().topology().getGraphElements(SiteType.Vertex).size()
: game.board().topology().getGraphElements(SiteType.Edge).size();
if (locationIds != null)
for (final IntFunction loc : locationIds)
{
concepts.or(loc.concepts(game));
final int site = loc.eval(new Context(game, new Trial(game)));
if (site < maxSiteOnBoard)
concepts.set(Concept.PiecesPlacedOnBoard.id(), true);
else
concepts.set(Concept.PiecesPlacedOutsideBoard.id(), true);
}
if (region != null)
{
concepts.or(region.concepts(game));
final int[] sitesRegion = region.eval(new Context(game, new Trial(game))).sites();
for (final int site : sitesRegion)
{
if (site < maxSiteOnBoard)
concepts.set(Concept.PiecesPlacedOnBoard.id(), true);
else
concepts.set(Concept.PiecesPlacedOutsideBoard.id(), true);
}
}
if (coords != null)
concepts.set(Concept.PiecesPlacedOnBoard.id(), true);
if (container != null)
if (container.contains("Hand"))
concepts.set(Concept.PiecesPlacedOutsideBoard.id(), true);
if (stateFn.eval(new Context(game, new Trial(game))) > Constants.UNDEFINED)
concepts.set(Concept.SiteState.id(), true);
if (rotationFn.eval(new Context(game, new Trial(game))) > Constants.UNDEFINED)
{
concepts.set(Concept.PieceRotation.id(), true);
concepts.set(Concept.SetRotation.id(), true);
}
concepts.or(countFn.concepts(game));
concepts.or(rotationFn.concepts(game));
concepts.or(stateFn.concepts(game));
concepts.or(valueFn.concepts(game));
if (countsFn != null)
for (final IntFunction function : countsFn)
concepts.or(function.concepts(game));
return concepts;
}
@Override
public BitSet writesEvalContextRecursive()
{
final BitSet writeEvalContext = new BitSet();
if (locationIds != null)
for (final IntFunction loc : locationIds)
writeEvalContext.or(loc.writesEvalContextRecursive());
if (region != null)
writeEvalContext.or(region.writesEvalContextRecursive());
writeEvalContext.or(countFn.writesEvalContextRecursive());
writeEvalContext.or(rotationFn.writesEvalContextRecursive());
writeEvalContext.or(stateFn.writesEvalContextRecursive());
writeEvalContext.or(valueFn.writesEvalContextRecursive());
if (countsFn != null)
for (final IntFunction function : countsFn)
writeEvalContext.or(function.writesEvalContextRecursive());
return writeEvalContext;
}
@Override
public BitSet readsEvalContextRecursive()
{
final BitSet readEvalContext = new BitSet();
if (locationIds != null)
for (final IntFunction loc : locationIds)
readEvalContext.or(loc.readsEvalContextRecursive());
if (region != null)
readEvalContext.or(region.readsEvalContextRecursive());
readEvalContext.or(countFn.readsEvalContextRecursive());
readEvalContext.or(rotationFn.readsEvalContextRecursive());
readEvalContext.or(stateFn.readsEvalContextRecursive());
readEvalContext.or(valueFn.readsEvalContextRecursive());
if (countsFn != null)
for (final IntFunction function : countsFn)
readEvalContext.or(function.readsEvalContextRecursive());
return readEvalContext;
}
@Override
public void preprocess(final Game game)
{
// Some tests about the expected items of that ludeme.
for (final String it : items)
{
boolean found = false;
for (int i = 1; i < game.equipment().components().length; i++)
{
final String nameComponent = game.equipment().components()[i].name();
if (nameComponent.contains(it))
{
found = true;
break;
}
}
if (!found)
{
throw new RuntimeException("Place: The component " + it
+ " is expected but the corresponding component is not defined in the equipment.");
}
}
if (container != null)
{
boolean found = false;
for (int i = 1; i < game.equipment().containers().length; i++)
{
final String nameContainer = game.equipment().containers()[i].name();
if (nameContainer.contains(container))
{
found = true;
break;
}
}
if (!found)
{
throw new RuntimeException("Place: The container " + container
+ " is expected but the corresponding container is not defined in the equipment.");
}
}
type = SiteType.use(type, game);
if (locationIds != null)
for (final IntFunction locationId : locationIds)
locationId.preprocess(game);
if (region != null)
region.preprocess(game);
countFn.preprocess(game);
rotationFn.preprocess(game);
stateFn.preprocess(game);
valueFn.preprocess(game);
if (countsFn != null)
for (final IntFunction function : countsFn)
function.preprocess(game);
}
//-------------------------------------------------------------------------
@Override
public String toString()
{
return "";
}
//-------------------------------------------------------------------------
@Override
public String toEnglish(final Game game)
{
String regionString = "";
if (locationIds != null)
{
regionString = "[";
for (final IntFunction i : locationIds)
regionString += i.toEnglish(game) + ",";
regionString = regionString.substring(0,regionString.length()-1) + "]";
}
else if (coords != null)
{
regionString = "[";
for (final String s : coords)
regionString += s + ",";
regionString = regionString.substring(0,regionString.length()-1) + "]";
}
else if (region != null)
{
regionString = region.toEnglish(game);
}
return "place stack of " +
Arrays.toString(items) +
" at " + type.name().toLowerCase() +
" " + regionString;
}
//-------------------------------------------------------------------------
}
| 12,927 | 27.165577 | 106 | java |
Ludii | Ludii-master/Core/src/game/rules/start/set/Set.java | package game.rules.start.set;
import annotations.Name;
import annotations.Opt;
import annotations.Or;
import annotations.Or2;
import game.Game;
import game.functions.booleans.BooleanFunction;
import game.functions.ints.IntFunction;
import game.functions.region.RegionFunction;
import game.rules.Rule;
import game.rules.start.StartRule;
import game.rules.start.set.player.SetAmount;
import game.rules.start.set.player.SetScore;
import game.rules.start.set.players.SetTeam;
import game.rules.start.set.remember.SetRememberValue;
import game.rules.start.set.sites.SetCost;
import game.rules.start.set.sites.SetCount;
import game.rules.start.set.sites.SetPhase;
import game.rules.start.set.sites.SetSite;
import game.types.board.HiddenData;
import game.types.board.SiteType;
import game.types.play.RoleType;
import other.IntArrayFromRegion;
import other.context.Context;
/**
* Sets some aspect of the initial game state.
*
* @author Eric.Piette
*/
@SuppressWarnings("javadoc")
public final class Set extends StartRule
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/**
* For setting the remembering values.
*
* @param setType The type of property to set.
* @param name The name of the remembering values.
* @param value The value to remember.
* @param regionValue The values to remember.
* @param unique If True we remember a value only if not already
* remembered[False].
*
* @example (set RememberValue 5)
*/
public static Rule construct
(
final SetRememberValueType setType,
@Opt final String name,
@Or final IntFunction value,
@Or final RegionFunction regionValue,
@Opt @Name final BooleanFunction unique
)
{
int numNonNull = 0;
if (value != null)
numNonNull++;
if (regionValue != null)
numNonNull++;
if (numNonNull != 1)
throw new IllegalArgumentException(
"Set(): With SetRememberValueType only one value or regionValue parameter must be non-null.");
switch (setType)
{
case RememberValue:
return new SetRememberValue(name, value, regionValue, unique);
default:
break;
}
// We should never reach that except if we forget some codes.
throw new IllegalArgumentException("Set(): A SetRememberValueType is not implemented.");
}
//-------------------------------------------------------------------------
/**
* For setting the hidden information.
*
* @param setType The type of property to set.
* @param dataType The type of hidden data [Invisible].
* @param dataTypes The types of hidden data [Invisible].
* @param type The graph element type [default of the board].
* @param at The site to set the hidden information.
* @param region The region to set the hidden information.
* @param level The level to set the hidden information [0].
* @param value The value to set [True].
* @param to The player with these hidden information.
*
* @example (set Hidden What at:5 to:P1)
* @example (set Hidden What at:6 to:P2)
* @example (set Hidden Count (sites Occupied by:Next) to:P1)
*/
public static Rule construct
(
final SetStartHiddenType setType,
@Opt @Or final HiddenData dataType,
@Opt @Or final HiddenData[] dataTypes,
@Opt final SiteType type,
@Name @Or2 final IntFunction at,
@Or2 final RegionFunction region,
@Name @Opt final IntFunction level,
@Opt final BooleanFunction value,
@Name final RoleType to
)
{
int numNonNull = 0;
if (dataType != null)
numNonNull++;
if (dataTypes != null)
numNonNull++;
if (numNonNull > 1)
throw new IllegalArgumentException(
"Set(): With SetHiddenType only one dataType or dataTypes parameter must be non-null.");
int numNonNull2 = 0;
if (at != null)
numNonNull2++;
if (region != null)
numNonNull2++;
if (numNonNull2 != 1)
throw new IllegalArgumentException(
"Set(): With SetHiddenType one at or region parameter must be non-null.");
switch (setType)
{
case Hidden:
return new game.rules.start.set.hidden.SetHidden(
dataTypes != null ? dataTypes : dataType != null ? new HiddenData[]
{ dataType } : null, type, new IntArrayFromRegion(at, region), level, value, to);
default:
break;
}
// We should never reach that except if we forget some codes.
throw new IllegalArgumentException("Set(): A SetStartHiddenType is not implemented.");
}
//-------------------------------------------------------------------------
/**
* For setting a site to a player.
*
* @param role The owner of the site.
* @param type The graph element type [default SiteType of the board].
* @param loc The location to place a piece.
* @param coord The coordinate of the location to place a piece.
*
* @example (set P1 Vertex 5)
*/
public static Rule construct
(
final RoleType role,
@Opt final SiteType type,
@Opt final IntFunction loc,
@Opt @Name final String coord
)
{
return new SetSite(role, type, loc, coord);
}
/**
* For setting sites to a player.
*
* @param role The owner of the site.
* @param type The graph element type [default SiteType of the board].
* @param locs The sites to fill.
* @param region The region to fill.
* @param coords The coordinates of the sites to fill.
*
* @example (set P1 Vertex (sites {0 5 6} ))
*/
public static Rule construct
(
final RoleType role,
@Opt final SiteType type,
@Opt final IntFunction[] locs,
@Opt final RegionFunction region,
@Opt final String[] coords
)
{
return new SetSite(role, type, locs, region, coords);
}
//-------------------------------------------------------------------------
/**
* For setting the count, the cost or the phase to sites.
*
* @param startType The property to set.
* @param value The value.
* @param type The graph element type [default SiteType of the board].
* @param at The site to set.
* @param to The region to set.
*
* @example (set Count 5 to:(sites Track) )
*
* @example (set Cost 5 Vertex at:10)
*
* @example (set Phase 1 Cell at:3)
*/
public static Rule construct
(
final SetStartSitesType startType,
final IntFunction value,
@Opt final SiteType type,
@Or @Name final IntFunction at,
@Or @Name final RegionFunction to
)
{
int numNonNull = 0;
if (to != null)
numNonNull++;
if (at != null)
numNonNull++;
if (numNonNull != 1)
throw new IllegalArgumentException(
"Set(): With SetStartSitesType Exactly one region or site parameter must be non-null.");
switch (startType)
{
case Count:
return new SetCount(value, type, at, to);
case Cost:
return new SetCost(value, type, at, to);
case Phase:
return new SetPhase(value, type, at, to);
default:
break;
}
// We should never reach that except if we forget some codes.
throw new IllegalArgumentException("Set(): A SetStartSitesType is not implemented.");
}
//-------------------------------------------------------------------------
/**
* For setting the amount or the score of a player.
*
* @param startType The property to set.
* @param role The roleType of the player.
* @param value The value to set.
*
* @example (set Amount 5000)
*/
public static Rule construct
(
final SetStartPlayerType startType,
@Opt final RoleType role,
final IntFunction value
)
{
switch (startType)
{
case Amount:
return new SetAmount(role, value);
case Score:
return new SetScore(role, value);
default:
break;
}
// We should never reach that except if we forget some codes.
throw new IllegalArgumentException("Set(): A SetStartPlayerType is not implemented.");
}
//-------------------------------------------------------------------------
/**
* For setting a team.
*
* @param startType The property to set.
* @param roles The roleType of the player.
* @param index The index of the team.
*
* @example (set Team 1 {P1 P3})
*/
public static Rule construct
(
final SetStartPlayersType startType,
final IntFunction index,
final RoleType[] roles
)
{
switch (startType)
{
case Team:
return new SetTeam(index, roles);
default:
break;
}
// We should never reach that except if we forget some codes.
throw new IllegalArgumentException("Set(): A SetStartPlayersType is not implemented.");
}
private Set()
{
// Ensure that compiler does pick up default constructor
}
@Override
public void eval(final Context context)
{
// Should not be called, should only be called on subclasses
throw new UnsupportedOperationException("Set.eval(): Should never be called directly.");
}
//-------------------------------------------------------------------------
@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.
}
} | 9,516 | 26.909091 | 99 | java |
Ludii | Ludii-master/Core/src/game/rules/start/set/SetRememberValueType.java | package game.rules.start.set;
/**
* Defines properties that can be set in the starting rules to remember a value.
*/
public enum SetRememberValueType
{
/** To remember a value. */
RememberValue,
} | 201 | 19.2 | 80 | java |
Ludii | Ludii-master/Core/src/game/rules/start/set/SetStartGraphType.java | package game.rules.start.set;
/**
* Defines properties that can be set in the starting rules that do require only
* the graph element type.
*/
public enum SetStartGraphType
{
/** Makes all items invisible to all players. */
AllInvisible,
}
| 246 | 19.583333 | 80 | java |
Ludii | Ludii-master/Core/src/game/rules/start/set/SetStartHiddenType.java | package game.rules.start.set;
/**
* Defines the types of hidden information that can be set in the starting rule.
*/
public enum SetStartHiddenType
{
/** Sets the hidden information of a location. */
Hidden,
} | 214 | 20.5 | 80 | java |
Ludii | Ludii-master/Core/src/game/rules/start/set/SetStartPlayerType.java | package game.rules.start.set;
/**
* Defines the player properties that can be set in the starting rules.
*/
public enum SetStartPlayerType
{
/** Sets the initial amount for a player. */
Amount,
/** Sets the initial score of a player. */
Score,
}
| 254 | 17.214286 | 71 | java |
Ludii | Ludii-master/Core/src/game/rules/start/set/SetStartPlayersType.java | package game.rules.start.set;
/**
* Defines the properties related to players that can be set in the starting rules.
*/
public enum SetStartPlayersType
{
/** Sets a team of players. */
Team,
}
| 198 | 17.090909 | 83 | java |
Ludii | Ludii-master/Core/src/game/rules/start/set/SetStartSitesType.java | package game.rules.start.set;
/**
* Defines the properties of board sites that can be set in the starting rules.
*/
public enum SetStartSitesType
{
/** Sets the count of a site or region. */
Count,
/** Sets the cost of a site or region. */
Cost,
/** Sets the phase of a site or region. */
Phase,
}
| 309 | 17.235294 | 79 | java |
Ludii | Ludii-master/Core/src/game/rules/start/set/package-info.java | /**
* The {\tt (set ...)} start `super' ludeme sets some aspect of the initial game
* state. This can include initial scores for players, initial teams, starting
* amounts, etc.
*/
package game.rules.start.set;
| 215 | 29.857143 | 80 | java |
Ludii | Ludii-master/Core/src/game/rules/start/set/hidden/SetHidden.java | package game.rules.start.set.hidden;
import java.util.BitSet;
import annotations.Hide;
import annotations.Name;
import annotations.Opt;
import game.Game;
import game.functions.booleans.BooleanConstant;
import game.functions.booleans.BooleanFunction;
import game.functions.ints.IntConstant;
import game.functions.ints.IntFunction;
import game.rules.start.StartRule;
import game.types.board.HiddenData;
import game.types.board.SiteType;
import game.types.play.RoleType;
import game.types.state.GameType;
import gnu.trove.list.array.TIntArrayList;
import main.StringRoutines;
import other.IntArrayFromRegion;
import other.PlayersIndices;
import other.action.Action;
import other.action.hidden.ActionSetHidden;
import other.action.hidden.ActionSetHiddenCount;
import other.action.hidden.ActionSetHiddenRotation;
import other.action.hidden.ActionSetHiddenState;
import other.action.hidden.ActionSetHiddenValue;
import other.action.hidden.ActionSetHiddenWhat;
import other.action.hidden.ActionSetHiddenWho;
import other.concept.Concept;
import other.context.Context;
import other.move.Move;
/**
* Sets the hidden information of a region.
*
* @author Eric.Piette
*/
@Hide
public final class SetHidden extends StartRule
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/** Hidden data type. */
private final HiddenData[] dataTypes;
/** Which region. */
private final IntArrayFromRegion region;
/** Level. */
private final IntFunction levelFn;
/** Value to set. */
private final BooleanFunction valueFn;
/** The player to set the hidden information. */
private final IntFunction whoFn;
/** The RoleType if used */
private final RoleType roleType;
/** Cell/Edge/Vertex. */
private SiteType type;
//-------------------------------------------------------------------------
/**
* To set hidden information.
*
* @param dataTypes The types of hidden data [Invisible].
* @param type The graph element type [default of the board].
* @param region The region to set the hidden information.
* @param level The level to set the hidden information [0].
* @param value The value to set [True].
* @param to The roleType with these hidden information.
*/
public SetHidden
(
@Opt final HiddenData[] dataTypes,
@Opt final SiteType type,
final IntArrayFromRegion region,
@Name @Opt final IntFunction level,
@Opt final BooleanFunction value,
@Name final RoleType to
)
{
this.dataTypes = dataTypes;
this.region = region;
levelFn = (level == null) ? new IntConstant(0) : level;
valueFn = (value == null) ? new BooleanConstant(true) : value;
this.type = type;
whoFn = RoleType.toIntFunction(to);
roleType = to;
}
//-------------------------------------------------------------------------
@Override
public void eval(final Context context)
{
final int[] sites = region.eval(context);
final int level = levelFn.eval(context);
final SiteType realType = (type != null) ? type : context.game().board().defaultSite();
final boolean value = valueFn.eval(context);
final int who = whoFn.eval(context);
final int numPlayers = context.game().players().count();
if (RoleType.manyIds(roleType))
{
final TIntArrayList idPlayers = PlayersIndices.getIdRealPlayers(context, roleType);
if (dataTypes == null)
{
for (final int site : sites)
{
for (int i = 0; i < idPlayers.size(); i++)
{
final int pid = idPlayers.get(i);
final Action action = new ActionSetHidden(pid, realType, site, level, value);
action.apply(context, true);
final Move move = new Move(action);
context.trial().addMove(move);
context.trial().addInitPlacement();
}
}
}
else
{
for (final HiddenData hiddenData : dataTypes)
{
switch (hiddenData)
{
case What:
for (final int site : sites)
{
for (int i = 0; i < idPlayers.size(); i++)
{
final int pid = idPlayers.get(i);
final Action action = new ActionSetHiddenWhat(pid, realType, site, level, value);
action.apply(context, true);
final Move move = new Move(action);
context.trial().addMove(move);
context.trial().addInitPlacement();
}
}
break;
case Who:
for (final int site : sites)
{
for (int i = 0; i < idPlayers.size(); i++)
{
final int pid = idPlayers.get(i);
final Action action = new ActionSetHiddenWho(pid, realType, site, level, value);
action.apply(context, true);
final Move move = new Move(action);
context.trial().addMove(move);
context.trial().addInitPlacement();
}
}
break;
case State:
for (final int site : sites)
{
for (int i = 0; i < idPlayers.size(); i++)
{
final int pid = idPlayers.get(i);
final Action action = new ActionSetHiddenState(pid, realType, site, level, value);
action.apply(context, true);
final Move move = new Move(action);
context.trial().addMove(move);
context.trial().addInitPlacement();
}
}
break;
case Count:
for (final int site : sites)
{
for (int i = 0; i < idPlayers.size(); i++)
{
final int pid = idPlayers.get(i);
final Action action = new ActionSetHiddenCount(pid, realType, site, level, value);
action.apply(context, true);
final Move move = new Move(action);
context.trial().addMove(move);
context.trial().addInitPlacement();
}
}
break;
case Rotation:
for (final int site : sites)
{
for (int i = 0; i < idPlayers.size(); i++)
{
final int pid = idPlayers.get(i);
final Action action = new ActionSetHiddenRotation(pid, realType, site, level, value);
action.apply(context, true);
final Move move = new Move(action);
context.trial().addMove(move);
context.trial().addInitPlacement();
}
}
break;
case Value:
for (final int site : sites)
{
for (int i = 0; i < idPlayers.size(); i++)
{
final int pid = idPlayers.get(i);
final Action action = new ActionSetHiddenValue(pid, realType, site, level, value);
action.apply(context, true);
final Move move = new Move(action);
context.trial().addMove(move);
context.trial().addInitPlacement();
}
}
break;
default:
break;
}
}
}
}
else
{
if (who >= 1 && who <= numPlayers) // The player has to be a real player.
{
if (dataTypes == null)
{
for (final int site : sites)
{
final Action action = new ActionSetHidden(who, realType, site, level, value);
action.apply(context, true);
final Move move = new Move(action);
context.trial().addMove(move);
context.trial().addInitPlacement();
}
}
else
{
for (final HiddenData hiddenData : dataTypes)
{
switch (hiddenData)
{
case What:
for (final int site : sites)
{
final Action action = new ActionSetHiddenWhat(who, realType, site, level, value);
action.apply(context, true);
final Move move = new Move(action);
context.trial().addMove(move);
context.trial().addInitPlacement();
}
break;
case Who:
for (final int site : sites)
{
final Action action = new ActionSetHiddenWho(who, realType, site, level, value);
action.apply(context, true);
final Move move = new Move(action);
context.trial().addMove(move);
context.trial().addInitPlacement();
}
break;
case State:
for (final int site : sites)
{
final Action action = new ActionSetHiddenState(who, realType, site, level, value);
action.apply(context, true);
final Move move = new Move(action);
context.trial().addMove(move);
context.trial().addInitPlacement();
}
break;
case Count:
for (final int site : sites)
{
final Action action = new ActionSetHiddenCount(who, realType, site, level, value);
action.apply(context, true);
final Move move = new Move(action);
context.trial().addMove(move);
context.trial().addInitPlacement();
}
break;
case Rotation:
for (final int site : sites)
{
final Action action = new ActionSetHiddenRotation(who, realType, site, level, value);
action.apply(context, true);
final Move move = new Move(action);
context.trial().addMove(move);
context.trial().addInitPlacement();
}
break;
case Value:
for (final int site : sites)
{
final Action action = new ActionSetHiddenValue(who, realType, site, level, value);
action.apply(context, true);
final Move move = new Move(action);
context.trial().addMove(move);
context.trial().addInitPlacement();
}
break;
default:
break;
}
}
}
}
}
}
//-------------------------------------------------------------------------
@Override
public long gameFlags(final Game game)
{
long gameFlags = GameType.HiddenInfo;
gameFlags |= SiteType.gameFlags(type);
gameFlags |= region.gameFlags(game);
gameFlags |= levelFn.gameFlags(game);
gameFlags |= valueFn.gameFlags(game);
gameFlags |= whoFn.gameFlags(game);
return gameFlags;
}
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
concepts.or(super.concepts(game));
concepts.or(SiteType.concepts(type));
concepts.or(region.concepts(game));
concepts.or(levelFn.concepts(game));
concepts.or(valueFn.concepts(game));
concepts.or(whoFn.concepts(game));
concepts.set(Concept.HiddenInformation.id(), true);
if (dataTypes == null)
concepts.set(Concept.InvisiblePiece.id(), true);
else
for (final HiddenData dataType : dataTypes)
{
switch (dataType)
{
case What:
concepts.set(Concept.HidePieceType.id(), true);
break;
case Who:
concepts.set(Concept.HidePieceOwner.id(), true);
break;
case Count:
concepts.set(Concept.HidePieceCount.id(), true);
break;
case Value:
concepts.set(Concept.HidePieceValue.id(), true);
break;
case Rotation:
concepts.set(Concept.HidePieceRotation.id(), true);
break;
case State:
concepts.set(Concept.HidePieceState.id(), true);
break;
default:
break;
}
}
return concepts;
}
@Override
public BitSet writesEvalContextRecursive()
{
final BitSet writeEvalContext = new BitSet();
writeEvalContext.or(super.writesEvalContextRecursive());
writeEvalContext.or(region.writesEvalContextRecursive());
writeEvalContext.or(levelFn.writesEvalContextRecursive());
writeEvalContext.or(valueFn.writesEvalContextRecursive());
writeEvalContext.or(whoFn.writesEvalContextRecursive());
return writeEvalContext;
}
@Override
public BitSet readsEvalContextRecursive()
{
final BitSet readEvalContext = new BitSet();
readEvalContext.or(super.readsEvalContextRecursive());
readEvalContext.or(region.readsEvalContextRecursive());
readEvalContext.or(levelFn.readsEvalContextRecursive());
readEvalContext.or(valueFn.readsEvalContextRecursive());
readEvalContext.or(whoFn.readsEvalContextRecursive());
return readEvalContext;
}
@Override
public boolean missingRequirement(final Game game)
{
boolean missingRequirement = false;
missingRequirement |= super.missingRequirement(game);
missingRequirement |= region.missingRequirement(game);
missingRequirement |= levelFn.missingRequirement(game);
missingRequirement |= valueFn.missingRequirement(game);
missingRequirement |= whoFn.missingRequirement(game);
if (roleType != null && !game.requiresTeams())
{
if (RoleType.isTeam(roleType) && !game.requiresTeams())
{
game.addRequirementToReport(
"(set Hidden ...): A roletype corresponding to a team is used but the game has no team: "
+ roleType + ".");
missingRequirement = true;
}
final int indexRoleType = roleType.owner();
if (indexRoleType > game.players().count())
{
game.addRequirementToReport(
"The roletype used in the rule (set Hidden ...) is wrong: " + roleType + ".");
missingRequirement = true;
}
}
return missingRequirement;
}
@Override
public boolean willCrash(final Game game)
{
boolean willCrash = false;
willCrash |= super.willCrash(game);
willCrash |= region.willCrash(game);
willCrash |= levelFn.willCrash(game);
willCrash |= valueFn.willCrash(game);
willCrash |= whoFn.willCrash(game);
return willCrash;
}
@Override
public boolean isStatic()
{
return false;
}
@Override
public void preprocess(final Game game)
{
type = SiteType.use(type, game);
region.preprocess(game);
levelFn.preprocess(game);
valueFn.preprocess(game);
whoFn.preprocess(game);
}
//-------------------------------------------------------------------------
@Override
public String toEnglish(final Game game)
{
String hiddenDataTypeString = "all properties";
if (dataTypes != null)
{
hiddenDataTypeString = "";
for (final HiddenData h : dataTypes)
hiddenDataTypeString += h.name().toLowerCase() + ", ";
hiddenDataTypeString = "properties " + hiddenDataTypeString.substring(0, hiddenDataTypeString.length()-2);
}
String regionString = "";
if (region != null)
regionString = " in region " + region.toEnglish(game);
String levelString = "";
if (levelFn != null)
levelString = " at level " + levelFn.toEnglish(game);
String valueString = "";
if (valueFn != null)
valueString = " to value " + valueFn.toEnglish(game);
String whoString = "";
if (whoFn != null)
whoString = " for Player " + whoFn.toEnglish(game);
else if (roleType != null)
whoString = " for " + roleType.name().toLowerCase();
String typeString = " sites";
if (type != null)
typeString = " " + type.name().toLowerCase() + StringRoutines.getPlural(type.name()) + " ";
return "set the hidden values for " + hiddenDataTypeString + valueString + whoString + " at all" + typeString + regionString + levelString;
}
//-------------------------------------------------------------------------
}
| 14,595 | 28.192 | 141 | java |
Ludii | Ludii-master/Core/src/game/rules/start/set/player/SetAmount.java | package game.rules.start.set.player;
import java.util.BitSet;
import annotations.Hide;
import annotations.Opt;
import game.Game;
import game.functions.ints.IntFunction;
import game.rules.start.StartRule;
import game.types.play.RoleType;
import game.types.state.GameType;
import other.action.state.ActionSetAmount;
import other.concept.Concept;
import other.context.Context;
import other.move.Move;
/**
* Initializes the amount of the players.
*
* @author Eric.Piette
* @remarks This is used mainly for betting games.
*/
@Hide
public final class SetAmount extends StartRule
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/** The players. */
protected final IntFunction playersFn;
/** The amount. */
protected final IntFunction amountFn;
//-------------------------------------------------------------------------
/**
* @param role The roleType of the player.
* @param amount The amount to set.
*/
public SetAmount
(
@Opt final RoleType role,
final IntFunction amount
)
{
if (role != null)
this.playersFn = RoleType.toIntFunction(role);
else
this.playersFn = null;
this.amountFn = amount;
}
//-------------------------------------------------------------------------
@Override
public void eval(final Context context)
{
final int amount = amountFn.eval(context);
int[] players;
if (playersFn != null)
{
players = new int[]
{ playersFn.eval(context) };
}
else
{
players = new int[context.game().players().count()];
for (int i = 0; i < players.length; i++)
players[i] = i + 1;
}
for (int i = 0; i < players.length; i++)
{
final int playerId = players[i];
final Move move;
final ActionSetAmount actionAmount = new ActionSetAmount(playerId, amount);
actionAmount.apply(context, true);
move = new Move(actionAmount);
context.trial().addMove(move);
context.trial().addInitPlacement();
}
}
//-------------------------------------------------------------------------
@Override
public boolean isStatic()
{
return false;
}
@Override
public long gameFlags(final Game game)
{
long gameFlags = GameType.Bet | amountFn.gameFlags(game);
if (playersFn != null)
gameFlags |= playersFn.gameFlags(game);
return gameFlags;
}
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
concepts.or(amountFn.concepts(game));
concepts.set(Concept.InitialAmount.id(), true);
if (playersFn != null)
concepts.or(playersFn.concepts(game));
return concepts;
}
@Override
public BitSet writesEvalContextRecursive()
{
final BitSet writeEvalContext = new BitSet();
writeEvalContext.or(amountFn.writesEvalContextRecursive());
if (playersFn != null)
writeEvalContext.or(playersFn.writesEvalContextRecursive());
return writeEvalContext;
}
@Override
public BitSet readsEvalContextRecursive()
{
final BitSet readEvalContext = new BitSet();
readEvalContext.or(amountFn.readsEvalContextRecursive());
if (playersFn != null)
readEvalContext.or(playersFn.readsEvalContextRecursive());
return readEvalContext;
}
@Override
public void preprocess(final Game game)
{
if (playersFn != null)
playersFn.preprocess(game);
amountFn.preprocess(game);
}
//-------------------------------------------------------------------------
@Override
public String toString()
{
final String str = "initAmount ";
return str;
}
@Override
public boolean isSet()
{
return false;
}
}
| 3,557 | 20.433735 | 78 | java |
Ludii | Ludii-master/Core/src/game/rules/start/set/player/SetScore.java | package game.rules.start.set.player;
import java.util.BitSet;
import annotations.Hide;
import annotations.Opt;
import game.Game;
import game.functions.ints.IntFunction;
import game.rules.start.StartRule;
import game.types.play.RoleType;
import game.types.state.GameType;
import other.action.state.ActionSetScore;
import other.concept.Concept;
import other.context.Context;
import other.move.Move;
/**
* Initialises the score of the players.
*
* @author Eric.Piette
*/
@Hide
public final class SetScore extends StartRule
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/** The players. */
protected final IntFunction players[];
/** The score. */
protected final IntFunction scores[];
/** To init the same score to each player. */
protected final boolean InitSameScoreToEachPlayer;
//-------------------------------------------------------------------------
/**
* @param role The roleType of a player.
* @param score The new score of a player.
*
* @example (set Score P1 100)
*/
public SetScore
(
final RoleType role,
@Opt final IntFunction score
)
{
if (role == RoleType.Each || role == RoleType.All)
{
InitSameScoreToEachPlayer = true;
players = new IntFunction[0];
}
else
{
players = new IntFunction[]
{ RoleType.toIntFunction(role) };
InitSameScoreToEachPlayer = false;
}
scores = new IntFunction[]
{ score };
}
//-------------------------------------------------------------------------
@Override
public void eval(final Context context)
{
// To handle the Each roleType.
if (InitSameScoreToEachPlayer)
{
final int score = scores[0].eval(context);
for (int pid = 1; pid < context.game().players().size(); pid++)
{
final Move move;
final ActionSetScore actionScore = new ActionSetScore(pid, score, Boolean.FALSE);
actionScore.apply(context, true);
move = new Move(actionScore);
context.trial().addMove(move);
context.trial().addInitPlacement();
}
}
else
{
final int length = Math.min(players.length, scores.length);
for (int i = 0; i < length; i++)
{
final int playerId = players[i].eval(context);
final int score = scores[i].eval(context);
final Move move;
final ActionSetScore actionScore = new ActionSetScore(playerId, score, Boolean.FALSE);
actionScore.apply(context, true);
move = new Move(actionScore);
context.trial().addMove(move);
context.trial().addInitPlacement();
}
}
}
//-------------------------------------------------------------------------
@Override
public boolean isStatic()
{
return false;
}
@Override
public long gameFlags(final Game game)
{
return GameType.Score;
}
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
if (players != null)
for (final IntFunction player : players)
concepts.or(player.concepts(game));
if (scores != null)
for (final IntFunction score : scores)
concepts.or(score.concepts(game));
concepts.set(Concept.Scoring.id(), true);
concepts.set(Concept.InitialScore.id(), true);
return concepts;
}
@Override
public BitSet writesEvalContextRecursive()
{
final BitSet writeEvalContext = new BitSet();
if (players != null)
for (final IntFunction player : players)
writeEvalContext.or(player.writesEvalContextRecursive());
if (scores != null)
for (final IntFunction score : scores)
writeEvalContext.or(score.writesEvalContextRecursive());
return writeEvalContext;
}
@Override
public BitSet readsEvalContextRecursive()
{
final BitSet readEvalContext = new BitSet();
if (players != null)
for (final IntFunction player : players)
readEvalContext.or(player.readsEvalContextRecursive());
if (scores != null)
for (final IntFunction score : scores)
readEvalContext.or(score.readsEvalContextRecursive());
return readEvalContext;
}
@Override
public void preprocess(final Game game)
{
// Do nothing.
}
//-------------------------------------------------------------------------
@Override
public String toString()
{
String str = "(initScore ";
final int length = Math.min(players.length, scores.length);
for (int i = 0 ; i < length ; i++)
{
str += players[i] + " = " + scores[i];
if(i != length-1)
str+=",";
}
str+=")";
return str;
}
//-------------------------------------------------------------------------
@Override
public String toEnglish(final Game game)
{
String englishString = "set the scores of the players as follows, ";
for (int i = 0; i < players.length; i++)
englishString += players[i].toEnglish(game) + "=" + scores[i].toEnglish(game) + ", ";
return englishString.substring(0, englishString.length()-2);
}
//-------------------------------------------------------------------------
}
| 4,906 | 23.292079 | 90 | java |
Ludii | Ludii-master/Core/src/game/rules/start/set/players/SetTeam.java | package game.rules.start.set.players;
import java.util.BitSet;
import annotations.Hide;
import game.Game;
import game.functions.ints.IntFunction;
import game.rules.start.StartRule;
import game.types.play.RoleType;
import game.types.state.GameType;
import other.action.state.ActionAddPlayerToTeam;
import other.concept.Concept;
import other.context.Context;
import other.move.Move;
import other.trial.Trial;
/**
* Creates a team.
*
* @author Eric.Piette
*/
@Hide
public final class SetTeam extends StartRule
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/** The index of the team. */
final IntFunction teamIdFn;
/** The index of the players on the team. */
final IntFunction[] players;
/** The roletypes used to check them in the required warning method. */
final RoleType[] roles;
/**
* @param team The index of the team.
* @param roles The roleType of each player on the team.
*/
public SetTeam
(
final IntFunction team,
final RoleType[] roles
)
{
teamIdFn = team;
players = new IntFunction[roles.length];
for (int i = 0; i < roles.length; i++)
{
final RoleType role = roles[i];
players[i] = RoleType.toIntFunction(role);
}
this.roles = roles;
}
@Override
public void eval(final Context context)
{
final int teamId = teamIdFn.eval(context);
for (final IntFunction player : players)
{
final int playerIndex = player.eval(context);
// We ignore all the player indices which are not real players.
if (playerIndex < 1 || playerIndex > context.game().players().count())
continue;
final ActionAddPlayerToTeam actionTeam = new ActionAddPlayerToTeam(teamId, playerIndex);
actionTeam.apply(context, true);
context.trial().addMove(new Move(actionTeam));
context.trial().addInitPlacement();
}
}
//-------------------------------------------------------------------------
@Override
public boolean isStatic()
{
for (final IntFunction player : players)
if (!player.isStatic())
return false;
if (!teamIdFn.isStatic())
return false;
return true;
}
@Override
public long gameFlags(final Game game)
{
long gameFlags = GameType.Team;
for (final IntFunction player : players)
gameFlags |= player.gameFlags(game);
gameFlags |= teamIdFn.gameFlags(game);
return gameFlags;
}
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
concepts.set(Concept.Team.id(), true);
for (final IntFunction player : players)
concepts.or(player.concepts(game));
concepts.or(teamIdFn.concepts(game));
return concepts;
}
@Override
public BitSet writesEvalContextRecursive()
{
final BitSet writeEvalContext = new BitSet();
for (final IntFunction player : players)
writeEvalContext.or(player.writesEvalContextRecursive());
writeEvalContext.or(teamIdFn.writesEvalContextRecursive());
return writeEvalContext;
}
@Override
public BitSet readsEvalContextRecursive()
{
final BitSet readEvalContext = new BitSet();
for (final IntFunction player : players)
readEvalContext.or(player.readsEvalContextRecursive());
readEvalContext.or(teamIdFn.readsEvalContextRecursive());
return readEvalContext;
}
@Override
public void preprocess(final Game game)
{
for (final IntFunction player : players)
player.preprocess(game);
teamIdFn.preprocess(game);
}
@Override
public boolean missingRequirement(final Game game)
{
boolean missingRequirement = false;
// We check if the roles are corrects.
if (roles != null)
{
for(final RoleType role : roles)
{
final int indexOwnerPhase = role.owner();
if (indexOwnerPhase < 1 || indexOwnerPhase > game.players().count())
{
game.addRequirementToReport(
"At least a roletype is wrong in a starting rules (set Team ...): " + role + ".");
missingRequirement = true;
break;
}
}
}
final int teamId = teamIdFn.eval(new Context(game, new Trial(game)));
if (teamId < 1 || teamId > game.players().count())
{
game.addRequirementToReport(
"In (set Team ...), the index of the team is wrong.");
missingRequirement = true;
}
return missingRequirement;
}
//-------------------------------------------------------------------------
@Override
public String toString()
{
final String str = "(SetTeam)";
return str;
}
//-------------------------------------------------------------------------
@Override
public String toEnglish(final Game game)
{
String playersString = "[";
if (players != null)
{
for (final IntFunction i : players)
playersString += "Player " + i.toEnglish(game) + ",";
playersString = playersString.substring(0, playersString.length());
playersString += "]";
}
else if (roles != null)
{
for (final RoleType i : roles)
playersString += i.name() + ",";
playersString = playersString.substring(0, playersString.length());
playersString += "]";
}
return "Set Team " + teamIdFn.toEnglish(game) + " as the following players " + playersString;
}
//-------------------------------------------------------------------------
}
| 5,177 | 23.424528 | 95 | java |
Ludii | Ludii-master/Core/src/game/rules/start/set/remember/SetRememberValue.java | package game.rules.start.set.remember;
import java.util.BitSet;
import annotations.Hide;
import annotations.Name;
import annotations.Opt;
import annotations.Or;
import game.Game;
import game.functions.booleans.BooleanConstant;
import game.functions.booleans.BooleanFunction;
import game.functions.ints.IntFunction;
import game.functions.region.RegionFunction;
import game.rules.start.StartRule;
import game.types.state.GameType;
import gnu.trove.list.array.TIntArrayList;
import other.IntArrayFromRegion;
import other.action.state.ActionRememberValue;
import other.concept.Concept;
import other.context.Context;
import other.move.Move;
/**
* Set a remembered value.
*
* @author Eric.Piette
*/
@Hide
public final class SetRememberValue extends StartRule
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/** The values to remember. */
private final IntArrayFromRegion values;
/** If True we remember it only if not only remembered. */
private final BooleanFunction uniqueFn;
/** The name of the remembering values. */
private final String name;
/**
* @param name The name of the remembering values.
* @param value The value to remember.
* @param regionValue The values to remember.
* @param unique If True we remember a value only if not already remembered
* [False].
*/
public SetRememberValue
(
@Opt final String name,
@Or final IntFunction value,
@Or final RegionFunction regionValue,
@Opt @Name final BooleanFunction unique
)
{
values = new IntArrayFromRegion(value, regionValue);
uniqueFn = (unique == null) ? new BooleanConstant(false) : unique;
this.name = name;
}
@Override
public void eval(final Context context)
{
final int[] valuesToRemember = values.eval(context);
final boolean hasToBeUnique = uniqueFn.eval(context);
for (final int valueToRemember : valuesToRemember)
{
boolean isUnique = true;
if (hasToBeUnique)
{
final TIntArrayList valuesInMemory = (name == null) ? context.state().rememberingValues()
: context.state().mapRememberingValues().get(name);
if (valuesInMemory != null)
for (int i = 0; i < valuesInMemory.size(); i++)
{
final int valueInMemory = valuesInMemory.get(i);
if (valueInMemory == valueToRemember)
{
isUnique = false;
break;
}
}
}
if (!hasToBeUnique || (hasToBeUnique && isUnique))
{
final ActionRememberValue action = new ActionRememberValue(name, valueToRemember);
action.apply(context, true);
context.trial().addMove(new Move(action));
context.trial().addInitPlacement();
}
}
}
//-------------------------------------------------------------------------
@Override
public boolean isStatic()
{
return false;
}
@Override
public long gameFlags(final Game game)
{
final long gameFlags = GameType.RememberingValues | values.gameFlags(game) | uniqueFn.gameFlags(game);
return gameFlags;
}
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
concepts.or(values.concepts(game));
concepts.or(uniqueFn.concepts(game));
concepts.or(super.concepts(game));
concepts.set(Concept.Variable.id(), true);
return concepts;
}
@Override
public BitSet writesEvalContextRecursive()
{
final BitSet writeEvalContext = new BitSet();
writeEvalContext.or(values.writesEvalContextRecursive());
writeEvalContext.or(uniqueFn.writesEvalContextRecursive());
writeEvalContext.or(super.writesEvalContextRecursive());
return writeEvalContext;
}
@Override
public BitSet readsEvalContextRecursive()
{
final BitSet readEvalContext = new BitSet();
readEvalContext.or(values.readsEvalContextRecursive());
readEvalContext.or(uniqueFn.readsEvalContextRecursive());
readEvalContext.or(super.readsEvalContextRecursive());
return readEvalContext;
}
@Override
public void preprocess(final Game game)
{
values.preprocess(game);
uniqueFn.preprocess(game);
}
@Override
public boolean missingRequirement(final Game game)
{
boolean missingRequirement = false;
missingRequirement |= values.missingRequirement(game);
missingRequirement |= uniqueFn.missingRequirement(game);
missingRequirement |= super.missingRequirement(game);
return missingRequirement;
}
//-------------------------------------------------------------------------
@Override
public String toEnglish(final Game game)
{
return "remember the values " + values.toEnglish(game);
}
//-------------------------------------------------------------------------
}
| 4,690 | 26.115607 | 104 | java |
Ludii | Ludii-master/Core/src/game/rules/start/set/sites/SetCost.java | package game.rules.start.set.sites;
import java.util.BitSet;
import annotations.Hide;
import annotations.Opt;
import annotations.Or;
import game.Game;
import game.functions.ints.IntFunction;
import game.functions.region.RegionFunction;
import game.rules.start.StartRule;
import game.types.board.SiteType;
import main.StringRoutines;
import other.IntArrayFromRegion;
import other.action.graph.ActionSetCost;
import other.concept.Concept;
import other.context.Context;
import other.move.Move;
/**
* Sets the cost of graph element(s).
*
* @author Eric.Piette
*/
@Hide
public final class SetCost extends StartRule
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/** The region to set the weight. */
private final IntArrayFromRegion region;
/** The cost. */
private final IntFunction costFn;
/** The type of the graph element. */
private SiteType type;
//-------------------------------------------------------------------------
/**
* @param type The type of the graph element.
* @param site The site to set.
* @param region The region to set.
* @param cost The new cost.
*/
public SetCost
(
final IntFunction cost,
@Opt final SiteType type,
@Or final IntFunction site,
@Or final RegionFunction region
)
{
this.type = type;
this.region = new IntArrayFromRegion(site, region);
costFn = cost;
}
//-------------------------------------------------------------------------
@Override
public void eval(final Context context)
{
final int[] locs = region.eval(context);
for (final int loc : locs)
{
final ActionSetCost actionSetCost = new ActionSetCost(type, loc, costFn.eval(context));
actionSetCost.apply(context, true);
context.trial().addMove(new Move(actionSetCost));
context.trial().addInitPlacement();
}
}
//-------------------------------------------------------------------------
@Override
public boolean isStatic()
{
return false;
}
@Override
public long gameFlags(final Game game)
{
long gameFlags = 0L;
gameFlags |= SiteType.gameFlags(type);
gameFlags |= costFn.gameFlags(game);
return gameFlags;
}
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
if (region != null)
concepts.or(region.concepts(game));
concepts.or(SiteType.concepts(type));
concepts.set(Concept.InitialCost.id(), true);
concepts.or(costFn.concepts(game));
return concepts;
}
@Override
public BitSet writesEvalContextRecursive()
{
final BitSet writeEvalContext = new BitSet();
if (region != null)
writeEvalContext.or(region.writesEvalContextRecursive());
writeEvalContext.or(costFn.writesEvalContextRecursive());
return writeEvalContext;
}
@Override
public BitSet readsEvalContextRecursive()
{
final BitSet readEvalContext = new BitSet();
if (region != null)
readEvalContext.or(region.readsEvalContextRecursive());
readEvalContext.or(costFn.readsEvalContextRecursive());
return readEvalContext;
}
@Override
public void preprocess(final Game game)
{
type = SiteType.use(type, game);
costFn.preprocess(game);
}
//-------------------------------------------------------------------------
@Override
public String toString()
{
final String str = "(setCost)";
return str;
}
@Override
public String toEnglish(final Game game)
{
String englishString = "set the cost of";
if (type != null)
englishString += " " + type.name() + StringRoutines.getPlural(type.name());
else
englishString += " sites";
if (region != null)
englishString += " in " + region.toEnglish(game);
englishString = " to " + costFn.toEnglish(game);
return englishString;
}
}
| 3,773 | 22.296296 | 90 | java |
Ludii | Ludii-master/Core/src/game/rules/start/set/sites/SetCount.java | package game.rules.start.set.sites;
import java.util.BitSet;
import annotations.Hide;
import annotations.Opt;
import annotations.Or;
import game.Game;
import game.functions.ints.IntFunction;
import game.functions.region.RegionFunction;
import game.rules.start.StartRule;
import game.types.board.SiteType;
import game.types.state.GameType;
import main.StringRoutines;
import other.IntArrayFromRegion;
import other.action.BaseAction;
import other.action.state.ActionSetCount;
import other.concept.Concept;
import other.context.Context;
import other.move.Move;
import other.trial.Trial;
/**
* Sets the count at a site or a region.
*
* @author Eric.Piette
*/
@Hide
public final class SetCount extends StartRule
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/** The region to set the count. */
private final IntArrayFromRegion region;
/** The site to modify the count. */
private final IntFunction countFn;
/** Add on Cell/Edge/Vertex. */
protected SiteType type;
//-------------------------------------------------------------------------
/**
* @param count The value of the count.
* @param type The graph element type [default SiteType of the board].
* @param site The site to modify the count.
* @param region The region to modify the count.
*/
public SetCount
(
final IntFunction count,
@Opt final SiteType type,
@Or final IntFunction site,
@Or final RegionFunction region
)
{
this.region = new IntArrayFromRegion(site, region);
countFn = count;
this.type = type;
}
//-------------------------------------------------------------------------
@Override
public void eval(final Context context)
{
if (context.components().length == 1)
{
System.err.println(
"Start Rule (set Count ...): At least a piece has to be defined to set the count of a site");
return;
}
final int what = context.components()[context.components().length - 1].index();
final int[] locs = region.eval(context);
for (final int loc : locs)
{
final BaseAction actionAtomic = new ActionSetCount(type, loc, what, countFn.eval(context));
actionAtomic.apply(context, true);
context.trial().addMove(new Move(actionAtomic));
context.trial().addInitPlacement();
}
}
//-------------------------------------------------------------------------
@Override
public boolean isStatic()
{
return region.isStatic() && countFn.isStatic();
}
@Override
public long gameFlags(final Game game)
{
long gameFlags = GameType.Count;
gameFlags |= SiteType.gameFlags(type);
gameFlags |= region.gameFlags(game);
gameFlags |= countFn.gameFlags(game);
return gameFlags;
}
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
final int maxSiteOnBoard = (type == null)
? game.board().topology().getGraphElements(game.board().defaultSite()).size()
: (type.equals(SiteType.Cell)) ? game.board().topology().getGraphElements(SiteType.Cell).size()
: (type.equals(SiteType.Vertex))
? game.board().topology().getGraphElements(SiteType.Vertex).size()
: game.board().topology().getGraphElements(SiteType.Edge).size();
if (region != null)
{
concepts.or(region.concepts(game));
final int[] sitesRegion = region.eval(new Context(game, new Trial(game)));
for (final int site : sitesRegion)
{
if (site < maxSiteOnBoard)
concepts.set(Concept.PiecesPlacedOnBoard.id(), true);
else
concepts.set(Concept.PiecesPlacedOutsideBoard.id(), true);
}
}
concepts.or(SiteType.concepts(type));
concepts.set(Concept.PieceCount.id(), true);
concepts.or(countFn.concepts(game));
return concepts;
}
@Override
public BitSet writesEvalContextRecursive()
{
final BitSet writeEvalContext = new BitSet();
if (region != null)
writeEvalContext.or(region.writesEvalContextRecursive());
writeEvalContext.or(countFn.writesEvalContextRecursive());
return writeEvalContext;
}
@Override
public BitSet readsEvalContextRecursive()
{
final BitSet readEvalContext = new BitSet();
if (region != null)
readEvalContext.or(region.readsEvalContextRecursive());
readEvalContext.or(countFn.readsEvalContextRecursive());
return readEvalContext;
}
@Override
public void preprocess(final Game game)
{
type = SiteType.use(type, game);
region.preprocess(game);
countFn.preprocess(game);
}
//-------------------------------------------------------------------------
@Override
public String toString()
{
final String str = "(set " + region + " " + countFn + ")";
return str;
}
//-------------------------------------------------------------------------
@Override
public int howManyPlace(final Game game)
{
// region may not yet have been preprocessed, so do that first
region.preprocess(game);
return region.eval(new Context(game, null)).length;
}
@Override
public int count(final Game game)
{
return countFn.eval(new Context(game, new Trial(game)));
}
//-------------------------------------------------------------------------
@Override
public String toEnglish(final Game game)
{
return "set the count of the " + type.name().toLowerCase() + StringRoutines.getPlural(type.name()) + " in " + region.toEnglish(game) + " to " + countFn.toEnglish(game);
}
//-------------------------------------------------------------------------
}
| 5,470 | 25.177033 | 170 | java |
Ludii | Ludii-master/Core/src/game/rules/start/set/sites/SetPhase.java | package game.rules.start.set.sites;
import java.util.BitSet;
import annotations.Hide;
import annotations.Opt;
import annotations.Or;
import game.Game;
import game.functions.ints.IntFunction;
import game.functions.region.RegionFunction;
import game.rules.start.StartRule;
import game.types.board.SiteType;
import other.IntArrayFromRegion;
import other.action.graph.ActionSetPhase;
import other.context.Context;
import other.move.Move;
/**
* Sets the phase of a graph element.
*
* @author Eric.Piette
*/
@Hide
public final class SetPhase extends StartRule
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/** The region to set the pahse. */
private final IntArrayFromRegion region;
/** The phase. */
private final IntFunction phaseFn;
/** The type of the graph element. */
private SiteType type;
//-------------------------------------------------------------------------
/**
* @param type The type of the graph element.
* @param site The site to set.
* @param region The region to set.
* @param phase The new phase.
*/
public SetPhase
(
final IntFunction phase,
@Opt final SiteType type,
@Or final IntFunction site,
@Or final RegionFunction region
)
{
this.type = type;
this.region = new IntArrayFromRegion(site, region);
this.phaseFn = phase;
}
//-------------------------------------------------------------------------
@Override
public void eval(final Context context)
{
final int[] locs = region.eval(context);
for (final int loc : locs)
{
final ActionSetPhase actionSetPhase = new ActionSetPhase(type, loc, phaseFn.eval(context));
actionSetPhase.apply(context, true);
context.trial().addMove(new Move(actionSetPhase));
context.trial().addInitPlacement();
}
}
//-------------------------------------------------------------------------
@Override
public boolean isStatic()
{
return false;
}
@Override
public long gameFlags(final Game game)
{
long gameFlags = SiteType.gameFlags(type);
gameFlags |= phaseFn.gameFlags(game);
return gameFlags;
}
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
if (region != null)
concepts.or(region.concepts(game));
concepts.or(SiteType.concepts(type));
concepts.or(phaseFn.concepts(game));
return concepts;
}
@Override
public BitSet writesEvalContextRecursive()
{
final BitSet writeEvalContext = new BitSet();
if (region != null)
writeEvalContext.or(region.writesEvalContextRecursive());
writeEvalContext.or(phaseFn.writesEvalContextRecursive());
return writeEvalContext;
}
@Override
public BitSet readsEvalContextRecursive()
{
final BitSet readEvalContext = new BitSet();
if (region != null)
readEvalContext.or(region.readsEvalContextRecursive());
readEvalContext.or(phaseFn.readsEvalContextRecursive());
return readEvalContext;
}
@Override
public void preprocess(final Game game)
{
type = SiteType.use(type, game);
phaseFn.preprocess(game);
}
//-------------------------------------------------------------------------
@Override
public String toString()
{
final String str = "(SetPhase)";
return str;
}
}
| 3,267 | 22.681159 | 94 | java |
Ludii | Ludii-master/Core/src/game/rules/start/set/sites/SetSite.java | package game.rules.start.set.sites;
import java.util.BitSet;
import annotations.Hide;
import annotations.Name;
import annotations.Opt;
import game.Game;
import game.equipment.component.Component;
import game.functions.ints.IntFunction;
import game.functions.ints.board.Id;
import game.functions.region.RegionFunction;
import game.rules.start.Start;
import game.rules.start.StartRule;
import game.types.board.SiteType;
import game.types.play.RoleType;
import main.Constants;
import other.concept.Concept;
import other.context.Context;
import other.topology.SiteFinder;
import other.topology.TopologyElement;
import other.trial.Trial;
/**
* Sets a site to the first piece of a player.
*
* @author Eric.Piette
*/
@Hide
public final class SetSite extends StartRule
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/** The role of the owned of the piece to set. */
private final RoleType role;
/** Which cell. */
private final IntFunction siteId;
/** Which coord. */
private final String coord;
/** Cell, Edge or Vertex. */
private SiteType type;
//-----------------Data to fill a region------------------------------------
/** Which cells. */
private final IntFunction[] locationIds;
/** Which region. */
private final RegionFunction region;
/** Which coords. */
private final String[] coords;
//-------------------------------------------------------------------------
/**
* @param role The owner of the site.
* @param type The graph element type [default SiteType of the board].
* @param loc The location to place a piece.
* @param coord The coordinate of the location to place a piece.
*/
public SetSite
(
final RoleType role,
@Opt final SiteType type,
@Opt final IntFunction loc,
@Opt @Name final String coord
)
{
siteId = (loc == null) ? null : loc;
this.coord = (coord == null) ? null : coord;
locationIds = null;
region = null;
coords = null;
this.type = type;
this.role = role;
}
/**
* @param role The roleType.
* @param type The graph element type [default SiteType of the board].
* @param locs The sites to fill.
* @param region The region to fill.
* @param coords The coordinates of the sites to fill.
*/
public SetSite
(
final RoleType role,
@Opt final SiteType type,
@Opt final IntFunction[] locs,
@Opt final RegionFunction region,
@Opt final String[] coords
)
{
locationIds = (locs == null) ? null : locs;
this.region = (region == null) ? null : region;
this.coords = (coords == null) ? null : coords;
coord = null;
siteId = null;
this.type = type;
this.role = role;
}
//-------------------------------------------------------------------------
@Override
public void eval(final Context context)
{
int what = new Id(null, role).eval(context);
if (role == RoleType.Neutral)
{
for (int i = 1; i < context.components().length; i++)
{
final Component component = context.components()[i];
if (component.owner() == 0)
{
what = component.index();
break;
}
}
}
else if (role == RoleType.Shared || role == RoleType.All)
{
for (int i = 1; i < context.components().length; i++)
{
final Component component = context.components()[i];
if (component.owner() == context.game().players().size())
{
what = component.index();
break;
}
}
// if (context.game().usesUnionFindAdjacent())
// {
// final int[] locs = region.eval(context).sites();
// for (final int loc : locs)
// {
// UnionFindD.evalSetGT(context, loc, role, AbsoluteDirection.Adjacent);
// }
// }
// else if (context.game().usesUnionFindOrthogonal())
// {
// final int[] locs = region.eval(context).sites();
// for (final int loc : locs)
// {
// UnionFindD.evalSetGT(context, loc, role, AbsoluteDirection.Orthogonal);
// }
// }
}
else
{
boolean find = false;
for (int i = 1; i < context.components().length; i++)
{
final Component component = context.components()[i];
if (component.index() == what)
{
find = true;
break;
}
}
if (!find)
what = Constants.UNDEFINED;
}
// If we try to set something else than a player piece, the starting rule do
// nothing.
if (what < 1 || what >= context.components().length)
{
System.err.println("Warning: A piece which not exist is trying to be set in the starting rule.");
return;
}
// Check if the goal is to fill a region
if (locationIds != null || region != null || coords != null)
{
evalFill(context, what);
}
else
{
if (siteId == null && coord == null)
return;
int site = Constants.UNDEFINED;
if (coord != null)
{
final TopologyElement element = SiteFinder.find(context.board(), coord, type);
if (element == null)
throw new RuntimeException("In the starting rules (place) the coordinate " + coord + " not found.");
site = element.index();
}
else if (siteId != null)
{
site = siteId.eval(context);
}
Start.placePieces(context, site, what, 1, Constants.UNDEFINED, Constants.UNDEFINED, Constants.UNDEFINED,
false, type);
}
}
/**
* To eval the place ludeme for a region/list of sites.
*
* @param context The context of the game.
*/
private void evalFill(final Context context, final int what)
{
// place with coords
if (coords != null)
{
for (final String coordinate : coords)
{
final TopologyElement element = SiteFinder.find(context.board(), coordinate, type);
if (element == null)
{
System.out.println("** SetSite.evalFill(): Coord " + coordinate + " not found.");
}
else
{
Start.placePieces(context, element.index(), what, 1, Constants.UNDEFINED, Constants.UNDEFINED,
Constants.UNDEFINED,
false, type);
}
}
}
// place with regions
else if (region != null)
{
final int[] locs = region.eval(context).sites();
for (final int loc : locs)
{
Start.placePieces(context, loc, what, 1, Constants.UNDEFINED, Constants.UNDEFINED, Constants.UNDEFINED,
false, type);
}
}
// place with locs
else if (locationIds != null)
{
for (final IntFunction loc : locationIds)
{
Start.placePieces(context, loc.eval(context), what, 1, Constants.UNDEFINED, Constants.UNDEFINED,
Constants.UNDEFINED, false,
type);
}
}
}
//-------------------------------------------------------------------------
/**
* @return posn
*/
public IntFunction posn()
{
return siteId;
}
@Override
public int count(final Game game)
{
return 1;
}
@Override
public int howManyPlace(final Game game)
{
if (region != null)
return region.eval(new Context(game, null)).sites().length;
if (locationIds != null)
return locationIds.length;
else
return 1;
}
//-------------------------------------------------------------------------
@Override
public boolean isStatic()
{
return false;
}
@Override
public long gameFlags(final Game game)
{
long flags = 0L;
flags |= SiteType.gameFlags(type);
if (siteId != null)
flags = siteId.gameFlags(game);
if (region != null)
flags |= region.gameFlags(game);
return flags;
}
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
concepts.or(super.concepts(game));
final int maxSiteOnBoard = (type == null)
? game.board().topology().getGraphElements(game.board().defaultSite()).size()
: (type.equals(SiteType.Cell)) ? game.board().topology().getGraphElements(SiteType.Cell).size()
: (type.equals(SiteType.Vertex))
? game.board().topology().getGraphElements(SiteType.Vertex).size()
: game.board().topology().getGraphElements(SiteType.Edge).size();
if (siteId != null)
{
concepts.or(siteId.concepts(game));
final int site = siteId.eval(new Context(game, new Trial(game)));
if (site < maxSiteOnBoard)
concepts.set(Concept.PiecesPlacedOnBoard.id(), true);
else
concepts.set(Concept.PiecesPlacedOutsideBoard.id(), true);
}
if (locationIds != null)
for (final IntFunction loc : locationIds)
{
concepts.or(loc.concepts(game));
final int site = loc.eval(new Context(game, new Trial(game)));
if (site < maxSiteOnBoard)
concepts.set(Concept.PiecesPlacedOnBoard.id(), true);
else
concepts.set(Concept.PiecesPlacedOutsideBoard.id(), true);
}
if (region != null)
{
concepts.or(region.concepts(game));
final int[] sitesRegion = region.eval(new Context(game, new Trial(game))).sites();
for (final int site : sitesRegion)
{
if (site < maxSiteOnBoard)
concepts.set(Concept.PiecesPlacedOnBoard.id(), true);
else
concepts.set(Concept.PiecesPlacedOutsideBoard.id(), true);
}
}
if (coords != null)
concepts.set(Concept.PiecesPlacedOnBoard.id(), true);
concepts.or(SiteType.concepts(type));
return concepts;
}
@Override
public BitSet writesEvalContextRecursive()
{
final BitSet writeEvalContext = new BitSet();
if (region != null)
writeEvalContext.or(region.writesEvalContextRecursive());
if (locationIds != null)
for (final IntFunction loc : locationIds)
writeEvalContext.or(loc.writesEvalContextRecursive());
if (siteId != null)
writeEvalContext.or(siteId.writesEvalContextRecursive());
return writeEvalContext;
}
@Override
public BitSet readsEvalContextRecursive()
{
final BitSet readEvalContext = new BitSet();
if (region != null)
readEvalContext.or(region.readsEvalContextRecursive());
if (locationIds != null)
for (final IntFunction loc : locationIds)
readEvalContext.or(loc.readsEvalContextRecursive());
if (siteId != null)
readEvalContext.or(siteId.readsEvalContextRecursive());
return readEvalContext;
}
@Override
public void preprocess(final Game game)
{
type = SiteType.use(type, game);
if (siteId != null)
siteId.preprocess(game);
if (locationIds != null)
for (final IntFunction locationId : locationIds)
locationId.preprocess(game);
if (region != null)
region.preprocess(game);
}
//-------------------------------------------------------------------------
@Override
public String toString()
{
final String str = "(set)";
return str;
}
//-------------------------------------------------------------------------
@Override
public String toEnglish(final Game game)
{
String regionString = "";
if (coord != null)
{
regionString = type.name().toLowerCase() + " " + coord;
}
else if (siteId != null)
{
regionString = type.name().toLowerCase() + " " + siteId.toEnglish(game);
}
else if (locationIds != null)
{
regionString = "[";
for (final IntFunction i : locationIds)
regionString += i.toEnglish(game) + ",";
regionString = regionString.substring(0,regionString.length()-1) + "]";
}
else if (coords != null)
{
regionString = "[";
for (final String s : coords)
regionString += s + ",";
regionString = regionString.substring(0,regionString.length()-1) + "]";
}
else if (region != null)
{
regionString = region.toEnglish(game);
}
return "set " + regionString + " to the first piece of " + role.name();
}
//-------------------------------------------------------------------------
}
| 11,451 | 24.114035 | 107 | java |
Ludii | Ludii-master/Core/src/game/rules/start/split/Split.java | package game.rules.start.split;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.List;
import game.Game;
import game.equipment.component.Component;
import game.equipment.container.Container;
import game.equipment.container.other.Deck;
import game.rules.start.StartRule;
import game.types.board.SiteType;
import game.types.state.GameType;
import main.Constants;
import other.action.Action;
import other.action.move.move.ActionMove;
import other.concept.Concept;
import other.context.Context;
import other.move.Move;
import other.state.stacking.BaseContainerStateStacking;
/**
* Splits a deck of cards.
*
* @author Eric.Piette and cambolbro
*
* @remarks This ludeme is used for card games.
*/
public final class Split extends StartRule
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/**
* @param type The type of object to split.
* @example (split Deck)
*/
public Split(final SplitType type)
{
// Nothing to do here until we have many types.
switch (type)
{
case Deck:
break;
default:
break;
}
}
//-------------------------------------------------------------------------
@Override
public void eval(final Context context)
{
// If no deck nothing to do.
if (context.game().handDeck().isEmpty())
return;
final List<Integer> handIndex = new ArrayList<>();
for (final Container c : context.containers())
if (c.isHand() && !c.isDeck() && !c.isDice())
handIndex.add(Integer.valueOf(context.sitesFrom()[c.index()]));
// If each player does not have a hand, nothing to do.
if (handIndex.size() != context.game().players().count())
return;
final Deck deck = context.game().handDeck().get(0);
final BaseContainerStateStacking cs = (BaseContainerStateStacking) context.containerState(deck.index());
final int indexSiteDeck = context.sitesFrom()[deck.index()];
final int sizeDeck = cs.sizeStackCell(indexSiteDeck);
int hand = 0;
for (int indexCard = 0; indexCard < sizeDeck; indexCard++)
{
final Action actionAtomic = ActionMove.construct(SiteType.Cell, indexSiteDeck, 0, SiteType.Cell,
handIndex.get(hand).intValue(), Constants.OFF, Constants.OFF, Constants.OFF, Constants.OFF, false);
actionAtomic.apply(context, true);
context.trial().addMove(new Move(actionAtomic));
context.trial().addInitPlacement();
if (hand == context.game().players().count() - 1)
hand = 0;
else
hand++;
}
}
//-------------------------------------------------------------------------
@Override
public boolean isStatic()
{
return true;
}
@Override
public long gameFlags(final Game game)
{
return GameType.Card;
}
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
concepts.set(Concept.Card.id(), true);
return concepts;
}
@Override
public BitSet writesEvalContextRecursive()
{
final BitSet writeEvalContext = new BitSet();
return writeEvalContext;
}
@Override
public BitSet readsEvalContextRecursive()
{
final BitSet readEvalContext = new BitSet();
return readEvalContext;
}
@Override
public boolean missingRequirement(final Game game)
{
boolean missingRequirement = false;
boolean gameHasCard = false;
for (int i = 1; i < game.equipment().components().length; i++)
{
final Component component = game.equipment().components()[i];
if (component.isCard())
{
gameHasCard = true;
break;
}
}
if (!gameHasCard)
{
game.addRequirementToReport("The ludeme (split Deck ...) is used but the equipment has no cards.");
missingRequirement = true;
}
return missingRequirement;
}
@Override
public void preprocess(final Game game)
{
// Do nothing
}
//-------------------------------------------------------------------------
@Override
public String toString()
{
final String str = "(splitDeck)";
return str;
}
}
| 3,947 | 22.927273 | 106 | java |
Ludii | Ludii-master/Core/src/game/rules/start/split/SplitType.java | package game.rules.start.split;
/**
* Defines properties that can be split in the starting rules.
*/
public enum SplitType
{
/** To split a deck of cards. */
Deck,
}
| 171 | 14.636364 | 62 | java |
Ludii | Ludii-master/Core/src/game/rules/start/split/package-info.java | /**
* The {\tt (split ...)} start `super' ludeme to split objects between players.
*/
package game.rules.start.split;
| 120 | 23.2 | 79 | java |
Ludii | Ludii-master/Core/src/game/types/dummy.java | package game.types;
/**
* Hey, dummy, this is a dummy file to trick JavaDoc into picking up this package's package-info.java.
*/
public abstract class dummy
{
// Intentionally blank
}
| 188 | 17.9 | 102 | java |
Ludii | Ludii-master/Core/src/game/types/package-info.java | /**
* @chapter This package defines various types used to specify the behaviour of ludemes.
* Types are constant values denoted in {\tt UpperCamelCase} syntax.
*
* @section These core types define possible combinations of options for various ludemes.
*/
package game.types;
| 289 | 35.25 | 89 | java |
Ludii | Ludii-master/Core/src/game/types/board/BasisType.java | package game.types.board;
/**
* Defines known tiling types for boards.
*
* @author cambolbro
*/
public enum BasisType
{
/** No tiling; custom graph. */
NoBasis,
//--------------- Regular ---------------
/** Triangular tiling. */
Triangular,
/** Square tiling. */
Square,
/** Hexagonal tiling. */
Hexagonal,
//--------------- Semi-regular ---------------
/** Semi-regular tiling made up of hexagons surrounded by triangles. */
T33336,
/** Semi-regular tiling made up of alternating rows of squares and triangles. */
T33344,
/** Semi-regular tiling made up of squares and pairs of triangles. */
T33434,
/** Rhombitrihexahedral tiling (e.g. Kensington). */
T3464,
/** Semi-regular tiling 3.6.3.6 made up of hexagons with interstitial triangles. */
T3636,
/** Semi-regular tiling made up of squares, hexagons and dodecagons. */
T4612,
/** Semi-regular tiling 4.8.8. made up of octagons with interstitial squares. */
T488,
/** Semi-regular tiling made up of triangles and dodecagons. */
T31212,
//--------------- Exotic ---------------
///** Pentagonal tiling p4 (442). */
//P4_442,
/** Tiling 3.3.3.3.3.3,3.3.4.3.4. */
T333333_33434,
//--------------- 3D ---------------
/** Square pyramidal tiling (e.g. Shibumi). */
SquarePyramidal,
/** Hexagonal pyramidal tiling. */
HexagonalPyramidal,
//--------------- Concentric ---------------
/** Concentric tiling (e.g. Morris boards, wheel boards, ...). */
Concentric,
//--------------- Circular ---------------
/** Circular tiling (e.g. Round Merels). */
Circle,
/** Spiral tiling (e.g. Mehen). */
Spiral,
//--------------- Mathematical ---------------
/** Tiling derived from the weak dual of a graph. */
Dual,
/** Brick tiling using 1x2 rectangular brick tiles. */
Brick,
/** Mesh formed by random spread of points within an outline shape. */
Mesh,
//--------------- Specialised ---------------
/** Morris tiling with concentric square rings and empty centre. */
Morris,
/** Tiling on a square grid based on Celtic knotwork. */
Celtic,
/** Quadhex board consisting of a hexagon tessellated by quadrilaterals (e.g. Three Player Chess). */
QuadHex,
;
//-------------------------------------------------------------------------
// public boolean isRegular()
// {
// return this == Triangular || this == Square || this == Hexagonal;
// }
//-------------------------------------------------------------------------
}
| 2,483 | 21.378378 | 102 | java |
Ludii | Ludii-master/Core/src/game/types/board/HiddenData.java | package game.types.board;
/**
* Defines possible data to be hidden.
*
* @author Eric.Piette
*/
public enum HiddenData
{
/** The id of the component on the location is hidden. */
What,
/** The owner of the component of the location is hidden. */
Who,
/** The local state of the location is hidden. */
State,
/** The number of components on the location is hidden. */
Count,
/** The rotation of the component on the location is hidden. */
Rotation,
/** The piece value of the component on the location is hidden. */
Value,
}
| 546 | 18.535714 | 67 | java |
Ludii | Ludii-master/Core/src/game/types/board/LandmarkType.java | package game.types.board;
/**
* Defines certain landmarks that can be used to specify individual sites on the board.
*
* @author Eric.Piette
*/
public enum LandmarkType
{
/** The central site of the board. */
CentreSite,
/** The site that is furthest to the left. */
LeftSite,
/** The site that is furthest to the right */
RightSite,
/** The site that is furthest to the top. */
Topsite,
/** The site that is furthest to the bottom. */
BottomSite,
/** The first site indexed in the graph. */
FirstSite,
/** The last site indexed in the graph. */
LastSite,
} | 589 | 18.666667 | 87 | java |
Ludii | Ludii-master/Core/src/game/types/board/PuzzleElementType.java | package game.types.board;
/**
* Defines the possible types of variables that can be used in deduction
* puzzles.
*
* @author Eric.Piette
*/
public enum PuzzleElementType
{
/** A variable corresponding to a cell. */
Cell,
/** A variable corresponding to an edge. */
Edge,
/** A variable corresponding to a vertex. */
Vertex,
/** A variable corresponding to a hint. */
Hint,
;
/**
* @param puzzleElement The puzzle type to convert.
* @return The corresponding SiteType.
*/
public static SiteType convert(final PuzzleElementType puzzleElement)
{
switch (puzzleElement)
{
case Cell:
return SiteType.Cell;
case Edge:
return SiteType.Edge;
case Vertex:
return SiteType.Vertex;
default:
return null;
}
}
}
| 760 | 16.697674 | 72 | java |
Ludii | Ludii-master/Core/src/game/types/board/RegionTypeDynamic.java | package game.types.board;
/**
* Defines regions which can change during play.
*
* @author cambolbro and Eric.Piette
*/
public enum RegionTypeDynamic
{
/** All the empty sites of the current state. */
Empty,
/** All the occupied sites of the current state. */
NotEmpty,
/** All the sites occupied by a piece of the mover. */
Own,
/** All the sites not occupied by a piece of the mover. */
NotOwn,
/** All the sites occupied by a piece of an enemy of the mover. */
Enemy,
/** All the sites empty or occupied by a {\tt Neutral} piece. */
NotEnemy,
}
| 576 | 19.607143 | 67 | java |
Ludii | Ludii-master/Core/src/game/types/board/RegionTypeStatic.java | package game.types.board;
/**
* Defines known (predefined) regions of the board.
*
* @author Eric.Piette and cambolbro
*/
public enum RegionTypeStatic
{
/** Row areas. */
Rows,
/** Column areas. */
Columns,
/** All direction areas. */
AllDirections,
/** Hint areas. */
HintRegions,
/** Layers areas. */
Layers,
/** diagonal areas. */
Diagonals,
/** SubGrid areas. */
SubGrids,
/** Region areas. */
Regions,
/** Vertex areas. */
Vertices,
/** Corner areas. */
Corners,
/** Side areas. */
Sides,
/** Side areas that are not corners. */
SidesNoCorners,
/** All site areas. */
AllSites,
/** Touching areas. */
Touching
}
| 658 | 15.897436 | 51 | java |
Ludii | Ludii-master/Core/src/game/types/board/RelationType.java | package game.types.board;
import game.util.directions.AbsoluteDirection;
/**
* Defines the possible relation types between graph elements.
*
* @author Eric.Piette
*/
public enum RelationType
{
/** Orthogonal relation. */
Orthogonal,
/** Diagonal relation. */
Diagonal,
/** Diagonal-off relation. */
OffDiagonal,
/** Adjacent relation. */
Adjacent,
/** Any relation. */
All;
//-------------------------------------------------------------------------
/**
* @param relation The relation to convert.
* @return The equivalent in absolute direction.
*/
public static AbsoluteDirection convert(final RelationType relation)
{
switch (relation)
{
case Adjacent:
return AbsoluteDirection.Adjacent;
case Diagonal:
return AbsoluteDirection.Diagonal;
case All:
return AbsoluteDirection.All;
case OffDiagonal:
return AbsoluteDirection.OffDiagonal;
case Orthogonal:
return AbsoluteDirection.Orthogonal;
}
// We should never reach that except if we forget some codes.
throw new IllegalArgumentException("RelationType.convert(): a RelationType is not implemented.");
}
//-------------------------------------------------------------------------
/**
* Returns true if this is equal to or a subset of rA
*
* @param rA
* @return True of this is super set of the entry.
*/
public boolean supersetOf(final RelationType rA)
{
if (this.equals(rA))
return true;
if (this.equals(All))
return true;
if (this.equals(Adjacent) && rA.equals(Orthogonal))
return true;
return false;
}
}
| 1,570 | 20.22973 | 99 | java |
Ludii | Ludii-master/Core/src/game/types/board/ShapeType.java | package game.types.board;
/**
* Defines shape types for known board shapes.
*
* @author Eric.Piette and cambolbro
*/
public enum ShapeType
{
/** No defined board shape. */
NoShape,
/** Custom board shape defined by the user. */
Custom,
/** Square board shape. */
Square,
/** Rectangular board shape. */
Rectangle,
/** Triangular board shape. */
Triangle,
/** Hexagonal board shape. */
Hexagon,
/** Cross board shape. */
Cross,
/** Diamond board shape. */
Diamond,
/** Diamond board shape extended vertically. */
Prism,
/** General quadrilateral board shape. */
Quadrilateral,
/** 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,
/** Regular polygon with sides of the same length. */
Regular,
/** General polygon. */
Polygon,
;
}
| 1,166 | 15.208333 | 108 | java |
Ludii | Ludii-master/Core/src/game/types/board/SiteType.java | package game.types.board;
import java.util.BitSet;
import game.Game;
import game.types.state.GameType;
import other.concept.Concept;
/**
* Defines the element types that make up each graph.
*
* @author Eric.Piette and Matthew Stephenson and cambolbro
*/
public enum SiteType
{
/** Graph vertex. */
Vertex,
/** Graph edge. */
Edge,
/** Graph cell/face. */
Cell;
//-------------------------------------------------------------------------
/**
* @param preferred The graph element type.
* @param game The game.
* @return Graph element type to use, based on a preferred type (using game
* settings if null).
*/
public static SiteType use
(
final SiteType preferred, final Game game
)
{
if (preferred != null)
return preferred;
return game.board().defaultSite();
}
/**
* @param type The graph element type.
* @return The corresponding flags to return for the siteType.
*/
public static long gameFlags
(
final SiteType type
)
{
long gameFlags = 0l;
if (type != null)
{
switch (type)
{
case Vertex: gameFlags |= (GameType.Vertex | GameType.Graph); break;
case Edge: gameFlags |= (GameType.Edge | GameType.Graph); break;
case Cell: gameFlags |= GameType.Cell; break;
}
}
return gameFlags;
}
/**
* @param type The graph element type.
* @return The corresponding flags to return for the siteType.
*/
public static BitSet concepts
(
final SiteType type
)
{
final BitSet concepts = new BitSet();
if (type != null)
{
switch (type)
{
case Vertex: concepts.set(Concept.Vertex.id(), true); break;
case Edge: concepts.set(Concept.Edge.id(), true); break;
case Cell: concepts.set(Concept.Cell.id(), true); break;
}
}
return concepts;
}
}
| 1,799 | 18.78022 | 76 | java |
Ludii | Ludii-master/Core/src/game/types/board/StepType.java | package game.types.board;
/**
* Defines possible ``turtle steps'' for describing walks through adjacent sites.
*
* @author cambolbro and Eric.Piette
*
* @remarks For example, the movement of a Chess knight may be described as {\tt (walkToSites \{ \{F F R F\} \{F F L F\} \})}. Please note that a walk cannot leave the playing area and return.
*/
public enum StepType
{
/** Forward a step. */
F,
/** Turn left a step. */
L,
/** Turn right a step. */
R,
}
| 473 | 21.571429 | 192 | java |
Ludii | Ludii-master/Core/src/game/types/board/StoreType.java | package game.types.board;
/**
* Defines the different stores for a mancala board.
*
* @author Eric.Piette
*/
public enum StoreType
{
/** No store. */
None,
/** Outer store. */
Outer,
/** Inner store. */
Inner;
}
| 226 | 10.947368 | 52 | java |
Ludii | Ludii-master/Core/src/game/types/board/TilingBoardlessType.java | package game.types.board;
/**
* Defines supported tiling types for boardless games.
*
* @author Eric.Piette
*/
public enum TilingBoardlessType
{
/** Square tiling. */
Square,
/** Triangular tiling. */
Triangular,
/** Hexagonal tiling. */
Hexagonal,
;
}
| 268 | 12.45 | 54 | java |
Ludii | Ludii-master/Core/src/game/types/board/TrackStepType.java | package game.types.board;
//import game.functions.trackStep.TrackStep;
/**
* Defines special steps for describing tracks on the board.
*
* @author cambolbro
*
* @remarks For example, a track may be defined as { 0 N Repeat E End }.
*/
public enum TrackStepType
{
/** Off the track. */
Off,
/** End of the track. */
End,
/** Repeat stepping in the current direction. */
Repeat;
// public TrackStep eval()
// {
// return null;
// }
}
| 454 | 15.25 | 72 | java |
Ludii | Ludii-master/Core/src/game/types/board/TrackType.java | package game.types.board;
/**
* Defines that a track is used.
*
* @author Eric.Piette
*/
public enum TrackType
{
/** Track. */
Track
}
| 143 | 10.076923 | 32 | java |
Ludii | Ludii-master/Core/src/game/types/board/package-info.java | /**
* Board types are constant values for specifying various aspects of the board and its constituent graph elements.
*/
package game.types.board;
| 149 | 29 | 114 | java |
Ludii | Ludii-master/Core/src/game/types/component/CardType.java | package game.types.component;
/**
* Defines possible rank values of cards.
*
* @author Eric.Piette and cambolbro
*/
public enum CardType
{
/** Joker rank. */
Joker( 0, "?"),
/** Ace rank. */
Ace( 1, "A"),
/** Two rank. */
Two( 2, "2"),
/** Three rank. */
Three( 3, "3"),
/** Four rank. */
Four( 4, "4"),
/** Five rank. */
Five( 5, "5"),
/** Six rank. */
Six( 6, "6"),
/** Seven rank. */
Seven( 7, "7"),
/** Eight rank. */
Eight( 8, "8"),
/** Nine rank. */
Nine( 9, "9"),
/** Ten rank. */
Ten( 10, "10"),
/** Jack rank. */
Jack( 10, "J"),
/** Queen rank. */
Queen(10, "Q"),
/** King rank. */
King( 10, "K"),
;
//-------------------------------------------------------------------------
private int number; // number shown on the card, if any
private String label; // common name of the card
//-------------------------------------------------------------------------
CardType(final int number, final String label)
{
this.number = number;
this.label = label;
}
//-------------------------------------------------------------------------
/**
* @return The common name of the card.
*/
public String label()
{
return label;
}
/**
* @return The default number shown on the card, if any.
*/
public int number()
{
return number;
}
//-------------------------------------------------------------------------
/**
* @return True if the card is royal.
*/
public boolean isRoyal()
{
boolean result = this == Jack || this == Queen || this == King;
result = result || (this == Joker); // add Joker so picture is shown correctly
return result;
}
//-------------------------------------------------------------------------
}
| 1,757 | 16.405941 | 81 | java |
Ludii | Ludii-master/Core/src/game/types/component/DealableType.java | package game.types.component;
/**
* Specifies which types of components can be dealt.
*
* @author Eric.Piette
*/
public enum DealableType
{
/** Domino component. */
Dominoes,
/** Card component. */
Cards,
}
| 219 | 12.75 | 52 | java |
Ludii | Ludii-master/Core/src/game/types/component/SuitType.java | package game.types.component;
import java.util.BitSet;
import game.Game;
import metadata.graphics.GraphicsItem;
/**
* Defines the possible suit types of cards.
*
* @author Eric.Piette and cambolbro
*/
public enum SuitType implements GraphicsItem
{
/** Club suit. */
Clubs(1),
/** Spade suit. */
Spades(2),
/** Diamond suit. */
Diamonds(3),
/** Heart suit. */
Hearts(4),
;
/**
* The corresponding value.
*/
public final int value;
private SuitType(final int value)
{
this.value = value;
}
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
return concepts;
}
@Override
public long gameFlags(final Game game)
{
final long gameFlags = 0l;
return gameFlags;
}
@Override
public boolean needRedraw()
{
return false;
}
}
| 826 | 13.258621 | 44 | java |
Ludii | Ludii-master/Core/src/game/types/component/package-info.java | /**
* Component types are constant values for specifying various aspects of components in the game.
* These can include pieces, cards, dice, and so on.
*/
package game.types.component;
| 188 | 30.5 | 96 | java |
Ludii | Ludii-master/Core/src/game/types/play/GravityType.java | package game.types.play;
/**
* Defines the possible types of gravity that can occur in a game.
*
* @author Eric.Piette
*/
public enum GravityType
{
/** Gravity corresponding to pieces dropping in a pyramidal tilling. */
PyramidalDrop,
}
| 245 | 17.923077 | 72 | java |
Ludii | Ludii-master/Core/src/game/types/play/ModeType.java | package game.types.play;
/**
* Defines the possible modes of play.
*
* @author cambolbro and Eric.Piette
*/
public enum ModeType
{
/** Players alternate making discrete moves. */
Alternating,
/** Players move at the same time. */
Simultaneous,
/** Simulation game */
Simulation,
}
| 306 | 15.157895 | 49 | java |
Ludii | Ludii-master/Core/src/game/types/play/PassEndType.java | package game.types.play;
/**
* Defines the possible types of ending results if all players are passed their
* turn.
*
* @author Eric.Piette
*/
public enum PassEndType
{
/** The game in a draw. */
Draw,
/** The game does not end. */
NoEnd
}
| 252 | 13.882353 | 79 | java |
Ludii | Ludii-master/Core/src/game/types/play/PinType.java | package game.types.play;
/**
* Defines the possible types of pin that can occur in a game.
*
* @author Eric.Piette
*/
public enum PinType
{
/**
* For Shibumi games, that's not allowed to remove pieces if they are supported
* by more than 1 piece.
*/
SupportMultiple,
}
| 284 | 15.764706 | 80 | java |
Ludii | Ludii-master/Core/src/game/types/play/PrevType.java | package game.types.play;
/**
* Defines the possible previous states to refer to.
*
* @author Eric.Piette
*/
public enum PrevType
{
/** The state corresponding to the previous move. */
Mover,
/** The state corresponding to the previous turn. */
MoverLastTurn
;
}
| 274 | 15.176471 | 53 | java |
Ludii | Ludii-master/Core/src/game/types/play/RepetitionType.java | package game.types.play;
/**
* Defines the possible types of repetition that can occur in a game.
*
* @author cambolbro
*/
public enum RepetitionType
{
/** Situational State repeated within a turn. */
SituationalInTurn,
/** Positional State repeated within a turn. */
PositionalInTurn,
/** State repeated within a game (pieces on the board only). */
Positional,
/** State repeated within a game (all data in the state). */
Situational
}
| 457 | 19.818182 | 69 | java |
Ludii | Ludii-master/Core/src/game/types/play/ResultType.java | package game.types.play;
/**
* Defines expected outcomes for each game.
*
* @author cambolbro
*
* @remarks Tie means that everybody wins. Draw means that nobody wins.
*/
public enum ResultType
{
/** Somebody wins. */
Win,
/** Somebody loses. */
Loss,
/** Nobody wins. */
Draw,
/** Everybody wins. */
Tie,
/** Game abandoned, typically for being too long. */
Abandon,
/** Game stopped due to run-time error. */
Crash,
}
| 450 | 14.033333 | 71 | java |
Ludii | Ludii-master/Core/src/game/types/play/RoleType.java | package game.types.play;
import game.functions.ints.IntConstant;
import game.functions.ints.IntFunction;
import game.functions.ints.board.Id;
import main.Constants;
/**
* Defines the possible role types of the players in a game.
*
* @author cambolbro and Eric.Piette
*
* @remarks Each player will have at least one, and possibly more than one, role type in a game.
* For example, players may belong to permanent or temporary teams, or may be denoted
* as the {\tt Ally} or {\tt Enemy} of a given player, etc.
*/
public enum RoleType
{
/** Neutral role, owned by nobody. */
Neutral(0),
/** Player 1. */
P1(1),
/** Player 2. */
P2(2),
/** Player 3. */
P3(3),
/** Player 4. */
P4(4),
/** Player 5. */
P5(5),
/** Player 6. */
P6(6),
/** Player 7. */
P7(7),
/** Player 8. */
P8(8),
/** Player 9. */
P9(9),
/** Player 10. */
P10(10),
/** Player 11. */
P11(11),
/** Player 12. */
P12(12),
/** Player 13. */
P13(13),
/** Player 14. */
P14(14),
/** Player 15. */
P15(15),
/** Player 16. */
P16(16),
/** Team 1 (index 1). */
Team1(1),
/** Team 2 (index 2). */
Team2(2),
/** Team 3 (index 3). */
Team3(3),
/** Team 4 (index 4). */
Team4(4),
/** Team 5 (index 5). */
Team5(5),
/** Team 6 (index 6). */
Team6(6),
/** Team 7 (index 7). */
Team7(7),
/** Team 8 (index 8). */
Team8(8),
/** Team 9 (index 9). */
Team9(9),
/** Team 10 (index 10). */
Team10(10),
/** Team 11 (index 11). */
Team11(11),
/** Team 12 (index 12). */
Team12(12),
/** Team 13 (index 13). */
Team13(13),
/** Team 14 (index 14). */
Team14(14),
/** Team 15 (index 15). */
Team15(15),
/** Team 16 (index 16). */
Team16(16),
/** Team of the mover (index Mover). */
TeamMover(Constants.NOBODY),
/** Applies to each player (for iteration), e.g. same piece owned by each player */
Each(Constants.NOBODY),
/** Shared role, shared by all players. */
Shared(Constants.NOBODY),
/** All players. */
All(Constants.NOBODY),
/** Player who is moving. */
Mover(Constants.NOBODY),
/** Player who is moving next turn. */
Next(Constants.NOBODY),
/** Player who made the previous decision move. */
Prev(Constants.NOBODY),
/** Players who are not moving. */
NonMover(Constants.NOBODY),
/** Enemy players. */
Enemy(Constants.NOBODY),
/** Friend players (Mover + Allies). */
Friend(Constants.NOBODY),
/** Ally players. */
Ally(Constants.NOBODY),
/** Placeholder for iterator over all players, e.g. from end.ForEach. */
Player(Constants.NOBODY);
//-------------------------------------------------------------------------
private static final RoleType[] PlayerIdToRole = RoleType.values();
private final int owner;
/**
* Default constructor, to avoid RoleType(null) warning during compilation (e.g. Trax).
*/
private RoleType()
{
owner = Constants.NOBODY;
}
/**
* Constructor.
*
* @param owner The index.
*/
private RoleType(final int owner)
{
this.owner = owner;
}
/**
* @return The corresponding player.
*/
public int owner()
{
return owner;
}
/**
* @param role The roleType.
* @return True if the roleType is about a team.
*/
public static boolean isTeam(final RoleType role)
{
return (role.toString().contains("Team"));
}
/**
* @param role The roleType.
* @return True if the roleType can corresponds to many players.
*/
public static boolean manyIds(final RoleType role)
{
return isTeam(role) | role.equals(Ally) | role.equals(Enemy) | role.equals(NonMover) | role.equals(All) | role.equals(Friend);
}
/**
* @param pid The index of the player.
* @return The corresponding roletype of the index.
*/
public static RoleType roleForPlayerId(final int pid)
{
if (pid > 0 && pid <= Constants.MAX_PLAYERS)
return PlayerIdToRole[pid];
return Neutral;
}
/**
* @param roleType
* @return An IntFunction representation of given RoleType
*/
public static IntFunction toIntFunction(final RoleType roleType)
{
if (roleType.owner > 0)
return new IntConstant(roleType.owner);
else
return new Id(null, roleType);
}
}
| 4,103 | 19.727273 | 128 | java |
Ludii | Ludii-master/Core/src/game/types/play/WhenType.java | package game.types.play;
/**
* Defines when to perform certain tests or actions within a game.
*
* @author cambolbro
*/
public enum WhenType
{
/** Start of a turn. */
StartOfTurn,
/** End of a turn. */
EndOfTurn,
}
| 227 | 14.2 | 66 | java |
Ludii | Ludii-master/Core/src/game/types/play/package-info.java | /**
* Play types are constant values for specifying various aspects of play.
* These are typically to do with the ``start'', ``play'' and ``end'' rules.
*/
package game.types.play;
| 185 | 30 | 76 | java |
Ludii | Ludii-master/Core/src/game/types/state/GameType.java | package game.types.state;
import java.io.Serializable;
import game.Game;
/**
* Defines known characteristics of games.
*
* @author cambolbro and Eric.Piette
*
* @remarks These flags are used to determine which state to choose for a given
* game description.
*/
public interface GameType extends Serializable
{
/**
* On if this game may generate moves that use from-positions (in addition to to-positions).
*/
public final static long UsesFromPositions = 0x1L;
/**
* On if the game involved a state value for a site.
*/
public final static long SiteState = (0x1L << 1);
/**
* On if the game involved a count for a site.
*/
public final static long Count = (0x1L << 2);
/**
* On if the game has hidden info.
*/
public final static long HiddenInfo = (0x1L << 3);
/**
* On if the game is a stacking game.
*/
public final static long Stacking = (0x1L << 4);
/**
* On if the game is a boardless game.
*/
public final static long Boardless = (0x1L << 5);
/**
* On if the game involves some stochastic values.
*/
public final static long Stochastic = (0x1L << 6);
/**
* On if the game is a deduction puzzle.
*/
public final static long DeductionPuzzle = (0x1L << 7);
/**
* On if the game involves score.
*/
public final static long Score = (0x1L << 8);
/**
* On if we store the visited sites in the same turn.
*/
public final static long Visited = (0x1L << 9);
/**
* On if the game has simultaneous actions.
*/
public final static long Simultaneous = (0x1L << 10);
/**
* On if this game is 3D games.
*/
public final static long ThreeDimensions = (0x1L << 11);
/**
* On if the game does not end if all the players pass.
*/
public final static long NotAllPass = (0x1L << 12);
/**
* On if the game involves card.
*/
public final static long Card = (0x1L << 13);
/**
* On if the game involves large piece.
*/
public final static long LargePiece = (0x1L << 14);
/**
* On if the game involves some capture in sequence.
*/
public final static long SequenceCapture = (0x1L << 15);
/**
* On if the games has some tracks defined.
*/
public final static long Track = (0x1L << 16);
/**
* On if the game has some rotation values.
*/
public final static long Rotation = (0x1L << 17);
/**
* On if the game has team.
*/
public final static long Team = (0x1L << 18);
/**
* On if the game has some betting actions.
*/
public final static long Bet = (0x1L << 19);
/**
* On if the game has some hash scores.
*/
public final static long HashScores = (0x1L << 20);
/**
* On If the game has some hash amounts.
*/
public final static long HashAmounts = (0x1L << 21);
/**
* On if the game has some hash phases.
*/
public final static long HashPhases = (0x1L << 22);
/**
* On if the game is a graph game.
*/
public final static long Graph = (0x1L << 23);
/**
* On if the game can be played on the vertices.
*/
public final static long Vertex = (0x1L << 24);
/**
* On if the game can be played on the cells.
*/
public final static long Cell = (0x1L << 25);
/**
* On if the game can played on the edges.
*/
public final static long Edge = (0x1L << 26);
/**
* On if the game has dominoes.
*/
public final static long Dominoes = (0x1L << 27);
/**
* On if the game has a line of play used.
*/
public final static long LineOfPlay = (0x1L << 28);
/**
* On if the game has some replay actions.
*/
public final static long MoveAgain = (0x1L << 29);
/**
* On if the game uses some piece values.
*/
public final static long Value = (0x1L << 30);
/**
* On if the game has some vote actions.
*/
public final static long Vote = (0x1L << 31);
/**
* On if the game has some Note actions.
*/
public final static long Note = (0x1L << 32);
/**
* On if the game involves loop.
*/
public final static long Loops = (0x1L << 33);
/**
* On if the game needs some adjacent step distance between sites.
*/
public final static long StepAdjacentDistance = (0x1L << 34);
/**
* On if the game needs some orthogonal step distance between sites.
*/
public final static long StepOrthogonalDistance = (0x1L << 35);
/**
* On if the game needs some diagonal step distance between sites.
*/
public final static long StepDiagonalDistance = (0x1L << 36);
/**
* On if the game needs some off step distance between sites.
*/
public final static long StepOffDistance = (0x1L << 37);
/**
* On if the game needs some neighbours step distance between sites.
*/
public final static long StepAllDistance = (0x1L << 38);
/**
* On if the tracks on the game have an internal loop.
*/
public final static long InternalLoopInTrack = (0x1L << 39);
/**
* On if the game uses a swap rule.
*/
public final static long UsesSwapRule = (0x1L << 40);
/**
* On if the game checks the positional repetition in the game.
*/
public final static long RepeatPositionalInGame = (0x1L << 41);
/**
* On if the game checks the positional repetition in the turn.
*/
public final static long RepeatPositionalInTurn = (0x1L << 42);
/**
* On if the game uses some pending states/values.
*/
public final static long PendingValues = (0x1L << 43);
/**
* On if the game uses some maps to values.
*/
public final static long MapValue = (0x1L << 44);
/**
* On if the game uses some values to remember.
*/
public final static long RememberingValues = (0x1L << 45);
/**
* On if the game involves payoff.
*/
public final static long Payoff = (0x1L << 46);
/**
* On if the game checks the situational repetition in the game.
*/
public final static long RepeatSituationalInGame = (0x1L << 47);
/**
* On if the game checks the situational repetition in the turn.
*/
public final static long RepeatSituationalInTurn = (0x1L << 48);
/**
* On if the game checks the repetition of cycles.
*/
public final static long CycleDetection = (0x1L << 49);
/**
* @param game The game.
* @return Accumulated flags for this state type.
*/
public long gameFlags(final Game game);
/**
* @return true of the function is immutable, allowing extra optimisations.
*/
public 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 void preprocess(final Game game);
}
| 6,687 | 22.384615 | 93 | java |
Ludii | Ludii-master/Core/src/game/types/state/package-info.java | /**
* State types are constant values for specifying various aspects of the current game state.
*/
package game.types.state;
| 127 | 24.6 | 92 | java |
Ludii | Ludii-master/Core/src/game/util/dummy.java | package game.util;
/**
* Hey, dummy, this is a dummy file to trick JavaDoc into picking up this package's package-info.java.
*/
public abstract class dummy
{
// Intentionally blank
}
| 187 | 17.8 | 102 | java |
Ludii | Ludii-master/Core/src/game/util/package-info.java | /**
* @chapter Utilities ludemes are useful support classes used by various other types of ludemes.
*/
package game.util;
| 124 | 24 | 96 | java |
Ludii | Ludii-master/Core/src/game/util/directions/AbsoluteDirection.java | package game.util.directions;
import java.util.BitSet;
import game.functions.directions.Directions;
import game.functions.directions.DirectionsFunction;
import game.types.board.RelationType;
import other.concept.Concept;
/**
* Describes categories of absolute directions.
*
* @author Eric.Piette and cambolbro
*
* @remarks Absolute directions may be used to describe connectivity type, specific board sides, player movement directions, etc.
*/
public enum AbsoluteDirection implements Direction
{
/** All directions. */
All
{
@Override
public boolean matches(final DirectionFacing baseDirn, final DirectionType dirn)
{
return true;
}
},
/** Angled directions. */
Angled
{
@Override
public boolean matches(final DirectionFacing baseDirn, final DirectionType dirn)
{
return dirn.getDirectionActual().uniqueName() == DirectionUniqueName.NW
|| dirn.getDirectionActual().uniqueName() == DirectionUniqueName.NNW
|| dirn.getDirectionActual().uniqueName() == DirectionUniqueName.WNW
|| dirn.getDirectionActual().uniqueName() == DirectionUniqueName.WSW
|| dirn.getDirectionActual().uniqueName() == DirectionUniqueName.SE
|| dirn.getDirectionActual().uniqueName() == DirectionUniqueName.SW
|| dirn.getDirectionActual().uniqueName() == DirectionUniqueName.SSE
|| dirn.getDirectionActual().uniqueName() == DirectionUniqueName.SSW
|| dirn.getDirectionActual().uniqueName() == DirectionUniqueName.NNE
|| dirn.getDirectionActual().uniqueName() == DirectionUniqueName.ESE
|| dirn.getDirectionActual().uniqueName() == DirectionUniqueName.ENE
|| dirn.getDirectionActual().uniqueName() == DirectionUniqueName.NE;
}
},
/** Adjacent directions. */
Adjacent
{
@Override
public boolean matches(final DirectionFacing baseDirn, final DirectionType dirn)
{
return false;
}
},
/** Axial directions. */
Axial
{
@Override
public boolean matches(final DirectionFacing baseDirn, final DirectionType dirn)
{
return dirn.getDirectionActual().uniqueName() == DirectionUniqueName.N
|| dirn.getDirectionActual().uniqueName() == DirectionUniqueName.S
|| dirn.getDirectionActual().uniqueName() == DirectionUniqueName.E
|| dirn.getDirectionActual().uniqueName() == DirectionUniqueName.W
|| dirn.getDirectionActual().uniqueName() == DirectionUniqueName.U
|| dirn.getDirectionActual().uniqueName() == DirectionUniqueName.D;
}
},
/** Orthogonal directions. */
Orthogonal
{
@Override
public boolean matches(final DirectionFacing baseDirn, final DirectionType dirn)
{
return false;
}
},
/** Diagonal directions. */
Diagonal
{
@Override
public boolean matches(final DirectionFacing baseDirn, final DirectionType dirn)
{
return false;
}
},
/** Off-diagonal directions. */
OffDiagonal
{
@Override
public boolean matches(final DirectionFacing baseDirn, final DirectionType dirn)
{
return false;
}
},
/** Directions on the same layer. */
SameLayer
{
@Override
public boolean matches(final DirectionFacing baseDirn, final DirectionType dirn)
{
return false;
}
},
/** Upward directions. */
Upward
{
@Override
public boolean matches(final DirectionFacing baseDirn, final DirectionType dirn)
{
return dirn.getDirectionActual().uniqueName() == DirectionUniqueName.U
|| dirn.getDirectionActual().uniqueName() == DirectionUniqueName.UN
|| dirn.getDirectionActual().uniqueName() == DirectionUniqueName.UE
|| dirn.getDirectionActual().uniqueName() == DirectionUniqueName.US
|| dirn.getDirectionActual().uniqueName() == DirectionUniqueName.UW
|| dirn.getDirectionActual().uniqueName() == DirectionUniqueName.UNW
|| dirn.getDirectionActual().uniqueName() == DirectionUniqueName.UNE
|| dirn.getDirectionActual().uniqueName() == DirectionUniqueName.USE
|| dirn.getDirectionActual().uniqueName() == DirectionUniqueName.USW;
}
},
/** Downward directions. */
Downward
{
@Override
public boolean matches(final DirectionFacing baseDirn, final DirectionType dirn)
{
return dirn.getDirectionActual().uniqueName() == DirectionUniqueName.D
|| dirn.getDirectionActual().uniqueName() == DirectionUniqueName.DN
|| dirn.getDirectionActual().uniqueName() == DirectionUniqueName.DE
|| dirn.getDirectionActual().uniqueName() == DirectionUniqueName.DS
|| dirn.getDirectionActual().uniqueName() == DirectionUniqueName.DW
|| dirn.getDirectionActual().uniqueName() == DirectionUniqueName.DNW
|| dirn.getDirectionActual().uniqueName() == DirectionUniqueName.DNE
|| dirn.getDirectionActual().uniqueName() == DirectionUniqueName.DSE
|| dirn.getDirectionActual().uniqueName() == DirectionUniqueName.DSW;
}
},
/** Rotational directions. */
Rotational
{
@Override
public boolean matches(final DirectionFacing baseDirn, final DirectionType dirn)
{
return dirn.getDirectionActual().uniqueName() == DirectionUniqueName.CW
|| dirn.getDirectionActual().uniqueName() == DirectionUniqueName.CCW
|| dirn.getDirectionActual().uniqueName() == DirectionUniqueName.In
|| dirn.getDirectionActual().uniqueName() == DirectionUniqueName.Out;
}
},
/** Base directions. */
Base
{
@Override
public boolean matches(final DirectionFacing baseDirn, final DirectionType dirn)
{
return false;
}
},
/** Support directions. */
Support
{
@Override
public boolean matches(final DirectionFacing baseDirn, final DirectionType dirn)
{
return false;
}
},
// -------------------Intercardinal equivalent absolute direction--------------
/** North. */
N{
@Override
public boolean matches(final DirectionFacing baseDirn, final DirectionType dirn)
{
return dirn.getDirectionActual().uniqueName() == DirectionUniqueName.N;
}
},
/** East. */
E
{
@Override
public boolean matches(final DirectionFacing baseDirn, final DirectionType dirn)
{
return dirn.getDirectionActual().uniqueName() == DirectionUniqueName.E;
}
},
/** South. */
S
{
@Override
public boolean matches(final DirectionFacing baseDirn, final DirectionType dirn)
{
return dirn.getDirectionActual().uniqueName() == DirectionUniqueName.S;
}
},
/** West. */
W
{
@Override
public boolean matches(final DirectionFacing baseDirn, final DirectionType dirn)
{
return dirn.getDirectionActual().uniqueName() == DirectionUniqueName.W;
}
},
/** North-East. */
NE
{
@Override
public boolean matches(final DirectionFacing baseDirn, final DirectionType dirn)
{
return dirn.getDirectionActual().uniqueName() == DirectionUniqueName.NE;
}
},
/** South-East. */
SE
{
@Override
public boolean matches(final DirectionFacing baseDirn, final DirectionType dirn)
{
return dirn.getDirectionActual().uniqueName() == DirectionUniqueName.SE;
}
},
/** North-West. */
NW
{
@Override
public boolean matches(final DirectionFacing baseDirn, final DirectionType dirn)
{
return dirn.getDirectionActual().uniqueName() == DirectionUniqueName.NW;
}
},
/** South-West. */
SW
{
@Override
public boolean matches(final DirectionFacing baseDirn, final DirectionType dirn)
{
return dirn.getDirectionActual().uniqueName() == DirectionUniqueName.SW;
}
},
/** North-North-West. */
NNW
{
@Override
public boolean matches(final DirectionFacing baseDirn, final DirectionType dirn)
{
return dirn.getDirectionActual().uniqueName() == DirectionUniqueName.NNW;
}
},
/** West-North-West. */
WNW
{
@Override
public boolean matches(final DirectionFacing baseDirn, final DirectionType dirn)
{
return dirn.getDirectionActual().uniqueName() == DirectionUniqueName.WNW;
}
},
/** West-South-West. */
WSW
{
@Override
public boolean matches(final DirectionFacing baseDirn, final DirectionType dirn)
{
return dirn.getDirectionActual().uniqueName() == DirectionUniqueName.WSW;
}
},
/** South-South-West. */
SSW
{
@Override
public boolean matches(final DirectionFacing baseDirn, final DirectionType dirn)
{
return dirn.getDirectionActual().uniqueName() == DirectionUniqueName.SSW;
}
},
/** South-South-East. */
SSE
{
@Override
public boolean matches(final DirectionFacing baseDirn, final DirectionType dirn)
{
return dirn.getDirectionActual().uniqueName() == DirectionUniqueName.SSE;
}
},
/** East-South-East. */
ESE
{
@Override
public boolean matches(final DirectionFacing baseDirn, final DirectionType dirn)
{
return dirn.getDirectionActual().uniqueName() == DirectionUniqueName.ESE;
}
},
/** East-North-East. */
ENE
{
@Override
public boolean matches(final DirectionFacing baseDirn, final DirectionType dirn)
{
return dirn.getDirectionActual().uniqueName() == DirectionUniqueName.ENE;
}
},
/** North-North-East. */
NNE
{
@Override
public boolean matches(final DirectionFacing baseDirn, final DirectionType dirn)
{
return dirn.getDirectionActual().uniqueName() == DirectionUniqueName.NNE;
}
},
// -------------------Rotational equivalent absolute direction--------------
/** Clockwise directions. */
CW
{
@Override
public boolean matches(final DirectionFacing baseDirn, final DirectionType dirn)
{
return dirn.getDirectionActual().uniqueName() == DirectionUniqueName.CW;
}
},
/** Counter-Clockwise directions. */
CCW
{
@Override
public boolean matches(final DirectionFacing baseDirn, final DirectionType dirn)
{
return dirn.getDirectionActual().uniqueName() == DirectionUniqueName.CCW;
}
},
/** Inwards directions. */
In
{
@Override
public boolean matches(final DirectionFacing baseDirn, final DirectionType dirn)
{
return dirn.getDirectionActual().uniqueName() == DirectionUniqueName.In;
}
},
/** Outwards directions. */
Out
{
@Override
public boolean matches(final DirectionFacing baseDirn, final DirectionType dirn)
{
return dirn.getDirectionActual().uniqueName() == DirectionUniqueName.Out;
}
},
// -------------------Spatial equivalent absolute direction--------------
/** Upper direction. */
U
{
@Override
public boolean matches(final DirectionFacing baseDirn, final DirectionType dirn)
{
return dirn.getDirectionActual().uniqueName() == DirectionUniqueName.U;
}
},
/** Upwards-North direction. */
UN
{
@Override
public boolean matches(final DirectionFacing baseDirn, final DirectionType dirn)
{
return dirn.getDirectionActual().uniqueName() == DirectionUniqueName.UN;
}
},
/** Upwards-North-East direction. */
UNE
{
@Override
public boolean matches(final DirectionFacing baseDirn, final DirectionType dirn)
{
return dirn.getDirectionActual().uniqueName()==DirectionUniqueName.UNE;
}
},
/** Upwards-East direction. */
UE
{
@Override
public boolean matches(final DirectionFacing baseDirn, final DirectionType dirn)
{
return dirn.getDirectionActual().uniqueName() == DirectionUniqueName.UE;
}
},
/** Upwards-South-East direction. */
USE
{
@Override
public boolean matches(final DirectionFacing baseDirn, final DirectionType dirn)
{
return dirn.getDirectionActual().uniqueName() == DirectionUniqueName.USE;
}
},
/** Upwards-South direction. */
US
{
@Override
public boolean matches(final DirectionFacing baseDirn, final DirectionType dirn)
{
return dirn.getDirectionActual().uniqueName() == DirectionUniqueName.US;
}
},
/** Upwards-South-West direction. */
USW
{
@Override
public boolean matches(final DirectionFacing baseDirn, final DirectionType dirn)
{
return dirn.getDirectionActual().uniqueName() == DirectionUniqueName.USW;
}
},
/** Upwards-West direction. */
UW
{
@Override
public boolean matches(final DirectionFacing baseDirn, final DirectionType dirn)
{
return dirn.getDirectionActual().uniqueName() == DirectionUniqueName.UW;
}
},
/** Upwards-North-West direction. */
UNW
{
@Override
public boolean matches(final DirectionFacing baseDirn, final DirectionType dirn)
{
return dirn.getDirectionActual().uniqueName() == DirectionUniqueName.UNW;
}
},
/** Down direction. */
D
{
@Override
public boolean matches(final DirectionFacing baseDirn, final DirectionType dirn)
{
return dirn.getDirectionActual().uniqueName() == DirectionUniqueName.D;
}
},
/** Down-North direction. */
DN
{
@Override
public boolean matches(final DirectionFacing baseDirn, final DirectionType dirn)
{
return dirn.getDirectionActual().uniqueName() == DirectionUniqueName.DN;
}
},
/** Down-North-East. */
DNE
{
@Override
public boolean matches(final DirectionFacing baseDirn, final DirectionType dirn)
{
return dirn.getDirectionActual().uniqueName() == DirectionUniqueName.DNE;
}
},
/** Down-East direction. */
DE
{
@Override
public boolean matches(final DirectionFacing baseDirn, final DirectionType dirn)
{
return dirn.getDirectionActual().uniqueName() == DirectionUniqueName.DE;
}
},
/** Down-South-East. */
DSE
{
@Override
public boolean matches(final DirectionFacing baseDirn, final DirectionType dirn)
{
return dirn.getDirectionActual().uniqueName() == DirectionUniqueName.DSE;
}
},
/** Down-South direction. */
DS
{
@Override
public boolean matches(final DirectionFacing baseDirn, final DirectionType dirn)
{
return dirn.getDirectionActual().uniqueName() == DirectionUniqueName.DS;
}
},
/** Down-South-West. */
DSW
{
@Override
public boolean matches(final DirectionFacing baseDirn, final DirectionType dirn)
{
return dirn.getDirectionActual().uniqueName() == DirectionUniqueName.DSW;
}
},
/** Down-West direction. */
DW
{
@Override
public boolean matches(final DirectionFacing baseDirn, final DirectionType dirn)
{
return dirn.getDirectionActual().uniqueName() == DirectionUniqueName.DW;
}
},
/** Down North West. */
DNW
{
@Override
public boolean matches(final DirectionFacing baseDirn, final DirectionType dirn)
{
return dirn.getDirectionActual().uniqueName() == DirectionUniqueName.DNW;
}
},
;
//-------------------------------------------------------------------------
/**
* NOTE: baseDirn may be null; it represents the facing of the piece, and may
* not be relevant
*
* @param baseDirn
* @param dirn
* @return true if baseDirn+dirn matches the requirements of this category
*/
public abstract boolean matches(final DirectionFacing baseDirn, final DirectionType dirn);
/**
* @param dirn The direction.
* @return Whether the given direction is a specific direction (e.g. N) as
* opposed to belonging to a class of directions (e.g. Adjacent).
*/
public static boolean specific(final AbsoluteDirection dirn)
{
return convert(dirn) != null;
}
/**
* @return The specific direction corresponding to the absolute direction.
*/
public boolean specific()
{
return specific(this);
}
/**
* @param absoluteDirection
* @return the corresponding direction.
*/
public static DirectionFacing convert(final AbsoluteDirection absoluteDirection)
{
switch (absoluteDirection)
{
// Absolute with no equivalent directions
case Adjacent:
return null;
case All:
return null;
case Axial:
return null;
case Angled:
return null;
case Diagonal:
return null;
case OffDiagonal:
return null;
case Orthogonal:
return null;
case Downward:
return null;
case SameLayer:
return null;
case Upward:
return null;
case Rotational:
return null;
// Absolute with an equivalent intercardinalDirection
case E:
return CompassDirection.E;
case ENE:
return CompassDirection.ENE;
case ESE:
return CompassDirection.ESE;
case N:
return CompassDirection.N;
case NE:
return CompassDirection.NE;
case NNE:
return CompassDirection.NNE;
case NNW:
return CompassDirection.NNW;
case NW:
return CompassDirection.NW;
case S:
return CompassDirection.S;
case SE:
return CompassDirection.SE;
case SSE:
return CompassDirection.SSE;
case SSW:
return CompassDirection.SSW;
case SW:
return CompassDirection.SW;
case W:
return CompassDirection.W;
case WNW:
return CompassDirection.WNW;
case WSW:
return CompassDirection.WSW;
// Absolute with an equivalent RotationalDirection
case CCW:
return RotationalDirection.CCW;
case CW:
return RotationalDirection.CW;
case In:
return RotationalDirection.In;
case Out:
return RotationalDirection.Out;
// Absolute with an equivalent SpatialDirection
case U:
return SpatialDirection.U;
case UN:
return SpatialDirection.UN;
case UNE:
return SpatialDirection.UNE;
case UE:
return SpatialDirection.UE;
case USE:
return SpatialDirection.USE;
case US:
return SpatialDirection.US;
case USW:
return SpatialDirection.USW;
case UW:
return SpatialDirection.UW;
case UNW:
return SpatialDirection.UNW;
case D:
return SpatialDirection.D;
case DN:
return SpatialDirection.DN;
case DNE:
return SpatialDirection.DNE;
case DE:
return SpatialDirection.DE;
case DSE:
return SpatialDirection.DSE;
case DS:
return SpatialDirection.DS;
case DSW:
return SpatialDirection.DSW;
case DW:
return SpatialDirection.DW;
case DNW:
return SpatialDirection.DNW;
default:
break;
}
return null;
}
@Override
public DirectionsFunction directionsFunctions()
{
return new Directions(this, null);
}
/**
* @param absoluteDirection The direction to convert.
* @return The equivalent in relation type.
*/
public static RelationType converToRelationType(final AbsoluteDirection absoluteDirection)
{
switch (absoluteDirection)
{
case Adjacent:
return RelationType.Adjacent;
case Diagonal:
return RelationType.Diagonal;
case All:
return RelationType.All;
case OffDiagonal:
return RelationType.OffDiagonal;
case Orthogonal:
return RelationType.Orthogonal;
default:
return null;
}
}
/**
* @param absoluteDirection The direction.
* @return The involved concepts.
*/
public static BitSet concepts(final AbsoluteDirection absoluteDirection)
{
final BitSet concepts = new BitSet();
switch (absoluteDirection)
{
case Adjacent:
{
concepts.set(Concept.AdjacentDirection.id(), true);
break;
}
case Diagonal:
{
concepts.set(Concept.DiagonalDirection.id(), true);
break;
}
case All:
{
concepts.set(Concept.AllDirections.id(), true);
break;
}
case OffDiagonal:
{
concepts.set(Concept.OffDiagonalDirection.id(), true);
break;
}
case Orthogonal:
{
concepts.set(Concept.OrthogonalDirection.id(), true);
break;
}
case Rotational:
{
concepts.set(Concept.RotationalDirection.id(), true);
break;
}
case SameLayer:
{
concepts.set(Concept.SameLayerDirection.id(), true);
break;
}
default:
}
return concepts;
}
}
| 18,899 | 23.199744 | 129 | java |
Ludii | Ludii-master/Core/src/game/util/directions/CompassDirection.java | package game.util.directions;
import java.util.BitSet;
import game.Game;
/**
* Compass directions.
*
* @author Eric.Piette and cambolbro
*/
public enum CompassDirection implements DirectionFacing
{
/** North. */
N(DirectionUniqueName.N){ @Override public AbsoluteDirection toAbsolute(){ return AbsoluteDirection.N; }},
/** North-North-East. */
NNE(DirectionUniqueName.NNE){ @Override public AbsoluteDirection toAbsolute(){ return AbsoluteDirection.NNE; }},
/** North-East. */
NE(DirectionUniqueName.NE){ @Override public AbsoluteDirection toAbsolute(){ return AbsoluteDirection.NE; }},
/** East-North-East. */
ENE(DirectionUniqueName.ENE){ @Override public AbsoluteDirection toAbsolute(){ return AbsoluteDirection.ENE; }},
/** East. */
E(DirectionUniqueName.E){ @Override public AbsoluteDirection toAbsolute(){ return AbsoluteDirection.E; }},
/** East-South-East. */
ESE(DirectionUniqueName.ESE){ @Override public AbsoluteDirection toAbsolute(){ return AbsoluteDirection.ESE; }},
/** South-East. */
SE(DirectionUniqueName.SE){ @Override public AbsoluteDirection toAbsolute(){ return AbsoluteDirection.SE; }},
/** South-South-East. */
SSE(DirectionUniqueName.SSE){ @Override public AbsoluteDirection toAbsolute(){ return AbsoluteDirection.SSE; }},
/** South. */
S(DirectionUniqueName.S){ @Override public AbsoluteDirection toAbsolute(){ return AbsoluteDirection.S; }},
/** South-South-West. */
SSW(DirectionUniqueName.SSW){ @Override public AbsoluteDirection toAbsolute(){ return AbsoluteDirection.SSW; }},
/** South-West. */
SW(DirectionUniqueName.SW){ @Override public AbsoluteDirection toAbsolute(){ return AbsoluteDirection.SW; }},
/** West-South-West. */
WSW(DirectionUniqueName.WSW){ @Override public AbsoluteDirection toAbsolute(){ return AbsoluteDirection.WSW; }},
/** West. */
W(DirectionUniqueName.W){ @Override public AbsoluteDirection toAbsolute(){ return AbsoluteDirection.W; }},
/** West-North-West. */
WNW(DirectionUniqueName.WNW){ @Override public AbsoluteDirection toAbsolute(){ return AbsoluteDirection.WNW; }},
/** North-West. */
NW(DirectionUniqueName.NW){ @Override public AbsoluteDirection toAbsolute(){ return AbsoluteDirection.NW; }},
/** North-North-West. */
NNW(DirectionUniqueName.NNW){ @Override public AbsoluteDirection toAbsolute(){ return AbsoluteDirection.NNW; }},
;
/** Left direction of each direction. */
private static final CompassDirection[] LEFT;
/** Leftward direction of each direction. */
private static final CompassDirection[] LEFTWARD;
/** Right direction of each direction. */
private static final CompassDirection[] RIGHT;
/** Rightward direction of each direction. */
private static final CompassDirection[] RIGHTWARD;
/** Opposite direction of each direction. */
private static final CompassDirection[] OPPOSITE;
static
{
LEFT = new CompassDirection[]
{ NNW, N, NNE, NE, ENE, E, ESE, SE, SSE, S, SSW, SW, WSW, W, WNW, NW };
LEFTWARD = new CompassDirection[]
{ W, WNW, NW, NNW, N, NNE, NE, ENE, E, ESE, SE, SSE, S, SSW, SW, WSW };
RIGHT = new CompassDirection[]
{ NNE, NE, ENE, E, ESE, SE, SSE, S, SSW, SW, WSW, W, WNW, NW, NNW, N };
RIGHTWARD = new CompassDirection[]
{ E, ESE, SE, SSE, S, SSW, SW, WSW, W, WNW, NW, NNW, N, NNE, NE, ENE };
OPPOSITE = new CompassDirection[]
{ S, SSW, SW, WSW, W, WNW, NW, NNW, N, NNE, NE, ENE, E, ESE, SE, SSE };
}
/** The unique name of each direction. */
final DirectionUniqueName uniqueName;
/**
* @param origDirnType
*/
private CompassDirection(final DirectionUniqueName uniqueName)
{
this.uniqueName = uniqueName;
}
@Override
public DirectionFacing left()
{
return LEFT[ordinal()];
}
@Override
public DirectionFacing leftward()
{
return LEFTWARD[ordinal()];
}
@Override
public DirectionFacing right()
{
return RIGHT[ordinal()];
}
@Override
public DirectionFacing rightward()
{
return RIGHTWARD[ordinal()];
}
@Override
public DirectionFacing opposite()
{
return OPPOSITE[ordinal()];
}
@Override
public int index()
{
return ordinal();
}
@Override
public DirectionUniqueName uniqueName()
{
return uniqueName;
}
@Override
public int numDirectionValues()
{
return CompassDirection.values().length;
}
//-------------------------------------------------------------------------
// Ludeme overrides
@Override
public BitSet concepts(final Game game)
{
return new BitSet();
}
@Override
public BitSet readsEvalContextRecursive()
{
return new BitSet();
}
@Override
public BitSet writesEvalContextRecursive()
{
return new BitSet();
}
@Override
public BitSet readsEvalContextFlat()
{
return new BitSet();
}
@Override
public BitSet writesEvalContextFlat()
{
return new BitSet();
}
@Override
public boolean missingRequirement(final Game game)
{
return false;
}
@Override
public boolean willCrash(final Game game)
{
return false;
}
@Override
public String toEnglish(final Game game)
{
return name();
}
}
| 5,018 | 23.846535 | 114 | java |
Ludii | Ludii-master/Core/src/game/util/directions/Direction.java | package game.util.directions;
import game.functions.directions.DirectionsFunction;
/**
* The different direction which can be used by some moves.
*
* @author Eric.Piette
*/
public interface Direction
{
/**
* @return The corresponding direction functions.
*/
public DirectionsFunction directionsFunctions();
}
| 322 | 18 | 59 | java |
Ludii | Ludii-master/Core/src/game/util/directions/DirectionFacing.java | package game.util.directions;
import other.Ludeme;
/**
* Provides a general ``direction'' description for use in a variety of
* contexts.
*
* @author mrraow and Eric.Piette
*
* @usage Provides an Interface as each basis can have its own set of
* directions.
*/
public interface DirectionFacing extends Ludeme
{
/**
* @return Direction left of this one.
*/
public DirectionFacing left();
/**
* @return Direction right of this one.
*/
public DirectionFacing right();
/**
* @return Direction rightward of this one.
*/
public DirectionFacing rightward();
/**
* @return Direction leftward of this one.
*/
public DirectionFacing leftward();
/**
* @return The opposite direction.
*/
public DirectionFacing opposite();
/**
* @return Index of this direction.
*/
public int index();
/**
* @return Index of this direction.
*/
public DirectionUniqueName uniqueName();
/**
* @return Number of possible distinct values in Direction enum.
*/
public int numDirectionValues();
/**
* @return Direction converted to an AbsoluteDirection
*/
public AbsoluteDirection toAbsolute();
//-------------------------------------------------------------------------
/**
* An efficient implementation of Maps with Direction objects as key.
* Very similar to EnumMap, but works with keys of the Direction type
* (which is an interface that is expected to always be implemented
* by an enum, but is not yet an enum itself).
*
* This map should only ever contain keys of a single enum implementing
* Direction; keys from different enums should not be mixed!
*
* @author Dennis Soemers
*
* @param <V>
*/
public static class DirectionMap<V>
{
/** Stored values (one per possible key) */
protected final Object[] values;
/**
* For every possible key, true if and only if we actually stored something
* there
*/
protected final boolean[] occupied;
/** Number of stored objects */
protected int size = 0;
/**
* Constructor
*
* @param exampleKey
*/
public DirectionMap(final DirectionFacing exampleKey)
{
values = new Object[exampleKey.numDirectionValues()];
occupied = new boolean[exampleKey.numDirectionValues()];
}
/**
* @param key
* @return Value stored for given key, or null if none stored
*/
@SuppressWarnings("unchecked")
public V get(final DirectionFacing key)
{
return (V) values[key.index()];
}
/**
* Puts given value for given key in the map
*
* @param key
* @param value
* @return Previously stored value (null if no value previously stored)
*/
public V put(final DirectionFacing key, final V value)
{
final int idx = key.index();
@SuppressWarnings("unchecked")
final V old = (V) values[idx];
values[idx] = value;
if (!occupied[idx])
{
++size;
occupied[idx] = true;
}
return old;
}
}
}
| 2,919 | 20.15942 | 77 | java |
Ludii | Ludii-master/Core/src/game/util/directions/DirectionType.java | package game.util.directions;
/**
* Associates a direction to an unique index.
*
* @author Eric.Piette
*/
public class DirectionType
{
/** The unique index of the direction. */
private final int index;
/** The name of the current direction. */
private final DirectionFacing directionActual;
//-------------------------------------------------------------------------
/**
* @param directionActual The current direction.
*/
public DirectionType(final DirectionFacing directionActual)
{
super();
this.index = directionActual.index();
this.directionActual = directionActual;
}
//-------------------------------------------------------------------------
/**
* @return The direction.
*/
public DirectionFacing getDirection()
{
return this.directionActual;
}
/**
* @return The index of the direction.
*/
public int index()
{
return index;
}
/**
* @return The actual direction.
*/
public DirectionFacing getDirectionActual()
{
return directionActual;
}
//-------------------------------------------------------------------------
@Override
public String toString()
{
return "[Direction: " + directionActual + "]";
}
}
| 1,190 | 18.209677 | 76 | java |
Ludii | Ludii-master/Core/src/game/util/directions/DirectionUniqueName.java | package game.util.directions;
import annotations.Hide;
/**
* provides that for efficiency rather than necessity, each direction has a unique name
* @remarks this is the canonical list,
* Feel free to ad extra names as required, but these should be actual directions not filters.
*
* @author mrraow
*/
@Hide
public enum DirectionUniqueName
{
/** North direction. */
N,
/** North-North-East direction. */
NNE,
/** North-East direction. */
NE,
/** East direction. */
E,
/** South-South-East direction. */
SSE,
/** South-East direction. */
SE,
/** South direction. */
S,
/** South-South-West direction. */
SSW,
/** South-West direction. */
SW,
/** West direction. */
W,
/** North-West direction. */
NW,
/** North-North-West direction. */
NNW,
/** West-North-West direction. */
WNW,
/** East-North-East direction. */
ENE,
/** East-South-East direction. */
ESE,
/** West-South-West direction. */
WSW,
/** Clockwise direction. */
CW,
/** Outwards direction. */
Out,
/** Counter-Clockwise direction. */
CCW,
/** Inwards direction. */
In,
/** Upper-North-West direction. */
UNW,
/** Upper-North-East direction. */
UNE,
/** Upper-South-East direction. */
USE,
/** Upper-South-West direction. */
USW,
/** Down-North-west direction. */
DNW,
/** Down-North-East direction. */
DNE,
/** Down-South-East direction. */
DSE,
/** Down-South-West direction. */
DSW,
/** Upper direction. */
U,
/** Upper-North direction. */
UN,
/** Upper-West direction. */
UW,
/** Upper-East direction. */
UE,
/** Upper-South direction. */
US,
/** Down direction. */
D,
/** Down-North direction. */
DN,
/** Down-West direction. */
DW,
/** Down-East direction. */
DE,
/** Down-South direction. */
DS,
}
| 1,820 | 13.116279 | 100 | java |
Ludii | Ludii-master/Core/src/game/util/directions/RelativeDirection.java | package game.util.directions;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.List;
import game.functions.directions.Directions;
import game.functions.directions.DirectionsFunction;
import other.concept.Concept;
//-----------------------------------------------------------------------------
/**
* Describes categories of relative directions.
*
* @author Eric.Piette and cambolbro
*
* @remarks Relative directions are typically used to describe player movements or relationships between items.
*/
public enum RelativeDirection implements Direction
{
/** Forward (only) direction. */
Forward(true)
{
@Override
public List<DirectionFacing> directions(final DirectionFacing baseDirn, final List<DirectionFacing> supportedDirections)
{
final List<DirectionFacing> directions = new ArrayList<DirectionFacing>();
if (supportedDirections.contains(baseDirn))
directions.add(baseDirn);
return directions;
}
},
/** Backward (only) direction. */
Backward(true)
{
@Override
public List<DirectionFacing> directions(final DirectionFacing baseDirn, final List<DirectionFacing> supportedDirections)
{
final List<DirectionFacing> directions = new ArrayList<DirectionFacing>();
if (supportedDirections.contains(baseDirn.opposite()))
directions.add(baseDirn.opposite());
return directions;
}
},
/** Rightward (only) direction. */
Rightward(true)
{
@Override
public List<DirectionFacing> directions(final DirectionFacing baseDirn, final List<DirectionFacing> supportedDirections)
{
final List<DirectionFacing> directions = new ArrayList<DirectionFacing>();
if (supportedDirections.contains(baseDirn.rightward()))
directions.add(baseDirn.rightward());
return directions;
}
},
/** Leftward (only) direction. */
Leftward(true)
{
@Override
public List<DirectionFacing> directions(final DirectionFacing baseDirn, final List<DirectionFacing> supportedDirections)
{
final List<DirectionFacing> directions = new ArrayList<DirectionFacing>();
if (supportedDirections.contains(baseDirn.leftward()))
directions.add(baseDirn.leftward());
return directions;
}
},
/** Forwards directions. */
Forwards(true)
{
@Override
public List<DirectionFacing> directions(final DirectionFacing baseDirn, final List<DirectionFacing> supportedDirections)
{
final List<DirectionFacing> directions = new ArrayList<DirectionFacing>();
DirectionFacing directionToAdd = baseDirn.leftward().right();
while (directionToAdd != baseDirn.rightward())
{
if (supportedDirections.contains(directionToAdd))
directions.add(directionToAdd);
directionToAdd = directionToAdd.right();
}
return directions;
}
},
/** Backwards directions. */
Backwards(true)
{
@Override
public List<DirectionFacing> directions(final DirectionFacing baseDirn, final List<DirectionFacing> supportedDirections)
{
final List<DirectionFacing> directions = new ArrayList<DirectionFacing>();
DirectionFacing directionToAdd = baseDirn.opposite().leftward().right();
while (directionToAdd != baseDirn.opposite().rightward())
{
if (supportedDirections.contains(directionToAdd))
directions.add(directionToAdd);
directionToAdd = directionToAdd.right();
}
return directions;
}
},
/** Rightwards directions. */
Rightwards(true)
{
@Override
public List<DirectionFacing> directions(final DirectionFacing baseDirn, final List<DirectionFacing> supportedDirections)
{
final List<DirectionFacing> directions = new ArrayList<DirectionFacing>();
DirectionFacing directionToAdd = baseDirn.right();
while (directionToAdd != baseDirn.opposite())
{
if (supportedDirections.contains(directionToAdd))
directions.add(directionToAdd);
directionToAdd = directionToAdd.right();
}
return directions;
}
},
/** Leftwards directions. */
Leftwards(true)
{
@Override
public List<DirectionFacing> directions(final DirectionFacing baseDirn, final List<DirectionFacing> supportedDirections)
{
final List<DirectionFacing> directions = new ArrayList<DirectionFacing>();
DirectionFacing directionToAdd = baseDirn.left();
while (directionToAdd != baseDirn.opposite())
{
if (supportedDirections.contains(directionToAdd))
directions.add(directionToAdd);
directionToAdd = directionToAdd.left();
}
return directions;
}
},
/** Forward-Left direction. */
FL(true)
{
@Override
public List<DirectionFacing> directions(final DirectionFacing baseDirn, final List<DirectionFacing> supportedDirections)
{
final List<DirectionFacing> directions = new ArrayList<DirectionFacing>(1);
DirectionFacing left = baseDirn.left();
while (!supportedDirections.contains(left))
{
left = left.left();
}
directions.add(left);
return directions;
}
},
/** Forward-Left-Left direction. */
FLL(true)
{
@Override
public List<DirectionFacing> directions(final DirectionFacing baseDirn, final List<DirectionFacing> supportedDirections)
{
final List<DirectionFacing> directions = new ArrayList<DirectionFacing>(1);
DirectionFacing left = baseDirn.left();
while (!supportedDirections.contains(left))
{
left = left.left();
}
while (!supportedDirections.contains(left))
{
left = left.left();
}
directions.add(left);
return directions;
}
},
/** Forward-Left-Left-Left direction. */
FLLL(true)
{
@Override
public List<DirectionFacing> directions(final DirectionFacing baseDirn, final List<DirectionFacing> supportedDirections)
{
final List<DirectionFacing> directions = new ArrayList<DirectionFacing>(1);
DirectionFacing left = baseDirn.left();
while (!supportedDirections.contains(left))
{
left = left.left();
}
while (!supportedDirections.contains(left))
{
left = left.left();
}
while (!supportedDirections.contains(left))
{
left = left.left();
}
directions.add(left);
return directions;
}
},
/** Backward-Left direction. */
BL(true)
{
@Override
public List<DirectionFacing> directions(final DirectionFacing baseDirn, final List<DirectionFacing> supportedDirections)
{
final List<DirectionFacing> directions = new ArrayList<DirectionFacing>(1);
DirectionFacing left = baseDirn.opposite().left();
while (!supportedDirections.contains(left))
{
left = left.left();
}
directions.add(left);
return directions;
}
},
/** Backward-Left-Left direction. */
BLL(true)
{
@Override
public List<DirectionFacing> directions(final DirectionFacing baseDirn, final List<DirectionFacing> supportedDirections)
{
final List<DirectionFacing> directions = new ArrayList<DirectionFacing>(1);
DirectionFacing left = baseDirn.opposite().left();
while (!supportedDirections.contains(left))
{
left = left.left();
}
while (!supportedDirections.contains(left))
{
left = left.left();
}
directions.add(left);
return directions;
}
},
/** Backward-Left-Left-Left direction. */
BLLL(true)
{
@Override
public List<DirectionFacing> directions(final DirectionFacing baseDirn, final List<DirectionFacing> supportedDirections)
{
final List<DirectionFacing> directions = new ArrayList<DirectionFacing>(1);
DirectionFacing left = baseDirn.opposite().left();
while (!supportedDirections.contains(left))
{
left = left.left();
}
while (!supportedDirections.contains(left))
{
left = left.left();
}
while (!supportedDirections.contains(left))
{
left = left.left();
}
directions.add(left);
return directions;
}
},
/** Forward-Right direction. */
FR(true)
{
@Override
public List<DirectionFacing> directions(final DirectionFacing baseDirn, final List<DirectionFacing> supportedDirections)
{
final List<DirectionFacing> directions = new ArrayList<DirectionFacing>(1);
DirectionFacing right = baseDirn.right();
while (!supportedDirections.contains(right))
{
right = right.right();
}
directions.add(right);
return directions;
}
},
/** Forward-Right-Right direction. */
FRR(true)
{
@Override
public List<DirectionFacing> directions(final DirectionFacing baseDirn, final List<DirectionFacing> supportedDirections)
{
final List<DirectionFacing> directions = new ArrayList<DirectionFacing>(1);
DirectionFacing right = baseDirn.right();
while (!supportedDirections.contains(right))
{
right = right.right();
}
while (!supportedDirections.contains(right))
{
right = right.right();
}
directions.add(right);
return directions;
}
},
/** Forward-Right-Right-Right direction. */
FRRR(true)
{
@Override
public List<DirectionFacing> directions(final DirectionFacing baseDirn, final List<DirectionFacing> supportedDirections)
{
final List<DirectionFacing> directions = new ArrayList<DirectionFacing>(1);
DirectionFacing right = baseDirn.right();
while (!supportedDirections.contains(right))
{
right = right.right();
}
while (!supportedDirections.contains(right))
{
right = right.right();
}
while (!supportedDirections.contains(right))
{
right = right.right();
}
directions.add(right);
return directions;
}
},
/** Backward-Right direction. */
BR(true)
{
@Override
public List<DirectionFacing> directions(final DirectionFacing baseDirn, final List<DirectionFacing> supportedDirections)
{
final List<DirectionFacing> directions = new ArrayList<DirectionFacing>(1);
DirectionFacing right = baseDirn.opposite().right();
while (!supportedDirections.contains(right))
{
right = right.right();
}
directions.add(right);
return directions;
}
},
/** Backward-Right-Right direction. */
BRR(true)
{
@Override
public List<DirectionFacing> directions(final DirectionFacing baseDirn, final List<DirectionFacing> supportedDirections)
{
final List<DirectionFacing> directions = new ArrayList<DirectionFacing>(1);
DirectionFacing right = baseDirn.opposite().right();
while (!supportedDirections.contains(right))
{
right = right.right();
}
while (!supportedDirections.contains(right))
{
right = right.right();
}
directions.add(right);
return directions;
}
},
/** Backward-Right-Right-Right direction. */
BRRR(true)
{
@Override
public List<DirectionFacing> directions(final DirectionFacing baseDirn, final List<DirectionFacing> supportedDirections)
{
final List<DirectionFacing> directions = new ArrayList<DirectionFacing>(1);
DirectionFacing right = baseDirn.opposite().right();
while (!supportedDirections.contains(right))
{
right = right.right();
}
while (!supportedDirections.contains(right))
{
right = right.right();
}
while (!supportedDirections.contains(right))
{
right = right.right();
}
directions.add(right);
return directions;
}
},
/** Same direction. */
SameDirection(true) {
@Override
public List<DirectionFacing> directions(final DirectionFacing baseDirn, final List<DirectionFacing> supportedDirections)
{
final List<DirectionFacing> directions = new ArrayList<DirectionFacing>();
return directions;
}
},
/** Opposite direction. */
OppositeDirection(true)
{
@Override
public List<DirectionFacing> directions(final DirectionFacing baseDirn, final List<DirectionFacing> supportedDirections)
{
final List<DirectionFacing> directions = new ArrayList<DirectionFacing>();
return directions;
}
},
;
//-------------------------------------------------------------------------
/**
* @param baseDirn The original direction.
* @param supportedDirections The supported directions.
*
* @return The corresponding directions.
*/
public abstract List<DirectionFacing> directions(final DirectionFacing baseDirn, final List<DirectionFacing> supportedDirections);
/**
* @param isAbsolute
*/
private RelativeDirection(final boolean isAbsolute)
{
// Nothing to do.
}
@Override
public DirectionsFunction directionsFunctions()
{
return new Directions(this, null, null, null);
}
/**
* @param relativeDirection The direction.
* @return The involved concepts.
*/
public static BitSet concepts(final RelativeDirection relativeDirection)
{
final BitSet concepts = new BitSet();
switch (relativeDirection)
{
case Forward:
{
concepts.set(Concept.ForwardDirection.id(), true);
break;
}
case Backward:
{
concepts.set(Concept.BackwardDirection.id(), true);
break;
}
case Forwards:
{
concepts.set(Concept.ForwardsDirection.id(), true);
break;
}
case Backwards:
{
concepts.set(Concept.BackwardsDirection.id(), true);
break;
}
case Rightward:
{
concepts.set(Concept.RightwardDirection.id(), true);
break;
}
case Leftward:
{
concepts.set(Concept.LeftwardDirection.id(), true);
break;
}
case Rightwards:
{
concepts.set(Concept.RightwardsDirection.id(), true);
break;
}
case Leftwards:
{
concepts.set(Concept.LeftwardsDirection.id(), true);
break;
}
case FL:
{
concepts.set(Concept.ForwardLeftDirection.id(), true);
break;
}
case FR:
{
concepts.set(Concept.ForwardRightDirection.id(), true);
break;
}
case BL:
{
concepts.set(Concept.BackwardLeftDirection.id(), true);
break;
}
case BR:
{
concepts.set(Concept.BackwardRightDirection.id(), true);
break;
}
case SameDirection:
{
concepts.set(Concept.SameDirection.id(), true);
break;
}
case OppositeDirection:
{
concepts.set(Concept.OppositeDirection.id(), true);
break;
}
default:
}
return concepts;
}
}
| 13,718 | 23.630162 | 131 | java |
Ludii | Ludii-master/Core/src/game/util/directions/RotationalDirection.java | package game.util.directions;
import java.util.BitSet;
import game.Game;
/**
* Rotational directions.
*
* @author Eric.Piette
*/
public enum RotationalDirection implements DirectionFacing
{
/** Outwards direction. */
Out(DirectionUniqueName.Out){ @Override public AbsoluteDirection toAbsolute(){ return AbsoluteDirection.Out; }},
/** Clockwise direction. */
CW(DirectionUniqueName.CW){ @Override public AbsoluteDirection toAbsolute(){ return AbsoluteDirection.CW; }},
/** Inwards direction. */
In(DirectionUniqueName.In){ @Override public AbsoluteDirection toAbsolute(){ return AbsoluteDirection.In; }},
/** Counter-Clockwise direction. */
CCW(DirectionUniqueName.CCW){ @Override public AbsoluteDirection toAbsolute(){ return AbsoluteDirection.CCW; }},
;
/** Left direction of each direction. */
private static final RotationalDirection[] LEFT;
/** Right direction of each direction. */
private static final RotationalDirection[] RIGHT;
/** Opposite direction of each direction. */
private static final RotationalDirection[] OPPOSITE;
static
{
LEFT = new RotationalDirection[]
{ CCW, In, CW, Out };
RIGHT = new RotationalDirection[]
{ CW, In, CCW, Out};
OPPOSITE = new RotationalDirection[]
{ In, CCW, Out, CW };
}
/** The unique name of each direction. */
final DirectionUniqueName uniqueName;
/**
* @param origDirnType
*/
private RotationalDirection(final DirectionUniqueName uniqueName)
{
this.uniqueName = uniqueName;
}
@Override
public DirectionFacing left()
{
return LEFT[ordinal()];
}
@Override
public DirectionFacing leftward()
{
return LEFT[ordinal()];
}
@Override
public DirectionFacing right()
{
return RIGHT[ordinal()];
}
@Override
public DirectionFacing rightward()
{
return RIGHT[ordinal()];
}
@Override
public DirectionFacing opposite()
{
return OPPOSITE[ordinal()];
}
@Override
public int index()
{
return ordinal();
}
@Override
public DirectionUniqueName uniqueName()
{
return uniqueName;
}
@Override
public int numDirectionValues()
{
return RotationalDirection.values().length;
}
//-------------------------------------------------------------------------
// Ludeme overrides
@Override
public BitSet concepts(final Game game)
{
return new BitSet();
}
@Override
public BitSet readsEvalContextRecursive()
{
return new BitSet();
}
@Override
public BitSet writesEvalContextRecursive()
{
return new BitSet();
}
@Override
public BitSet readsEvalContextFlat()
{
return new BitSet();
}
@Override
public BitSet writesEvalContextFlat()
{
return new BitSet();
}
@Override
public boolean missingRequirement(final Game game)
{
return false;
}
@Override
public boolean willCrash(final Game game)
{
return false;
}
@Override
public String toEnglish(final Game game)
{
return name();
}
}
| 2,872 | 17.416667 | 114 | java |
Ludii | Ludii-master/Core/src/game/util/directions/SpatialDirection.java | package game.util.directions;
import java.util.BitSet;
import game.Game;
/**
* Describes intercardinal directions extended to 3D.
*
* @author Eric Piette and cambolbro
*
* @remarks Spatial directions are used for 3D tilings such as the Shibumi board.
*/
public enum SpatialDirection implements DirectionFacing
{
/** Down direction. */
D(DirectionUniqueName.D){ @Override public AbsoluteDirection toAbsolute(){ return AbsoluteDirection.D; }},
/** Down-North direction. */
DN(DirectionUniqueName.DN){ @Override public AbsoluteDirection toAbsolute(){ return AbsoluteDirection.DN; }},
/** Down-North-East direction. */
DNE(DirectionUniqueName.DNE){ @Override public AbsoluteDirection toAbsolute(){ return AbsoluteDirection.DNE; }},
/** Down-East direction. */
DE(DirectionUniqueName.DE){ @Override public AbsoluteDirection toAbsolute(){ return AbsoluteDirection.DE; }},
/** Down-South-East direction. */
DSE(DirectionUniqueName.DSE){ @Override public AbsoluteDirection toAbsolute(){ return AbsoluteDirection.DSE; }},
/** Down-South direction. */
DS(DirectionUniqueName.DS){ @Override public AbsoluteDirection toAbsolute(){ return AbsoluteDirection.DS; }},
/** Down-South-West direction. */
DSW(DirectionUniqueName.DSW){ @Override public AbsoluteDirection toAbsolute(){ return AbsoluteDirection.DSW; }},
/** Down-West direction. */
DW(DirectionUniqueName.DW){ @Override public AbsoluteDirection toAbsolute(){ return AbsoluteDirection.DW; }},
/** Down-South-West direction. */
DNW(DirectionUniqueName.DSW){ @Override public AbsoluteDirection toAbsolute(){ return AbsoluteDirection.DSW; }},
/** Upwards direction. */
U(DirectionUniqueName.U){ @Override public AbsoluteDirection toAbsolute(){ return AbsoluteDirection.U; }},
/** Upwards-North direction. */
UN(DirectionUniqueName.UN){ @Override public AbsoluteDirection toAbsolute(){ return AbsoluteDirection.UN; }},
/** Upwards-North-East direction. */
UNE(DirectionUniqueName.UNE){ @Override public AbsoluteDirection toAbsolute(){ return AbsoluteDirection.UNE; }},
/** Upwards-East direction. */
UE(DirectionUniqueName.UE){ @Override public AbsoluteDirection toAbsolute(){ return AbsoluteDirection.UE; }},
/** Upwards-South-East direction. */
USE(DirectionUniqueName.USE){ @Override public AbsoluteDirection toAbsolute(){ return AbsoluteDirection.USE; }},
/** Upwards-South direction. */
US(DirectionUniqueName.US){ @Override public AbsoluteDirection toAbsolute(){ return AbsoluteDirection.US; }},
/** Upwards-South-West direction. */
USW(DirectionUniqueName.USW){ @Override public AbsoluteDirection toAbsolute(){ return AbsoluteDirection.USW; }},
/** Upwards-West direction. */
UW(DirectionUniqueName.UW){ @Override public AbsoluteDirection toAbsolute(){ return AbsoluteDirection.UW; }},
/** Upwards-North-West direction. */
UNW(DirectionUniqueName.UNW){ @Override public AbsoluteDirection toAbsolute(){ return AbsoluteDirection.UNW; }},
;
/** Left direction of each direction. */
private static final SpatialDirection[] LEFT;
/** Right direction of each direction. */
private static final SpatialDirection[] RIGHT;
/** Opposite direction of each direction. */
private static final SpatialDirection[] OPPOSITE;
// /** Upwards directions of each direction. */
// private static final SpatialDirection[] UP;
//
// /** Downwards directions of each direction. */
// private static final SpatialDirection[] DOWN;
static
{
LEFT = new SpatialDirection[]
{ D, DNW, DN, DNE, DE, DSE, DS, DSW, DW, U, UNW, UN, UNE, UE, USE, US, USW, UW };
RIGHT = new SpatialDirection[]
{ D, DNE, DE, DSE, DS, DSW, DW, DNW, DN, U, UNE, UE, USE, US, USW, UW, UNW, UN, };
OPPOSITE = new SpatialDirection[]
{ U, US, USW, UW, UNW, UN, UNE, UE, USE, D, DS, DSW, DW, DNW, DN, DNE, DE, DSE };
// UP = new SpatialDirection[]
// { UNW, UNE, USE, USW };
// DOWN = new SpatialDirection[]
// { DNW, DNE, DSE, DSW };
}
/** The unique name of each direction. */
final DirectionUniqueName uniqueName;
/**
* @param origDirnType
*/
private SpatialDirection(final DirectionUniqueName uniqueName)
{
this.uniqueName = uniqueName;
}
@Override
public DirectionFacing left()
{
return LEFT[ordinal()];
}
@Override
public DirectionFacing leftward()
{
return LEFT[ordinal()];
}
@Override
public DirectionFacing right()
{
return RIGHT[ordinal()];
}
@Override
public DirectionFacing rightward()
{
return RIGHT[ordinal()];
}
@Override
public DirectionFacing opposite()
{
return OPPOSITE[ordinal()];
}
@Override
public int index()
{
return ordinal();
}
@Override
public DirectionUniqueName uniqueName()
{
return uniqueName;
}
@Override
public int numDirectionValues()
{
return SpatialDirection.values().length;
}
//-------------------------------------------------------------------------
// Ludeme overrides
@Override
public BitSet concepts(final Game game)
{
return new BitSet();
}
@Override
public BitSet readsEvalContextRecursive()
{
return new BitSet();
}
@Override
public BitSet writesEvalContextRecursive()
{
return new BitSet();
}
@Override
public BitSet readsEvalContextFlat()
{
return new BitSet();
}
@Override
public BitSet writesEvalContextFlat()
{
return new BitSet();
}
@Override
public boolean missingRequirement(final Game game)
{
return false;
}
@Override
public boolean willCrash(final Game game)
{
return false;
}
@Override
public String toEnglish(final Game game)
{
return name();
}
}
| 5,509 | 26.969543 | 114 | java |
Ludii | Ludii-master/Core/src/game/util/directions/StackDirection.java | package game.util.directions;
/**
* Describes the bottom or the top of a stack as origin for functions.
*
* @author Eric Piette
*/
public enum StackDirection
{
/** To check the stack from the bottom. */
FromBottom,
/** To check the stack from the top. */
FromTop;
}
| 277 | 16.375 | 70 | java |
Ludii | Ludii-master/Core/src/game/util/directions/package-info.java | /**
* Direction utilities define the various types of directions used in game descriptions.
* These include:
* \begin{itemize}
* \item {\it absolute} directions that remain constant in all contexts, and
* \item {\it relative} directions that depend on the player and their orientation.
* \end{itemize}
*/
package game.util.directions;
| 343 | 33.4 | 89 | java |
Ludii | Ludii-master/Core/src/game/util/end/Payoff.java | package game.util.end;
import java.util.BitSet;
import game.Game;
import game.functions.floats.FloatFunction;
import game.types.play.RoleType;
import game.types.state.GameType;
import other.BaseLudeme;
/**
* Defines a payoff to set when using the {\tt (payoffs ...)} end rule.
*
* @author Eric.Piette
*/
public class Payoff extends BaseLudeme
{
final RoleType role;
final FloatFunction payoff;
//-------------------------------------------------------------------------
/**
* @param role The role of the player.
* @param payoff The payoff of the player.
*
* @example (payoff P1 5.5)
*/
public Payoff(final RoleType role, final FloatFunction payoff)
{
this.role = role;
this.payoff = payoff;
}
//-------------------------------------------------------------------------
/**
* @return The role.
*/
public RoleType role()
{
return role;
}
/**
* @return The payoff.
*/
public FloatFunction payoff()
{
return payoff;
}
/**
* @param game The game.
* @return The game flags.
*/
public long gameFlags(final Game game)
{
long gameFlags = 0L;
gameFlags |= GameType.Payoff;
gameFlags |= payoff.gameFlags(game);
return gameFlags;
}
/**
* To preprocess.
*
* @param game The game.
*/
public void preprocess(final Game game)
{
payoff.preprocess(game);
}
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
concepts.or(payoff.concepts(game));
return concepts;
}
@Override
public BitSet writesEvalContextRecursive()
{
final BitSet writeEvalContext = new BitSet();
return writeEvalContext;
}
@Override
public BitSet readsEvalContextRecursive()
{
final BitSet readEvalContext = new BitSet();
return readEvalContext;
}
@Override
public boolean missingRequirement(final Game game)
{
boolean missingRequirement = false;
// We check if the role is correct.
if (role != null)
{
final int indexOwnerPhase = role().owner();
if (((indexOwnerPhase < 1 && !role().equals(RoleType.Mover)) && !role().equals(RoleType.Next)
&& !role().equals(RoleType.Prev)) || indexOwnerPhase > game.players().count())
{
game.addRequirementToReport(
"The ludeme (payoff ...) is used with an incorrect RoleType: " + role() + ".");
missingRequirement = true;
}
}
if (payoff != null)
missingRequirement |= payoff.missingRequirement(game);
return missingRequirement;
}
@Override
public boolean willCrash(final Game game)
{
boolean willCrash = false;
if (payoff != null)
willCrash |= payoff.willCrash(game);
return willCrash;
}
}
| 2,610 | 18.631579 | 96 | java |
Ludii | Ludii-master/Core/src/game/util/end/Score.java | package game.util.end;
import java.util.BitSet;
import game.Game;
import game.functions.ints.IntFunction;
import game.types.play.RoleType;
import game.types.state.GameType;
import other.BaseLudeme;
import other.concept.Concept;
/**
* Defines a score to set when using the {\tt (byScore ...)} end rule.
*
* @author Eric.Piette
*/
public class Score extends BaseLudeme
{
final RoleType role;
final IntFunction score;
//-------------------------------------------------------------------------
/**
* @param role The role of the player.
* @param score The score of the player.
*
* @example (score P1 100)
*/
public Score
(
final RoleType role,
final IntFunction score
)
{
this.role = role;
this.score = score;
}
//-------------------------------------------------------------------------
/**
* @return The role.
*/
public RoleType role()
{
return role;
}
/**
* @return The score.
*/
public IntFunction score()
{
return score;
}
/**
* @param game The game.
* @return The game flags.
*/
public long gameFlags(final Game game)
{
long gameFlags = 0L;
gameFlags |= GameType.Score;
gameFlags |= score.gameFlags(game);
return gameFlags;
}
/**
* To preprocess.
*
* @param game The game.
*/
public void preprocess(final Game game)
{
score.preprocess(game);
}
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
concepts.or(score.concepts(game));
concepts.set(Concept.Scoring.id(), true);
return concepts;
}
@Override
public BitSet writesEvalContextRecursive()
{
final BitSet writeEvalContext = new BitSet();
writeEvalContext.or(score.writesEvalContextRecursive());
return writeEvalContext;
}
@Override
public BitSet readsEvalContextRecursive()
{
final BitSet readEvalContext = new BitSet();
readEvalContext.or(score.readsEvalContextRecursive());
return readEvalContext;
}
@Override
public boolean missingRequirement(final Game game)
{
boolean missingRequirement = false;
// We check if the role is correct.
if (role != null)
{
final int indexOwnerPhase = role().owner();
if (((indexOwnerPhase < 1 && !role().equals(RoleType.Mover)) && !role().equals(RoleType.Next)
&& !role().equals(RoleType.Prev)) || indexOwnerPhase > game.players().count())
{
game.addRequirementToReport(
"The ludeme (score ...) is used with an incorrect RoleType: " + role() + ".");
missingRequirement = true;
}
}
if (score != null)
missingRequirement |= score.missingRequirement(game);
return missingRequirement;
}
@Override
public boolean willCrash(final Game game)
{
boolean willCrash = false;
if (score != null)
willCrash |= score.willCrash(game);
return willCrash;
}
}
| 2,785 | 18.758865 | 96 | java |
Ludii | Ludii-master/Core/src/game/util/end/package-info.java | /**
* This section describes support utility ludemes relevant to end rules.
*/
package game.util.end;
| 104 | 20 | 72 | java |
Ludii | Ludii-master/Core/src/game/util/equipment/Card.java | package game.util.equipment;
import annotations.Name;
import annotations.Opt;
import game.Game;
import game.types.component.CardType;
import main.Constants;
import other.BaseLudeme;
/**
* Defines an instance of a playing card.
*
* @author Eric.Piette
*/
public class Card extends BaseLudeme
{
/**
* The rank of the card.
*/
final private int rank;
/**
* The value of the card.
*/
final private int value;
/**
* The trump rank of the card.
*/
final private int trumpRank;
/**
* The trump value of the card.
*/
final private int trumpValue;
/**
* The trump value of the card.
*/
final private int biased;
/**
* The type of the card.
*/
final private CardType type;
//-------------------------------------------------------------------------
/**
* @param type The type of the card.
* @param rank The rank of the card.
* @param value The value of the card.
* @param trumpRank The trump rank of the card.
* @param trumpValue The trump value of the card.
* @param biased The biased value of the card.
*
* @example (card Seven rank:0 value:0 trumpRank:0 trumpValue:0)
*/
public Card
(
final CardType type,
@Name final Integer rank,
@Name final Integer value,
@Opt @Name final Integer trumpRank,
@Opt @Name final Integer trumpValue,
@Opt @Name final Integer biased
)
{
this.type = type;
this.rank = rank.intValue();
this.value = value.intValue();
this.trumpRank = (trumpRank == null) ? rank.intValue() : trumpRank.intValue();
this.trumpValue = (trumpValue == null) ? value.intValue() : trumpValue.intValue();
this.biased = (biased == null) ? Constants.UNDEFINED : biased.intValue();
}
/**
* @return The type of the card.
*/
public CardType type()
{
return type;
}
/**
* @return The rank of the card.
*/
public int rank()
{
return rank;
}
/**
* @return The value of the card.
*/
public int value()
{
return value;
}
/**
* @return The trump rank of the card.
*/
public int trumpRank()
{
return trumpRank;
}
/**
* @return The trump value of the card.
*/
public int trumpValue()
{
return trumpValue;
}
/**
* @return The biased value of the card.
*/
public int biased()
{
return biased;
}
@Override
public String toEnglish(final Game game)
{
return "a " + type.name() + " card with a rank of " + rank + ", a value of " + value + ", a trumprank of " + trumpRank + ", a trumpValue of " + trumpValue;
}
}
| 2,513 | 18.19084 | 157 | java |
Ludii | Ludii-master/Core/src/game/util/equipment/Hint.java | package game.util.equipment;
import annotations.Opt;
import other.BaseLudeme;
/**
* Defines a hint value to a region or a specific site.
*
* @author Eric.Piette
* @remarks This is used only for deduction puzzles.
*/
public class Hint extends BaseLudeme
{
/** The hint to put. */
final private Integer hint;
/** The place to put the hints. */
final private Integer[] region;
//-------------------------------------------------------------------------
/**
* For creating hints in a region.
*
* @param region The locations.
* @param hint The value of the hint [0].
* @example (hint {0 1 2 3 4 5} 1)
*/
public Hint
(
final Integer[] region,
@Opt final Integer hint
)
{
this.region = region;
this.hint = (hint == null) ? Integer.valueOf(0) : hint;
}
/**
* For creating hint in a site.
*
* @param site The location.
* @param hint The value of the hint [0].
* @example (hint 1 1)
*/
public Hint
(
final Integer site,
@Opt final Integer hint
)
{
this.hint = (hint == null) ? Integer.valueOf(0) : hint;
this.region = new Integer[1];
this.region[0] = site;
}
//-------------------------------------------------------------------------
/**
* @return The hint.
*/
public Integer hint()
{
return hint;
}
/**
* @return The list of the site in the region.
*/
public Integer[] region()
{
return region;
}
}
| 1,407 | 17.773333 | 76 | java |
Ludii | Ludii-master/Core/src/game/util/equipment/Region.java | package game.util.equipment;
import java.io.Serializable;
import java.util.List;
import annotations.Hide;
import game.Game;
import game.equipment.container.board.Board;
import game.types.board.SiteType;
import game.util.directions.AbsoluteDirection;
import game.util.graph.Step;
import gnu.trove.list.array.TIntArrayList;
import main.collections.ChunkSet;
import other.BaseLudeme;
import other.topology.Edge;
import other.topology.SiteFinder;
import other.topology.Topology;
import other.topology.TopologyElement;
/**
* Defines a region of sites within a container.
*
* @author cambolbro
*/
public final class Region extends BaseLudeme implements Serializable
{
/** */
private static final long serialVersionUID = 1L;
/** Sites in the region. */
private final ChunkSet bitSet;
private final String name;
//-------------------------------------------------------------------------
/**
* Constructor with a name, a board and coords.
*
* @param name
* @param board
* @param coords
*/
@Hide
public Region
(
final String name,
final Board board,
final String... coords
)
{
assert(board != null);
bitSet = new ChunkSet(1, board.topology().cells().size());
for (final String coord : coords)
{
final TopologyElement element = SiteFinder.find(board, coord, SiteType.Cell);
if (element == null)
System.out.println("** Region: Coord " + coord + " not found.");
else
bitSet.setChunk(element.index(), 1);
}
this.name = name;
}
/**
* Constructor with a counter.
*
* @param count
*/
@Hide
public Region(final int count)
{
bitSet = new ChunkSet(1, count);
bitSet.set(0, count);
name = "?";
}
/**
* Constructor with a ChunkSet.
*
* @param bitSet
*/
@Hide
public Region(final ChunkSet bitSet)
{
this.bitSet = bitSet.clone();
name = "?";
}
/**
* Copy constructor.
*
* @param other
*/
@Hide
public Region(final Region other)
{
bitSet = other.bitSet().clone();
name = "?";
}
/**
* Constructor for an empty region.
*/
@Hide
public Region()
{
bitSet = new ChunkSet();
name = "?";
}
/**
* Constructor with a array of int.
* @param bitsToSet
*/
@Hide
public Region(final int[] bitsToSet)
{
bitSet = new ChunkSet();
// In practice we very often pass arrays sorted from low to high, or
// at least partially sorted as such. A reverse loop through such an
// array is more efficient, since it lets us set the highest bit
// as early as possible, which means our ChunkSet can be correctly
// sized early on and doesn't need many subsequent re-sizes
for (int i = bitsToSet.length - 1; i >= 0; --i)
bitSet.set(bitsToSet[i]);
name = "?";
}
/**
* Constructor with a list of elements.
*
* @param elements the graph elements.
*/
@Hide
public Region(final List<? extends TopologyElement> elements)
{
bitSet = new ChunkSet();
for (final TopologyElement v : elements)
bitSet.set(v.index());
name = "?";
}
/**
* Constructor with a list
*
* @param list the list of sites.
*/
@Hide
public Region(final TIntArrayList list)
{
bitSet = new ChunkSet();
for (int i = 0 ; i < list.size();i++)
bitSet.set(list.get(i));
name = "?";
}
//-------------------------------------------------------------------------
/**
* @return The ChunkSet representation of the sites.
*/
public ChunkSet bitSet()
{
return bitSet;
}
/**
* @return Region name.
*/
public String name()
{
return name;
}
/**
* @return Number of set entries.
*/
public int count()
{
return bitSet.cardinality();
}
/**
* @return True if the region is empty.
*/
public boolean isEmpty()
{
return bitSet.isEmpty();
}
/**
* @return Array of ints containing the indices in the BitSet that are set.
*/
public int[] sites()
{
final int[] sites = new int[count()];
for (int i = 0, n = bitSet.nextSetBit(0); n >= 0; ++i, n = bitSet.nextSetBit(n + 1))
sites[i] = n;
return sites;
}
//-------------------------------------------------------------------------
/**
* To set a new count.
* @param newCount
*/
public void set(final int newCount)
{
bitSet.clear();
bitSet.set(0, newCount);
}
/**
* To set the current bitset with another region.
* @param other
*/
public void set(final Region other)
{
//bitSet = (ChunkSet) other.bitSet().clone();
bitSet.clear();
bitSet.or(other.bitSet());
}
/**
* @param n
* @return The bit.
*/
public int nthValue(final int n)
{
int bit = -1;
for (int i = 0; i <= n; ++i)
{
bit = bitSet.nextSetBit(bit + 1);
}
return bit;
}
/**
* To add a new site in the region.
*
* @param val
*/
public void add(final int val)
{
bitSet.set(val);
}
/**
* To remove a site in the region.
*
* @param val
*/
public void remove(final int val)
{
bitSet.clear(val);
}
/**
* @param loc
* @return true if this location is in this region
*/
public boolean contains(final int loc)
{
return bitSet.get(loc);
}
/**
*
*
* @param n
*/
public void removeNth(final int n)
{
remove(nthValue(n));
}
/**
* Performs a logical OR with this Region's BitSet and the other Region's
* BitSet. NOTE: this method modifies this Region, it does not create a new
* Region!
*
* @param other
*/
public void union(final Region other)
{
bitSet.or(other.bitSet());
}
/**
* Performs a logical OR with this Region's BitSet and the other BitSet.
* NOTE: this method modifies this Region, it does not create a new Region!
*
* @param other
*/
public void union(final ChunkSet other)
{
bitSet.or(other);
}
/**
* Performs a logical And with this Region's BitSet and the other Region's
* BitSet. NOTE: this method modifies this Region, it does not create a new
* Region!
*
* @param other
*/
public void intersection(final Region other)
{
bitSet.and(other.bitSet());
}
/**
* Removes bits in other from this bitset.
* NOTE: this method modifies this Region, it does not create a new Region!
*
* @param other
*/
public void remove(final Region other)
{
bitSet.andNot(other.bitSet());
}
//-------------------------------------------------------------------------
@Override
public int hashCode()
{
final int prime = 31;
int result = 1;
result = prime * result + (/*(bitSet == null) ? 0 :*/ bitSet.hashCode());
return result;
}
@Override
public boolean equals(final Object other)
{
return (other instanceof Region) && bitSet.equals(((Region) other).bitSet);
}
//-------------------------------------------------------------------------
/**
* Expand this region to adjacent cells a specified number of times.
*
* @param region The region.
* @param graph The topology.
* @param numLayers The number of layers.
* @param type The graph element type.
*/
public static void expand(final Region region, final Topology graph, final int numLayers, final SiteType type)
{
final List<? extends TopologyElement> elements = graph.getGraphElements(type);
for (int layer = 0; layer < numLayers; layer++)
{
final ChunkSet nbors = new ChunkSet();
final int[] sites = region.sites();
for (final int site : sites)
{
final TopologyElement element = elements.get(site);
for (final TopologyElement elementAdj : element.adjacent())
nbors.set(elementAdj.index(), true);
}
region.union(nbors);
}
}
/**
* Expand this region to one direction choice.
*
* @param region The region to expand.
* @param graph The graph.
* @param numLayers The number of layers.
* @param dirnChoice The direction.
* @param type The graph element type.
*/
public static void expand
(
final Region region,
final Topology graph,
final int numLayers,
final AbsoluteDirection dirnChoice,
final SiteType type
)
{
for (int i = 0; i < numLayers; i++)
{
final int[] sites = region.sites();
if (type.equals(SiteType.Edge))
{
for (final int site : sites)
{
final Edge edge = graph.edges().get(site);
for (final Edge edgeAdj : edge.adjacent())
if (!region.contains(edgeAdj.index()))
region.add(edgeAdj.index());
}
}
else
{
for (final int site : sites)
{
final List<Step> steps = graph.trajectories().steps(type, site, dirnChoice);
for (final Step step : steps)
{
if (step.from().siteType() != step.to().siteType())
continue;
final int to = step.to().id();
if (!region.contains(to))
region.add(to);
}
}
}
}
}
//-------------------------------------------------------------------------
@Override
public String toString()
{
String str = "[";
for (int n = bitSet.nextSetBit(0); n >= 0; n = bitSet.nextSetBit(n + 1))
str += n + ",";
if (str.length() > 1)
str = str.substring(0, str.length() - 1);
str += "]";
return str;
}
@Override
public String toEnglish(final Game game)
{
String regionName = "";
if (!name.equals("?"))
regionName = "region \"" + name + "\" ";
return regionName + toString();
}
//-------------------------------------------------------------------------
}
| 9,229 | 18.978355 | 111 | java |
Ludii | Ludii-master/Core/src/game/util/equipment/TrackStep.java | package game.util.equipment;
import java.io.Serializable;
import annotations.Hide;
import annotations.Or;
import game.types.board.TrackStepType;
import game.util.directions.CompassDirection;
import other.BaseLudeme;
//-----------------------------------------------------------------------------
/**
* Defines a step within a track.
*
* @author cambolbro
*
* @remarks Track steps may be specified by number, dim function, compass direction
* or constant attribute (End/Off/Repeat).
*/
@Hide
public final class TrackStep extends BaseLudeme implements Serializable
{
/** */
private static final long serialVersionUID = 1L;
/** Dim function or integer. */
private final Integer dim;
/** Compass direction. */
private final CompassDirection dirn;
/** Constant value: Off/End/Repeat. */
private final TrackStepType step;
//-------------------------------------------------------------------------
/**
* Constructor defining either a number, a direction or a step type.
*
* @param dim Dim function or integer.
* @param dirn Compass direction.
* @param step Track step type: Off/End/Repeat.
*/
public TrackStep
(
@Or final Integer dim,
@Or final CompassDirection dirn,
@Or final TrackStepType step
)
{
int numNonNull = 0;
if (dim != null)
numNonNull++;
if (dirn != null)
numNonNull++;
if (step != null)
numNonNull++;
if (numNonNull != 1)
throw new IllegalArgumentException("TrackStep(): Exactly one parameter must be non-null.");
this.dim = dim;
this.dirn = dirn;
this.step = step;
}
//-------------------------------------------------------------------------
/**
* @return Integer value or dim function.
*/
public Integer dim()
{
return dim;
}
/**
* @return Compass direction.
*/
public CompassDirection dirn()
{
return dirn;
}
/**
* @return Track step type: Off/End/Repeat.
*/
public TrackStepType step()
{
return step;
}
//-------------------------------------------------------------------------
@Override
public int hashCode()
{
if (dim != null)
return dim.hashCode();
if (dirn != null)
return dirn.hashCode();
if (step != null)
return step.hashCode();
return 0;
}
@Override
public boolean equals(Object other)
{
return
other instanceof TrackStep
&&
(dim == null && ((TrackStep)other).dim == null || dim.equals(((TrackStep)other).dim))
&&
(dirn == null && ((TrackStep)other).dirn == null || dirn.equals(((TrackStep)other).dirn))
&&
(step == null && ((TrackStep)other).step == null || step.equals(((TrackStep)other).step));
}
//-------------------------------------------------------------------------
@Override
public String toString()
{
return "A TrackStep...";
}
//-------------------------------------------------------------------------
}
| 2,852 | 20.613636 | 94 | java |
Ludii | Ludii-master/Core/src/game/util/equipment/Values.java | package game.util.equipment;
import game.functions.range.Range;
import game.types.board.SiteType;
import other.BaseLudeme;
/**
* Defines the set of values of a graph variable in a deduction puzzle.
*
* @author Eric.Piette
*/
public class Values extends BaseLudeme
{
/** The graph element type. */
final private SiteType type;
/** The range of the values. */
final private Range range;
//-------------------------------------------------------------------------
/**
* @param type The graph element type.
* @param range The range of the values.
* @example (values Cell (range 1 9))
*/
public Values
(
final SiteType type,
final Range range
)
{
this.range = range;
this.type = type;
}
//-------------------------------------------------------------------------
/**
* @return The graph element type.
*/
public SiteType type()
{
return type;
}
/**
* @return The range.
*/
public Range range()
{
return range;
}
}
| 972 | 16.690909 | 76 | java |
Ludii | Ludii-master/Core/src/game/util/equipment/package-info.java | /**
* Ludeme utilities are useful support classes that various types of ludeme classes refer to.
*/
package game.util.equipment;
| 131 | 25.4 | 93 | java |
Ludii | Ludii-master/Core/src/game/util/graph/Bucket.java | package game.util.graph;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* Bucket for sorting coordinates along a dimension.
*
* @author cambolbro
*/
public class Bucket
{
private final List<ItemScore> items = new ArrayList<ItemScore>();
private double total = 0; // item total score of items
//-------------------------------------------------------------------------
/**
* @return a List of ItemScore.
*/
public List<ItemScore> items()
{
return Collections.unmodifiableList(items);
}
/**
* @return The mean.
*/
public double mean()
{
return items.isEmpty() ? 0 : total / items.size();
}
//-------------------------------------------------------------------------
/**
* To add an item.
*
* @param item The item.
*/
public void addItem(final ItemScore item)
{
items.add(item);
total += item.score();
}
//-------------------------------------------------------------------------
}
| 977 | 18.176471 | 76 | java |
Ludii | Ludii-master/Core/src/game/util/graph/Edge.java | package game.util.graph;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.List;
import game.types.board.SiteType;
import game.util.directions.AbsoluteDirection;
import main.math.Point3D;
import main.math.Vector;
//-----------------------------------------------------------------------------
/**
* Defines a Graph edge.
*
* @author cambolbro
*/
public class Edge extends GraphElement
{
/** These can't be final, as faces might get merged. */
private Vertex vertexA = null;
private Vertex vertexB = null;
/** These can't be final, as faces get calculated afterwards. */
private Face left = null;
private Face right = null;
/** Whether to use end point pivots to define curved edge. */
//private final boolean curved;
private Vector tangentA = null;
private Vector tangentB = null;
//-------------------------------------------------------------------------
/**
* Define an edge.
*
* @param id
* @param va
* @param vb
*/
public Edge
(
final int id, final Vertex va, final Vertex vb //, final boolean curved
)
{
this.id = id;
this.vertexA = va;
this.vertexB = vb;
// this.curved = curved;
setMidpoint();
}
//-------------------------------------------------------------------------
/**
* @return The vertex A.
*/
public Vertex vertexA()
{
return vertexA;
}
/**
* Set the vertex A.
*
* @param vertA
*/
public void setVertexA(final Vertex vertA)
{
vertexA = vertA;
setMidpoint();
}
/**
* @return The vertex B.
*/
public Vertex vertexB()
{
return vertexB;
}
/**
* Set the vertex B.
*
* @param vertB
*/
public void setVertexB(final Vertex vertB)
{
vertexB = vertB;
setMidpoint();
}
/**
* @return The face to the left.
*/
public Face left()
{
return left;
}
/**
* Set the face to the left.
*
* @param face
*/
public void setLeft(final Face face)
{
left = face;
}
/**
* @return The face to the right.
*/
public Face right()
{
return right;
}
/**
* Set the face to the right.
*
* @param face
*/
public void setRight(final Face face)
{
right = face;
}
/**
* @return True if the edge is curved.
*/
public boolean curved()
{
// return curved;
return tangentA != null && tangentB != null;
}
// public void setCurved(final boolean value)
// {
// curved = value;
// }
/**
* @return The vector of the tangent from the vertex A.
*/
public Vector tangentA()
{
return tangentA;
}
/**
* Set the vector of the tangent A.
*
* @param vec
*/
public void setTangentA(final Vector vec)
{
tangentA = vec;
}
/**
* @return The vector of the tangent from the vertex B.
*/
public Vector tangentB()
{
return tangentB;
}
/**
* Set the vector of the tangent B.
*
* @param vec
*/
public void setTangentB(final Vector vec)
{
tangentB = vec;
}
//-------------------------------------------------------------------------
@Override
public Vertex pivot()
{
if (vertexA.pivot() != null)
return vertexA.pivot();
return vertexB.pivot();
}
//-------------------------------------------------------------------------
@Override
public SiteType siteType()
{
return SiteType.Edge;
}
//-------------------------------------------------------------------------
/**
* @param vertex
* @return True if the vertex is on the edge.
*/
public boolean contains(final Vertex vertex)
{
return contains(vertex.id());
}
/**
* @param vid
* @return True if the vertex is on the edge.
*/
public boolean contains(final int vid)
{
return vertexA.id() == vid || vertexB.id() == vid;
}
//-------------------------------------------------------------------------
/**
* @return True if the edge is exterior.
*/
public boolean isExterior()
{
return left == null || right == null;
}
//-------------------------------------------------------------------------
/**
* @return The length of the edge.
*/
public double length()
{
return vertexA.pt().distance(vertexB.pt()); //MathRoutines.distance(va.x(), va.y(), vb.x(), vb.y());
}
//-------------------------------------------------------------------------
/**
* @param other
* @return True if the edge is the same of the object in entry.
*/
public boolean matches(final Edge other)
{
return matches(other.vertexA.id(), other.vertexB.id());
}
/**
* @param vc
* @param vd
* @return True if the edge uses the two vertices in entry.
*/
public boolean matches(final Vertex vc, final Vertex vd)
{
return matches(vc.id(), vd.id());
}
/**
* @param idA
* @param idB
* @return True if the edge uses the two vertices indices in entry.
*/
public boolean matches(final int idA, final int idB)
{
return vertexA.id() == idA && vertexB.id() == idB
||
vertexA.id() == idB && vertexB.id() == idA;
}
/**
* @param idA
* @param idB
* @param curved
* @return True if the edge match and if the edge is curved.
*/
public boolean matches(final int idA, final int idB, final boolean curved)
{
return (
vertexA.id() == idA && vertexB.id() == idB
||
vertexA.id() == idB && vertexB.id() == idA
)
&&
curved() == curved;
}
//-------------------------------------------------------------------------
/**
* @param other
* @param tolerance
* @return True if the vertices are coincident.
*/
public boolean coincidentVertices(final Edge other, final double tolerance)
{
return vertexA.coincident(other.vertexA, tolerance) && vertexB.coincident(other.vertexB, tolerance)
||
vertexA.coincident(other.vertexB, tolerance) && vertexB.coincident(other.vertexA, tolerance);
}
//-------------------------------------------------------------------------
/**
* @param other
* @return True if two edges shares a vertex.
*/
public boolean sharesVertex(final Edge other)
{
return sharesVertex(other.vertexA().id()) || sharesVertex(other.vertexB().id());
}
/**
* @param v
* @return True if the vertex is on the edge.
*/
public boolean sharesVertex(final Vertex v)
{
return sharesVertex(v.id());
}
/**
* @param vid
* @return True if the vertex is on the edge.
*/
public boolean sharesVertex(final int vid)
{
return vertexA.id() == vid || vertexB.id() == vid;
}
//-------------------------------------------------------------------------
/**
* @param vid
* @return The other vertex of the edge.
*/
public Vertex otherVertex(final int vid)
{
if (vid == vertexA.id())
return vertexB;
if (vid == vertexB.id())
return vertexA;
return null;
}
/**
* @param v
* @return The other vertex of the edge.
*/
public Vertex otherVertex(final Vertex v)
{
return otherVertex(v.id());
}
//-------------------------------------------------------------------------
/**
* @param fid
* @return The other face of the edge.
*/
public Face otherFace(final int fid)
{
if (left != null && left.id() == fid)
return right;
if (right != null && right.id() == fid)
return left;
return null;
}
/**
* @param face
* @return The other face of the edge.
*/
public Face otherFace(final Face face)
{
return otherFace(face.id());
}
//-------------------------------------------------------------------------
/**
* Set the midpoint of the edge.
*/
public void setMidpoint()
{
pt = new Point3D
(
(vertexA.pt.x() + vertexB.pt.x()) * 0.5,
(vertexA.pt.y() + vertexB.pt.y()) * 0.5,
(vertexA.pt.z() + vertexB.pt.z()) * 0.5
);
}
//-------------------------------------------------------------------------
@Override
public List<GraphElement> nbors()
{
final List<GraphElement> nbors = new ArrayList<GraphElement>();
for (final Edge edgeA : vertexA.edges())
if (edgeA.id() != id)
nbors.add(edgeA);
for (final Edge edgeB : vertexB.edges())
if (edgeB.id() != id)
nbors.add(edgeB);
return nbors;
}
//-------------------------------------------------------------------------
@Override
public void stepsTo(final Steps steps)
{
//-------------------------------------------------
// Steps to coincident edges
for (int v = 0; v < 2; v++)
{
final Vertex vertex = (v == 0) ? vertexA : vertexB;
for (final Edge other : vertex.edges())
{
if (other.id == id)
continue; // don't step to self
final Step newStep = new Step(this, other);
newStep.directions().set(AbsoluteDirection.Orthogonal.ordinal());
newStep.directions().set(AbsoluteDirection.Adjacent.ordinal());
newStep.directions().set(AbsoluteDirection.All.ordinal());
steps.add(newStep);
}
}
// **
// ** TODO: Assumes that all coincident edges are orthogonal/adjacent.
// ** Instead, perhaps only the straightest continuation should
// ** be orthogonal and all others diagonal?
// **
//-------------------------------------------------
// Steps to vertices
for (int v = 0; v < 2; v++)
{
final Vertex vertex = (v == 0) ? vertexA : vertexB;
final Step newStep = new Step(this, vertex);
newStep.directions().set(AbsoluteDirection.Orthogonal.ordinal());
newStep.directions().set(AbsoluteDirection.Adjacent.ordinal());
newStep.directions().set(AbsoluteDirection.All.ordinal());
steps.add(newStep);
}
//-------------------------------------------------
// Steps to faces
final BitSet usedFaces = new BitSet();
if (left != null)
{
// Left edge is orthogonal (perpendicular)
usedFaces.set(left.id(), true);
final Step newStep = new Step(this, left);
newStep.directions().set(AbsoluteDirection.Orthogonal.ordinal());
newStep.directions().set(AbsoluteDirection.Adjacent.ordinal());
newStep.directions().set(AbsoluteDirection.All.ordinal());
steps.add(newStep);
}
if (right != null)
{
// Right edge is orthogonal (perpendicular)
usedFaces.set(right.id(), true);
final Step newStep = new Step(this, right);
newStep.directions().set(AbsoluteDirection.Orthogonal.ordinal());
newStep.directions().set(AbsoluteDirection.Adjacent.ordinal());
newStep.directions().set(AbsoluteDirection.All.ordinal());
steps.add(newStep);
}
// Add faces coincident with end points
for (int v = 0; v < 2; v++)
{
final Vertex vertex = (v == 0) ? vertexA : vertexB;
for (final Face face : vertex.faces())
{
if (usedFaces.get(face.id()))
continue;
usedFaces.set(face.id(), true);
final Step newStep = new Step(this, face);
newStep.directions().set(AbsoluteDirection.Orthogonal.ordinal());
newStep.directions().set(AbsoluteDirection.Adjacent.ordinal());
newStep.directions().set(AbsoluteDirection.All.ordinal());
steps.add(newStep);
}
}
}
//-------------------------------------------------------------------------
@Override
public String toString()
{
final StringBuilder sb = new StringBuilder();
sb.append("Edge[" + id + "]: " + vertexA.id() + " => " + vertexB.id());
if (left != null)
sb.append(" L=" + left.id());
if (right != null)
sb.append(" R=" + right.id());
sb.append(" " + properties);
// if (curved)
// sb.append(" curved");
if (tangentA != null)
sb.append(" " + tangentA);
if (tangentB != null)
sb.append(" " + tangentB);
sb.append(" \"" + situation.label() + "\"");
return sb.toString();
}
//-------------------------------------------------------------------------
}
| 11,526 | 19.920145 | 103 | java |
Ludii | Ludii-master/Core/src/game/util/graph/Face.java | package game.util.graph;
import java.awt.geom.Point2D;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.Collections;
import java.util.List;
import game.types.board.SiteType;
import game.util.directions.AbsoluteDirection;
import main.math.MathRoutines;
import main.math.Point3D;
//-----------------------------------------------------------------------------
/**
* Defines a face in a graph.
*
* @author cambolbro
*/
public class Face extends GraphElement
{
private final List<Vertex> vertices = new ArrayList<Vertex>();
private final List<Edge> edges = new ArrayList<Edge>();
//-------------------------------------------------------------------------
/**
* A face.
*
* @param id
*/
public Face(final int id)
{
this.id = id;
}
//-------------------------------------------------------------------------
// @Override
// public int id()
// {
// return id;
// }
/**
* @return The vertices of the face.
*/
public List<Vertex> vertices()
{
return Collections.unmodifiableList(vertices);
}
/**
* @return The edges of the face.
*/
public List<Edge> edges()
{
return Collections.unmodifiableList(edges);
}
//-------------------------------------------------------------------------
// public void clearVertices()
// {
// vertices.clear();
// }
//
// public void addVertex(final Vertex vertex)
// {
// vertices.add(vertex);
// }
//
// public void removeVertex(final int n)
// {
// vertices.remove(n);
// }
//
// public void clearEdges()
// {
// edges.clear();
// }
//
// public void addEdge(final Edge edge)
// {
// edges.add(edge);
// }
//
// public void removeEdge(final int n)
// {
// edges.remove(n);
// }
//-------------------------------------------------------------------------
@Override
public Vertex pivot()
{
for (final Vertex vertex : vertices)
if (vertex.pivot() != null)
return vertex.pivot();
return null;
}
//-------------------------------------------------------------------------
@Override
public SiteType siteType()
{
return SiteType.Cell;
}
//-------------------------------------------------------------------------
/**
* Add a vertex and an edge to the face.
*
* @param vertex
* @param edge
*/
public void addVertexAndEdge(final Vertex vertex, final Edge edge)
{
vertices.add(vertex);
edges.add(edge);
setMidpoint();
}
//-------------------------------------------------------------------------
/**
* @param vids
*
* @return Whether the provided list of vertex indices matches this cell's
* vertices, forwards or backwards, starting at any point.
*/
public boolean matches(final int ... vids)
{
final int numSides = vertices.size();
// System.out.print("\nFace:");
// for (final Vertex vertex : vertices)
// System.out.print(" " + vertex.id());
// System.out.println();
if (vids.length != numSides)
return false;
int start;
for (start = 0; start < numSides; start++)
if (vertices.get(start).id() == vids[0])
break;
if (start >= numSides)
return false;
// Try forwards
// System.out.print("Forwards:");
int n;
for (n = 0; n < numSides; n++)
{
final int nn = (start + n) % numSides;
// System.out.print(" " + vertices.get(nn).id());
if (vertices.get(nn).id() != vids[n])
break;
}
if (n >= numSides)
return true; // all match
// Try backwards
// System.out.print("\nBackwards:");
for (n = 0; n < numSides; n++)
{
final int nn = (start - n + numSides) % numSides;
// System.out.print(" " + vertices.get(nn).id());
if (vertices.get(nn).id() != vids[n])
break;
}
// System.out.println();
return (n >= numSides); // all match
}
//-------------------------------------------------------------------------
/**
* Set the midpoint.
*/
public void setMidpoint()
{
double xx = 0;
double yy = 0;
double zz = 0;
if (!vertices.isEmpty())
{
for (final Vertex vertex : vertices)
{
xx += vertex.pt().x();
yy += vertex.pt().y();
zz += vertex.pt().z();
}
xx /= vertices.size();
yy /= vertices.size();
zz /= vertices.size();
}
pt = new Point3D(xx, yy, zz);
}
//-------------------------------------------------------------------------
/**
* @param vertexIn
* @return True if vertexIn is one of the face's vertices.
*/
public boolean contains(final Vertex vertexIn)
{
for (final Vertex vertex : vertices())
if (vertex.id() == vertexIn.id())
return true;
return false;
}
/**
* @param edgeIn
* @return true if that face contains that edge.
*/
public boolean contains(final Edge edgeIn)
{
for (final Edge edge : edges())
if (edge.id() == edgeIn.id())
return true;
return false;
}
/**
* @param p Point to test.
* @return Whether pt is within this face (assume planar).
*/
public boolean contains(final Point2D p)
{
final List<Point2D> poly = new ArrayList<>();
for (final Vertex vertex : vertices)
poly.add(vertex.pt2D());
return MathRoutines.pointInPolygon(p, poly);
}
//-------------------------------------------------------------------------
@Override
public List<GraphElement> nbors()
{
final List<GraphElement> nbors = new ArrayList<GraphElement>();
for (final Edge edge : edges())
{
final Face nbor = edge.otherFace(id);
if (nbor != null)
nbors.add(nbor);
}
return nbors;
}
//-------------------------------------------------------------------------
@Override
public void stepsTo(final Steps steps)
{
final BitSet usedFaces = new BitSet();
usedFaces.set(id, true); // set this face as 'used' to exclude self from tests
//-------------------------------------------------
// Steps to adjacent cells
for (final Edge edge : edges)
{
final Face other = edge.otherFace(id);
if (other == null)
continue;
usedFaces.set(other.id(), true); // used as an adjacent neighbour
final Step newStep = new Step(this, other);
newStep.directions().set(AbsoluteDirection.Orthogonal.ordinal());
newStep.directions().set(AbsoluteDirection.Adjacent.ordinal());
newStep.directions().set(AbsoluteDirection.All.ordinal());
steps.add(newStep);
}
// **
// ** TODO: Assumes that all coincident edges are orthogonal/adjacent.
// ** Instead, perhaps only the straightest continuation should
// ** be orthogonal and all others diagonal?
// **
//-------------------------------------------------
// Steps to diagonal cells joined by a vertex, e.g. square grid.
for (final Vertex vertex : vertices)
{
// Look for a diagonal cell connected through this vertex
double bestDistance = 1000000;
Face diagonal = null;
// Check faces around each vertex
for (final Face other : vertex.faces())
{
if (usedFaces.get(other.id()))
continue;
final double dist = MathRoutines.distanceToLine(vertex.pt2D(), pt2D(), other.pt2D());
if (dist < bestDistance)
{
bestDistance = dist;
diagonal = other;
}
}
if (diagonal == null)
continue; // no diagonal on this corner
// **
// ** TODO: Check for case of diagonals of equal angle.
// **
usedFaces.set(diagonal.id(), true); // adjacent diagonal neighbour
final Step newStep = new Step(this, diagonal);
newStep.directions().set(AbsoluteDirection.Diagonal.ordinal());
newStep.directions().set(AbsoluteDirection.Adjacent.ordinal());
newStep.directions().set(AbsoluteDirection.All.ordinal());
steps.add(newStep);
}
//-------------------------------------------------
// Steps to off-diagonal cells joined by a vertex, e.g. tri grid.
for (final Vertex vertex : vertices)
{
// Look for remaining off-diagonal cells connected through this vertex
for (final Face other : vertex.faces())
{
if (usedFaces.get(other.id()))
continue;
usedFaces.set(other.id(), true); // adjacent off-diagonal neighbour
final Step newStep = new Step(this, other);
newStep.directions().set(AbsoluteDirection.OffDiagonal.ordinal());
newStep.directions().set(AbsoluteDirection.Adjacent.ordinal());
newStep.directions().set(AbsoluteDirection.All.ordinal());
steps.add(newStep);
}
}
//-------------------------------------------------
// Steps to non-adjacent diagonal cells joined by an edge, e.g. hex grid.
for (final Vertex vertex : vertices)
{
// Look for non-adjacent diagonal cell connected through and edge
if (vertex.edges().size() != 3)
continue; // only applies to trivalent intersections
final Vertex otherVertex = vertex.edgeAwayFrom(this);
if (otherVertex == null)
{
System.out.println("** Null otherVertex in Face non-adjacent diagonals test.");
continue;
}
for (final Face otherFace : otherVertex.faces())
{
if (usedFaces.get(otherFace.id()))
continue;
final double distV = MathRoutines.distanceToLine(vertex.pt2D(), pt2D(), otherFace.pt2D());
final double distOV = MathRoutines.distanceToLine(otherVertex.pt2D(), pt2D(), otherFace.pt2D());
final double distAB = MathRoutines.distance(pt2D(), otherFace.pt2D());
final double error = (distV + distOV) / distAB;
if (error > 0.1)
{
// Edge is not close to lying on a diagonal between both faces
continue;
}
usedFaces.set(otherFace.id(), true); // non-adjacent diagonal neighbour
final Step newStep = new Step(this, otherFace);
newStep.directions().set(AbsoluteDirection.Diagonal.ordinal());
newStep.directions().set(AbsoluteDirection.All.ordinal());
steps.add(newStep);
}
}
//-------------------------------------------------
// Steps to vertices
for (final Vertex vertex : vertices)
{
final Step newStep = new Step(this, vertex);
newStep.directions().set(AbsoluteDirection.Orthogonal.ordinal());
newStep.directions().set(AbsoluteDirection.Adjacent.ordinal());
newStep.directions().set(AbsoluteDirection.All.ordinal());
steps.add(newStep);
}
//-------------------------------------------------
// Steps to edges
for (final Edge edge : edges)
{
final Step newStep = new Step(this, edge);
newStep.directions().set(AbsoluteDirection.Orthogonal.ordinal());
newStep.directions().set(AbsoluteDirection.Adjacent.ordinal());
newStep.directions().set(AbsoluteDirection.All.ordinal());
steps.add(newStep);
}
// return stepsTo;
}
//-------------------------------------------------------------------------
/**
* From: Yuceer and Oflazer 'A Rotation, Scaling, and Translation Invariant
* Pattern Classification System', Pattern Recognition, 26:5, 1993, 687--710.
*
* @return Angular momentum through this polygon.
*/
public double momentum()
{
// final int numVertices = vertices().size();
// double xav = 0;
// double yav = 0;
// for (final Vertex vertex : face.vertices())
// {
// xav += vertex.pt().x();
// yav += vertex.pt().y();
// }
// xav /= numVertices;
// yav /= numVertices;
//
// double rav = 0;
// for (final Vertex vertex : face.vertices())
// {
// final double dx = vertex.pt().x() - xav;
// final double dy = vertex.pt().y() - yav;
// rav += Math.sqrt(dx * dx + dy * dy);
// vertex.pt().x();
// yav += vertex.pt().y();
// }
// xav /= numVertices;
// yav /= numVertices;
double Txx = 0;
double Tyy = 0;
double Txy = 0;
for (final Vertex vertex : vertices())
{
final double x = vertex.pt().x() - pt.x();
final double y = vertex.pt().y() - pt.y();
Txx += x * x;
Tyy += y * y;
Txy += x * y;
}
// Txx -= numVertices * pt.x() * pt.x();
// Tyy -= numVertices * pt.y() * pt.y();
// Txy -= numVertices * pt.x() * pt.y();
System.out.println("\nTxx=" + Txx + ", Tyy=" + Tyy + ", Txy=" + Txy + ".");
final double sinTheta =
(Tyy - Txx + Math.sqrt((Tyy - Txx) * (Tyy - Txx) + 4 * Txy * Txy))
/
Math.sqrt
(
(
8 * Txy * Txy + 2 * (Tyy - Txx) * (Tyy - Txx)
+
2 * Math.abs(Tyy - Txx) * Math.sqrt((Tyy - Txx) * (Tyy - Txx) + 4 * Txy * Txy)
)
);
System.out.println("sinTheta=" + sinTheta);
final double cosTheta =
2 * Txy
/
Math.sqrt
(
(
8 * Txy * Txy + 2 * (Tyy - Txx) * (Tyy - Txx)
+
2 * Math.abs(Tyy - Txx) * Math.sqrt((Tyy - Txx) * (Tyy - Txx) + 4 * Txy * Txy)
)
);
System.out.println("cosTheta=" + cosTheta);
//double theta = Math.asin(sinTheta);
final double theta = Math.acos(cosTheta);
return theta;
}
//-------------------------------------------------------------------------
@Override
public String toString()
{
final StringBuilder sb = new StringBuilder();
sb.append("Face[" + id + "]:");
for (final Vertex vertex : vertices)
sb.append(" " + vertex.id());
sb.append(" " + properties);
sb.append(" \"" + situation.label() + "\"");
return sb.toString();
}
//-------------------------------------------------------------------------
}
| 13,097 | 23.077206 | 100 | java |
Ludii | Ludii-master/Core/src/game/util/graph/Graph.java | package game.util.graph;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.Collections;
import java.util.List;
import annotations.Hide;
import annotations.Name;
import annotations.Opt;
import game.Game;
import game.functions.graph.BaseGraphFunction;
import game.types.board.BasisType;
import game.types.board.ShapeType;
import game.types.board.SiteType;
import gnu.trove.list.array.TIntArrayList;
import main.math.MathRoutines;
import main.math.Point3D;
import main.math.Vector;
import other.context.Context;
//-----------------------------------------------------------------------------
/**
* Defines the graph of a custom board described by a set of vertices and edges.
*
* @author cambolbro
*/
public class Graph extends BaseGraphFunction
{
private static final long serialVersionUID = 1L;
/** Types of graph elements. */
public final static SiteType[] siteTypes = { SiteType.Vertex, SiteType.Edge, SiteType.Cell };
private final List<Vertex> vertices = new ArrayList<Vertex>();
private final List<Edge> edges = new ArrayList<Edge>();
private final List<Face> faces = new ArrayList<Face>();
/**
* List of perimeters (vertices) for each connected component in the graph.
* This list is used for rough working during graph measurements
* (for thread safety) and is not intended for reuse afterwards.
*/
private final List<Perimeter> perimeters = new ArrayList<Perimeter>();
private final Trajectories trajectories = new Trajectories();
private final boolean[] duplicateCoordinates = new boolean[SiteType.values().length];
//-------------------------------------------------------------------------
/**
* @param vertices List of vertex positions in {x y} or {x y z} format.
* @param edges List of vertex index pairs {vi vj} describing edge end points.
*
* @example (graph vertices:{ {0 0} {1.5 0 0.5} {0.5 1} }
* edges:{ {0 1} {0 2} {1 2} } )
*/
public Graph
(
@Name final Float[][] vertices,
@Opt @Name final Integer[][] edges
)
{
setVertices(vertices);
if (edges != null)
setEdges(edges);
assemble(false);
}
/**
* @param vertices The vertices.
* @param edges The edges.
*/
@Hide
public Graph
(
final List<Vertex> vertices,
final List<Edge> edges
)
{
for (final Vertex vertex : vertices)
addVertex(vertex.pt());
// Link up pivots
for (final Vertex vertex : vertices)
if (vertex.pivot() != null)
{
final Vertex newVertex = this.vertices.get(vertex.id());
final Vertex pivot = findVertex(vertex.pivot().pt2D());
if (pivot == null)
{
// System.out.println("** Failed to find pivot in Graph constructor.");
}
newVertex.setPivot(pivot);
}
for (final Edge edge : edges)
{
final Edge newEdge = findOrAddEdge(edge.vertexA().id(), edge.vertexB().id()); //, edge.curved());
if (edge.tangentA() != null)
newEdge.setTangentA(new Vector(edge.tangentA()));
if (edge.tangentB() != null)
newEdge.setTangentB(new Vector(edge.tangentB()));
}
assemble(false);
}
/**
* @param other Stop JavaDoc whining.
*/
@Hide
public Graph(final Graph other)
{
deepCopy(other);
}
/**
* Default constructor when edges and vertices are not known (or not needed
* to be known), e.g. for Mancala.
*/
@Hide
public Graph()
{
}
//-------------------------------------------------------------------------
/**
* @return The vertices of the graph.
*/
public List<Vertex> vertices()
{
return Collections.unmodifiableList(vertices);
}
/**
* @return The edges of the graph.
*/
public List<Edge> edges()
{
return Collections.unmodifiableList(edges);
}
/**
* @return The faces of the graph.
*/
public List<Face> faces()
{
return Collections.unmodifiableList(faces);
}
/**
* @return The perimeters of the graph.
*/
public List<Perimeter> perimeters()
{
return Collections.unmodifiableList(perimeters);
}
/**
* @return The trajectories of the graph.
*/
public Trajectories trajectories()
{
return trajectories;
}
/**
* @param siteType Site type to check.
*
* @return Whether this graph contains duplicate coordinates.
*/
public boolean duplicateCoordinates(final SiteType siteType)
{
return duplicateCoordinates[siteType.ordinal()];
}
/**
* Sets the duplicate coordinate flag to true.
*
* @param siteType Site type to check.
*/
public void setDuplicateCoordinates(final SiteType siteType)
{
duplicateCoordinates[siteType.ordinal()] = true;
}
//-------------------------------------------------------------------------
/**
* Set the dimension of the graph.
*
* @param array
*/
public void setDim(final int[] array)
{
dim = array;
}
//-------------------------------------------------------------------------
/**
* Clear the perimeters.
*/
public void clearPerimeters()
{
perimeters.clear();
}
/**
* Add a perimeter.
*
* @param perimeter The perimeter to add.
*/
public void addPerimeter(final Perimeter perimeter)
{
perimeters.add(perimeter);
}
/**
* Remove a perimeter.
*
* @param n The index of the perimeter.
*/
public void removePerimeter(final int n)
{
perimeters.remove(n);
}
//-------------------------------------------------------------------------
/**
* @param type The graph element type.
*
* @return The graph element list of the specified type.
*/
public List<? extends GraphElement> elements(final SiteType type)
{
switch (type)
{
case Vertex: return vertices;
case Edge: return edges;
case Cell: return faces;
}
return null;
}
//-------------------------------------------------------------------------
/**
* @param type The graph element type.
* @param id The index of the element.
*
* @return The specified graph element of the specified type.
*/
public GraphElement element(final SiteType type, final int id)
{
switch (type)
{
case Vertex: return vertices.get(id);
case Edge: return edges.get(id);
case Cell: return faces.get(id);
}
return null;
}
//-------------------------------------------------------------------------
/**
* Helper function for convenience.
*
* @param vertexList The list of the vertices.
* @param edgeList The list of the edges.
*
* @return Graph made from lists of vertex (x,y) pairs and edge (a, b) pairs.
*/
public static Graph createFromLists
(
final List<double[]> vertexList,
final List<int[]> edgeList
)
{
// Convert to arrays to construct graph
final Float[][] vertexArray = new Float[vertexList.size()][3];
for (int v = 0; v < vertexList.size(); v++)
{
final double[] values = vertexList.get(v);
vertexArray[v][0] = Float.valueOf((float)values[0]);
vertexArray[v][1] = Float.valueOf((float)values[1]);
if (values.length > 2)
vertexArray[v][2] = Float.valueOf((float)values[2]);
else
vertexArray[v][2] = Float.valueOf(0f);
}
final Integer[][] edgeArray = new Integer[edgeList.size()][2];
for (int e = 0; e < edgeList.size(); e++)
{
edgeArray[e][0] = Integer.valueOf(edgeList.get(e)[0]);
edgeArray[e][1] = Integer.valueOf(edgeList.get(e)[1]);
}
return new Graph(vertexArray, edgeArray);
}
//-------------------------------------------------------------------------
/**
* Clear the graph.
*/
public void clear()
{
faces.clear();
edges.clear();
vertices.clear();
}
/**
* Clear a type of graph element.
*
* @param siteType The type of the graph element.
*/
public void clear(final SiteType siteType)
{
switch (siteType)
{
case Vertex:
vertices.clear();
//$FALL-THROUGH$
case Edge:
edges.clear();
for (final Vertex vertex : vertices())
vertex.clearEdges();
//$FALL-THROUGH$
case Cell:
faces.clear();
for (final Edge edge : edges())
{
edge.setLeft(null);
edge.setRight(null);
}
for (final Vertex vertex : vertices())
vertex.clearFaces();
//$FALL-THROUGH$
default: // do nothing
}
}
//-------------------------------------------------------------------------
/**
* Make a deep copy.
*
* @param other
*/
public void deepCopy(final Graph other)
{
clear();
for (final Vertex otherVertex : other.vertices)
addVertex(otherVertex.pt.x(), otherVertex.pt.y(), otherVertex.pt.z());
for (final Edge otherEdge : other.edges)
findOrAddEdge(otherEdge.vertexA().id(), otherEdge.vertexB().id()); // links to vertices
for (final Face otherFace : other.faces)
{
final int[] vids = new int[otherFace.vertices().size()];
for (int v = 0; v < otherFace.vertices().size(); v++)
vids[v] = otherFace.vertices().get(v).id();
findOrAddFace(vids); // links to vertices and edges, and sets edge faces
}
perimeters.clear(); // just delete old perimeters
//trajectories.clear();
// Do not assemble: instead, manually link edges and faces
}
//-------------------------------------------------------------------------
/**
* Shift all elements by the specified amount.
*
* @param dx The x position.
* @param dy The y position.
* @param dz The z position.
*/
public void translate(final double dx, final double dy, final double dz)
{
for (final Vertex vertex : vertices)
{
final double xx = vertex.pt().x() + dx;
final double yy = vertex.pt().y() + dy;
final double zz = vertex.pt().z() + dz;
vertex.pt().set(xx, yy, zz);
}
recalculateEdgeAndFacePositions();
}
/**
* Scale all elements by the specified amount.
*
* @param sx The scale on x.
* @param sy The scale on y.
* @param sz The scale on z.
*/
public void scale(final double sx, final double sy, final double sz)
{
for (final Vertex vertex : vertices)
{
final double xx = vertex.pt().x() * sx;
final double yy = vertex.pt().y() * sy;
final double zz = vertex.pt().z() * sz;
vertex.pt().set(xx, yy, zz);
}
recalculateEdgeAndFacePositions();
}
/**
* Rotate all elements by the specified amount (including edge end point
* tangents).
*
* @param degrees The degrees of the rotation.
*/
public void rotate(final double degrees)
{
final double theta = Math.toRadians(degrees);
// for (final Vertex vertex : vertices)
// vertex.pt().set(vertex.pt());
// Find pivot
final Rectangle2D bounds = bounds();
final double pivotX = bounds.getX() + bounds.getWidth() / 2.0;
final double pivotY = bounds.getY() + bounds.getHeight() / 2.0;
// // Pivot is centre of mass
// double pivotX = 0;
// double pivotY = 0;
// for (final Vertex vertex : graph.vertices())
// {
// pivotX += vertex.x();
// pivotY += vertex.y();
// }
// pivotX /= graph.vertices().size();
// pivotY /= graph.vertices().size();
// Perform rotation
for (final Vertex vertex : vertices)
{
// x′ = x.cosθ − y.sinθ
// y′ = y.cosθ + x.sinθ
final double dx = vertex.pt().x() - pivotX;
final double dy = vertex.pt().y() - pivotY;
final double xx = pivotX + dx * Math.cos(theta) - dy * Math.sin(theta);
final double yy = pivotY + dy * Math.cos(theta) + dx * Math.sin(theta);
vertex.pt().set(xx, yy);
}
// Also rotate edge end point tangents (if any)
for (final Edge edge : edges)
{
if (edge.tangentA() != null)
edge.tangentA().rotate(theta);
if (edge.tangentB() != null)
edge.tangentB().rotate(theta);
}
recalculateEdgeAndFacePositions();
}
/**
* Skew all elements by the specified amount (including edge end point
* tangents).
*
* @param amount The amount.
*/
public void skew(final double amount)
{
final Rectangle2D bounds = bounds();
for (final Vertex vertex : vertices)
{
final double offset = (vertex.pt().y() - bounds.getMinY()) * amount;
final double xx = vertex.pt().x() + offset;
final double yy = vertex.pt().y();
final double zz = vertex.pt().z();
vertex.pt().set(xx, yy, zz);
}
// Also skew edge end point tangents (if any)
for (final Edge edge : edges)
{
if (edge.tangentA() != null)
{
final double offset = (edge.tangentA().y() - bounds.getMinY()) * amount;
final double xx = edge.tangentA().x() + offset;
final double yy = edge.tangentA().y();
final double zz = edge.tangentA().z();
edge.tangentA().set(xx, yy, zz);
//edge.tangentA().normalise();
}
if (edge.tangentB() != null)
{
final double offset = (edge.tangentB().y() - bounds.getMinY()) * amount;
final double xx = edge.tangentB().x() + offset;
final double yy = edge.tangentB().y();
final double zz = edge.tangentB().z();
edge.tangentB().set(xx, yy, zz);
//edge.tangentB().normalise();
}
}
recalculateEdgeAndFacePositions();
}
//-------------------------------------------------------------------------
/**
* @return True if the graph is regular.
*/
public boolean isRegular()
{
if (basis == BasisType.Square || basis == BasisType.Triangular || basis == BasisType.Hexagonal)
return true;
// Get reference basis to check
BasisType refBasis = null;
if (faces.size() > 0)
refBasis = faces.get(0).basis();
else if (edges.size() > 0)
refBasis = edges.get(0).basis();
else if (vertices.size() > 0)
refBasis = vertices.get(0).basis();
if (refBasis == null || refBasis == BasisType.NoBasis)
return false; // no basis found
for (final GraphElement ge : vertices)
if (ge.basis() != refBasis)
return false;
for (final GraphElement ge : edges)
if (ge.basis() != refBasis)
return false;
for (final GraphElement ge : faces)
if (ge.basis() != refBasis)
return false;
return true;
}
//-------------------------------------------------------------------------
/**
* @param pt The Point2D.
*
* @return Vertex at same location within specified tolerance (e.g. 0.1).
*/
public Vertex findVertex(final Point2D pt)
{
return findVertex(pt.getX(), pt.getY(), 0);
}
/**
* @param pt The Point3D.
*
* @return Vertex at same location within specified tolerance (e.g. 0.1).
*/
public Vertex findVertex(final Point3D pt)
{
return findVertex(pt.x(), pt.y(), pt.z());
}
/**
* @param vertex The vertex.
*
* @return Vertex at same location within specified tolerance (e.g. 0.1).
*/
public Vertex findVertex(final Vertex vertex)
{
return findVertex(vertex.pt.x(), vertex.pt.y(), vertex.pt.z());
}
/**
* @param x The x position.
* @param y The y position.
*
* @return Vertex at same location within specified tolerance (e.g. 0.1).
*/
public Vertex findVertex(final double x, final double y)
{
for (final Vertex vertex : vertices)
if (vertex.coincident(x, y, 0, tolerance))
return vertex;
return null;
}
/**
* @param x The x position.
* @param y The y position.
* @param z The z position.
*
* @return Vertex at same location within specified tolerance (e.g. 0.1).
*/
public Vertex findVertex(final double x, final double y, final double z)
{
for (final Vertex vertex : vertices)
if (vertex.coincident(x, y, z, tolerance))
return vertex;
return null;
}
//-------------------------------------------------------------------------
/**
* @param idA The index of the vertex A.
* @param idB The index of the vertex B.
*
* @return The corresponding edge.
*/
public Edge findEdge(final int idA, final int idB)
{
for (final Edge edge : edges)
if (edge.matches(idA, idB))
return edge;
return null;
}
/**
* @param idA The index of the vertex A.
* @param idB The index of the vertex B.
* @param curved True if the edge has to be curved.
*
* @return The corresponding edge.
*/
public Edge findEdge(final int idA, final int idB, final boolean curved)
{
for (final Edge edge : edges)
if (edge.matches(idA, idB, curved))
return edge;
return null;
}
/**
* @param vertexA The vertex A.
* @param vertexB The vertex b.
* @return The corresponding edge.
*/
public Edge findEdge(final Vertex vertexA, final Vertex vertexB)
{
return findEdge(vertexA.id(), vertexB.id());
}
/**
* @param vertexA The vertex A.
* @param vertexB The vertex B.
* @param curved True if the edge has to be curved.
*
* @return The corresponding edge.
*/
public Edge findEdge(final Vertex vertexA, final Vertex vertexB, final boolean curved)
{
return findEdge(vertexA.id(), vertexB.id(), curved);
}
/**
* @param ax The x position of the vertex A.
* @param ay The y position of the vertex A.
* @param bx The x position of the vertex B.
* @param by The y position of the vertex B.
*
* @return The corresponding edge.
*/
public Edge findEdge
(
final double ax, final double ay,
final double bx, final double by
)
{
final Vertex vertexA = findVertex(ax, ay);
if (vertexA == null)
return null;
final Vertex vertexB = findVertex(bx, by);
if (vertexB == null)
return null;
return findEdge(vertexA.id(), vertexB.id());
}
/**
*
* @param ax The x position of the vertex A.
* @param ay The y position of the vertex A.
* @param az The z position of the vertex A.
* @param bx The x position of the vertex B.
* @param by The y position of the vertex B.
* @param bz The z position of the vertex B.
*
* @return The corresponding edge.
*/
public Edge findEdge
(
final double ax, final double ay, final double az,
final double bx, final double by, final double bz
)
{
final Vertex vertexA = findVertex(ax, ay, az);
if (vertexA == null)
return null;
final Vertex vertexB = findVertex(bx, by, bz);
if (vertexB == null)
return null;
return findEdge(vertexA.id(), vertexB.id());
}
//-------------------------------------------------------------------------
/**
* @param vertIds The indices of the vertices.
* @return The corresponding face.
*/
public Face findFace(final int ... vertIds)
{
for (final Face face : faces)
if (face.matches(vertIds))
return face;
return null;
}
/**
* @param pts The list of all the Point3D.
* @return The corresponding face.
*/
public Face findFace(final List<Point3D> pts)
{
final int[] vertIds = new int[pts.size()];
for (int v = 0; v < pts.size(); v++)
{
final Point3D pt = pts.get(v);
final Vertex vertex = findVertex(pt.x(), pt.y(), pt.z());
if (vertex == null)
return null;
vertIds[v] = vertex.id();
}
return findFace(vertIds);
}
//-------------------------------------------------------------------------
/**
* @param vertexA The vertex A.
* @param vertexB The vertex B.
* @return True if the edge containing these vertices exist.
*/
public boolean containsEdge(final Vertex vertexA, final Vertex vertexB)
{
return findEdge(vertexA.id(), vertexB.id()) != null;
}
/**
* @param idA The index of the vertex A.
* @param idB The index of the vertex B.
* @return True if the edge containing these vertices exist.
*/
public boolean containsEdge(final int idA, final int idB)
{
return findEdge(idA, idB) != null;
}
//-------------------------------------------------------------------------
/**
* @param vids The indices of the vertices.
* @return True if the face containing these vertices exist.
*/
public boolean containsFace(final int ... vids)
{
return findFace(vids) != null;
}
//-------------------------------------------------------------------------
/**
* Add a vertex.
*
* @param vertex The vertex.
*/
public void addVertex(final Vertex vertex)
{
vertices.add(vertex);
}
/**
* Add an edge.
*
* @param edge The edge.
*/
public void addEdge(final Edge edge)
{
edges.add(edge);
}
/**
* Add a face.
*
* @param face The face.
*/
public void addFace(final Face face)
{
faces.add(face);
}
/**
* Add a face to the front of the face list.
*
* @param face The face.
*/
public void addFaceToFront(final Face face)
{
faces.add(0, face);
}
//-------------------------------------------------------------------------
/**
* @param pt The point2D of the vertex centroid.
* @return The vertex added.
*/
public Vertex addVertex(final Point2D pt)
{
return addVertex(pt.getX(), pt.getY(), 0);
}
/**
* @param pt The point3D of the vertex centroid.
* @return The vertex added.
*/
public Vertex addVertex(final Point3D pt)
{
return addVertex(pt.x(), pt.y(), pt.z());
}
/**
* @param x The x position of the vertex.
* @param y The y position of the vertex.
* @return The vertex added.
*/
public Vertex addVertex(final double x, final double y)
{
return addVertex(x, y, 0);
}
/**
* @param x The x position of the vertex.
* @param y The y position of the vertex.
* @param z The z position of the vertex.
* @return The vertex added.
*/
public Vertex addVertex(final double x, final double y, final double z)
{
final Vertex newVertex = new Vertex(vertices.size(), x, y, z);
vertices.add(newVertex);
return newVertex;
}
/**
* @param x The x position of the vertex.
* @param y The y position of the vertex.
* @return The vertex if found.
*/
public Vertex findOrAddVertex(final double x, final double y)
{
return findOrAddVertex(x, y, 0);
}
/**
* @param pt The point2D of the vertex centroid.
* @return The vertex if found.
*/
public Vertex findOrAddVertex(final Point2D pt)
{
return findOrAddVertex(pt.getX(), pt.getY(), 0);
}
/**
*
* @param x The x position of the vertex.
* @param y The y position of the vertex.
* @param z The z position of the vertex.
* @return The vertex if found.
*/
public Vertex findOrAddVertex(final double x, final double y, final double z)
{
final Vertex existing = findVertex(x, y, z);
if (existing != null)
return existing;
return addVertex(x, y, z);
}
//-------------------------------------------------------------------------
/**
* @return Existing edge if found, otherwise new edge.
*/
// public Edge findOrAddEdge(final Vertex vertexA, final Vertex vertexB, final boolean curved)
// {
// return findOrAddEdge(vertexA.id(), vertexB.id(), curved);
// }
/**
* @param vertexA The vertex A.
* @param vertexB The vertex B.
* @param tangentA The tangent A.
* @param tangentB The tangent B.
*
* @return The edge found or added.
*/
public Edge findOrAddEdge(final Vertex vertexA, final Vertex vertexB, final Vector tangentA, final Vector tangentB)
{
return findOrAddEdge(vertexA.id(), vertexB.id(), tangentA, tangentB);
}
/**
* @param vertexA The vertex A.
* @param vertexB The vertex B.
*
* @return The edge found or added.
*/
public Edge findOrAddEdge(final Vertex vertexA, final Vertex vertexB)
{
return findOrAddEdge(vertexA.id(), vertexB.id()); //, false);
}
// public Edge findOrAddEdge(final int vertIdA, final int vertIdB)
// {
// return findOrAddEdge(vertIdA, vertIdB, false);
// }
/**
*
* @param vertIdA The index of the vertex A.
* @param vertIdB The index of the vertex B.
*
* @return The edge found or added.
*/
public Edge findOrAddEdge(final int vertIdA, final int vertIdB) //, final boolean curved)
{
if (vertIdA >= vertices.size() || vertIdB >= vertices.size())
{
System.out.println("** Graph.addEdge(): Trying to add edge " + vertIdA + "-" +
vertIdB + " but only " + vertices.size() + " vertices.");
return null;
}
for (final Edge edge : edges)
if (edge.matches(vertIdA, vertIdB)) //, curved))
{
//System.out.println("Duplicate edge found.");
return edge; // don't add duplicate edge
}
return addEdge(vertIdA, vertIdB); //, curved);
}
/**
*
* @param vertIdA The index of the vertex A.
* @param vertIdB The index of the vertex B.
* @param tangentA The tangent A.
* @param tangentB The tangent B.
*
* @return The edge found or added.
*/
public Edge findOrAddEdge
(
final int vertIdA, final int vertIdB,
final Vector tangentA, final Vector tangentB
)
{
if (vertIdA >= vertices.size() || vertIdB >= vertices.size())
{
System.out.println("** Graph.addEdge(): Trying to add edge " + vertIdA + "-" +
vertIdB + " but only " + vertices.size() + " vertices.");
return null;
}
// **
// ** TODO: Match should include tangents? Otherwise can't distinguish
// ** curved edges from non-curved edges or each other.
// **
for (final Edge edge : edges)
if (edge.matches(vertIdA, vertIdB)) //, tangentA, tangentB))
{
//System.out.println("Duplicate edge found.");
return edge; // don't add duplicate edge
}
return addEdge(vertIdA, vertIdB, tangentA, tangentB);
}
/**
* @param vertexA The vertex A.
* @param vertexB The vertex B.
*
* @return The edge added.
*/
public Edge addEdge(final Vertex vertexA, final Vertex vertexB)
{
return addEdge(vertexA.id(), vertexB.id()); //, false);
}
// public Edge addEdge(final Vertex vertexA, final Vertex vertexB, final boolean curved)
// {
// return addEdge(vertexA.id(), vertexB.id(), curved);
// }
// public Edge addEdge(final int vertIdA, final int vertIdB)
// {
// return addEdge(vertIdA, vertIdB); //, false);
// }
/**
* @param vertIdA The index of the vertex A.
* @param vertIdB The index of the vertex B.
*
* @return The edge added.
*/
public Edge addEdge(final int vertIdA, final int vertIdB) //, final boolean curved)
{
if (vertIdA >= vertices.size() || vertIdB >= vertices.size())
{
System.out.println("** Graph.addEdge(): Trying to add edge " + vertIdA + "-" +
vertIdB + " but only " + vertices.size() + " vertices.");
return null;
}
final Vertex vertexA = vertices.get(vertIdA);
final Vertex vertexB = vertices.get(vertIdB);
final Edge newEdge = new Edge(edges.size(), vertexA, vertexB); //, curved);
edges.add(newEdge);
vertexA.addEdge(newEdge);
vertexA.sortEdges();
vertexB.addEdge(newEdge);
vertexB.sortEdges();
// Set basis and shape to common basis and shape, if any
if (vertexA.basis() == vertexB.basis())
newEdge.setBasis(vertexA.basis());
if (vertexA.shape() == vertexB.shape())
newEdge.setShape(vertexA.shape());
return newEdge;
}
/**
* @param vertexA The vertex A.
* @param vertexB The vertex B.
* @param tangentA The tangent A.
* @param tangentB The tangent B.
*
* @return The edge added.
*/
public Edge addEdge(final Vertex vertexA, final Vertex vertexB, final Vector tangentA, final Vector tangentB)
{
return addEdge(vertexA.id(), vertexB.id(), tangentA, tangentB);
}
/**
*
* @param vertIdA The index of the vertex A.
* @param vertIdB The index of the vertex B.
* @param tangentA The tangent A.
* @param tangentB The tangent B.
*
* @return The edge added.
*/
public Edge addEdge(final int vertIdA, final int vertIdB, final Vector tangentA, final Vector tangentB)
{
if (vertIdA >= vertices.size() || vertIdB >= vertices.size())
{
System.out.println("** Graph.addEdge(): Trying to add edge " + vertIdA + "-" +
vertIdB + " but only " + vertices.size() + " vertices.");
return null;
}
final Vertex vertexA = vertices.get(vertIdA);
final Vertex vertexB = vertices.get(vertIdB);
final Edge newEdge = new Edge(edges.size(), vertexA, vertexB); //, (tangentA != null && tangentB != null));
edges.add(newEdge);
vertexA.addEdge(newEdge);
vertexA.sortEdges();
vertexB.addEdge(newEdge);
vertexB.sortEdges();
// Set basis and shape to common basis and shape, if any
if (vertexA.basis() == vertexB.basis())
newEdge.setBasis(vertexA.basis());
if (vertexA.shape() == vertexB.shape())
newEdge.setShape(vertexA.shape());
newEdge.setTangentA(tangentA);
newEdge.setTangentB(tangentB);
return newEdge;
}
//-------------------------------------------------------------------------
/**
* Creates edges between vertices that are approximately a unit distance apart.
*/
public void makeEdges() //final double u)
{
for (final Vertex vertexA : vertices)
for (final Vertex vertexB : vertices)
{
if (vertexA.id() == vertexB.id())
continue;
final double dist = vertexA.pt().distance(vertexB.pt());
if (Math.abs(dist - unit) < 0.05)
findOrAddEdge(vertexA, vertexB);
}
}
//-------------------------------------------------------------------------
/**
* @param vertIds The list of the indices of the vertices.
* @return The face added or found.
*/
public Face findOrAddFace(final int ... vertIds)
{
if (vertIds.length > vertices.size())
{
// System.out.println("** vertIds.length=" + vertIds.length + ", vertices.size()=" + vertices.size());
return null; // not a simple face
}
for (final int vid : vertIds)
if (vid >= vertices.size())
{
System.out.println("** Graph.addFace(): Vertex " + vid + " specified but only " + vertices.size() + " vertices.");
return null;
}
for (final Face face : faces)
if (face.matches(vertIds))
{
System.out.println("** Matching face found.");
return face; // just return existing face
}
// Create the new face
final Face newFace = new Face(faces.size());
final BasisType refBasis = vertices.isEmpty() ? null : vertices.get(0).basis();
final ShapeType refShape = vertices.isEmpty() ? null : vertices.get(0).shape();
boolean allSameBasis = true;
final boolean allSameShape = true;
for (int v = 0; v < vertIds.length; v++)
{
final int m = vertIds[v];
final int n = vertIds[(v + 1) % vertIds.length];
final Vertex vert = vertices.get(m);
final Vertex next = vertices.get(n);
final Edge edge = findEdge(vert.id(), next.id());
if (edge == null)
{
// Edge already exists. Don't add a new edge here or create
// faces can crash; it uses the vertices edge list but adding
// and edge will update them => ConcurrentModificationException.
System.out.println("** Graph.addFace(): Couldn't find edge between V" + m + " and V" + n + ".");
return null; // can't make this face
// Add an edge
//addEdge(vert.id(), next.id());
//edge = edges.get(edges.size() - 1);
}
if (v > 0 && vert.basis() != refBasis)
allSameBasis = false;
if (v > 0 && vert.shape() != refShape)
allSameBasis = false;
// if (edge.right() != null)
// System.out.println("** Graph.addFace(): Edge between V" + vm.id() + " and V" + vn.id() + " already has a right face.");
if (edge.vertexA().id() == vert.id())
edge.setRight(newFace); // edge facing direction of travel
else
edge.setLeft(newFace); // edge is backwards
newFace.addVertexAndEdge(vert, edge); // also updates face midpoint
}
// // Set tiling and shape of cell based on majority of edges
// final int numBasisTypes = BasisType.values().length;
// final int numShapeTypes = ShapeType.values().length;
//
// final int[] bases = new int[numBasisTypes];
// final int[] shapes = new int[numShapeTypes];
//
// for (final Edge edge : newFace.edges())
// {
// if (edge.basis() != null)
// bases[edge.basis().ordinal()]++;
//
// if (edge.shape() != null)
// shapes[edge.shape().ordinal()]++;
// }
//
// // Find maximum tiling and shape type among edges
// int maxTilingIndex = -1;
// int maxTilingCount = 0;
//
// for (int t = 0; t < numBasisTypes; t++)
// if (bases[t] > maxTilingCount)
// {
// maxTilingIndex = t;
// maxTilingCount = bases[t];
// }
//
// int maxShapeIndex = -1;
// int maxShapeCount = 0;
//
// for (int s = 0; s < numShapeTypes; s++)
// if (shapes[s] > maxShapeCount)
// {
// maxShapeIndex = s;
// maxShapeCount = shapes[s];
// }
// Add new face to incident vertex lists
for (final Vertex vertex : newFace.vertices())
// vertex.faces().add(newFace);
vertex.addFace(newFace);
// // Set maximum type, if found
// BasisType basisM = BasisType.NoBasis;
// ShapeType shapeM = ShapeType.NoShape;
//
// if (maxTilingIndex != -1)
// basisM = BasisType.values()[maxTilingIndex];
//
// if (maxShapeIndex != -1)
// shapeM = ShapeType.values()[maxShapeIndex];
final BasisType basisF = (allSameBasis) ? refBasis : BasisType.NoBasis;
final ShapeType shapeF = (allSameShape) ? refShape : ShapeType.NoShape;
newFace.setTilingAndShape(basisF, shapeF);
faces.add(newFace);
// System.out.println("Created new face " + newFace.id() + "...");
return newFace;
}
//-------------------------------------------------------------------------
/**
* @param pt Point to test.
* @return Face containing this point, else null if none.
*/
public Face faceContaining(final Point2D pt)
{
for (final Face face : faces)
if (face.contains(pt))
return face;
return null;
}
//-------------------------------------------------------------------------
/**
* Make the faces.
*
* @param checkCrossings
*/
public void makeFaces(final boolean checkCrossings)
{
final int MAX_FACE_SIDES = 32;
if (!faces.isEmpty())
clearFaces(); // remove existing faces
for (final Vertex vertexStart : vertices)
{
// System.out.println("\nStarting at vertex " + vertexStart.id() + "...");
for (final Edge edgeStart : vertexStart.edges())
{
// System.out.println("+ Has edge " + edgeStart.id());
// Look for cell containing this edge
final TIntArrayList vertIds = new TIntArrayList();
vertIds.add(vertexStart.id());
Vertex vert = vertexStart;
Edge edge = edgeStart;
boolean closed = false;
while (vertIds.size() <= MAX_FACE_SIDES)
{
// System.out.print("Vertex " + vert.id() + " has edges:");
// for (final Edge e : vert.edges())
// System.out.print(" " + e.id());
// System.out.println();
final Vertex prev = vert;
// Get next edge in CW order and move to next vertex
int n = vert.edgePosition(edge);
Vertex next = null;
final int numEdges = vert.edges().size();
int m;
for (m = 1; m < numEdges; m++)
{
// Get next edge in CW order on the same level
//
// TODO: Handle 3D faces!
//
edge = vert.edges().get((n + m) % vert.edges().size());
next = edge.otherVertex(vert);
// System.out.println("next vert " + next.id() + ": v.z=" + next.pt().z() + ", vs.z=" + vertexStart.pt().z());
if (Math.abs(next.pt().z() - vertexStart.pt().z()) < 0.0001)
{
// Next planar vert found
vert = next;
break;
}
}
if (m >= numEdges)
break; // no next CW edge found on same level
// System.out.println("+ + Vertex " + vert.id());
if (vert.id() == vertexStart.id())
{
// Face has been closed
closed = true;
break;
}
// Check for self-intersection without closure
if (vertIds.contains(vert.id()))
break;
vertIds.add(vert.id());
if (checkCrossings && isEdgeCrossing(prev, vert))
break;
}
if (closed && vertIds.size() >= 3)
{
// Polygon is closed and has at least three sides -- is a face
final List<Point2D> poly = new ArrayList<Point2D>();
for (int v = 0; v < vertIds.size(); v++)
{
final Vertex vertex = vertices.get(vertIds.getQuick(v));
poly.add(new Point2D.Double(vertex.pt.x(), vertex.pt.y()));
}
// System.out.println("poly has " + poly.size() + " sides...");
if (MathRoutines.clockwise(poly))
{
// System.out.println("Is clockwise...");
final int[] vids = vertIds.toArray();
if (!containsFace(vids))
{
// System.out.println("Not already present...");
findOrAddFace(vids);
}
}
}
}
}
}
/**
* Clear all existing faces.
*/
public void clearFaces()
{
for (final Edge edge : edges)
{
edge.setLeft(null);
edge.setRight(null);
}
for (final Vertex vertex : vertices)
vertex.clearFaces();
faces.clear();
}
//-------------------------------------------------------------------------
/**
* Remove an element from the graph.
*
* @param element The element.
* @param removeOrphans True if the orphans elements have also to be removed.
*/
public void remove(final GraphElement element, final boolean removeOrphans)
{
switch (element.siteType())
{
case Vertex:
removeVertex(element.id());
break;
case Edge:
removeEdge(element.id()); //, removeOrphans);
break;
case Cell:
removeFace(element.id(), removeOrphans);
break;
default: // do nothing
}
}
//-------------------------------------------------------------------------
/**
* Remove a vertex.
*
* @param vertex The vertex.
*/
public void removeVertex(final Vertex vertex)
{
removeVertex(vertex.id());
}
/**
* Remove a vertex.
*
* @param vid The index of the vertex.
*/
public void removeVertex(final int vid)
{
// System.out.println("Removing vertex " + vid + "...");
if (vid >= vertices.size())
{
System.out.println("Graph.removeVertex(): Index " + vid + " out of range.");
return;
}
final Vertex vertex = vertices.get(vid);
// Mark incident faces for removal
final BitSet facesToRemove = new BitSet();
for (final Face face : faces)
if (face.contains(vertex))
facesToRemove.set(face.id(), true);
// Unlink faces marked for removal from edge references
for (final Edge edge : edges)
{
if (edge.left() != null && facesToRemove.get(edge.left().id()))
edge.setLeft(null);
if (edge.right() != null && facesToRemove.get(edge.right().id()))
edge.setRight(null);
}
// Unlink faces marked for removal from vertex face lists
for (final Vertex vertexF : vertices())
for (int f = vertexF.faces().size() - 1; f >= 0; f--)
{
final Face face = vertexF.faces().get(f);
if (facesToRemove.get(face.id()))
vertexF.faces().remove(f);
}
// Remove faces marked for removal
for (int fid = faces.size() - 1; fid >= 0; fid--)
if (facesToRemove.get(fid))
faces.remove(fid);
// Mark incident edges for removal
final BitSet edgesToRemove = new BitSet();
for (final Edge edge : vertex.edges())
edgesToRemove.set(edge.id(), true);
// Unlink edges marked for removal from all vertex lists
for (final Vertex vertexE : vertices())
for (int e = vertexE.edges().size() - 1; e >= 0; e--)
{
final Edge edge = vertexE.edges().get(e);
if (edgesToRemove.get(edge.id()))
vertexE.removeEdge(e);
}
// Delete edges marked for removal
for (int eid = edges().size() - 1; eid >= 0; eid--)
if (edgesToRemove.get(eid))
edges.remove(eid);
vertices.remove(vid); // remove vertex
// Recalibrate indices
for (int f = 0; f < faces.size(); f++)
faces.get(f).setId(f);
for (int e = 0; e < edges.size(); e++)
edges.get(e).setId(e);
for (int v = 0; v < vertices.size(); v++)
vertices.get(v).setId(v);
}
//-------------------------------------------------------------------------
/**
* Removes edge defined by end point indices.
*
* @param vidA The index of the vertex A.
* @param vidB The index of the vertex B.
*/
public void removeEdge(final int vidA, final int vidB)
{
final Edge edge = findEdge(vidA, vidB);
if (edge != null)
removeEdge(edge.id());
}
/**
* @param eid Index of edge to remove.
*/
public void removeEdge(final int eid) //, final boolean removeOrphans)
{
if (eid >= edges.size())
{
System.out.println("Graph.removeEdge(): Index " + eid + " out of range.");
return;
}
// Remove evidence of edge from graph
final Edge edge = edges.get(eid);
// Remove any faces that use this edge
for (int fid = faces.size() - 1; fid >= 0; fid--)
if (faces.get(fid).contains(edge))
removeFace(fid, false);
// Remember the end point indices (ordered [min,max])
final Vertex[] endpoints = new Vertex[2];
endpoints[0] = (edge.vertexA().id() <= edge.vertexB().id()) ? edge.vertexA() : edge.vertexB();
endpoints[1] = (edge.vertexA().id() <= edge.vertexB().id()) ? edge.vertexB() : edge.vertexA();
// Remove the edge from each endpoint's list of outgoing edges
// boolean deadVertex = false;
for (int v = 0; v < 2; v++)
{
final Vertex vertex = endpoints[v];
for (int e = vertex.edges().size() - 1; e >= 0; e--)
if (vertex.edges().get(e).id() == edge.id())
{
vertex.removeEdge(e); // remove edge from vertex's outgoing list
// if (removeOrphans && vertex.edges().isEmpty())
// {
// vertex.setId(-1); // potential orphan
// deadVertex = true;
// }
}
}
// if (deadVertex)
// {
// // Remove dead vertices
// for (int v = vertices.size() - 1; v >= 0; v--)
// {
// final Vertex vertex = vertices.get(v);
// if (vertex.id() == -1)
// vertices.remove(v);
// }
//
// // Recalibrate remaining vertex indices
// for (int v = 0; v < vertices.size(); v++)
// vertices.get(v).setId(v);
// }
// Remove the edge and recalibrate indices.
// Do this *after* removing edge from vertex edge lists!
edges.remove(eid);
for (int e = eid; e < edges.size(); e++)
edges.get(e).decrementId();
}
//-------------------------------------------------------------------------
/**
* @param fid The index of the face.
* @param removeOrphans Remove edges that are faceless after the removal. This
* is primarily for the Hole operator.
*/
public void removeFace(final int fid, final boolean removeOrphans)
{
if (fid >= faces.size())
{
System.out.println("Graph.removeFace(): Index " + fid + " out of range.");
return;
}
final Face face = faces.get(fid);
// Remove face from edges' left and right references
final BitSet edgesToRemove = new BitSet();
for (final Edge edge : face.edges())
{
// Don't call removeEdge() yet, as that will delete this face
if (edge.left() != null && edge.left().id() == fid)
{
// Unlink left reference
edge.setLeft(null);
if (removeOrphans && edge.right() == null)
edgesToRemove.set(edge.id()); // edge no longer needed
}
if (edge.right() != null && edge.right().id() == fid)
{
// Unlink right reference
edge.setRight(null);
if (removeOrphans && edge.left() == null)
edgesToRemove.set(edge.id()); // edge no longer needed
}
}
// Remove face from vertex lists
for (final Vertex vertex : face.vertices())
// for (final Vertex vertex : vertices())
for (int n = vertex.faces().size() - 1; n >= 0; n--)
if (vertex.faces().get(n).id() == fid)
// vertex.faces().remove(n);
vertex.removeFace(n);
// Remove this face and recalibrate indices
faces.remove(fid);
for (int f = fid; f < faces.size(); f++)
faces.get(f).decrementId();
// Now it's safe to remove edges
for (int e = edges.size() - 1; e >= 0; e--)
if (edgesToRemove.get(e))
removeEdge(e);
// System.out.println("Now " + faces.size() + " faces.");
// for (final Face fc : faces)
// System.out.println(fc.id());
}
//-------------------------------------------------------------------------
/**
* Sets the tiling and shape type of all elements for this graph, unless they
* have already been set.
*
* @param bt The basis.
* @param st the shape.
*/
public void setBasisAndShape(final BasisType bt, final ShapeType st)
{
for (final Vertex vertex : vertices)
{
if (vertex.basis() == null)
vertex.setBasis(bt);
if (vertex.shape() == null)
vertex.setShape(st);
}
for (final Edge edge : edges)
{
if (edge.basis() == null)
edge.setBasis(bt);
if (edge.shape() == null)
edge.setShape(st);
}
for (final Face face : faces)
{
if (face.basis() == null)
face.setBasis(bt);
if (face.shape() == null)
face.setShape(st);
}
basis = bt;
shape = st;
}
//-------------------------------------------------------------------------
/**
* Synchronise the indices.
*/
public void synchroniseIds()
{
for (int n = 0; n < vertices.size(); n++)
vertices.get(n).setId(n);
for (int n = 0; n < edges.size(); n++)
edges.get(n).setId(n);
for (int n = 0; n < faces.size(); n++)
faces.get(n).setId(n);
}
//-------------------------------------------------------------------------
/**
* Reorder the indices.
*/
public void reorder()
{
reorder(SiteType.Vertex);
reorder(SiteType.Edge);
reorder(SiteType.Cell);
}
/**
* Reorder the indices of a graph element type.
*
* @param type The graph element type.
*/
public void reorder(final SiteType type)
{
// Give each element a score that prefers higher and righter positions
final List<? extends GraphElement> elements = elements(type);
final List<ItemScore> rank = new ArrayList<ItemScore>();
for (int n = 0; n < elements.size(); n++)
{
final GraphElement ge = elements.get(n);
final double score = ge.pt().y() * 100 + ge.pt().x();
rank.add(new ItemScore(n, score));
}
Collections.sort(rank);
// Append elements in new order
for (int es = 0; es < rank.size(); es++)
{
final GraphElement ge = elements.get(rank.get(es).id());
ge.setId(es);
switch (type)
{
case Vertex: vertices.add((Vertex)ge); break;
case Edge: edges.add((Edge)ge); break;
case Cell: faces.add((Face)ge); break;
default: // do nothing
}
}
// Remove unneeded duplicate entries
for (int es = 0; es < rank.size(); es++)
elements.remove(0);
for (int n = 0; n < elements.size(); n++)
elements.get(n).setId(n);
}
//-------------------------------------------------------------------------
private void setVertices(final Number[][] positions)
{
vertices.clear();
if (positions != null)
for (int v = 0; v < positions.length; v++)
{
final Number[] position = positions[v];
if (position.length == 2)
addVertex(position[0].floatValue(), position[1].floatValue(), 0);
else
addVertex(position[0].floatValue(), position[1].floatValue(), position[2].floatValue());
}
}
/**
* Note: This method is inefficient as it checks all edges for uniqueness.
* This is good to do for manually specified edge lists which can contain errors.
* Automatically generated edge lists may not need this test.
*/
private void setEdges(final Integer[][] pairs)
{
edges.clear();
if (pairs != null)
for (int e = 0; e < pairs.length; e++)
findOrAddEdge(pairs[e][0].intValue(), pairs[e][1].intValue());
}
//-------------------------------------------------------------------------
private void assemble(final boolean checkCrossings)
{
linkEdgesToVertices();
makeFaces(checkCrossings);
linkFacesToVertices();
// This will not override tiling and shape already set in elements
setBasisAndShape(BasisType.NoBasis, ShapeType.NoShape);
}
//-------------------------------------------------------------------------
/**
* Ensure that each vertex has a complete list of its edges,
* sorted in clockwise order.
*/
public void linkEdgesToVertices()
{
for (final Vertex vertex : vertices)
// vertex.edges().clear();
vertex.clearEdges();
for (final Edge edge : edges)
{
// vertices.get(edge.vertexA().id()).edges().add(edge);
// vertices.get(edge.vertexB().id()).edges().add(edge);
vertices.get(edge.vertexA().id()).addEdge(edge);
vertices.get(edge.vertexB().id()).addEdge(edge);
}
for (final Vertex vertex : vertices)
vertex.sortEdges();
}
/**
* Ensure that each vertex has a complete list of its faces,
* sorted in clockwise order.
*/
public void linkFacesToVertices()
{
for (final Vertex vertex : vertices)
// vertex.faces().clear();
vertex.clearFaces();
for (final Face face : faces)
for (final Vertex vertex : face.vertices())
// vertex.faces().add(face);
vertex.addFace(face);
for (final Vertex vertex : vertices)
vertex.sortFaces();
}
//-------------------------------------------------------------------------
/**
*
* @param vertexA The vertex A.
* @param vertexB The vertex B.
* @return True if the corresponding edge is crossing another.
*/
public boolean isEdgeCrossing(final Vertex vertexA, final Vertex vertexB)
{
final double localTolerance = 0.001;
final Point2D ptA = vertexA.pt2D();
final Point2D ptB = vertexB.pt2D();
for (final Edge edge : edges)
{
if (edge.matches(vertexA, vertexB))
return false; // don't treat as crossing
final Point2D ptEA = edge.vertexA().pt2D();
final Point2D ptEB = edge.vertexB().pt2D();
if
(
ptA.distance(ptEA) < localTolerance || ptA.distance(ptEB) < localTolerance
||
ptB.distance(ptEA) < localTolerance || ptB.distance(ptEB) < localTolerance
)
continue;
if
(
MathRoutines.lineSegmentsIntersect
(
ptA.getX(), ptA.getY(), ptB.getX(), ptB.getY(),
ptEA.getX(), ptEA.getY(), ptEB.getX(), ptEB.getY()
)
)
return true;
}
return false;
}
//-------------------------------------------------------------------------
/**
* Trim.
*/
public void trim()
{
// Trim orphaned edges
for (int eid = edges.size() - 1; eid >= 0; eid--)
{
final Edge edge = edges.get(eid);
if (edge.vertexA().edges().size() == 1 || edge.vertexB().edges().size() == 1)
removeEdge(eid); // orphaned edge
}
// Detect pivots
final BitSet pivotIds = new BitSet();
for (final Vertex vertex : vertices)
if (vertex.pivot() != null)
pivotIds.set(vertex.pivot().id());
// Trim orphaned vertices that are not pivots
for (int vid = vertices.size() - 1; vid >= 0; vid--)
{
final Vertex vertex = vertices.get(vid);
if (vertex.edges().isEmpty() && !pivotIds.get(vid))
removeVertex(vid); // orphaned non-pivot vertex
}
}
//-------------------------------------------------------------------------
/**
* Clear the properties.
*/
public void clearProperties()
{
for (final Vertex vertex : vertices)
vertex.properties().clear();
for (final Edge edge : edges)
edge.properties().clear();
for (final Face face : faces)
face.properties().clear();
}
//-------------------------------------------------------------------------
/**
* Compute the measures.
*
* @param boardless True if the board is boardless.
*/
public void measure(final boolean boardless)
{
MeasureGraph.measure(this, false);
}
//-------------------------------------------------------------------------
/**
* @return Measure of variance in edge length.
*/
public double distance()
{
if (vertices.size() < 2)
return 0;
double avg = 0;
int found = 0;
for (final Vertex va : vertices)
for (final Vertex vb : vertices)
{
if (va.id() == vb.id())
continue;
final double dist = va.pt.distance(vb.pt);
avg += dist;
found++;
}
avg /= found;
return avg;
}
/**
* @return Measure of variance in edge length.
*/
public double variance()
{
if (vertices.size() < 2)
return 0;
final double avg = distance();
double varn = 0;
int found = 0;
for (final Vertex va : vertices)
for (final Vertex vb : vertices)
{
if (va.id() == vb.id())
continue;
found++;
final double dist = va.pt.distance(vb.pt);
varn += Math.abs(dist - avg); // * (dist - avg);
}
varn /= found;
return varn;
}
//-------------------------------------------------------------------------
/**
* @return Bounding box of original vertex pairs.
*/
public Rectangle2D bounds()
{
return bounds(vertices);
}
/**
* @param elements The elements of the graph.
* @return Bounding box of original vertex pairs.
*/
public static Rectangle2D bounds(final List<? extends GraphElement> elements)
{
final double limit = 1000000;
double x0 = limit;
double y0 = limit;
double x1 = -limit;
double y1 = -limit;
for (final GraphElement ge : elements)
{
final double x = ge.pt.x();
final double y = ge.pt.y();
if (x < x0) x0 = x;
if (x > x1) x1 = x;
if (y < y0) y0 = y;
if (y > y1) y1 = y;
}
if (x0 == limit || y0 == limit)
return new Rectangle2D.Double(0, 0, 0, 0);
return new Rectangle2D.Double(x0, y0, x1-x0, y1-y0);
}
//-------------------------------------------------------------------------
/**
* Normalise all vertices.
*/
public void normalise()
{
final Rectangle2D bounds = bounds(elements(SiteType.Vertex));
final double maxExtent = Math.max(bounds.getWidth(), bounds.getHeight());
if (maxExtent == 0)
{
System.out.println("** Normalising graph with zero bounding box.");
return;
}
final double scale = 1.0 / maxExtent;
final double offX = -bounds.getX() + (maxExtent - bounds.getWidth()) / 2.0; // * scale;
final double offY = -bounds.getY() + (maxExtent - bounds.getHeight()) / 2.0; // * scale;
for (final Vertex vertex : vertices)
{
final double xx = (vertex.pt.x() + offX) * scale;
final double yy = (vertex.pt.y() + offY) * scale;
final double zz = (vertex.pt.z() + offY) * scale;
vertex.pt.set(xx, yy, zz);
}
}
//-------------------------------------------------------------------------
/**
* Compute again the edges and faces positions.
*/
public void recalculateEdgeAndFacePositions()
{
for (final Edge edge : edges)
edge.setMidpoint();
for (final Face face : faces)
face.setMidpoint();
}
//-------------------------------------------------------------------------
/**
* Remove duplicate edges from the specified edge list.
*
* @param edges the list of the edges.
*/
public static void removeDuplicateEdges(final List<Edge> edges)
{
for (int ea = 0; ea < edges.size(); ea++)
{
final Edge edgeA = edges.get(ea);
for (int eb = edges.size() - 1; eb > ea; eb--)
if (edgeA.matches(edges.get(eb)))
{
// Remove this duplicate edge
for (int ec = eb + 1; ec < edges.size(); ec++)
edges.get(ec).decrementId();
edges.remove(eb);
}
}
}
//-------------------------------------------------------------------------
/**
* @return Average edge length.
*/
public double averageEdgeLength()
{
if (edges.isEmpty())
return 0;
double avg = 0;
for (final Edge edge : edges)
avg += edge.length();
return avg / edges.size();
}
//-------------------------------------------------------------------------
/**
* @return Centroid of graph.
*/
public Point2D centroid()
{
if (vertices.isEmpty())
return new Point2D.Double(0, 0);
double midX = 0;
double midY = 0;
for (final Vertex vertex : vertices)
{
midX += vertex.pt().x();
midY += vertex.pt().y();
}
return new Point2D.Double(midX / vertices().size(), midY / vertices().size());
}
//-------------------------------------------------------------------------
@Override
public Graph eval(final Context context, final SiteType siteType)
{
return this;
}
@Override
public long gameFlags(Game game)
{
return 0;
}
@Override
public void preprocess(Game game)
{
// Nothing to do.
}
//-------------------------------------------------------------------------
@Override
public String toString()
{
final StringBuilder sb = new StringBuilder();
if (vertices.isEmpty())
return "Graph has no vertices.";
sb.append("Graph basis: " + basis + "\n");
sb.append("Graph shape: " + shape + "\n");
sb.append("Graph is " + (isRegular() ? "" : "not ") + "regular.\n");
sb.append("Vertices:\n");
for (final Vertex vertex : vertices)
sb.append("- V: " + vertex.toString() + "\n");
if (edges.isEmpty())
{
sb.append("No edges.");
}
else
{
sb.append("Edges:\n");
for (final Edge edge : edges)
sb.append("- E: " + edge.toString() + "\n");
}
if (faces.isEmpty())
{
sb.append("No faces.");
}
else
{
sb.append("Faces:\n");
for (final Face face : faces)
sb.append("- F: " + face.toString() + "\n");
}
return sb.toString();
}
//-------------------------------------------------------------------------
}
| 56,448 | 23.966387 | 125 | java |
Ludii | Ludii-master/Core/src/game/util/graph/GraphElement.java | package game.util.graph;
import java.awt.geom.Point2D;
import java.util.List;
import game.types.board.BasisType;
import game.types.board.ShapeType;
import game.types.board.SiteType;
import main.Constants;
import main.math.Point3D;
//-----------------------------------------------------------------------------
/**
* Shared storage for graph elements.
*
* @author combolbro
*/
public abstract class GraphElement
{
/** Id is not final; can change when merging or modifying graphs. */
protected int id = Constants.UNDEFINED;
protected Point3D pt;
/** Tiling and shape used when creating this element. */
protected BasisType basis = null;
protected ShapeType shape = null;
protected Properties properties = new Properties();
protected final Situation situation = new Situation();
protected boolean flag = false;
//-------------------------------------------------------------------------
/**
* @return The index of the graph element.
*/
public int id()
{
return id;
}
/**
* Set the index of the graph element.
*
* @param newId The new index.
*/
public void setId(final int newId)
{
id = newId;
}
/**
* Decrement the index.
*/
public void decrementId()
{
id--;
}
/**
* @return 3D position of the centroid.
*/
public Point3D pt()
{
return pt;
}
/**
* @return 2D position of the centroid.
*/
public Point2D pt2D()
{
return new Point2D.Double(pt.x(), pt.y());
}
/**
* Overrides the elements reference point.
* @param x
* @param y
* @param z
*/
public void setPt(final double x, final double y, final double z)
{
pt = new Point3D(x, y, z);
}
/**
* @return The properties of the element.
*/
public Properties properties()
{
return properties;
}
/**
* @return Positional situation, for coordinate labelling.
*/
public Situation situation()
{
return situation;
}
/**
* @return True if the element is flagged.
*/
public boolean flag()
{
return flag;
}
/**
* Set the flag of the element.
*
* @param value New flag value.
*/
public void setFlag(final boolean value)
{
flag = value;
}
//-------------------------------------------------------------------------
/**
* @return This element's pivot vertex, else null if none.
*/
public abstract Vertex pivot();
//-------------------------------------------------------------------------
/**
* @return This element's basis type.
*/
public BasisType basis()
{
return basis;
}
/**
* @param type Basis type to set this element.
*/
public void setBasis(final BasisType type)
{
basis = type;
}
/**
* @return This element's shape type.
*/
public ShapeType shape()
{
return shape;
}
/**
* @param type Shape type to set this element.
*/
public void setShape(final ShapeType type)
{
shape = type;
}
/**
* @return The type of the graph element.
*/
public abstract SiteType siteType();
//-------------------------------------------------------------------------
/**
* Sets this element's basis and shape type.
*
* @param basisIn The new basis.
* @param shapeIn The new shape.
*/
public void setTilingAndShape(final BasisType basisIn, final ShapeType shapeIn)
{
basis = basisIn;
shape = shapeIn;
}
//-------------------------------------------------------------------------
/**
* @param other The graph element to check.
* @return True if this is this graph element.
*/
public boolean matches(final GraphElement other)
{
return siteType() == other.siteType() && id == other.id;
}
//-------------------------------------------------------------------------
/**
* @return Element label for debugging purposes.
*/
public String label()
{
return siteType().toString().substring(0, 1) + id;
}
//-------------------------------------------------------------------------
/**
* @return List of connected neighbour elements.
*/
public abstract List<GraphElement> nbors();
/**
* @param steps List of steps from this element, by relation type.
*/
public abstract void stepsTo(final Steps steps);
//-------------------------------------------------------------------------
}
| 4,183 | 17.932127 | 80 | java |
Ludii | Ludii-master/Core/src/game/util/graph/ItemScore.java | package game.util.graph;
/**
* Helper class for reordering graph elements.
* @author cambolbro
*/
public class ItemScore implements Comparable<ItemScore>
{
private final int id;
private final double score;
//-------------------------------------------------
/**
* @param id The index.
* @param score The score.
*/
public ItemScore(final int id, final double score)
{
this.id = id;
this.score = score;
}
//-------------------------------------------------
/**
* @return The index.
*/
public int id()
{
return id;
}
/**
* @return The score.
*/
public double score()
{
return score;
}
//-------------------------------------------------
@Override
public int compareTo(final ItemScore other)
{
return (score == other.score)
? 0
: (score < other.score) ? - 1 : 1;
}
//-------------------------------------------------
}
| 907 | 15.509091 | 55 | java |
Ludii | Ludii-master/Core/src/game/util/graph/MeasureGraph.java | package game.util.graph;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.Collections;
import java.util.Deque;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import game.types.board.SiteType;
import main.Constants;
import main.math.MathRoutines;
import main.math.RCL;
import main.math.RCLType;
//-----------------------------------------------------------------------------
/**
* Measure graph properties. This helper class is not meant to be instantiated.
*
* @author cambolbro
*/
public abstract class MeasureGraph
{
//-------------------------------------------------------------------------
/**
* @param graph The graph to measure.
* @param boardless True if the graph is boardless.
*/
public static void measure(final Graph graph, final boolean boardless)
{
graph.clearProperties();
if (!boardless)
{
measurePivot(graph);
measurePerimeter(graph);
measureInnerOuter(graph);
measureExtremes(graph);
measureMajorMinor(graph);
measureCorners(graph);
measureSides(graph);
measurePhase(graph);
measureEdgeOrientation(graph);
measureSituation(graph);
}
measureCentre(graph);
//System.out.println(graph);
}
//-------------------------------------------------------------------------
/**
* @param graph The graph to measure.
*/
public static void measurePivot(final Graph graph)
{
for (final Vertex vertex : graph.vertices())
if (vertex.pivot() != null)
vertex.pivot().properties().add(Properties.PIVOT);
}
//-------------------------------------------------------------------------
/**
* Sets elements on the graph perimeter.
*
* Generate the perimeter from the vertices, not the edges. If the graph was
* generated in "use:Vertex" mode it will not have any faces, so edge analysis
* is misleading. It's safer to use vertices in all cases.
*
* @param graph The graph to measure.
*/
public static void measurePerimeter(final Graph graph)
{
// graph.perimeters().clear();
graph.clearPerimeters();
final BitSet covered = new BitSet();
// Generate the candidate polygons.
// There should be one for each connected component of graph.
while (true)
{
final Perimeter perimeter = createNextPerimeter(graph, covered);
if (perimeter == null)
break; // no more perimeters
// graph.perimeters().add(perimeter);
graph.addPerimeter(perimeter);
}
// Remove candidates contained in other candidates
for (int pa = graph.perimeters().size() - 1; pa >= 0; pa--)
{
final Point2D.Double ptA = (Point2D.Double)graph.perimeters().get(pa).startPoint();
boolean isInside = false;
for (int pb = 0; pb < graph.perimeters().size(); pb++)
{
if (pa == pb)
continue;
if (MathRoutines.pointInPolygon(ptA, graph.perimeters().get(pb).positions()))
{
isInside = true;
break;
}
}
if (isInside)
// graph.perimeters().remove(pa); // perimeter A is inside perimeter B
graph.removePerimeter(pa); // perimeter A is inside perimeter B
}
// Set properties of perimeter elements
for (final Perimeter perimeter : graph.perimeters())
{
final int numVerts = perimeter.elements().size();
for (int n = 0; n < numVerts; n++)
{
final Vertex vertexA = (Vertex)perimeter.elements().get(n);
final Vertex vertexB = (Vertex)perimeter.elements().get((n + 1) % numVerts);
vertexA.properties().set(Properties.PERIMETER);
vertexB.properties().set(Properties.PERIMETER); // redundant, but just to be safe...
final Edge edge = vertexA.incidentEdge(vertexB);
if (edge == null)
continue;
edge.properties().set(Properties.PERIMETER);
if (edge.left() != null)
edge.left().properties().set(Properties.PERIMETER);
else if (edge.right() != null)
edge.right().properties().set(Properties.PERIMETER);
}
}
// System.out.println("\nPerimeter report: " + perimeters.size() + " perimeters.");
// for (int n = 0; n < perimeters.size(); n++)
// {
// final Perimeter perimeter = perimeters.get(n);
// System.out.print("- " + n + " perimeter:");
// for (final GraphElement ge : perimeter.elements())
// System.out.print(" " + ge.id());
// System.out.print("\n- " + n + " inside :");
// for (final GraphElement ge : perimeter.inside())
// System.out.print(" " + ge.id());
// System.out.println();
// }
// final int[] counts = new int[3];
// for (int st = 0; st < siteTypes.length; st++)
// for (final GraphElement ge : graphElementList(graph, siteTypes[st]))
// if (ge.properties().get(Properties.PERIMETER))
// counts[st]++;
// System.out.println("Perimeter counts: vertices=" + counts[0] + ", edges=" + counts[1] + ", faces=" + counts[2] + ".");
}
/**
* @return The perimeter for the next unvisited connected component, else null if no more connected components.
*/
private static Perimeter createNextPerimeter(final Graph graph, final BitSet covered)
{
// Find leftmost unused vertex; it must be on the perimeter of its connected component
Vertex start = null;
double minX = 1000000;
for (final Vertex vertex : graph.vertices())
{
if (!covered.get(vertex.id()) && vertex.pt().x() < minX)
{
start = vertex;
minX = vertex.pt().x();
}
}
if (start == null)
return null; // no more perimeters to find
// Create polygon from leftmost vertex
final Perimeter perimeter = followPerimeterClockwise(start);
if (perimeter == null)
return null;
// Mark polygon vertices as covered
for (final GraphElement ge : perimeter.elements())
covered.set(ge.id(), true);
// Make a copy of this polygon converted to Point2D
final List<Point2D> polygon2D = perimeter.positions();
// Mark vertices contained by this polygon as covered
for (final Vertex vertex : graph.vertices())
if (!covered.get(vertex.id()) && MathRoutines.pointInPolygon(vertex.pt2D(), polygon2D))
{
if (!perimeter.on().get(vertex.id()))
perimeter.addInside(vertex);
covered.set(vertex.id(), true);
}
return perimeter;
}
/**
* @param from Leftmost unvisited vertex, guaranteed to be on the perimeter.
* @return Polygon formed by following this perimeter.
*/
private static Perimeter followPerimeterClockwise(final Vertex from)
{
final Perimeter perimeter = new Perimeter();
if (from.edges().isEmpty())
{
// Must be single disconnected vertex
perimeter.add(from);
return perimeter;
}
// Find vertex edge closest to 90 degrees (straight up)
Edge bestEdge = null;
double bestAngle = 1000000;
for (final Edge edge : from.edges())
{
final Vertex to = edge.otherVertex(from);
final double dx = to.pt().x() - from.pt().x();
final double dy = to.pt().y() - from.pt().y();
final double angle = Math.atan2(dx, -dy); // minimises in up direction
// Check dot product
if (angle < bestAngle)
{
bestEdge = edge;
bestAngle = angle;
}
}
// Follow this vertex around this perimeter
Vertex vertex = from;
Vertex prev = from;
Edge edge = bestEdge;
while (true)
{
perimeter.add(vertex);
// Step to next vertex
prev = vertex;
vertex = edge.otherVertex(vertex);
final int i = vertex.edgePosition(edge);
//edge = vertex.edges().get((i + 1) % vertex.edges().size());
for (int n = 1; n < vertex.edges().size(); n++)
{
edge = vertex.edges().get((i + n) % vertex.edges().size());
if (edge.otherVertex(vertex).id() != prev.id())
break; // avoid stepping back to previous vertex, in case of doubled edges
}
if (vertex.id() == from.id())
break; // closed loop completed
}
return perimeter;
}
//-------------------------------------------------------------------------
/**
* Determines inner and outer graph elements.
*
* @param graph The graph to measure.
*/
public static void measureInnerOuter(final Graph graph)
{
// Set all perimeter elements to outer
for (int st = 0; st < Graph.siteTypes.length; st++)
for (final GraphElement ge : graph.elements(Graph.siteTypes[st]))
if (ge.properties().get(Properties.PERIMETER))
ge.properties().set(Properties.OUTER);
// Set faces with a perimeter vertex to outer
for (final Face face : graph.faces())
for (final Vertex vertex : face.vertices())
if (vertex.properties().get(Properties.PERIMETER))
{
face.properties().set(Properties.OUTER);
face.properties().set(Properties.PERIMETER);
}
// Set edges with a perimeter vertex to outer
for (final Edge edge : graph.edges())
if
(
edge.vertexA().properties().get(Properties.PERIMETER)
&&
edge.vertexB().properties().get(Properties.PERIMETER)
&&
(edge.left() == null || edge.right() == null)
)
{
edge.properties().set(Properties.OUTER);
edge.properties().set(Properties.PERIMETER);
}
// Set faces with a null neighbour
for (final Face face : graph.faces())
for (final Edge edge : face.edges())
if (edge.left() == null || edge.right() == null)
face.properties().set(Properties.NULL_NBOR);
// Set non-outer items to inner
for (int st = 0; st < Graph.siteTypes.length; st++)
for (final GraphElement ge : graph.elements(Graph.siteTypes[st]))
if (!ge.properties().get(Properties.OUTER))
ge.properties().set(Properties.INNER);
}
//-------------------------------------------------------------------------
/**
* Determines the left/right/top/bottom graph elements.
*
* @param graph The graph to measure.
*/
public static void measureExtremes(final Graph graph)
{
final double tolerance = 0.01;
for (int st = 0; st < Graph.siteTypes.length; st++)
{
double minX = 1000000;
double minY = 1000000;
double maxX = -1000000;
double maxY = -1000000;
for (final GraphElement ge : graph.elements(Graph.siteTypes[st]))
{
if (ge.pt().x() < minX)
minX = ge.pt().x();
if (ge.pt().y() < minY)
minY = ge.pt().y();
if (ge.pt().x() > maxX)
maxX = ge.pt().x();
if (ge.pt().y() > maxY)
maxY = ge.pt().y();
}
for (final GraphElement ge : graph.elements(Graph.siteTypes[st]))
{
if (ge.pt().x() - minX < tolerance)
ge.properties().set(Properties.LEFT);
if (ge.pt().y() - minY < tolerance)
ge.properties().set(Properties.BOTTOM);
if (maxX - ge.pt().x() < tolerance)
ge.properties().set(Properties.RIGHT);
if (maxY - ge.pt().y() < tolerance)
ge.properties().set(Properties.TOP);
}
}
}
//-------------------------------------------------------------------------
/**
* Determines which cells are major and which are minor.
*
* @param graph The graph to measure.
*/
public static void measureMajorMinor(final Graph graph)
{
int maxSides = 0;
for (final Face face : graph.faces())
if (face.vertices().size() > maxSides)
maxSides = face.vertices().size();
for (final Face face : graph.faces())
if (face.vertices().size() == maxSides)
face.properties().set(Properties.MAJOR);
else
face.properties().set(Properties.MINOR);
}
//-------------------------------------------------------------------------
/**
* Determines outer graph elements that are corners.
*
* Assumes that measureExtremes() has already been called.
*
* Assumes only one perimeter per graph.
*
* @param graph The graph to measure.
*/
public static void measureCorners(final Graph graph)
{
cornersFromPerimeters(graph);
for (final Vertex vertex : graph.vertices())
{
if (!vertex.properties().get(Properties.CORNER))
continue;
// System.out.print("Vertex " + vertex.id() + " has edges:");
// for (final Edge edge : vertex.edges())
// System.out.print(" " + edge.id());
// System.out.println();
final boolean isConcave = vertex.properties().get(Properties.CORNER_CONCAVE);
// Check for incident edge with other endpoint on perimeter
boolean singleEdge = false;
for (final Edge edge : vertex.edges())
{
final Vertex other = edge.otherVertex(vertex);
if (other.properties().get(Properties.CORNER))
{
// Both endpoints of this edge are corners
edge.properties().set(Properties.CORNER);
if (isConcave)
edge.properties().set(Properties.CORNER_CONCAVE);
else
edge.properties().set(Properties.CORNER_CONVEX);
final Face faceL = edge.left();
final Face faceR = edge.right();
if (faceL != null)
{
faceL.properties().set(Properties.CORNER);
if (isConcave)
faceL.properties().set(Properties.CORNER_CONCAVE);
else
faceL.properties().set(Properties.CORNER_CONVEX);
}
else if (faceR != null)
{
faceR.properties().set(Properties.CORNER);
if (isConcave)
faceR.properties().set(Properties.CORNER_CONCAVE);
else
faceR.properties().set(Properties.CORNER_CONVEX);
}
singleEdge = true;
// Don't break! e.g. single square with 4 vertices will not pick up all vertices
//break;
}
}
if (singleEdge)
continue;
// Vertex is a corner on its own.
// Note that there may be more than two edges, e.g. Alquerque.
for (final Edge edge : vertex.edges())
{
if (!edge.properties().get(Properties.PERIMETER))
continue;
edge.properties().set(Properties.CORNER);
if (isConcave)
edge.properties().set(Properties.CORNER_CONCAVE);
else
edge.properties().set(Properties.CORNER_CONVEX);
if (isConcave)
{
for (final Face face : vertex.faces())
if (numPerimeterVertices(face) == 1)
{
face.properties().set(Properties.CORNER);
if (isConcave)
face.properties().set(Properties.CORNER_CONCAVE);
else
face.properties().set(Properties.CORNER_CONVEX);
}
}
else
{
final Face faceL = edge.left();
final Face faceR = edge.right();
if (faceL != null)
{
faceL.properties().set(Properties.CORNER);
faceL.properties().set(Properties.CORNER_CONVEX);
}
else if (faceR != null)
{
faceR.properties().set(Properties.CORNER);
faceR.properties().set(Properties.CORNER_CONVEX);
}
}
}
}
// // Debug report
// final int[] counts = new int[3];
// for (final Vertex vertex : graph.vertices())
// if (vertex.properties().get(Properties.CORNER))
// counts[0]++;
//
// for (final Edge edge : graph.edges())
// if (edge.properties().get(Properties.CORNER))
// counts[1]++;
//
// for (final Face face : graph.faces())
// if (face.properties().get(Properties.CORNER))
// counts[2]++;
//
// System.out.println("Corner counts: vertices=" + counts[0] +
// ", edges=" + counts[1] + ", faces=" + counts[2] + ".");
// // Debug report
// System.out.print("Vertex corners:");
// for (final Vertex vertex : graph.vertices())
// if (vertex.properties().get(Properties.CORNER))
// System.out.print(" " + vertex.id());
// System.out.println();
//
// System.out.print("Edge corners:");
// for (final Edge edge : graph.edges())
// if (edge.properties().get(Properties.CORNER))
// System.out.print(" " + edge.id());
// System.out.println();
//
// System.out.print("Face corners:");
// for (final Face face : graph.faces())
// if (face.properties().get(Properties.CORNER))
// System.out.print(" " + face.id());
// System.out.println();
}
static int numPerimeterVertices(final Face face)
{
int num = 0;
for (final Vertex vertex : face.vertices())
if (vertex.properties().get(Properties.PERIMETER))
num++;
return num;
}
/**
* Measures corners for the specified graph element type.
*/
static void cornersFromPerimeters(final Graph graph)
{
for (final Perimeter perimeter : graph.perimeters())
cornersFromPerimeter(graph, perimeter);
}
/**
* Measures corners for the specified graph element type.
*/
static void cornersFromPerimeter(final Graph graph, final Perimeter perimeter)
{
final double tolerance = 0.001;
if (perimeter.elements().size() < 6)
{
// Simple convex polygon
for (final GraphElement ge : perimeter.elements())
{
ge.properties().set(Properties.CORNER);
ge.properties().set(Properties.CORNER_CONVEX);
}
return;
}
final int num = perimeter.elements().size();
final List<Point2D> polygon2D = perimeter.positions();
//boolean isClockwise = MathRoutines.clockwise(polygon2D);
// System.out.print("\nPerimeter:");
// for (final GraphElement ge : perimeter.elements())
// System.out.print(" " + ge.id());
// System.out.println();
// Calculate average determinant at each perimeter site
final double[] scores = new double[num];
final int numK = 4;
for (int n = 0; n < num; n++)
{
final Point2D.Double pt = (Point2D.Double)polygon2D.get(n);
// Accumulated line segment error approach
double score = 0;
for (int k = 1; k < numK; k++)
{
final Point2D.Double ptA = (Point2D.Double)polygon2D.get((n - k + num) % num);
final Point2D.Double ptB = (Point2D.Double)polygon2D.get((n + k) % num);
double dist = MathRoutines.distanceToLine(pt, ptA, ptB);
if (MathRoutines.clockwise(ptA, pt, ptB))
dist = -dist;
score += dist / k; // / k; //(k * k);
}
//score /= numK;
scores[n] = score;
}
// Smooth the scores
final int numSmoothingPasses = 1;
final double[] temp = new double[num];
for (int pass = 0; pass < numSmoothingPasses; pass++)
{
for (int n = 0; n < num; n++)
temp[n] = (4 * scores[n] + scores[(n + 1) % num] + scores[(n - 1 + num) % num]) / 6;
for (int n = 0; n < num; n++)
scores[n] = temp[n];
}
// System.out.println("Smoothed:");
// for (int n = 0; n < num; n++)
// System.out.println("id=" + perimeter.elements().get(n).id() + ", scores=" + scores[n] + ".");
// Detect convex corners
final BitSet keep = new BitSet();
keep.set(0, num, true);
for (int n = 0; n < num; n++)
if
(
scores[n] < 0.320 // this value catches bad corners in rectangular shapes on hex
||
scores[n] < scores[(n - 1 + num) % num] - tolerance
||
scores[n] < scores[(n + 1) % num] - tolerance
)
keep.set(n, false);
// Keep similar nbors
final double similar = 0.95;
for (int n = keep.nextSetBit(0); n >= 0; n = keep.nextSetBit(n + 1))
{
if (scores[(n - 1 + num) % num] >= similar * scores[n])
keep.set((n - 1 + num) % num, true);
if (scores[(n + 1) % num] >= similar * scores[n])
keep.set((n + 1) % num, true);
}
for (int n = keep.nextSetBit(0); n >= 0; n = keep.nextSetBit(n + 1))
{
perimeter.elements().get(n).properties().set(Properties.CORNER);
perimeter.elements().get(n).properties().set(Properties.CORNER_CONVEX);
}
// Detect concave corners
keep.set(0, num, true);
// for (int n = 0; n < num; n++)
// if (scores[n] > 0) //-0.320
// {
// keep.set(n, false);
// }
// else if
// (
// scores[n] > 0
// ||
// scores[n] > scores[(n - 1 + num) % num] + tolerance
// ||
// scores[n] > scores[(n + 1) % num] + tolerance
// )
// {
// // Is a candidate for removal
// final double diffA = Math.abs(scores[n] - scores[(n - 1 + num) % num]);
// final double diffB = Math.abs(scores[n] - scores[(n + 1) % num]);
//
//// if (Math.min(diffA, diffB) > 0.1)
// keep.set(n, false);
// }
for (int n = 0; n < num; n++)
if
(
scores[n] > -0.25 // 0.320 // this value catches bad corners in rectangular shapes on hex
||
scores[n] > scores[(n - 1 + num) % num] + tolerance
||
scores[n] > scores[(n + 1) % num] + tolerance
)
keep.set(n, false);
for (int n = keep.nextSetBit(0); n >= 0; n = keep.nextSetBit(n + 1))
{
perimeter.elements().get(n).properties().set(Properties.CORNER);
perimeter.elements().get(n).properties().set(Properties.CORNER_CONCAVE);
}
// System.out.print("Corners:");
// int count = 0;
// for (final GraphElement ge : graph.vertices())
// if (ge.properties().get(Properties.CORNER))
// {
// System.out.print(" " + ge.id());
// count++;
// }
// System.out.println("\n" + count + " corners found.");
}
//-------------------------------------------------------------------------
/**
* Determines which board side perimeter graph elements are on.
*
* Must be done *after* corners have been determined.
*
* @param graph The graph to measure.
*/
public static void measureSides(final Graph graph)
{
final Point2D mid = graph.centroid();
for (final Perimeter perimeter : graph.perimeters())
findSides(graph, mid, perimeter);
// Determine edge and cell sides based on perimeter vertices
final long[] sides =
{
Properties.SIDE_N, Properties.SIDE_E, Properties.SIDE_S, Properties.SIDE_W,
Properties.SIDE_NE, Properties.SIDE_SE, Properties.SIDE_SW, Properties.SIDE_NW
};
for (final Vertex vertex : graph.vertices())
{
// Every perimeter vertex should be assigned a side by now
if (!vertex.properties().get(Properties.CORNER))
continue;
for (int side = 0; side < sides.length; side++)
{
final long sideCode = sides[side];
if (!vertex.properties().get(sideCode))
continue; // not this side
// Edges: both end points must be on this side
for (final Edge edge : vertex.edges())
{
final Vertex other = edge.otherVertex(vertex);
if (other.properties().get(sideCode))
edge.properties().set(sideCode);
}
// Cells: any face with this vertex is on this side
for (final Face face : vertex.faces())
face.properties().set(sideCode);
}
}
// Ensure that edges and faces inherit the side(s) their vertices are on
final long sidesMask =
Properties.SIDE_N | Properties.SIDE_E | Properties.SIDE_S | Properties.SIDE_W
|
Properties.SIDE_NE | Properties.SIDE_SE | Properties.SIDE_SW | Properties.SIDE_NW;
for (final Vertex vertex : graph.vertices())
{
for (final Edge edge : vertex.edges())
edge.properties().add(vertex.properties().get() & sidesMask);
for (final Face face : vertex.faces())
face.properties().add(vertex.properties().get() & sidesMask);
}
}
static void findSides(final Graph graph, final Point2D mid, final Perimeter perimeter)
{
// Find each side run
final int num = perimeter.elements().size();
for (int from = 0; from < num; from++)
{
final GraphElement geFrom = perimeter.elements().get(from);
if (geFrom.properties().get(Properties.CORNER))
{
// Handle this side run
int to = from;
GraphElement geTo;
do
{
geTo = perimeter.elements().get(++to % num);
} while (!geTo.properties().get(Properties.CORNER));
final int runLength = to - from;
sideFromRun(graph, perimeter, mid, from, runLength);
}
}
}
static void sideFromRun
(
final Graph graph, final Perimeter perimeter, final Point2D mid,
final int from, final int runLength
)
{
final int numDirections = 16;
final int num = perimeter.elements().size();
final GraphElement geFrom = perimeter.elements().get(from);
// Locate average position of elements along run
double avgX = geFrom.pt().x();
double avgY = geFrom.pt().y();
GraphElement ge = null;
for (int r = 0; r < runLength; r++)
{
ge = perimeter.elements().get((from + 1 + r) % num);
avgX += ge.pt().x();
avgY += ge.pt().y();
}
avgX /= (runLength + 1);
avgY /= (runLength + 1);
final int dirn = discreteDirection(mid, new Point2D.Double(avgX, avgY), numDirections);
long property = 0;
if (dirn == 0)
property = Properties.SIDE_E;
else if (dirn == numDirections / 4)
property = Properties.SIDE_N;
else if (dirn == numDirections / 2)
property = Properties.SIDE_W;
else if (dirn == 3 * numDirections / 4)
property = Properties.SIDE_S;
else if (dirn > 0 && dirn < numDirections / 4)
property = Properties.SIDE_NE;
else if (dirn > dirn / 4 && dirn < numDirections / 2)
property = Properties.SIDE_NW;
else if (dirn > dirn / 2 && dirn < 3 * numDirections / 4)
property = Properties.SIDE_SW;
else
property = Properties.SIDE_SE;
// Store result in run elements
for (int r = 0; r < runLength + 1; r++)
{
ge = perimeter.elements().get((from + r) % num);
ge.properties().set(property);
}
}
//-------------------------------------------------------------------------
/**
* @param angleIn Input angle.
* @param numDirections Number of direction increments.
* @return Index of the arc segment in which this direction lies.
*/
public static int discreteDirection(final double angleIn, final int numDirections)
{
final double arc = 2 * Math.PI / numDirections;
final double off = arc / 2;
double angle = angleIn;
while (angle < 0)
angle += 2 * Math.PI;
while (angle > 2 * Math.PI)
angle -= 2 * Math.PI;
return ((int)((angle + off) / arc) + numDirections) % numDirections;
}
/**
* @param ptA First end point of vector.
* @param ptB Second end point of vector.
* @param numDirections Number of the direction increments.
* @return Index of the arc segment in which this direction lies.
*/
public static int discreteDirection(final Point2D ptA, final Point2D ptB, final int numDirections)
{
final double angle = Math.atan2(ptB.getY() - ptA.getY(), ptB.getX() - ptA.getX());
return discreteDirection(angle, numDirections);
}
//-------------------------------------------------------------------------
/**
* Determines which graph element(s) are at the centre.
*
* Assumes that perimeter elements have already been set.
*
* @param graph The graph to measure.
*/
public static void measureCentre(final Graph graph)
{
final Rectangle2D bounds = Graph.bounds(graph.elements(SiteType.Vertex));
final Point2D mid = new Point2D.Double
(
bounds.getX() + bounds.getWidth() / 2.0,
bounds.getY() + bounds.getHeight() / 2.0
);
for (int st = 0; st < Graph.siteTypes.length; st++)
measureGeometricCentre(graph, mid, Graph.siteTypes[st]);
}
/**
* Measures total distance squared to perimeter and corner elements.
*
* Could be sped up by only taking a sample of perimeter elements, but this could lead to biases.
*
* Combine distance to: 1. perimeter, and 2. perimeter corners, for edge cases like single column of cells.
*/
private static void measureGeometricCentre(final Graph graph, final Point2D mid, final SiteType type)
{
final double tolerance = 0.0001;
final List<? extends GraphElement> list = graph.elements(type);
final List<GraphElement> perimeterGE = new ArrayList<GraphElement>();
// If board is large, do not include perimeter, just use the corners
if (list.size() < 100)
for (final GraphElement ge : list)
if (ge.properties().get(Properties.PERIMETER))
perimeterGE.add(ge);
final List<GraphElement> cornersGE = new ArrayList<GraphElement>();
for (final GraphElement ge : list)
if (ge.properties().get(Properties.CORNER))
cornersGE.add(ge);
final double[] distances = new double[list.size()];
for (final GraphElement geA : list)
{
double acc = 0;
for (final GraphElement geB : perimeterGE)
acc += MathRoutines.distanceSquared(geA.pt2D(), geB.pt2D());
for (final GraphElement geB : cornersGE)
acc += MathRoutines.distanceSquared(geA.pt2D(), geB.pt2D());
distances[geA.id()] = acc;
}
double minDistance = 1000000;
for (int n = 0; n < distances.length; n++)
if (distances[n] < minDistance)
minDistance = distances[n];
for (int n = 0; n < distances.length; n++)
if (Math.abs(distances[n] - minDistance) < tolerance)
list.get(n).properties().set(Properties.CENTRE);
}
//-------------------------------------------------------------------------
/**
* Determines the phase of each cell (no two adjacent cells have the same
* phase).
*
* @param graph The graph to measure.
*/
public static void measurePhase(final Graph graph)
{
for (int st = 0; st < Graph.siteTypes.length; st++)
measurePhase(graph, Graph.siteTypes[st]);
}
/**
* Determines the phase of each cell (no two adjacent cells have the same
* phase).
*
* @param graph The graph to measure.
* @param type The graph element type.
*/
public static void measurePhase(final Graph graph, final SiteType type)
{
final List<? extends GraphElement> elements = graph.elements(type);
if (elements.isEmpty())
return;
// for (final Face face : graph.faces())
// System.out.println("Face " + face.id() + " momentum is " + face.momentum() + ".");
while (true)
{
// Find the starting element, if any
GraphElement start = null;
for (final GraphElement ge : elements)
if (ge.properties().phase() == Constants.UNDEFINED)
{
start = ge;
break;
}
if (start == null)
break; // no more elements to set
// We need efficient adding and removing to/from front, and efficient adding to back.
// So a Deque is perfect for this
final Deque<GraphElement> queue = new ArrayDeque<GraphElement>();
final BitSet visited = new BitSet();
// Add the first face
start.properties().set(Properties.PHASE_0);
queue.add(start);
// Spread phase over remaining faces
while (!queue.isEmpty())
{
final GraphElement ge = queue.removeFirst();
if (visited.get(ge.id()))
continue;
// Gather known phases of all nbors
final List<GraphElement> nbors = ge.nbors();
final BitSet nborPhases = nborPhases(nbors);
int phase;
for (phase = 0; phase < 4; phase++)
if (!nborPhases.get(phase))
break; // this phase is not in any nbor
// Set this element's phase
if (phase == 0)
ge.properties().set(Properties.PHASE_0);
else if (phase == 1)
ge.properties().set(Properties.PHASE_1);
else if (phase == 2)
ge.properties().set(Properties.PHASE_2);
else if (phase == 3)
ge.properties().set(Properties.PHASE_3);
else if (phase == 4)
ge.properties().set(Properties.PHASE_4);
else if (phase == 5)
ge.properties().set(Properties.PHASE_5);
visited.set(ge.id(), true);
// Visit each nbor, prioritising more constrained ones
for (final GraphElement nbor : nbors)
{
if (visited.get(nbor.id()))
continue;
final List<GraphElement> nborNbors = nbor.nbors();
final BitSet nborNborPhases = nborPhases(nborNbors);
final int numNborNborPhases = nborNborPhases.cardinality();
if (numNborNborPhases > 1)
queue.addFirst(nbor); // more than one phase to match, higher priority
else
queue.addLast(nbor);
}
}
}
}
static BitSet nborPhases(final List<GraphElement> nbors)
{
final BitSet phases = new BitSet();
for (final GraphElement nbor : nbors)
{
if (nbor.properties().get(Properties.PHASE_0))
phases.set(0, true);
else if (nbor.properties().get(Properties.PHASE_1))
phases.set(1, true);
else if (nbor.properties().get(Properties.PHASE_2))
phases.set(2, true);
else if (nbor.properties().get(Properties.PHASE_3))
phases.set(3, true);
else if (nbor.properties().get(Properties.PHASE_4))
phases.set(4, true);
else if (nbor.properties().get(Properties.PHASE_5))
phases.set(5, true);
}
return phases;
}
//-------------------------------------------------------------------------
/**
* Determines the orientation of each edge (axial, angle, horz/vert, etc).
*
* @param graph The graph to measure.
*/
public static void measureEdgeOrientation(final Graph graph)
{
final int numDirections = 16;
for (final Edge edge : graph.edges())
{
final Vertex va = edge.vertexA();
final Vertex vb = edge.vertexB();
final int direction = discreteDirection(va.pt2D(), vb.pt2D(), numDirections);
if (direction == 0 || direction == numDirections / 2)
{
edge.properties().set(Properties.AXIAL);
edge.properties().set(Properties.HORIZONTAL);
}
else if (direction == numDirections / 4 || direction == 3 * numDirections / 4)
{
edge.properties().set(Properties.AXIAL);
edge.properties().set(Properties.VERTICAL);
}
else if
(
direction > 0 && direction < numDirections / 4
||
direction > numDirections / 2 && direction < 3 * numDirections / 4
)
{
edge.properties().set(Properties.ANGLED);
edge.properties().set(Properties.SLASH);
}
else
{
edge.properties().set(Properties.ANGLED);
edge.properties().set(Properties.SLOSH);
}
}
}
//-------------------------------------------------------------------------
/**
* Determines the coordinate label and row/column/level of each graph element.
*
* Note: Assumes that elements will not have negative z values.
*
* @param graph The graph to measure.
*/
public static void measureSituation(final Graph graph)
{
final double[] bestVertexThetas = { 0, 0.5 };
for (final SiteType siteType : SiteType.values())
{
final List<? extends GraphElement> elements = graph.elements(siteType);
if (elements.isEmpty())
continue;
// Estimate unit size (expected average distance between elements positions)
final Rectangle2D bounds = Graph.bounds(elements);
final double unit = (bounds.getWidth() + bounds.getHeight()) / 2 / Math.sqrt(elements.size());
// System.out.println("\n" + siteType + ":\n");
if (siteType == SiteType.Edge)
clusterByRowAndColumn(elements, unit, bestVertexThetas, true);
else
clusterByRowAndColumn(elements, unit, bestVertexThetas, false);
clusterByDimension(elements, RCLType.Layer, unit, 0);
setCoordinateLabels(graph, siteType, elements);
}
}
/**
* Clusters coordinates along a given dimension.
*
* @param elements The elements to measure.
* @param unit Estimated unit length.
* @param bestThetas The best theta values.
* @param useBestThetas True if the best theta values have to be used.
*/
public static void clusterByRowAndColumn
(
final List<? extends GraphElement> elements,
final double unit,
final double[] bestThetas,
final boolean useBestThetas
)
{
// final long startAt = System.nanoTime();
if (useBestThetas)
{
// Site types must be Edge: Use previously found best thetas from Vertex
clusterByDimension(elements, RCLType.Row, unit, bestThetas[0]);
clusterByDimension(elements, RCLType.Column, unit, bestThetas[1]);
return;
}
// Find best row angle
double bestError = 1000;
bestThetas[0] = 0;
for (int angle = 0; angle <= 60; angle += 15)
{
final double theta = angle / 180.0 * Math.PI;
final double error = clusterByDimension(elements, RCLType.Row, unit, theta);
if (error < bestError)
{
bestError = error;
bestThetas[0] = theta;
if (error < 0.01)
break; // won't get much better
}
}
clusterByDimension(elements, RCLType.Row, unit, bestThetas[0]);
// System.out.println("Best row angle is " + (int)(Math.toDegrees(bestThetas[0]) + 0.5) + ".");
// Find best column angle, based on best row angle
bestError = 1000;
bestThetas[1] = 0;
for (int angle = 90; angle <= 120; angle += 15)
{
final double theta = bestThetas[0] + angle / 180.0 * Math.PI;
final double error = clusterByDimension(elements, RCLType.Column, unit, theta);
if (error < bestError)
{
bestError = error;
bestThetas[1] = theta;
if (error < 0.01)
break; // won't get much better
}
}
clusterByDimension(elements, RCLType.Column, unit, bestThetas[1]);
// System.out.println("Best column angle is " + (int)(Math.toDegrees(bestThetas[1]) + 0.5) + ".");
// final long stopAt = System.nanoTime();
// final double secs = (stopAt - startAt) / 1000000.0;
// System.out.println("Time: " + secs + "ms.");
}
/**
* Clusters coordinates along a given dimension.
*
* @param elements The elements to measure.
* @param rclType Coordinate dimension to cluster on.
* @param unit Expected element spacing.
* @param theta Angle of base line.
*
* @return Average cluster error.
*/
public static double clusterByDimension
(
final List<? extends GraphElement> elements,
final RCLType rclType,
final double unit,
final double theta
)
{
// Prepare base line to measure from
Point2D refA=null, refB=null;
final Rectangle2D bounds = Graph.bounds(elements);
if (rclType == RCLType.Row)
{
refA = new Point2D.Double(bounds.getX() + bounds.getWidth() / 2, bounds.getY() - bounds.getHeight());
refB = new Point2D.Double
(
refA.getX() + bounds.getWidth() * Math.cos(theta),
refA.getY() + bounds.getWidth() * Math.sin(theta)
);
}
else if (rclType == RCLType.Column)
{
refA = new Point2D.Double(bounds.getX() - bounds.getWidth(), bounds.getY() + bounds.getHeight() / 2);
refB = new Point2D.Double
(
refA.getX() + bounds.getWidth() * Math.cos(theta),
refA.getY() + bounds.getWidth() * Math.sin(theta)
);
}
// Sort elements by distance from reference line AB
final List<ItemScore> rank = new ArrayList<ItemScore>();
final double margin = 0.6 * unit;
for (int n = 0; n < elements.size(); n++)
{
final double dist = (rclType == RCLType.Layer)
? elements.get(n).pt().z()
: MathRoutines.distanceToLine(elements.get(n).pt2D(), refA, refB);
rank.add(new ItemScore(n, dist));
}
Collections.sort(rank);
// System.out.print("Scores:");
// for (final ItemScore item : rank)
// System.out.print(" " + item.score());
// System.out.println();
// Cluster
final List<Bucket> buckets = new ArrayList<Bucket>();
Bucket bucket = null;
for (final ItemScore item : rank)
{
if (bucket == null || Math.abs(item.score() - bucket.mean()) > margin)
{
// Create a new bucket for this item
bucket = new Bucket();
buckets.add(bucket);
}
bucket.addItem(item);
}
// System.out.println(buckets.size() + " " + rclType + " buckets created.");
// System.out.print("Buckets:");
// for (final Bucket bkt : buckets)
// System.out.print(" " + bkt.mean() + " (" + bkt.items().size() + ")");
// System.out.println();
// Assign elements to buckets
for (int bid = 0; bid < buckets.size(); bid++)
for (final ItemScore item : buckets.get(bid).items())
{
final RCL rcl = elements.get(item.id()).situation().rcl();
switch (rclType)
{
case Row: rcl.setRow(bid); break;
case Column: rcl.setColumn(bid); break;
case Layer: rcl.setLayer(bid); break;
default: // do nothing
}
}
// Determine error
double error = 0;
for (final Bucket bkt : buckets)
{
double acc = 0;
for (final ItemScore item : bkt.items())
acc = (bkt.mean() - item.score()) * (bkt.mean() - item.score());
error += acc / bkt.items().size();
}
error += 0.01 * buckets.size(); // penalise greater bucket counts
//System.out.println("Error is " + error + ".");
return error;
}
/**
* Sets the coordinate label for each element based on its RCL situation.
*
* @param graph The graph to modify.
* @param siteType The graph element type.
* @param elements Elements to be labelled.
*/
public static void setCoordinateLabels
(
final Graph graph,
final SiteType siteType,
final List<? extends GraphElement> elements
)
{
// Check if distinct layers
boolean distinctLayers = false;
for (int eid = 0; eid < elements.size()-1; eid++)
if
(
elements.get(eid).situation().rcl().layer()
!=
elements.get(eid+1).situation().rcl().layer()
)
{
distinctLayers = true;
break;
}
// Create coordinates, checking for duplicates within this site type
final Map<String, GraphElement> map = new HashMap<String, GraphElement>();
map.clear();
for (final GraphElement element : elements)
{
// Column label
int column = element.situation().rcl().column();
String label = "" + (char)('A' + column % 26);
while (column >= 26)
{
column /= 26;
label = (char)('A' + column % 26 - 1) + label;
}
// Row label
label += (element.situation().rcl().row() + 1);
// Layer label
if (distinctLayers)
label += "/" + element.situation().rcl().layer();
if (map.get(label) != null)
{
// System.out.println("Duplicate " + siteType + " coordinate " + label + ".");
graph.setDuplicateCoordinates(siteType);
}
else
{
map.put(label, element);
}
element.situation().setLabel(label);
}
}
//-------------------------------------------------------------------------
}
| 41,052 | 27.708392 | 122 | java |
Ludii | Ludii-master/Core/src/game/util/graph/Perimeter.java | package game.util.graph;
import java.awt.geom.Point2D;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.Collections;
import java.util.List;
//-----------------------------------------------------------------------------
/**
* Vertex perimeter of a connected component in a graph.
*
* @author cambolbro
*/
public class Perimeter
{
/** Vertices on this perimeter. */
private final List<GraphElement> elements = new ArrayList<GraphElement>();
/** Positions of vertices on this perimeter (for using with MathRoutines). */
private final List<Point2D> positions = new ArrayList<Point2D>();
/** List of vertices inside this perimeter, not including the perimeter. */
private final List<GraphElement> inside = new ArrayList<GraphElement>();
/** Indices of vertices on this perimeter. */
final BitSet on = new BitSet();
/** Indices of vertices inside this perimeter. */
final BitSet in = new BitSet();
//-------------------------------------------------------------------------
/**
* @return The list of graph elements.
*/
public List<GraphElement> elements()
{
return Collections.unmodifiableList(elements);
}
/**
* @return The positions of the elements.
*/
public List<Point2D> positions()
{
return Collections.unmodifiableList(positions);
}
/**
* @return All the graph elements inside the perimeter.
*/
public List<GraphElement> inside()
{
return Collections.unmodifiableList(inside);
}
/**
* @return The bitset of the indices of vertices on this perimeter.
*/
public BitSet on()
{
return on;
}
/**
* @return The bitset of the indices of vertices in this perimeter.
*/
public BitSet in()
{
return in;
}
//-------------------------------------------------------------------------
/**
* @return The starting point of the perimeter.
*/
public Point2D startPoint()
{
if (positions.isEmpty())
return null;
return positions.get(0);
}
//-------------------------------------------------------------------------
/**
* Clear the perimeter.
*/
public void clear()
{
elements.clear();
positions.clear();
inside.clear();
on.clear();
in.clear();
}
//-------------------------------------------------------------------------
/**
* Add a vertex to the perimeter.
*
* @param vertex The vertex.
*/
public void add(final Vertex vertex)
{
elements.add(vertex);
positions.add(vertex.pt2D());
on.set(vertex.id(), true);
}
/**
* Add a vertex inside the perimeter.
*
* @param vertex The vertex.
*/
public void addInside(final Vertex vertex)
{
inside.add(vertex);
in.set(vertex.id(), true);
}
//-------------------------------------------------------------------------
// public void generatePoint2D()
// {
// perimeter2D.clear();
//
// for (final GraphElement ge : perimeter)
// perimeter2D.add(ge.pt2D());
// }
//-------------------------------------------------------------------------
}
| 2,980 | 20.292857 | 79 | java |
Ludii | Ludii-master/Core/src/game/util/graph/Poly.java | package game.util.graph;
import annotations.Name;
import annotations.Opt;
import game.functions.dim.DimFunction;
import main.math.Polygon;
import other.BaseLudeme;
//-----------------------------------------------------------------------------
/**
* Defines a polygon composed of a list of floating point (x,y) pairs.
*
* @author cambolbro
*
* @remarks The polygon can be concave.
*/
public class Poly extends BaseLudeme
{
private final Polygon polygon;
//-------------------------------------------------------------------------
/**
* For building a polygon with float points.
*
* @param pts Float points defining polygon.
* @param rotns Number of duplicate rotations to make.
*
* @example (poly { { 0 0 } { 0 2.5 } { 4.75 1 } })
*/
public Poly
(
final Float[][] pts,
@Opt @Name final Integer rotns
)
{
polygon = new Polygon(pts, (rotns == null ? 0 : rotns.intValue()));
}
/**
* For building a polygon with DimFunction points.
*
* @param pts Float points defining polygon.
* @param rotns Number of duplicate rotations to make.
*
* @example (poly { { 0 0 } { 0 2.5 } { 4.75 1 } })
*/
public Poly
(
final DimFunction[][] pts,
@Opt @Name final Integer rotns
)
{
final Float[][] floatPts = new Float[pts.length][];
// Translation from DimFunction to Float.
for (int i = 0; i < pts.length; i++)
{
final DimFunction[] yPoint = pts[i];
floatPts[i] = new Float[yPoint.length];
for (int j = 0; j < pts[i].length; j++)
floatPts[i][j] = Float.valueOf(pts[i][j].eval());
}
polygon = new Polygon(floatPts, (rotns == null ? 0 : rotns.intValue()));
}
//-------------------------------------------------------------------------
/**
* @return The polygon.
*/
public Polygon polygon()
{
return polygon;
}
//-------------------------------------------------------------------------
}
| 1,910 | 22.304878 | 79 | java |
Ludii | Ludii-master/Core/src/game/util/graph/Properties.java | package game.util.graph;
import main.Constants;
//-----------------------------------------------------------------------------
/**
* Record of graph element properties.
*
* @author cambolbro
*/
public class Properties
{
//-------------------------------------------------------------------------
/** Whether the element is inside the perimeter of the graph. */
public static final long INNER = (0x1L << 0);
/** Whether the element is on the perimeter and is an outer element. */
public static final long OUTER = (0x1L << 1);
/** Whether the element is on the perimeter. */
public static final long PERIMETER = (0x1L << 2);
/** Whether the element is a centre element. */
public static final long CENTRE = (0x1L << 3);
/** Whether the element is a major generator element in tiling. */
public static final long MAJOR = (0x1L << 4);
/** Whether the element is a minor satellite element in tiling. */
public static final long MINOR = (0x1L << 5);
/** Whether the element is a pivot element. */
public static final long PIVOT = (0x1L << 6);
/** Whether the element is an inter-layer element. */
public static final long INTERLAYER = (0x1L << 7);
/** Whether the element is a face with a null neighbour. */
public static final long NULL_NBOR = (0x1L << 8);
/** Whether the element is a corner. */
public static final long CORNER = (0x1L << 10);
/** Whether the element is a convex corner. */
public static final long CORNER_CONVEX = (0x1L << 11);
/** Whether the element is a concave corner. */
public static final long CORNER_CONCAVE = (0x1L << 12);
/** Whether the element is on the phase 0. */
public static final long PHASE_0 = (0x1L << 13);
/** Whether the element is on the phase 1. */
public static final long PHASE_1 = (0x1L << 14);
/** Whether the element is on the phase 2. */
public static final long PHASE_2 = (0x1L << 15);
/** Whether the element is on the phase 3. */
public static final long PHASE_3 = (0x1L << 16);
/** Whether the element is on the phase 4. */
public static final long PHASE_4 = (0x1L << 17);
/** Whether the element is on the phase 5. */
public static final long PHASE_5 = (0x1L << 18);
/** Whether the element is on the left of the board. */
public static final long LEFT = (0x1L << 25);
/** Whether the element is on the right of the board. */
public static final long RIGHT = (0x1L << 26);
/** Whether the element is on the top of the board. */
public static final long TOP = (0x1L << 27);
/** Whether the element is on the bottom of the board. */
public static final long BOTTOM = (0x1L << 28);
/** Whether the element is an axial edge. */
public static final long AXIAL = (0x1L << 30);
/** Whether the element is an horizontal edge. */
public static final long HORIZONTAL = (0x1L << 31);
/** Whether the element is a vertical edge. */
public static final long VERTICAL = (0x1L << 32);
/** Whether the element is an angled edge. */
public static final long ANGLED = (0x1L << 33);
/** Whether the element is a slash edge /. */
public static final long SLASH = (0x1L << 34);
/** Whether the element is a slosh edge \. */
public static final long SLOSH = (0x1L << 35);
/** Whether the element is on the North side. */
public static final long SIDE_N = (0x1L << 40);
/** Whether the element is on the East side. */
public static final long SIDE_E = (0x1L << 41);
/** Whether the element is on the South side. */
public static final long SIDE_S = (0x1L << 42);
/** Whether the element is on the West side. */
public static final long SIDE_W = (0x1L << 43);
/** Whether the element is on the North East side. */
public static final long SIDE_NE = (0x1L << 44);
/** Whether the element is on the South East side. */
public static final long SIDE_SE = (0x1L << 45);
/** Whether the element is on the South West side. */
public static final long SIDE_SW = (0x1L << 46);
/** Whether the element is on the North West side. */
public static final long SIDE_NW = (0x1L << 47);
private long properties = 0;
//-------------------------------------------------------------------------
/**
* Default constructor.
*/
public Properties()
{
}
/**
* Constructor with the properties in a long.
*
* @param properties The long value.
*/
public Properties(final long properties)
{
this.properties = properties;
}
/**
* Constructor with the properties.
*
* @param other The properties.
*/
public Properties(final Properties other)
{
this.properties = other.properties;
}
//-------------------------------------------------------------------------
/**
* Clear the properties.
*/
public void clear()
{
properties = 0;
}
/**
* @return The properties in a long.
*/
public long get()
{
return properties;
}
/**
* @param property The property to check.
* @return True if the property is on these properties.
*/
public boolean get(final long property)
{
return (properties & property) != 0;
}
/**
* To set a property.
*
* @param property The property to add.
*/
public void set(final long property)
{
properties |= property;
}
/**
* To set on a property.
*
* @param property The property.
* @param on The value.
*/
public void set(final long property, final boolean on)
{
if (on)
properties |= property;
else
properties &= ~property;
}
/**
* To add a property.
*
* @param other The property to add.
*/
public void add(final long other)
{
properties |= other;
}
// public void set(final long property)
// {
// properties = property;
// }
//-------------------------------------------------------------------------
/**
* @return The phase converted in an integer.
*/
public int phase()
{
if (get(PHASE_0))
return 0;
if (get(PHASE_1))
return 1;
if (get(PHASE_2))
return 2;
if (get(PHASE_3))
return 3;
if (get(PHASE_4))
return 4;
if (get(PHASE_5))
return 5;
return Constants.UNDEFINED;
}
/**
* Clear the phases.
*/
public void clearPhase()
{
properties &= ~PHASE_0;
properties &= ~PHASE_1;
properties &= ~PHASE_2;
properties &= ~PHASE_3;
properties &= ~PHASE_4;
properties &= ~PHASE_5;
}
/**
* Set the phase.
*
* @param phase The phase to set.
*/
public void setPhase(final int phase)
{
properties &= ~PHASE_0;
properties &= ~PHASE_1;
properties &= ~PHASE_2;
properties &= ~PHASE_3;
properties &= ~PHASE_4;
properties &= ~PHASE_5;
switch (phase)
{
case 0: properties |= PHASE_0; break;
case 1: properties |= PHASE_1; break;
case 2: properties |= PHASE_2; break;
case 3: properties |= PHASE_3; break;
case 4: properties |= PHASE_4; break;
case 5: properties |= PHASE_5; break;
default: // do nothing
}
}
//-------------------------------------------------------------------------
@Override
public String toString()
{
final StringBuilder sb = new StringBuilder();
if (get(Properties.INNER)) sb.append(" I");
if (get(Properties.OUTER)) sb.append(" O");
if (get(Properties.PIVOT)) sb.append(" PVT");
if (get(Properties.PERIMETER)) sb.append(" PRM");
if (get(Properties.INTERLAYER)) sb.append(" IL");
if (get(Properties.CORNER)) sb.append(" CNR");
if (get(Properties.CORNER_CONVEX)) sb.append("(X)");
if (get(Properties.CORNER_CONCAVE)) sb.append("(V)");
if (get(Properties.CENTRE)) sb.append(" CTR");
if (get(Properties.AXIAL)) sb.append(" AXL");
if (get(Properties.ANGLED)) sb.append(" AGL");
if (get(Properties.PHASE_0)) sb.append(" PH_0");
if (get(Properties.PHASE_1)) sb.append(" PH_1");
if (get(Properties.PHASE_2)) sb.append(" PH_2");
if (get(Properties.PHASE_3)) sb.append(" PH_3");
if (get(Properties.PHASE_4)) sb.append(" PH_4");
if (get(Properties.PHASE_5)) sb.append(" PH_5");
String side = "";
if (get(Properties.SIDE_N)) side += "/N";
if (get(Properties.SIDE_E)) side += "/E";
if (get(Properties.SIDE_S)) side += "/S";
if (get(Properties.SIDE_W)) side += "/W";
if (get(Properties.SIDE_NE)) side += "/NE";
if (get(Properties.SIDE_SE)) side += "/SE";
if (get(Properties.SIDE_SW)) side += "/SW";
if (get(Properties.SIDE_NW)) side += "/NW";
if (!side.isEmpty())
side = " SD_" + side.substring(1);
sb.append(side);
final String str = sb.toString();
return "<" + (str.isEmpty() ? "" : str.substring(1)) + ">";
}
//-------------------------------------------------------------------------
}
| 8,489 | 24.419162 | 79 | java |
Ludii | Ludii-master/Core/src/game/util/graph/Radial.java | package game.util.graph;
import java.awt.geom.Point2D;
import java.util.ArrayList;
import java.util.List;
import game.util.directions.AbsoluteDirection;
import main.math.MathRoutines;
//-----------------------------------------------------------------------------
/**
* Sequence of steps in a direction.
*
* @author cambolbro
*/
public class Radial
{
/** The array of steps making up this radial. */
private final GraphElement[] steps;
/**
* Direction of the first step in this radial.
* This is useful to store so that radials can be quickly sorted by direction in Trajectories.
*/
private final AbsoluteDirection direction;
/** Matching radials in the opposite direction (if any). */
private List<Radial> opposites = null;
//-------------------------------------------------------------------------
/**
* Constructor.
*
* @param steps The array of steps in this radial.
* @param direction The absolute direction of the radial.
*/
public Radial(final GraphElement[] steps, final AbsoluteDirection direction)
{
this.steps = steps;
this.direction = direction;
}
//-------------------------------------------------------------------------
/**
* @return The array of the graph elements in the steps.
*/
public GraphElement[] steps()
{
return steps;
}
/**
* @return Direction of the first step in this radial
*/
public AbsoluteDirection direction()
{
return direction;
}
/**
* @return The list of the opposite radials.
*/
public List<Radial> opposites()
{
return opposites;
}
//-------------------------------------------------------------------------
// Graph element routines
/**
* @return The origin of the steps.
*/
public GraphElement from()
{
return steps[0];
}
/**
* @return The last step.
*/
public GraphElement lastStep()
{
return steps[steps.length - 1];
}
//-------------------------------------------------------------------------
/**
* @param other The other radial.
* @return True if the radial match.
*/
public boolean matches(final Radial other)
{
if (direction != other.direction)
return false;
return stepsMatch(other);
}
/**
* @param other The radial.
* @return True if the step match.
*/
public boolean stepsMatch(final Radial other)
{
if (steps.length != other.steps.length)
return false;
for (int n = 0; n < steps.length; n++)
if (!steps[n].matches(other.steps[n]))
return false;
return true;
}
//-------------------------------------------------------------------------
/**
* @param other The opposite radial.
* @return Whether the specified radial is opposite to this one.
*/
public boolean isOppositeAngleTo(final Radial other)
{
final double threshold = 0.1; // amount of allowable bend ~9 degrees
final double tanThreshold = Math.tan(threshold);
final GraphElement geA = steps[1];
final GraphElement geB = steps[0];
final GraphElement geC = other.steps[1];
final Point2D ptA = geA.pt2D();
final Point2D ptB = geB.pt2D();
final Point2D ptC = geC.pt2D();
//final double diff = MathRoutines.angleDifference(ptA, ptB, ptC);
//
//return Math.abs(diff) < threshold;
// Same optimisation as in Trajectories::followRadial()
// see comments in that method for extensive explanation
final double absTanDiff = MathRoutines.absTanAngleDifferencePosX(ptA, ptB, ptC);
return absTanDiff < tanThreshold;
}
//-------------------------------------------------------------------------
/**
* Add an opposite radial.
*
* @param opp The opposite radial.
*/
public void addOpposite(final Radial opp)
{
if (opposites == null)
{
// Start the opposites list with this one
opposites = new ArrayList<Radial>();
opposites.add(opp);
}
else
{
// Check that this opposite isn't already included
for (final Radial existingOpposite : opposites)
if
(
(direction.specific() || opp.direction() == direction)
||
opp.stepsMatch(existingOpposite)
)
return;
opposites.add(opp);
}
}
//-------------------------------------------------------------------------
/**
* Removes subsets from the list of opposites.
*/
public void removeOppositeSubsets()
{
if (opposites == null)
return;
for (int o = opposites.size() - 1; o >= 0; o--)
{
final Radial oppositeO = opposites.get(o);
for (int n = 0; n < opposites.size(); n++)
{
if (n == o)
continue;
if (oppositeO.isSubsetOf(opposites.get(n)))
{
opposites.remove(o);
break;
}
}
}
}
//-------------------------------------------------------------------------
/**
* @param other The radial.
* @return True if the radial is a subset of the radial in entry.
*/
public boolean isSubsetOf(final Radial other)
{
//if (direction != other.direction)
// return false;
if (steps.length > other.steps.length)
return false;
for (int n = 0; n < steps.length; n++)
if (!steps[n].matches(other.steps[n]))
return false;
return true;
}
//-------------------------------------------------------------------------
@Override
public String toString()
{
final StringBuilder sb = new StringBuilder();
for (int n = 0; n < steps.length; n++)
{
if (n > 0)
sb.append("-");
sb.append(steps[n].label());
}
//sb.append(":" + direction);
if (opposites != null)
{
sb.append(" [");
for (int o = 0; o < opposites.size(); o++)
{
final Radial opp = opposites.get(o);
if (o > 0)
sb.append(", ");
for (int n = 0; n < opp.steps.length; n++)
{
if (n > 0)
sb.append("-");
sb.append(opp.steps[n].label());
}
//sb.append(":" + opp.direction());
}
sb.append("]");
}
return sb.toString();
}
//-------------------------------------------------------------------------
}
| 5,880 | 21.192453 | 95 | java |
Ludii | Ludii-master/Core/src/game/util/graph/Radials.java | package game.util.graph;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.Collections;
import java.util.List;
import game.types.board.SiteType;
import game.util.directions.AbsoluteDirection;
import main.math.MathRoutines;
//-----------------------------------------------------------------------------
/**
* Record of radials from a given element.
*
* @author cambolbro
*/
public class Radials
{
private final SiteType siteType;
private final int siteId;
private final List<Radial> radials = new ArrayList<Radial>();
private List<Radial>[] inDirection;
/** Sublists of distinct radials, i.e. no duplication with opposites. */
private List<Radial>[] distinctInDirection;
/** Total directions for these Steps. */
private final BitSet totalDirections = new BitSet();
//-------------------------------------------------------------------------
/**
* Constructor.
*
* @param siteType The graph element type.
* @param id The index of the radial.
*/
public Radials(final SiteType siteType, final int id)
{
this.siteType = siteType;
this.siteId = id;
allocate();
}
//-------------------------------------------------------------------------
/**
* @return The list of the radials.
*/
public List<Radial> radials()
{
return radials;
}
/**
* @param dirn The absolute direction.
* @return The list of the radials.
*/
public List<Radial> inDirection(final AbsoluteDirection dirn)
{
return inDirection[dirn.ordinal()];
}
/**
* @param dirn
* @return A subset of the "inDirection" radials, which excludes radials that are
* opposites of already-included radials.
*/
public List<Radial> distinctInDirection(final AbsoluteDirection dirn)
{
return distinctInDirection[dirn.ordinal()];
}
/**
* @return The bitset corresponding of the directions.
*/
public BitSet totalDirections()
{
return totalDirections;
}
//-------------------------------------------------------------------------
/**
* Allocate the radials.
*/
@SuppressWarnings("unchecked")
public void allocate()
{
final int numDirections = AbsoluteDirection.values().length;
inDirection = new ArrayList[numDirections];
distinctInDirection = new ArrayList[numDirections];
for (int dirn = 0; dirn < numDirections; dirn++)
{
inDirection[dirn] = new ArrayList<Radial>();
distinctInDirection[dirn] = new ArrayList<Radial>();
}
}
//-------------------------------------------------------------------------
/**
* Add a radial in a direction.
*
* @param dirn The direction.
* @param radial The radial.
*/
public void addInDirection(final AbsoluteDirection dirn, final Radial radial)
{
inDirection[dirn.ordinal()].add(radial);
}
/**
* Add a radial in a distinct direction.
*
* @param dirn The direction.
* @param radial The radial.
*/
public void addDistinctInDirection(final AbsoluteDirection dirn, final Radial radial)
{
distinctInDirection[dirn.ordinal()].add(radial);
}
//-------------------------------------------------------------------------
void addSafe(final Radial radial)
{
// Check if radial duplicates existing radial
for (final Radial existing : radials)
if (existing.matches(radial))
{
// Don't add duplicate radials
//System.out.println("Steps.add(): Duplicate steps:\na) " + step + "\nb) " + existing);
//existing.directions().or(radial.directions()); // keep any unknown directions
return;
}
// Check if is opposite of existing radial
for (final Radial existing : radials) //inDirection[radial.direction().ordinal()]) //radials)
if
(
radial.direction() == AbsoluteDirection.CW && existing.direction() == AbsoluteDirection.CCW
||
radial.direction() == AbsoluteDirection.CCW && existing.direction() == AbsoluteDirection.CW
||
radial.direction() == AbsoluteDirection.In && existing.direction() == AbsoluteDirection.Out
||
radial.direction() == AbsoluteDirection.Out && existing.direction() == AbsoluteDirection.In
||
radial.isOppositeAngleTo(existing)
&&
(
radial.direction().specific() && existing.direction().specific()
||
radial.direction() == existing.direction()
)
)
{
// Add but don't duplicate
radial.addOpposite(existing); // note - may be more than one opposite!
existing.addOpposite(radial);
}
// Check if is distinct for this direction
boolean isDistinct = true;
for (final Radial existing : inDirection[radial.direction().ordinal()])
{
// **
// ** TODO: Check this logic. If some radials start failing to be
// ** found, or recognised as distinct, this is the first
// ** thing to check.
// **
if (radial.stepsMatch(existing) || radial.isOppositeAngleTo(existing))
{
isDistinct = false;
break;
}
if (radial.opposites() != null)
for (final Radial existingOpposite : radial.opposites())
{
if (radial.stepsMatch(existingOpposite))
{
isDistinct = false;
break;
}
}
}
radials.add(radial);
// Store by direction
inDirection[radial.direction().ordinal()].add(radial);
totalDirections.set(radial.direction().ordinal());
if (isDistinct)
{
// distinct.add(radial);
distinctInDirection[radial.direction().ordinal()].add(radial);
}
}
/**
* Remove the subsets in the direction.
*
* @param dirn The direction.
*/
public void removeSubsetsInDirection(final AbsoluteDirection dirn)
{
final int dirnId = dirn.ordinal();
for (int n = inDirection[dirnId].size() - 1; n >= 0; n--)
{
final Radial radial = inDirection[dirnId].get(n);
for (int nn = 0; nn < inDirection[dirnId].size(); nn++)
{
if (n == nn)
continue;
if (radial.isSubsetOf(inDirection[dirnId].get(nn)))
{
inDirection[dirnId].remove(n);
break;
}
}
}
}
//-------------------------------------------------------------------------
/**
* Set the distinct radials.
*/
public void setDistinct()
{
// distinct.clear();
for (int dirn = 0; dirn < AbsoluteDirection.values().length; dirn++)
distinctInDirection[dirn].clear();
// Find distinct radials over all radials
// for (int r = 0; r < radials.size(); r++)
// {
// final Radial radial = radials.get(r);
//
// boolean isDistinct = true;
// for (int rr = 0; rr < radials.size() && isDistinct; rr++)
// {
// if (r == rr)
// continue;
//
// final Radial other = radials.get(rr);
// if (other.opposites() == null)
// continue;
//
// for (final Radial opp : other.opposites())
// if (radial.stepsMatch(opp))
// {
// isDistinct = false;
// break;
// }
// }
//
// //if (isDistinct)
// distinct.add(radial);
// }
// for (final Radial radial : radials)
// {
// boolean isDistinct = true;
// for (final Radial existing : distinct)
// {
// if (radial == existing)
// continue;
//
// if (existing.opposites() == null)
// continue;
//
// for (final Radial opp : existing.opposites())
// if (radial.stepsMatch(opp))
// {
// isDistinct = false;
// break;
// }
// }
//
// if (isDistinct)
// distinct.add(radial);
// }
// Find distinct radials within each direction
for (int dirn = 0; dirn < AbsoluteDirection.values().length; dirn++)
for (final Radial radial : inDirection[dirn])
{
boolean isDistinct = true;
for (final Radial existing : distinctInDirection[dirn])
{
if (radial == existing)
continue;
if (existing.opposites() == null)
continue;
for (final Radial opp : existing.opposites())
if (radial.stepsMatch(opp))
{
isDistinct = false;
break;
}
}
if (isDistinct)
distinctInDirection[dirn].add(radial);
}
}
//-------------------------------------------------------------------------
/**
* Sort radials in all lists CW from N.
*/
public void sort()
{
sort(radials);
for (int dirn = 0; dirn < AbsoluteDirection.values().length; dirn++)
{
sort(inDirection[dirn]);
sort(distinctInDirection[dirn]);
}
}
/**
* Sort radials in the specified list CW from N.
* @param list List of radials to be sorted
*/
public static void sort(final List<Radial> list)
{
final List<ItemScore> rank = new ArrayList<ItemScore>();
for (int n = 0; n < list.size(); n++)
{
final Radial radial = list.get(n);
final double theta = MathRoutines.angle
(
radial.steps()[0].pt2D(),
radial.steps()[1].pt2D()
);
double score = Math.PI / 2 - theta + 0.0001;
while (score < 0)
score += 2 * Math.PI;
rank.add(new ItemScore(n, score));
}
Collections.sort(rank);
// Remember original order
final Radial[] orig = list.toArray(new Radial[list.size()]);
// Set the items in list in new order
for (int r = 0; r < rank.size(); r++)
list.set(r, orig[rank.get(r).id()]);
}
//-------------------------------------------------------------------------
/**
* @param r1
* @param r2
* @return Angle formed by the two given radials, which are assumed to have a shared
* starting point.
*/
public static double angle(final Radial r1, final Radial r2)
{
assert (r1.steps()[0].equals(r2.steps()[0]));
// Law of Cosines
//
// we want to compute angle C, opposite of side c, radials form rays a and b
//
// c^2 = a^2 + b^2 - 2ab cos(C)
// 2ab cos(C) = a^2 + b^2 - c^2
// cos(C) = (a^2 + b^2 - c^2) / 2ab
// C = acos( (a^2 + b^2 - c^2) / 2ab )
final double a = r1.steps()[1].pt2D().distance(r1.steps()[0].pt2D());
final double b = r2.steps()[1].pt2D().distance(r2.steps()[0].pt2D());
final double c = r2.steps()[1].pt2D().distance(r1.steps()[1].pt2D());
return Math.acos((a*a + b*b - c*c) / (2.0 * a * b));
}
//-------------------------------------------------------------------------
@Override
public String toString()
{
final StringBuilder sb = new StringBuilder();
sb.append("Radials from " + siteType + " " + siteId + ":\n");
for (final AbsoluteDirection dirn : AbsoluteDirection.values())
{
for (final Radial radial : inDirection[dirn.ordinal()])
{
sb.append("- " + dirn + ": " + radial.toString());
// Denote if this radial is distinct
boolean isDistinct = false;
for (final Radial dist : distinctInDirection[dirn.ordinal()])
if (dist.matches(radial))
{
isDistinct = true;
break;
}
if (isDistinct)
sb.append("*");
sb.append("\n");
}
}
return sb.toString();
}
//-------------------------------------------------------------------------
}
| 10,777 | 24.006961 | 97 | java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.